WeKnora/migrations/versioned/000103_message_artifacts_ta...

87 lines
4.0 KiB
MySQL
Raw Normal View History

feat(artifacts): artifacts library page backed by a message_artifacts table (#3384) * feat(artifacts): add an artifacts library with its own message_artifacts table Skill-generated files were only reachable from inside the conversation that produced them. This adds a sidebar entry and a page that lists them across every conversation the user can see. Storage: artifacts move out of the messages.artifacts JSONB column into a new message_artifacts table (PostgreSQL 000103, SQLite 000023), backfilled on upgrade. The table is now the only source of truth; the old column is kept and the down migration writes the table back into it. The message repository loads artifacts for every message it returns and writes them on create, update (when non-nil) and fork, so callers still use Message.Artifacts. mod_time is stored as RFC 3339 text because the collector matches files on nanosecond mtimes, which PostgreSQL timestamps would truncate. API: GET /api/v1/artifacts lists the latest version of each file (grouped by session + source path, with version_count), scoped like the session list, with keyword / file type filters and paging. Downloads keep using the per-session endpoint. Frontend: "产物/Artifacts" sidebar entry (hidden without sandbox support), a library page with type tabs, search, date groups, infinite loading, preview drawer, download and jump-to-conversation; strings in all five locales. The sidebar's top-menu paths are now one shared list. * fix(artifacts): keep the restore hash guard and count versions by URL RecordRestoredArtifactMtime again only stamps rows whose content hash matches the restored content (and ignores empty hashes), and never rewrites the hash, matching MessageArtifacts.WithRestoredMtime. Without the guard a restore of v1's content also moved v2's mtime and relabelled v2 with v1's hash. The library's version_count now counts distinct URLs per (session, source path). A later answer that references an earlier file stores another row with the same URL, which COUNT(*) reported as an extra version. * fix(artifacts): scope the library to web chats and clear the legacy column The library used the session list's default scope, which counts sessions without an owner as legacy tenant-level rows. IM sessions are created without an owner, so every member saw the file names and titles of every IM chat (downloads then 404 for non-admins). The library now applies the same "web" bucket predicate as the home sidebar, extracted from QueryPaged so the two cannot drift: no IM mapping (including cleared ones), no embed marker, no API-key owner. Migrations 000103 / SQLite 000023 now clear messages.artifacts after the backfill. Message loads still SELECT *, so the stale copy was read on every history load. Only rows that carried artifacts are rewritten; the column stays for instances on the old binary during a rolling upgrade, and the down migration still rebuilds it from the table. * fix(migrations): keep the 000103 backfill alive on malformed artifact JSON A single file_size that is not an integer ("12.5", "") or a created_at that does not parse ("garbage", month 13) raised a cast error and failed the whole migration, blocking startup. Casts now go through pg_temp helpers that return NULL on bad input, falling back to 0 and the message's created_at; valid rows are unchanged. SQLite casts never raise; its migration test now covers the same malformed values. * docs(artifacts): describe the web-only library scope and the cleared legacy column
2026-09-18 04:10:19 +00:00
-- Migration: 000103_message_artifacts_table
-- Skill-generated files move out of the messages.artifacts JSONB column into
-- their own table so they can be listed across sessions (the artifact library)
-- without expanding every message's JSON. The table becomes the only source of
-- truth. After the backfill the legacy column is cleared (message loads still
-- SELECT *, so a stale copy would be read on every history load) but kept, so
-- instances still on the old binary during a rolling upgrade keep working. The
-- down migration rebuilds the column from this table.
DO $$ BEGIN RAISE NOTICE '[Migration 000103] Creating message_artifacts table'; END $$;
CREATE TABLE IF NOT EXISTS message_artifacts (
id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(),
session_id VARCHAR(36) NOT NULL,
message_id VARCHAR(36) NOT NULL,
position INTEGER NOT NULL,
url TEXT NOT NULL DEFAULT '',
file_name TEXT NOT NULL DEFAULT '',
file_type VARCHAR(32) NOT NULL DEFAULT '',
file_size BIGINT NOT NULL DEFAULT 0,
content_hash VARCHAR(64) NOT NULL DEFAULT '',
source_path TEXT NOT NULL DEFAULT '',
mod_time VARCHAR(64) NOT NULL DEFAULT '',
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_message_artifacts_message_position
ON message_artifacts (message_id, position);
CREATE INDEX IF NOT EXISTS idx_message_artifacts_session_created
ON message_artifacts (session_id, created_at);
COMMENT ON TABLE message_artifacts IS 'Files a skill script produced during an assistant turn, one row per file';
COMMENT ON COLUMN message_artifacts.position IS 'Zero-based position within the owning message; the download API addresses files by it';
COMMENT ON COLUMN message_artifacts.url IS 'Storage or resource:// URL; never returned to clients';
COMMENT ON COLUMN message_artifacts.mod_time IS 'Sandbox mtime as RFC 3339 text; kept at nanosecond precision because the collector matches files on it';
COMMENT ON COLUMN message_artifacts.source_path IS 'Absolute path inside the sandbox; repeated paths in a session are versions of one file';
DO $$ BEGIN RAISE NOTICE '[Migration 000103] Backfilling message_artifacts from messages.artifacts'; END $$;
-- A single malformed value (a numeric string, an impossible date) must not fail
-- the whole migration, so casts go through session-scoped helpers that return
-- NULL instead of raising; pg_temp objects vanish with the connection.
CREATE OR REPLACE FUNCTION pg_temp.wk_try_bigint(v TEXT) RETURNS BIGINT
LANGUAGE plpgsql IMMUTABLE AS $$
BEGIN
RETURN v::NUMERIC::BIGINT;
EXCEPTION WHEN others THEN
RETURN NULL;
END $$;
CREATE OR REPLACE FUNCTION pg_temp.wk_try_timestamptz(v TEXT) RETURNS TIMESTAMPTZ
LANGUAGE plpgsql IMMUTABLE AS $$
BEGIN
RETURN v::TIMESTAMPTZ;
EXCEPTION WHEN others THEN
RETURN NULL;
END $$;
INSERT INTO message_artifacts (
session_id, message_id, position, url, file_name, file_type, file_size,
content_hash, source_path, mod_time, created_at
)
SELECT
m.session_id,
m.id,
(a.ord - 1)::INTEGER,
COALESCE(a.elem ->> 'url', ''),
COALESCE(a.elem ->> 'file_name', ''),
LEFT(COALESCE(a.elem ->> 'file_type', ''), 32),
COALESCE(pg_temp.wk_try_bigint(a.elem ->> 'file_size'), 0),
LEFT(COALESCE(a.elem ->> 'content_hash', ''), 64),
COALESCE(a.elem ->> 'source_path', ''),
LEFT(COALESCE(a.elem ->> 'mod_time', ''), 64),
COALESCE(pg_temp.wk_try_timestamptz(a.elem ->> 'created_at'), m.created_at, CURRENT_TIMESTAMP)
FROM messages m
CROSS JOIN LATERAL jsonb_array_elements(
CASE WHEN jsonb_typeof(m.artifacts) = 'array' THEN m.artifacts ELSE '[]'::jsonb END
) WITH ORDINALITY AS a(elem, ord)
WHERE jsonb_typeof(a.elem) = 'object'
ON CONFLICT (message_id, position) DO NOTHING;
DO $$ BEGIN RAISE NOTICE '[Migration 000103] Clearing legacy messages.artifacts'; END $$;
-- Only rows that carried artifacts; rewriting every '[]' row would touch the
-- whole messages table for nothing.
UPDATE messages SET artifacts = NULL
WHERE artifacts IS NOT NULL AND artifacts <> '[]'::jsonb;