-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
feat(sdk,core,webapp): transcript storage for chat.agent #4896
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| --- | ||
| "@trigger.dev/sdk": minor | ||
| "@trigger.dev/core": minor | ||
| --- | ||
|
|
||
| `chat.agent` persists a conversation through a `TranscriptStorage`: an adapter with `load` and `save` that the runtime drives after every turn, failed turn and history-changing action. The platform snapshot stays the default; bring your own to write the conversation to your database as it happens. Each save carries both the changes since the last one (so a row store writes only what changed, and an undo is one `truncateAfter`) and the whole transcript as it now stands (so a document store writes it as-is with no state of its own). | ||
|
|
||
| ```ts | ||
| chat.agent({ | ||
| id: "my-chat", | ||
| storage: myTranscriptStorage, | ||
| run: async ({ messages, signal, streamText }) => | ||
| streamText({ model, messages, abortSignal: signal }), | ||
| }); | ||
| ``` | ||
|
|
||
| `chat.createLoadTranscriptAction(storage)` and `useLoadTranscript` read the conversation back the same way for every storage, and `runTranscriptStorageTests` from `@trigger.dev/sdk/ai/test` checks an implementation against the contract. | ||
|
|
||
| Compaction summaries and `chat.inject` context now survive a continuation run, and crash recovery runs for every agent, including one that owns its own context. `hydrateMessages` is deprecated in favour of `loadContext` on a storage. The snapshot format is now version 2, which older SDK versions cannot read. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
62 changes: 62 additions & 0 deletions
62
apps/webapp/app/components/runs/v3/agent/transcriptSnapshotSeed.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
| import { seedFromTranscriptSnapshot } from "./transcriptSnapshotSeed"; | ||
|
|
||
| const user = { id: "u-1", role: "user", parts: [{ type: "text", text: "hello" }] }; | ||
| const assistant = { id: "a-1", role: "assistant", parts: [{ type: "text", text: "world" }] }; | ||
|
|
||
| describe("seedFromTranscriptSnapshot", () => { | ||
| it("seeds from a version 1 snapshot in array order", () => { | ||
| const seed = seedFromTranscriptSnapshot({ | ||
| version: 1, | ||
| savedAt: 1_000, | ||
| messages: [user, assistant], | ||
| lastOutEventId: "42", | ||
| lastInEventId: "7", | ||
| }); | ||
|
|
||
| expect(seed).toBeDefined(); | ||
| expect(seed!.lastOutEventId).toBe("42"); | ||
| expect(seed!.messages.map((m) => m.id)).toEqual(["u-1", "a-1"]); | ||
| expect(seed!.messages.map((m) => m.timestamp)).toEqual([998, 999]); | ||
| expect(seed!.messages[1]!.message).toEqual(assistant); | ||
| }); | ||
|
|
||
| it("seeds from a version 2 snapshot, unwrapping the message envelope", () => { | ||
| const seed = seedFromTranscriptSnapshot({ | ||
| version: 2, | ||
| savedAt: 1_000, | ||
| messages: [ | ||
| { id: "u-1", final: true, message: user }, | ||
| { id: "a-1", final: false, message: assistant }, | ||
| ], | ||
| state: { summary: "irrelevant to rendering" }, | ||
| lastOutEventId: "42", | ||
| lastInEventId: "7", | ||
| }); | ||
|
|
||
| expect(seed).toBeDefined(); | ||
| expect(seed!.lastOutEventId).toBe("42"); | ||
| expect(seed!.messages.map((m) => m.id)).toEqual(["u-1", "a-1"]); | ||
| expect(seed!.messages.map((m) => m.timestamp)).toEqual([998, 999]); | ||
| expect(seed!.messages[1]!.message).toEqual(assistant); | ||
| }); | ||
|
|
||
| it("skips version 1 entries without an id but keeps the others' positions", () => { | ||
| const seed = seedFromTranscriptSnapshot({ | ||
| version: 1, | ||
| savedAt: 1_000, | ||
| messages: [{ role: "user", parts: [] }, assistant], | ||
| }); | ||
|
|
||
| expect(seed!.messages.map((m) => m.id)).toEqual(["a-1"]); | ||
| expect(seed!.messages[0]!.timestamp).toBe(999); | ||
| expect(seed!.lastOutEventId).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("returns undefined for an unknown version or a non-snapshot body", () => { | ||
| expect(seedFromTranscriptSnapshot({ version: 3, savedAt: 1, messages: [] })).toBeUndefined(); | ||
| expect(seedFromTranscriptSnapshot({ error: "not found" })).toBeUndefined(); | ||
| expect(seedFromTranscriptSnapshot(null)).toBeUndefined(); | ||
| expect(seedFromTranscriptSnapshot("[]")).toBeUndefined(); | ||
| }); | ||
| }); |
32 changes: 32 additions & 0 deletions
32
apps/webapp/app/components/runs/v3/agent/transcriptSnapshotSeed.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import type { UIMessage } from "@ai-sdk/react"; | ||
| import { parseTranscriptSnapshot } from "@trigger.dev/core/v3"; | ||
|
|
||
| export type TranscriptSnapshotSeed = { | ||
| messages: Array<{ id: string; message: UIMessage; timestamp: number }>; | ||
| lastOutEventId: string | undefined; | ||
| }; | ||
|
|
||
| /** | ||
| * Turn a fetched chat-snapshot blob into the messages the AgentView seeds | ||
| * before it opens the `.out` subscription. | ||
| * | ||
| * Each message gets a unique, monotonically increasing timestamp from | ||
| * `(savedAt - count + index)`. Live chunk timestamps are S2 arrival | ||
| * milliseconds in the present, so anything below `savedAt` sorts before | ||
| * live chunks while preserving the snapshot's own order. | ||
| * | ||
| * Reads both snapshot versions through `parseTranscriptSnapshot`. Returns | ||
| * `undefined` for anything that is not a snapshot this reader understands; | ||
| * the caller then falls back to the seq=0 SSE. | ||
| */ | ||
| export function seedFromTranscriptSnapshot(json: unknown): TranscriptSnapshotSeed | undefined { | ||
| const snapshot = parseTranscriptSnapshot<UIMessage>(json); | ||
| if (!snapshot) return undefined; | ||
| const count = snapshot.messages.length; | ||
| const messages = snapshot.messages.map((entry, i) => ({ | ||
| id: entry.id, | ||
| message: entry.message, | ||
| timestamp: snapshot.savedAt - count + i, | ||
| })); | ||
| return { messages, lastOutEventId: snapshot.lastOutEventId }; | ||
| } |
97 changes: 97 additions & 0 deletions
97
apps/webapp/app/routes/api.v1.sessions.$sessionId.transcript.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| import { json } from "@remix-run/server-runtime"; | ||
| import { pageTranscriptEntries, parseTranscriptSnapshot } from "@trigger.dev/core/v3"; | ||
| import { z } from "zod/v4"; | ||
| import { $replica } from "~/db.server"; | ||
| import { chatSnapshotStorageKey } from "~/services/realtime/chatSnapshot.server"; | ||
| import { resolveSessionByIdOrExternalId } from "~/services/realtime/sessions.server"; | ||
| import { anyResource, createLoaderApiRoute } from "~/services/routeBuilders/apiBuilder.server"; | ||
| import { downloadPacketFromObjectStore } from "~/v3/objectStore.server"; | ||
| import { logger } from "~/services/logger.server"; | ||
|
|
||
| const ParamsSchema = z.object({ | ||
| sessionId: z.string(), | ||
| }); | ||
|
|
||
| const SearchParamsSchema = z.object({ | ||
| limit: z.coerce.number().int().min(1).max(1000).optional(), | ||
| before: z.string().optional(), | ||
| }); | ||
|
|
||
| function sessionResource( | ||
| paramId: string, | ||
| session: { friendlyId: string; externalId: string | null } | null | undefined | ||
| ) { | ||
| const ids = new Set<string>([paramId]); | ||
| if (session) { | ||
| ids.add(session.friendlyId); | ||
| if (session.externalId) ids.add(session.externalId); | ||
| } | ||
| return anyResource([...ids].map((id) => ({ type: "sessions" as const, id }))); | ||
| } | ||
|
|
||
| function isObjectNotFound(error: unknown): boolean { | ||
| if (!error) return false; | ||
| const name = (error as { name?: unknown }).name; | ||
| if (name === "NoSuchKey" || name === "NotFound") return true; | ||
| const status = (error as { $metadata?: { httpStatusCode?: number } }).$metadata?.httpStatusCode; | ||
| if (status === 404) return true; | ||
| const message = error instanceof Error ? error.message : String(error); | ||
| return /not found|nosuchkey|404|does not exist/i.test(message); | ||
| } | ||
|
|
||
| export const loader = createLoaderApiRoute( | ||
| { | ||
| params: ParamsSchema, | ||
| searchParams: SearchParamsSchema, | ||
| corsStrategy: "none", | ||
| findResource: async (params, auth) => | ||
| resolveSessionByIdOrExternalId($replica, auth.environment.id, params.sessionId), | ||
| authorization: { | ||
| action: "read", | ||
| resource: (session, params) => sessionResource(params.sessionId, session), | ||
| }, | ||
| }, | ||
| async ({ authentication, resource: session, searchParams }) => { | ||
| if (!session) { | ||
| return json({ error: "Session not found" }, { status: 404 }); | ||
| } | ||
|
|
||
| let body: unknown; | ||
| try { | ||
| const packet = await downloadPacketFromObjectStore( | ||
| { dataType: "application/store", data: chatSnapshotStorageKey(session) }, | ||
| authentication.environment | ||
| ); | ||
| body = typeof packet.data === "string" ? JSON.parse(packet.data) : undefined; | ||
| } catch (error) { | ||
| // A missing blob is a valid empty transcript (a session that has not | ||
| // saved yet). Any other read failure must NOT look like an empty chat: | ||
| // return an error so the client falls back to the whole-blob read | ||
| // instead of rendering a saved conversation as empty. | ||
| if (isObjectNotFound(error)) { | ||
| return json({ messages: [], state: null }); | ||
| } | ||
| logger.error("transcript endpoint: snapshot read failed", { | ||
| sessionId: session.friendlyId, | ||
| error: error instanceof Error ? error.message : String(error), | ||
| }); | ||
| return json({ error: "Failed to read transcript" }, { status: 502 }); | ||
| } | ||
|
|
||
| const snapshot = parseTranscriptSnapshot(body); | ||
| if (!snapshot) { | ||
| return json({ messages: [], state: null }); | ||
| } | ||
|
|
||
| const page = pageTranscriptEntries(snapshot.messages, searchParams); | ||
| return json({ | ||
| messages: page.entries.map((entry) => entry.message), | ||
| state: snapshot.state, | ||
| cursors: { | ||
| lastOutEventId: snapshot.lastOutEventId, | ||
| lastInEventId: snapshot.lastInEventId, | ||
| }, | ||
| nextCursor: page.nextCursor, | ||
| }); | ||
| } | ||
| ); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.