@agent-native/core 0.14.3 → 0.14.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/agent/production-agent.d.ts.map +1 -1
  2. package/dist/agent/production-agent.js +23 -1
  3. package/dist/agent/production-agent.js.map +1 -1
  4. package/dist/agent/thread-data-builder.d.ts.map +1 -1
  5. package/dist/agent/thread-data-builder.js +13 -2
  6. package/dist/agent/thread-data-builder.js.map +1 -1
  7. package/dist/client/sharing/ShareButton.d.ts +18 -5
  8. package/dist/client/sharing/ShareButton.d.ts.map +1 -1
  9. package/dist/client/sharing/ShareButton.js +8 -45
  10. package/dist/client/sharing/ShareButton.js.map +1 -1
  11. package/dist/client/sharing/ShareButton.spec.js +13 -31
  12. package/dist/client/sharing/ShareButton.spec.js.map +1 -1
  13. package/dist/client/sse-event-processor.d.ts.map +1 -1
  14. package/dist/client/sse-event-processor.js +19 -4
  15. package/dist/client/sse-event-processor.js.map +1 -1
  16. package/dist/server/auth.d.ts.map +1 -1
  17. package/dist/server/auth.js +25 -2
  18. package/dist/server/auth.js.map +1 -1
  19. package/dist/server/google-auth-plugin.d.ts.map +1 -1
  20. package/dist/server/google-auth-plugin.js +17 -1
  21. package/dist/server/google-auth-plugin.js.map +1 -1
  22. package/dist/server/google-oauth.d.ts.map +1 -1
  23. package/dist/server/google-oauth.js +4 -0
  24. package/dist/server/google-oauth.js.map +1 -1
  25. package/dist/server/oauth-return-url.d.ts +1 -0
  26. package/dist/server/oauth-return-url.d.ts.map +1 -1
  27. package/dist/server/oauth-return-url.js +36 -2
  28. package/dist/server/oauth-return-url.js.map +1 -1
  29. package/dist/server/onboarding-html.d.ts.map +1 -1
  30. package/dist/server/onboarding-html.js +17 -1
  31. package/dist/server/onboarding-html.js.map +1 -1
  32. package/dist/server/ssr-handler.d.ts.map +1 -1
  33. package/dist/server/ssr-handler.js +35 -2
  34. package/dist/server/ssr-handler.js.map +1 -1
  35. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"thread-data-builder.d.ts","sourceRoot":"","sources":["../../src/agent/thread-data-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEhE,UAAU,WAAW;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,UAAU,4BAA4B;IACpC,4BAA4B,CAAC,EAAE,OAAO,CAAC;CACxC;AAED,KAAK,gBAAgB,GAAG,WAAW,CAAC,UAAU,CAAC,OAAO,qBAAqB,CAAC,CAAC,CAAC;AAC9E,KAAK,WAAW,GAAG,UAAU,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAyCvD;;;;GAIG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,QAAQ,EAAE,EAClB,KAAK,CAAC,EAAE,MAAM,EACd,OAAO,GAAE,4BAAiC,GACzC;IACD,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,IAAI,CAAC;IAChB,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAE,WAAW,EAAE,CAAC;IACvB,MAAM,EACF;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GACpC;QAAE,IAAI,EAAE,YAAY,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC;IAC5C,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC,GAAG,IAAI,CA2HP;AAqGD;;;;;;;;GAQG;AACH,wBAAgB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E,GAAG,EAAE,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC,CAcA;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,WAAW,GAAG,GAAG,CAoBtE;AA+BD;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,GAAG,EACT,YAAY,EAAE,gBAAgB,GAC7B,GAAG,CA+BL;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,GAAG,GAAG;IAC5C,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CACjB,CAyBA"}
@@ -176,7 +176,7 @@ function isTerminalAssistantStatus(status) {
176
176
  return type === "complete" || type === "incomplete";
177
177
  }
178
178
  function normalizeAttachmentIdentity(attachments) {
179
- if (!Array.isArray(attachments))
179
+ if (!Array.isArray(attachments) || attachments.length === 0)
180
180
  return undefined;
181
181
  return attachments.map((att) => ({
182
182
  type: att?.type,
@@ -192,11 +192,22 @@ function messageIdentityKeys(message) {
192
192
  const runId = getMessageRunId(message);
193
193
  if (runId)
194
194
  keys.push(`run:${runId}`);
195
+ // Normalize attachments through `normalizeAttachmentIdentity` so an
196
+ // explicit empty `[]` (assistant-ui's default for messages with no
197
+ // attachments) and an omitted/undefined `attachments` field hash to the
198
+ // same fingerprint. Without this, every user message ended up duplicated
199
+ // in `chat_threads`: one copy from `saveThreadData` (runtime export
200
+ // includes `attachments: []`) and one from `persistSubmittedUserMessage`
201
+ // → `buildUserMessage` (omits the field entirely). The merge couldn't
202
+ // dedupe them because their fingerprints differed by exactly one
203
+ // `[]` vs `undefined`. (Repro on slides prod: every user turn produced
204
+ // a `client_user → assistant → server_user` triple instead of a
205
+ // `user → assistant` pair.)
195
206
  try {
196
207
  keys.push(`fingerprint:${JSON.stringify({
197
208
  role: message?.role,
198
209
  content: message?.content,
199
- attachments: message?.attachments,
210
+ attachments: normalizeAttachmentIdentity(message?.attachments),
200
211
  })}`);
201
212
  }
202
213
  catch {
@@ -1 +1 @@
1
- {"version":3,"file":"thread-data-builder.js","sourceRoot":"","sources":["../../src/agent/thread-data-builder.ts"],"names":[],"mappings":"AAmBA,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAE3C,SAAS,2BAA2B,CAAC,KAIpC;IACC,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,SAAS,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IACzD,MAAM,GAAG,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;IACtC,OAAO,CACL,KAAK,CAAC,WAAW,KAAK,IAAI;QAC1B,IAAI,KAAK,uBAAuB;QAChC,IAAI,KAAK,yBAAyB;QAClC,IAAI,KAAK,WAAW;QACpB,IAAI,KAAK,SAAS;QAClB,IAAI,KAAK,eAAe;QACxB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,cAAc;QACvB,IAAI,KAAK,8BAA8B;QACvC,IAAI,KAAK,kBAAkB;QAC3B,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC;QACvB,GAAG,CAAC,QAAQ,CAAC,eAAe,CAAC;QAC7B,GAAG,CAAC,QAAQ,CAAC,iBAAiB,CAAC;QAC/B,GAAG,CAAC,QAAQ,CAAC,oBAAoB,CAAC;QAClC,GAAG,CAAC,QAAQ,CAAC,cAAc,CAAC;QAC5B,GAAG,CAAC,QAAQ,CAAC,eAAe,CAAC;QAC7B,GAAG,CAAC,QAAQ,CAAC,yBAAyB,CAAC;QACvC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC;QACnB,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC;QACnB,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC;QACnB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,CAAC;YAC1C,CAAC,CAAC,GAAG,CAAC,OAAO;iBACR,MAAM,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;iBACrC,GAAG,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;iBACvB,IAAI,CAAC,GAAG,CAAC;YACd,CAAC,CAAC,OAAO,GAAG,CAAC,OAAO,KAAK,QAAQ;gBAC/B,CAAC,CAAC,GAAG,CAAC,OAAO;gBACb,CAAC,CAAC,EAAE,CAAC;QACT,IAAI,SAAS,CAAC,IAAI,EAAE,EAAE,CAAC;YACrB,IAAI,CAAC,KAAK;gBAAE,KAAK,GAAG,SAAS,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAClD,OAAO,GAAG,SAAS,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;QAC3C,CAAC;IACH,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AAC5B,CAAC","sourcesContent":["import type { AgentChatAttachment, RunEvent } from \"./types.js\";\n\ninterface ContentPart {\n type: string;\n text?: string;\n toolCallId?: string;\n toolName?: string;\n argsText?: string;\n args?: Record<string, string>;\n result?: string;\n}\n\ninterface BuildAssistantMessageOptions {\n suppressInternalContinuation?: boolean;\n}\n\ntype AssistantMessage = NonNullable<ReturnType<typeof buildAssistantMessage>>;\ntype UserMessage = ReturnType<typeof buildUserMessage>;\n\nconst MAX_STORED_ATTACHMENT_CHARS = 60_000;\n\nfunction isInternalContinuationError(event: {\n error: string;\n errorCode?: string;\n recoverable?: boolean;\n}): boolean {\n const code = String(event.errorCode ?? \"\").toLowerCase();\n const msg = event.error.toLowerCase();\n return (\n event.recoverable === true ||\n code === \"builder_gateway_error\" ||\n code === \"builder_gateway_timeout\" ||\n code === \"stale_run\" ||\n code === \"timeout\" ||\n code === \"timeout_error\" ||\n code === \"http_408\" ||\n code === \"http_429\" ||\n code === \"http_500\" ||\n code === \"http_502\" ||\n code === \"http_503\" ||\n code === \"http_504\" ||\n code === \"rate_limited\" ||\n code === \"too_many_concurrent_requests\" ||\n code === \"overloaded_error\" ||\n msg.includes(\"timeout\") ||\n msg.includes(\"gateway error\") ||\n msg.includes(\"gateway timeout\") ||\n msg.includes(\"inactivity timeout\") ||\n msg.includes(\"stream ended\") ||\n msg.includes(\"stream closed\") ||\n msg.includes(\"temporarily unavailable\") ||\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\") ||\n msg.includes(\"529\")\n );\n}\n\n/**\n * Reconstruct an assistant-ui message from raw agent run events.\n * Mirrors the client-side processEvent logic so the server can persist\n * the assistant's response even if the frontend is disconnected.\n */\nexport function buildAssistantMessage(\n events: RunEvent[],\n runId?: string,\n options: BuildAssistantMessageOptions = {},\n): {\n id: string;\n createdAt: Date;\n role: \"assistant\";\n content: ContentPart[];\n status:\n | { type: \"complete\"; reason: \"stop\" }\n | { type: \"incomplete\"; reason: \"error\" };\n metadata: Record<string, unknown>;\n} | null {\n const content: ContentPart[] = [];\n let toolCallCounter = 0;\n let runError: {\n message: string;\n errorCode?: string;\n details?: string;\n recoverable?: boolean;\n } | null = null;\n let endedAtInternalContinuationBoundary = false;\n\n const appendText = (text: string) => {\n const last = content[content.length - 1];\n if (last && last.type === \"text\") {\n last.text = (last.text ?? \"\") + text;\n } else {\n content.push({ type: \"text\", text });\n }\n };\n\n for (const { event } of events) {\n if (event.type === \"clear\") {\n content.length = 0;\n toolCallCounter = 0;\n continue;\n }\n\n if (event.type === \"text\") {\n appendText(event.text ?? \"\");\n continue;\n }\n\n if (event.type === \"tool_start\") {\n const toolCallId = `tc_${++toolCallCounter}`;\n const args = (event.input ?? {}) as Record<string, string>;\n content.push({\n type: \"tool-call\",\n toolCallId,\n toolName: event.tool ?? \"unknown\",\n argsText: JSON.stringify(args),\n args,\n });\n continue;\n }\n\n if (event.type === \"tool_done\") {\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === event.tool &&\n part.result === undefined\n ) {\n part.result = event.result ?? \"\";\n break;\n }\n }\n continue;\n }\n\n if (event.type === \"loop_limit\") {\n // Older servers emitted this as a user-visible terminal event. Treat it\n // as an internal continuation boundary when rebuilding persisted turns.\n if (options.suppressInternalContinuation) {\n endedAtInternalContinuationBoundary = true;\n }\n continue;\n }\n\n if (event.type === \"auto_continue\") {\n if (options.suppressInternalContinuation) {\n endedAtInternalContinuationBoundary = true;\n }\n continue;\n }\n\n if (event.type === \"error\") {\n if (\n options.suppressInternalContinuation &&\n isInternalContinuationError(event)\n ) {\n endedAtInternalContinuationBoundary = true;\n continue;\n }\n if (event.errorCode === \"run_timeout\" && event.recoverable) {\n continue;\n }\n runError = {\n message: event.error,\n ...(event.errorCode ? { errorCode: event.errorCode } : {}),\n ...(event.details ? { details: event.details } : {}),\n ...(event.recoverable ? { recoverable: event.recoverable } : {}),\n };\n appendText(`${content.length > 0 ? \"\\n\\n\" : \"\"}Error: ${event.error}`);\n continue;\n }\n\n // done, missing_api_key — terminal signals, not content\n }\n\n if (content.length === 0 || endedAtInternalContinuationBoundary) return null;\n\n const metadata: Record<string, unknown> = {};\n if (runId) metadata.runId = runId;\n if (runError) {\n metadata.custom = {\n runError: {\n ...runError,\n ...(runId ? { runId } : {}),\n },\n };\n }\n\n return {\n id: `server-${runId ?? Date.now()}`,\n createdAt: new Date(),\n role: \"assistant\",\n content,\n status: runError\n ? { type: \"incomplete\" as const, reason: \"error\" as const }\n : { type: \"complete\" as const, reason: \"stop\" as const },\n metadata,\n };\n}\n\nfunction getStoredMessage(entry: any): any {\n return entry?.message ?? entry;\n}\n\nfunction getMessageRunId(message: any): string | undefined {\n const meta = message?.metadata;\n const direct = meta?.runId;\n const custom = meta?.custom?.runId;\n const errorRun = meta?.custom?.runError?.runId ?? meta?.runError?.runId;\n if (typeof direct === \"string\") return direct;\n if (typeof custom === \"string\") return custom;\n if (typeof errorRun === \"string\") return errorRun;\n return undefined;\n}\n\nfunction messageContentIsEmpty(content: unknown): boolean {\n if (Array.isArray(content)) return content.length === 0;\n return content == null || content === \"\";\n}\n\nfunction messageText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .filter(\n (part: any) => part?.type === \"text\" && typeof part.text === \"string\",\n )\n .map((part: any) => part.text)\n .join(\"\");\n}\n\nfunction isTerminalAssistantStatus(status: unknown): boolean {\n const type = (status as { type?: unknown } | undefined)?.type;\n return type === \"complete\" || type === \"incomplete\";\n}\n\nfunction normalizeAttachmentIdentity(attachments: unknown): unknown {\n if (!Array.isArray(attachments)) return undefined;\n return attachments.map((att: any) => ({\n type: att?.type,\n name: att?.name,\n contentType: att?.contentType,\n }));\n}\n\nfunction messageIdentityKeys(message: any): string[] {\n const keys: string[] = [];\n if (typeof message?.id === \"string\" && message.id) {\n keys.push(`id:${message.id}`);\n }\n const runId = getMessageRunId(message);\n if (runId) keys.push(`run:${runId}`);\n\n try {\n keys.push(\n `fingerprint:${JSON.stringify({\n role: message?.role,\n content: message?.content,\n attachments: message?.attachments,\n })}`,\n );\n } catch {\n // Best effort. id/runId usually exist for persisted assistant-ui rows.\n }\n if (message?.role === \"user\") {\n try {\n keys.push(\n `user-fingerprint:${JSON.stringify({\n role: message.role,\n content: message.content,\n attachments: normalizeAttachmentIdentity(message.attachments),\n })}`,\n );\n } catch {\n // Same best-effort behavior as the full fingerprint.\n }\n }\n return keys;\n}\n\nfunction messagesMatch(a: any, b: any): boolean {\n const bKeys = new Set(messageIdentityKeys(b));\n return messageIdentityKeys(a).some((key) => bKeys.has(key));\n}\n\nfunction chooseMergedMessageEntry(existingEntry: any, incomingEntry: any): any {\n const existing = getStoredMessage(existingEntry);\n const incoming = getStoredMessage(incomingEntry);\n if (\n existing?.role === \"assistant\" &&\n incoming?.role === \"assistant\" &&\n isTerminalAssistantStatus(existing?.status) &&\n !isTerminalAssistantStatus(incoming?.status)\n ) {\n return existingEntry;\n }\n return incomingEntry;\n}\n\n/**\n * Merge an incoming client-side full-thread save over the current SQL copy.\n *\n * The browser exports and PUTs the whole assistant-ui repository. If a server\n * completion save lands first, an older browser export can otherwise replace\n * `thread_data` wholesale and delete the assistant message the server just\n * reconstructed from run events. Preserve server-only messages while still\n * accepting client-only messages and metadata.\n */\nexport function mergeThreadDataForClientSave(\n existingRepo: any,\n incomingRepo: any,\n) {\n const merged =\n incomingRepo && typeof incomingRepo === \"object\" ? incomingRepo : {};\n if (\n existingRepo &&\n typeof existingRepo === \"object\" &&\n existingRepo.queuedMessages !== undefined &&\n merged.queuedMessages === undefined\n ) {\n merged.queuedMessages = existingRepo.queuedMessages;\n }\n\n const existingMessages = Array.isArray(existingRepo?.messages)\n ? existingRepo.messages\n : null;\n const incomingMessages = Array.isArray(merged.messages)\n ? merged.messages\n : null;\n if (!existingMessages || !incomingMessages) return merged;\n\n const incomingKeySets = incomingMessages.map(\n (entry: any) => new Set(messageIdentityKeys(getStoredMessage(entry))),\n );\n const usedIncoming = new Set<number>();\n const nextMessages: any[] = [];\n\n for (const existingEntry of existingMessages) {\n const existingKeys = messageIdentityKeys(getStoredMessage(existingEntry));\n const incomingIndex = incomingKeySets.findIndex(\n (keys, index) =>\n !usedIncoming.has(index) && existingKeys.some((key) => keys.has(key)),\n );\n\n if (incomingIndex === -1) {\n nextMessages.push(existingEntry);\n continue;\n }\n\n usedIncoming.add(incomingIndex);\n nextMessages.push(\n chooseMergedMessageEntry(existingEntry, incomingMessages[incomingIndex]),\n );\n }\n\n for (let index = 0; index < incomingMessages.length; index++) {\n if (!usedIncoming.has(index)) nextMessages.push(incomingMessages[index]);\n }\n\n merged.messages = nextMessages;\n return merged;\n}\n\nfunction escapeAttachmentAttribute(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n}\n\nfunction unwrapTextAttachmentEnvelope(text: string): string {\n const match = text.match(\n /^<attachment\\b[^>]*>\\n?([\\s\\S]*?)\\n?<\\/attachment>$/,\n );\n return match ? match[1] : text;\n}\n\nfunction truncateStoredAttachment(text: string): string {\n const unwrapped = unwrapTextAttachmentEnvelope(text);\n if (unwrapped.length <= MAX_STORED_ATTACHMENT_CHARS) return unwrapped;\n const omitted = unwrapped.length - MAX_STORED_ATTACHMENT_CHARS;\n return `${unwrapped.slice(0, MAX_STORED_ATTACHMENT_CHARS)}\\n\\n[Attachment truncated after ${MAX_STORED_ATTACHMENT_CHARS.toLocaleString()} characters; ${omitted.toLocaleString()} characters omitted from persisted chat history.]`;\n}\n\nfunction textAttachmentEnvelope(\n att: AgentChatAttachment,\n text: string,\n): string {\n const attrs = [\n `name=\"${escapeAttachmentAttribute(att.name || \"attachment\")}\"`,\n att.contentType\n ? `contentType=\"${escapeAttachmentAttribute(att.contentType)}\"`\n : null,\n att.type ? `type=\"${escapeAttachmentAttribute(att.type)}\"` : null,\n ].filter(Boolean);\n return `<attachment ${attrs.join(\" \")}>\\n${truncateStoredAttachment(text)}\\n</attachment>`;\n}\n\nfunction buildStoredAttachments(\n attachments: AgentChatAttachment[] | undefined,\n runId: string | undefined,\n): any[] {\n return (attachments ?? [])\n .map((att, index) => {\n const id = `server-${runId ?? Date.now()}-attachment-${index}`;\n if (att.type === \"image\" && att.data) {\n return {\n id,\n type: \"image\",\n name: att.name,\n contentType: att.contentType,\n status: { type: \"complete\" },\n content: [{ type: \"image\", image: att.data }],\n };\n }\n if (att.data) {\n return {\n id,\n type: \"file\",\n name: att.name,\n contentType: att.contentType,\n status: { type: \"complete\" },\n content: [\n {\n type: \"file\",\n data: att.data,\n mimeType: att.contentType,\n filename: att.name,\n },\n ],\n };\n }\n if (typeof att.text === \"string\" && att.text.length > 0) {\n return {\n id,\n type: \"file\",\n name: att.name,\n contentType: att.contentType,\n status: { type: \"complete\" },\n content: [\n { type: \"text\", text: textAttachmentEnvelope(att, att.text) },\n ],\n };\n }\n return null;\n })\n .filter(Boolean);\n}\n\nexport function buildUserMessage(opts: {\n text: string;\n attachments?: AgentChatAttachment[];\n runId?: string;\n createdAt?: Date;\n}): {\n id: string;\n createdAt: Date;\n role: \"user\";\n content: ContentPart[];\n attachments?: any[];\n metadata: Record<string, unknown>;\n} {\n const attachments = buildStoredAttachments(opts.attachments, opts.runId);\n return {\n id: `server-user-${opts.runId ?? Date.now()}`,\n createdAt: opts.createdAt ?? new Date(),\n role: \"user\",\n content: [{ type: \"text\", text: opts.text }],\n ...(attachments.length > 0 ? { attachments } : {}),\n metadata: {\n custom: {\n submittedRunId: opts.runId,\n },\n },\n };\n}\n\nexport function upsertUserMessage(repo: any, userMsg: UserMessage): any {\n const nextRepo = repo && typeof repo === \"object\" ? repo : {};\n if (!Array.isArray(nextRepo.messages)) nextRepo.messages = [];\n\n const lastIndex = nextRepo.messages.length - 1;\n const lastEntry = lastIndex >= 0 ? nextRepo.messages[lastIndex] : undefined;\n const lastMsg = getStoredMessage(lastEntry);\n if (lastMsg?.role === \"user\" && messagesMatch(lastMsg, userMsg)) {\n return nextRepo;\n }\n\n const isWrapped = Boolean(lastEntry && \"message\" in lastEntry);\n if (isWrapped) {\n const parentId =\n lastIndex >= 0 ? (getStoredMessage(lastEntry)?.id ?? null) : null;\n nextRepo.messages.push({ message: userMsg, parentId });\n } else {\n nextRepo.messages.push(userMsg);\n }\n return nextRepo;\n}\n\nfunction shouldReplaceLastAssistant(\n lastMessage: any,\n assistantMsg: AssistantMessage,\n): boolean {\n const lastContent = lastMessage?.content;\n if (messageContentIsEmpty(lastContent)) return true;\n\n const lastRunId = getMessageRunId(lastMessage);\n const nextRunId = getMessageRunId(assistantMsg);\n if (lastRunId && nextRunId && lastRunId === nextRunId) return true;\n if (lastRunId && nextRunId && lastRunId !== nextRunId) return false;\n\n const lastStatus = lastMessage?.status;\n if (lastStatus && !isTerminalAssistantStatus(lastStatus)) return true;\n\n try {\n if (JSON.stringify(lastContent) === JSON.stringify(assistantMsg.content)) {\n return true;\n }\n } catch {\n // Fall through to the text-prefix check.\n }\n\n const lastText = messageText(lastContent).trim();\n const nextText = messageText(assistantMsg.content).trim();\n if (isTerminalAssistantStatus(lastStatus)) return false;\n return Boolean(lastText && nextText && nextText.startsWith(lastText));\n}\n\n/**\n * Merge the server-reconstructed assistant message into persisted\n * assistant-ui thread data.\n *\n * The browser periodically saves thread data while a run is still streaming.\n * That can leave the last assistant message non-empty but partial/pending.\n * Completion must replace that same-run partial message instead of treating\n * any assistant content as proof that the frontend already saved the final\n * turn.\n */\nexport function upsertAssistantMessage(\n repo: any,\n assistantMsg: AssistantMessage,\n): any {\n const nextRepo = repo && typeof repo === \"object\" ? repo : {};\n if (!Array.isArray(nextRepo.messages)) nextRepo.messages = [];\n\n const lastIndex = nextRepo.messages.length - 1;\n const lastEntry = lastIndex >= 0 ? nextRepo.messages[lastIndex] : undefined;\n const lastMsg = getStoredMessage(lastEntry);\n const lastRole = lastMsg?.role;\n const isWrapped = Boolean(lastEntry && \"message\" in lastEntry);\n\n if (\n lastRole === \"assistant\" &&\n shouldReplaceLastAssistant(lastMsg, assistantMsg)\n ) {\n nextRepo.messages[lastIndex] = isWrapped\n ? { ...lastEntry, message: assistantMsg }\n : assistantMsg;\n return nextRepo;\n }\n\n if (isWrapped) {\n const parentId =\n nextRepo.messages.length > 0\n ? (getStoredMessage(nextRepo.messages[nextRepo.messages.length - 1])\n ?.id ?? null)\n : null;\n nextRepo.messages.push({ message: assistantMsg, parentId });\n } else {\n nextRepo.messages.push(assistantMsg);\n }\n return nextRepo;\n}\n\n/**\n * Extract title and preview from a thread runtime export.\n * Isomorphic — works on both server and client.\n */\nexport function extractThreadMeta(repo: any): {\n title: string;\n preview: string;\n} {\n const msgs = repo?.messages;\n if (!Array.isArray(msgs) || msgs.length === 0)\n return { title: \"\", preview: \"\" };\n\n let title = \"\";\n let preview = \"\";\n for (const entry of msgs) {\n // Support both wrapped ({ message: { role, content } }) and flat ({ role, content }) formats\n const msg = entry?.message ?? entry;\n if (msg.role !== \"user\") continue;\n const textParts = Array.isArray(msg.content)\n ? msg.content\n .filter((p: any) => p.type === \"text\")\n .map((p: any) => p.text)\n .join(\" \")\n : typeof msg.content === \"string\"\n ? msg.content\n : \"\";\n if (textParts.trim()) {\n if (!title) title = textParts.trim().slice(0, 80);\n preview = textParts.trim().slice(0, 120);\n }\n }\n return { title, preview };\n}\n"]}
1
+ {"version":3,"file":"thread-data-builder.js","sourceRoot":"","sources":["../../src/agent/thread-data-builder.ts"],"names":[],"mappings":"AAmBA,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAE3C,SAAS,2BAA2B,CAAC,KAIpC;IACC,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,SAAS,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IACzD,MAAM,GAAG,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;IACtC,OAAO,CACL,KAAK,CAAC,WAAW,KAAK,IAAI;QAC1B,IAAI,KAAK,uBAAuB;QAChC,IAAI,KAAK,yBAAyB;QAClC,IAAI,KAAK,WAAW;QACpB,IAAI,KAAK,SAAS;QAClB,IAAI,KAAK,eAAe;QACxB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,UAAU;QACnB,IAAI,KAAK,cAAc;QACvB,IAAI,KAAK,8BAA8B;QACvC,IAAI,KAAK,kBAAkB;QAC3B,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC;QACvB,GAAG,CAAC,QAAQ,CAAC,eAAe,CAAC;QAC7B,GAAG,CAAC,QAAQ,CAAC,iBAAiB,CAAC;QAC/B,GAAG,CAAC,QAAQ,CAAC,oBAAoB,CAAC;QAClC,GAAG,CAAC,QAAQ,CAAC,cAAc,CAAC;QAC5B,GAAG,CAAC,QAAQ,CAAC,eAAe,CAAC;QAC7B,GAAG,CAAC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,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IAEpC,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,KAAK,MAAM,KAAK,IAAI,IAAI,EAAE,CAAC;QACzB,6FAA6F;QAC7F,MAAM,GAAG,GAAG,KAAK,EAAE,OAAO,IAAI,KAAK,CAAC;QACpC,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM;YAAE,SAAS;QAClC,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;YAC1C,CAAC,CAAC,GAAG,CAAC,OAAO;iBACR,MAAM,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;iBACrC,GAAG,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;iBACvB,IAAI,CAAC,GAAG,CAAC;YACd,CAAC,CAAC,OAAO,GAAG,CAAC,OAAO,KAAK,QAAQ;gBAC/B,CAAC,CAAC,GAAG,CAAC,OAAO;gBACb,CAAC,CAAC,EAAE,CAAC;QACT,IAAI,SAAS,CAAC,IAAI,EAAE,EAAE,CAAC;YACrB,IAAI,CAAC,KAAK;gBAAE,KAAK,GAAG,SAAS,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAClD,OAAO,GAAG,SAAS,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;QAC3C,CAAC;IACH,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AAC5B,CAAC","sourcesContent":["import type { AgentChatAttachment, RunEvent } from \"./types.js\";\n\ninterface ContentPart {\n type: string;\n text?: string;\n toolCallId?: string;\n toolName?: string;\n argsText?: string;\n args?: Record<string, string>;\n result?: string;\n}\n\ninterface BuildAssistantMessageOptions {\n suppressInternalContinuation?: boolean;\n}\n\ntype AssistantMessage = NonNullable<ReturnType<typeof buildAssistantMessage>>;\ntype UserMessage = ReturnType<typeof buildUserMessage>;\n\nconst MAX_STORED_ATTACHMENT_CHARS = 60_000;\n\nfunction isInternalContinuationError(event: {\n error: string;\n errorCode?: string;\n recoverable?: boolean;\n}): boolean {\n const code = String(event.errorCode ?? \"\").toLowerCase();\n const msg = event.error.toLowerCase();\n return (\n event.recoverable === true ||\n code === \"builder_gateway_error\" ||\n code === \"builder_gateway_timeout\" ||\n code === \"stale_run\" ||\n code === \"timeout\" ||\n code === \"timeout_error\" ||\n code === \"http_408\" ||\n code === \"http_429\" ||\n code === \"http_500\" ||\n code === \"http_502\" ||\n code === \"http_503\" ||\n code === \"http_504\" ||\n code === \"rate_limited\" ||\n code === \"too_many_concurrent_requests\" ||\n code === \"overloaded_error\" ||\n msg.includes(\"timeout\") ||\n msg.includes(\"gateway error\") ||\n msg.includes(\"gateway timeout\") ||\n msg.includes(\"inactivity timeout\") ||\n msg.includes(\"stream ended\") ||\n msg.includes(\"stream closed\") ||\n msg.includes(\"temporarily unavailable\") ||\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\") ||\n msg.includes(\"529\")\n );\n}\n\n/**\n * Reconstruct an assistant-ui message from raw agent run events.\n * Mirrors the client-side processEvent logic so the server can persist\n * the assistant's response even if the frontend is disconnected.\n */\nexport function buildAssistantMessage(\n events: RunEvent[],\n runId?: string,\n options: BuildAssistantMessageOptions = {},\n): {\n id: string;\n createdAt: Date;\n role: \"assistant\";\n content: ContentPart[];\n status:\n | { type: \"complete\"; reason: \"stop\" }\n | { type: \"incomplete\"; reason: \"error\" };\n metadata: Record<string, unknown>;\n} | null {\n const content: ContentPart[] = [];\n let toolCallCounter = 0;\n let runError: {\n message: string;\n errorCode?: string;\n details?: string;\n recoverable?: boolean;\n } | null = null;\n let endedAtInternalContinuationBoundary = false;\n\n const appendText = (text: string) => {\n const last = content[content.length - 1];\n if (last && last.type === \"text\") {\n last.text = (last.text ?? \"\") + text;\n } else {\n content.push({ type: \"text\", text });\n }\n };\n\n for (const { event } of events) {\n if (event.type === \"clear\") {\n content.length = 0;\n toolCallCounter = 0;\n continue;\n }\n\n if (event.type === \"text\") {\n appendText(event.text ?? \"\");\n continue;\n }\n\n if (event.type === \"tool_start\") {\n const toolCallId = `tc_${++toolCallCounter}`;\n const args = (event.input ?? {}) as Record<string, string>;\n content.push({\n type: \"tool-call\",\n toolCallId,\n toolName: event.tool ?? \"unknown\",\n argsText: JSON.stringify(args),\n args,\n });\n continue;\n }\n\n if (event.type === \"tool_done\") {\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === event.tool &&\n part.result === undefined\n ) {\n part.result = event.result ?? \"\";\n break;\n }\n }\n continue;\n }\n\n if (event.type === \"loop_limit\") {\n // Older servers emitted this as a user-visible terminal event. Treat it\n // as an internal continuation boundary when rebuilding persisted turns.\n if (options.suppressInternalContinuation) {\n endedAtInternalContinuationBoundary = true;\n }\n continue;\n }\n\n if (event.type === \"auto_continue\") {\n if (options.suppressInternalContinuation) {\n endedAtInternalContinuationBoundary = true;\n }\n continue;\n }\n\n if (event.type === \"error\") {\n if (\n options.suppressInternalContinuation &&\n isInternalContinuationError(event)\n ) {\n endedAtInternalContinuationBoundary = true;\n continue;\n }\n if (event.errorCode === \"run_timeout\" && event.recoverable) {\n continue;\n }\n runError = {\n message: event.error,\n ...(event.errorCode ? { errorCode: event.errorCode } : {}),\n ...(event.details ? { details: event.details } : {}),\n ...(event.recoverable ? { recoverable: event.recoverable } : {}),\n };\n appendText(`${content.length > 0 ? \"\\n\\n\" : \"\"}Error: ${event.error}`);\n continue;\n }\n\n // done, missing_api_key — terminal signals, not content\n }\n\n if (content.length === 0 || endedAtInternalContinuationBoundary) return null;\n\n const metadata: Record<string, unknown> = {};\n if (runId) metadata.runId = runId;\n if (runError) {\n metadata.custom = {\n runError: {\n ...runError,\n ...(runId ? { runId } : {}),\n },\n };\n }\n\n return {\n id: `server-${runId ?? Date.now()}`,\n createdAt: new Date(),\n role: \"assistant\",\n content,\n status: runError\n ? { type: \"incomplete\" as const, reason: \"error\" as const }\n : { type: \"complete\" as const, reason: \"stop\" as const },\n metadata,\n };\n}\n\nfunction getStoredMessage(entry: any): any {\n return entry?.message ?? entry;\n}\n\nfunction getMessageRunId(message: any): string | undefined {\n const meta = message?.metadata;\n const direct = meta?.runId;\n const custom = meta?.custom?.runId;\n const errorRun = meta?.custom?.runError?.runId ?? meta?.runError?.runId;\n if (typeof direct === \"string\") return direct;\n if (typeof custom === \"string\") return custom;\n if (typeof errorRun === \"string\") return errorRun;\n return undefined;\n}\n\nfunction messageContentIsEmpty(content: unknown): boolean {\n if (Array.isArray(content)) return content.length === 0;\n return content == null || content === \"\";\n}\n\nfunction messageText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .filter(\n (part: any) => part?.type === \"text\" && typeof part.text === \"string\",\n )\n .map((part: any) => part.text)\n .join(\"\");\n}\n\nfunction isTerminalAssistantStatus(status: unknown): boolean {\n const type = (status as { type?: unknown } | undefined)?.type;\n return type === \"complete\" || type === \"incomplete\";\n}\n\nfunction normalizeAttachmentIdentity(attachments: unknown): unknown {\n if (!Array.isArray(attachments) || attachments.length === 0) return undefined;\n return attachments.map((att: any) => ({\n type: att?.type,\n name: att?.name,\n contentType: att?.contentType,\n }));\n}\n\nfunction messageIdentityKeys(message: any): string[] {\n const keys: string[] = [];\n if (typeof message?.id === \"string\" && message.id) {\n keys.push(`id:${message.id}`);\n }\n const runId = getMessageRunId(message);\n if (runId) keys.push(`run:${runId}`);\n\n // Normalize attachments through `normalizeAttachmentIdentity` so an\n // explicit empty `[]` (assistant-ui's default for messages with no\n // attachments) and an omitted/undefined `attachments` field hash to the\n // same fingerprint. Without this, every user message ended up duplicated\n // in `chat_threads`: one copy from `saveThreadData` (runtime export\n // includes `attachments: []`) and one from `persistSubmittedUserMessage`\n // → `buildUserMessage` (omits the field entirely). The merge couldn't\n // dedupe them because their fingerprints differed by exactly one\n // `[]` vs `undefined`. (Repro on slides prod: every user turn produced\n // a `client_user → assistant → server_user` triple instead of a\n // `user → assistant` pair.)\n try {\n keys.push(\n `fingerprint:${JSON.stringify({\n role: message?.role,\n content: message?.content,\n attachments: normalizeAttachmentIdentity(message?.attachments),\n })}`,\n );\n } catch {\n // Best effort. id/runId usually exist for persisted assistant-ui rows.\n }\n if (message?.role === \"user\") {\n try {\n keys.push(\n `user-fingerprint:${JSON.stringify({\n role: message.role,\n content: message.content,\n attachments: normalizeAttachmentIdentity(message.attachments),\n })}`,\n );\n } catch {\n // Same best-effort behavior as the full fingerprint.\n }\n }\n return keys;\n}\n\nfunction messagesMatch(a: any, b: any): boolean {\n const bKeys = new Set(messageIdentityKeys(b));\n return messageIdentityKeys(a).some((key) => bKeys.has(key));\n}\n\nfunction chooseMergedMessageEntry(existingEntry: any, incomingEntry: any): any {\n const existing = getStoredMessage(existingEntry);\n const incoming = getStoredMessage(incomingEntry);\n if (\n existing?.role === \"assistant\" &&\n incoming?.role === \"assistant\" &&\n isTerminalAssistantStatus(existing?.status) &&\n !isTerminalAssistantStatus(incoming?.status)\n ) {\n return existingEntry;\n }\n return incomingEntry;\n}\n\n/**\n * Merge an incoming client-side full-thread save over the current SQL copy.\n *\n * The browser exports and PUTs the whole assistant-ui repository. If a server\n * completion save lands first, an older browser export can otherwise replace\n * `thread_data` wholesale and delete the assistant message the server just\n * reconstructed from run events. Preserve server-only messages while still\n * accepting client-only messages and metadata.\n */\nexport function mergeThreadDataForClientSave(\n existingRepo: any,\n incomingRepo: any,\n) {\n const merged =\n incomingRepo && typeof incomingRepo === \"object\" ? incomingRepo : {};\n if (\n existingRepo &&\n typeof existingRepo === \"object\" &&\n existingRepo.queuedMessages !== undefined &&\n merged.queuedMessages === undefined\n ) {\n merged.queuedMessages = existingRepo.queuedMessages;\n }\n\n const existingMessages = Array.isArray(existingRepo?.messages)\n ? existingRepo.messages\n : null;\n const incomingMessages = Array.isArray(merged.messages)\n ? merged.messages\n : null;\n if (!existingMessages || !incomingMessages) return merged;\n\n const incomingKeySets = incomingMessages.map(\n (entry: any) => new Set(messageIdentityKeys(getStoredMessage(entry))),\n );\n const usedIncoming = new Set<number>();\n const nextMessages: any[] = [];\n\n for (const existingEntry of existingMessages) {\n const existingKeys = messageIdentityKeys(getStoredMessage(existingEntry));\n const incomingIndex = incomingKeySets.findIndex(\n (keys, index) =>\n !usedIncoming.has(index) && existingKeys.some((key) => keys.has(key)),\n );\n\n if (incomingIndex === -1) {\n nextMessages.push(existingEntry);\n continue;\n }\n\n usedIncoming.add(incomingIndex);\n nextMessages.push(\n chooseMergedMessageEntry(existingEntry, incomingMessages[incomingIndex]),\n );\n }\n\n for (let index = 0; index < incomingMessages.length; index++) {\n if (!usedIncoming.has(index)) nextMessages.push(incomingMessages[index]);\n }\n\n merged.messages = nextMessages;\n return merged;\n}\n\nfunction escapeAttachmentAttribute(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n}\n\nfunction unwrapTextAttachmentEnvelope(text: string): string {\n const match = text.match(\n /^<attachment\\b[^>]*>\\n?([\\s\\S]*?)\\n?<\\/attachment>$/,\n );\n return match ? match[1] : text;\n}\n\nfunction truncateStoredAttachment(text: string): string {\n const unwrapped = unwrapTextAttachmentEnvelope(text);\n if (unwrapped.length <= MAX_STORED_ATTACHMENT_CHARS) return unwrapped;\n const omitted = unwrapped.length - MAX_STORED_ATTACHMENT_CHARS;\n return `${unwrapped.slice(0, MAX_STORED_ATTACHMENT_CHARS)}\\n\\n[Attachment truncated after ${MAX_STORED_ATTACHMENT_CHARS.toLocaleString()} characters; ${omitted.toLocaleString()} characters omitted from persisted chat history.]`;\n}\n\nfunction textAttachmentEnvelope(\n att: AgentChatAttachment,\n text: string,\n): string {\n const attrs = [\n `name=\"${escapeAttachmentAttribute(att.name || \"attachment\")}\"`,\n att.contentType\n ? `contentType=\"${escapeAttachmentAttribute(att.contentType)}\"`\n : null,\n att.type ? `type=\"${escapeAttachmentAttribute(att.type)}\"` : null,\n ].filter(Boolean);\n return `<attachment ${attrs.join(\" \")}>\\n${truncateStoredAttachment(text)}\\n</attachment>`;\n}\n\nfunction buildStoredAttachments(\n attachments: AgentChatAttachment[] | undefined,\n runId: string | undefined,\n): any[] {\n return (attachments ?? [])\n .map((att, index) => {\n const id = `server-${runId ?? Date.now()}-attachment-${index}`;\n if (att.type === \"image\" && att.data) {\n return {\n id,\n type: \"image\",\n name: att.name,\n contentType: att.contentType,\n status: { type: \"complete\" },\n content: [{ type: \"image\", image: att.data }],\n };\n }\n if (att.data) {\n return {\n id,\n type: \"file\",\n name: att.name,\n contentType: att.contentType,\n status: { type: \"complete\" },\n content: [\n {\n type: \"file\",\n data: att.data,\n mimeType: att.contentType,\n filename: att.name,\n },\n ],\n };\n }\n if (typeof att.text === \"string\" && att.text.length > 0) {\n return {\n id,\n type: \"file\",\n name: att.name,\n contentType: att.contentType,\n status: { type: \"complete\" },\n content: [\n { type: \"text\", text: textAttachmentEnvelope(att, att.text) },\n ],\n };\n }\n return null;\n })\n .filter(Boolean);\n}\n\nexport function buildUserMessage(opts: {\n text: string;\n attachments?: AgentChatAttachment[];\n runId?: string;\n createdAt?: Date;\n}): {\n id: string;\n createdAt: Date;\n role: \"user\";\n content: ContentPart[];\n attachments?: any[];\n metadata: Record<string, unknown>;\n} {\n const attachments = buildStoredAttachments(opts.attachments, opts.runId);\n return {\n id: `server-user-${opts.runId ?? Date.now()}`,\n createdAt: opts.createdAt ?? new Date(),\n role: \"user\",\n content: [{ type: \"text\", text: opts.text }],\n ...(attachments.length > 0 ? { attachments } : {}),\n metadata: {\n custom: {\n submittedRunId: opts.runId,\n },\n },\n };\n}\n\nexport function upsertUserMessage(repo: any, userMsg: UserMessage): any {\n const nextRepo = repo && typeof repo === \"object\" ? repo : {};\n if (!Array.isArray(nextRepo.messages)) nextRepo.messages = [];\n\n const lastIndex = nextRepo.messages.length - 1;\n const lastEntry = lastIndex >= 0 ? nextRepo.messages[lastIndex] : undefined;\n const lastMsg = getStoredMessage(lastEntry);\n if (lastMsg?.role === \"user\" && messagesMatch(lastMsg, userMsg)) {\n return nextRepo;\n }\n\n const isWrapped = Boolean(lastEntry && \"message\" in lastEntry);\n if (isWrapped) {\n const parentId =\n lastIndex >= 0 ? (getStoredMessage(lastEntry)?.id ?? null) : null;\n nextRepo.messages.push({ message: userMsg, parentId });\n } else {\n nextRepo.messages.push(userMsg);\n }\n return nextRepo;\n}\n\nfunction shouldReplaceLastAssistant(\n lastMessage: any,\n assistantMsg: AssistantMessage,\n): boolean {\n const lastContent = lastMessage?.content;\n if (messageContentIsEmpty(lastContent)) return true;\n\n const lastRunId = getMessageRunId(lastMessage);\n const nextRunId = getMessageRunId(assistantMsg);\n if (lastRunId && nextRunId && lastRunId === nextRunId) return true;\n if (lastRunId && nextRunId && lastRunId !== nextRunId) return false;\n\n const lastStatus = lastMessage?.status;\n if (lastStatus && !isTerminalAssistantStatus(lastStatus)) return true;\n\n try {\n if (JSON.stringify(lastContent) === JSON.stringify(assistantMsg.content)) {\n return true;\n }\n } catch {\n // Fall through to the text-prefix check.\n }\n\n const lastText = messageText(lastContent).trim();\n const nextText = messageText(assistantMsg.content).trim();\n if (isTerminalAssistantStatus(lastStatus)) return false;\n return Boolean(lastText && nextText && nextText.startsWith(lastText));\n}\n\n/**\n * Merge the server-reconstructed assistant message into persisted\n * assistant-ui thread data.\n *\n * The browser periodically saves thread data while a run is still streaming.\n * That can leave the last assistant message non-empty but partial/pending.\n * Completion must replace that same-run partial message instead of treating\n * any assistant content as proof that the frontend already saved the final\n * turn.\n */\nexport function upsertAssistantMessage(\n repo: any,\n assistantMsg: AssistantMessage,\n): any {\n const nextRepo = repo && typeof repo === \"object\" ? repo : {};\n if (!Array.isArray(nextRepo.messages)) nextRepo.messages = [];\n\n const lastIndex = nextRepo.messages.length - 1;\n const lastEntry = lastIndex >= 0 ? nextRepo.messages[lastIndex] : undefined;\n const lastMsg = getStoredMessage(lastEntry);\n const lastRole = lastMsg?.role;\n const isWrapped = Boolean(lastEntry && \"message\" in lastEntry);\n\n if (\n lastRole === \"assistant\" &&\n shouldReplaceLastAssistant(lastMsg, assistantMsg)\n ) {\n nextRepo.messages[lastIndex] = isWrapped\n ? { ...lastEntry, message: assistantMsg }\n : assistantMsg;\n return nextRepo;\n }\n\n if (isWrapped) {\n const parentId =\n nextRepo.messages.length > 0\n ? (getStoredMessage(nextRepo.messages[nextRepo.messages.length - 1])\n ?.id ?? null)\n : null;\n nextRepo.messages.push({ message: assistantMsg, parentId });\n } else {\n nextRepo.messages.push(assistantMsg);\n }\n return nextRepo;\n}\n\n/**\n * Extract title and preview from a thread runtime export.\n * Isomorphic — works on both server and client.\n */\nexport function extractThreadMeta(repo: any): {\n title: string;\n preview: string;\n} {\n const msgs = repo?.messages;\n if (!Array.isArray(msgs) || msgs.length === 0)\n return { title: \"\", preview: \"\" };\n\n let title = \"\";\n let preview = \"\";\n for (const entry of msgs) {\n // Support both wrapped ({ message: { role, content } }) and flat ({ role, content }) formats\n const msg = entry?.message ?? entry;\n if (msg.role !== \"user\") continue;\n const textParts = Array.isArray(msg.content)\n ? msg.content\n .filter((p: any) => p.type === \"text\")\n .map((p: any) => p.text)\n .join(\" \")\n : typeof msg.content === \"string\"\n ? msg.content\n : \"\";\n if (textParts.trim()) {\n if (!title) title = textParts.trim().slice(0, 80);\n preview = textParts.trim().slice(0, 120);\n }\n }\n return { title, preview };\n}\n"]}
@@ -10,15 +10,28 @@ export interface ShareButtonProps {
10
10
  * button next to an iframe use this to disable the iframe's pointer events
11
11
  * while the popover is open, so popover hover/clicks aren't swallowed. */
12
12
  onOpenChange?: (open: boolean) => void;
13
- /** Optional public/share URL shown as a copyable link in the popover. */
13
+ /** Optional public/share URL shown as a copyable link in the popover.
14
+ * This is treated as the primary "Copy link" target — same convention
15
+ * as Google Docs' Share dialog, which copies the editor URL. */
14
16
  shareUrl?: string;
15
- /** Optional label for the copyable link section. */
17
+ /** Optional label for the primary copyable link section. */
16
18
  shareUrlLabel?: string;
17
- /** Optional helper text for the copyable link section. */
19
+ /** Optional helper text for the primary copyable link section. */
18
20
  shareUrlDescription?: ReactNode;
19
- /** When true, the share URL is only copyable after visibility is public. */
21
+ /** Optional secondary copyable link (e.g. a presentation / read-only
22
+ * surface for the same resource). Anyone with at least viewer access
23
+ * can open it — access is enforced on the resource itself, not the
24
+ * URL shape, so we never gate this behind visibility. */
25
+ secondaryShareUrl?: string;
26
+ /** Optional label for the secondary copyable link. */
27
+ secondaryShareUrlLabel?: string;
28
+ /** Optional helper text for the secondary copyable link. */
29
+ secondaryShareUrlDescription?: ReactNode;
30
+ /** @deprecated No longer enforced — access is checked on the resource,
31
+ * not the URL shape, mirroring Google Slides. Kept for callsite
32
+ * compatibility; the prop is now a no-op. */
20
33
  shareUrlRequiresPublic?: boolean;
21
- /** Optional helper text shown when the share URL requires public visibility. */
34
+ /** @deprecated See `shareUrlRequiresPublic`. No longer rendered. */
22
35
  shareUrlUnavailableDescription?: ReactNode;
23
36
  /** Optional template-specific copy for the visibility picker. */
24
37
  visibilityCopy?: Partial<Record<Visibility, {
@@ -1 +1 @@
1
- {"version":3,"file":"ShareButton.d.ts","sourceRoot":"","sources":["../../../src/client/sharing/ShareButton.tsx"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAqBf,MAAM,WAAW,gBAAgB;IAC/B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;oDACgD;IAChD,OAAO,CAAC,EAAE,SAAS,GAAG,OAAO,CAAC;IAC9B;;+EAE2E;IAC3E,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC;IACvC,yEAAyE;IACzE,QAAQ,CAAC,EA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IACtD,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,4DAA4D;IAC5D,4BAA4B,CAAC,EAAE,SAAS,CAAC;IACzC;;kDAE8C;IAC9C,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC,oEAAoE;IACpE,8BAA8B,CAAC,EAAE,SAAS,CAAC;IAC3C,iEAAiE;IACjE,cAAc,CAAC,EAAE,OAAO,CACtB,MAAM,CAAC,UAAU,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAC7D,CAAC;IACF,2EAA2E;IAC3E,UAAU,CAAC,EAAE,SAAS,CAAC;CACxB;AAED,KAAK,UAAU,GAAG,SAAS,GAAG,KAAK,GAAG,QAAQ,CAAC;AAkF/C;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,2CAiIlD"}
@@ -336,14 +336,10 @@ function SharePanel(props) {
336
336
  ? s.principalId
337
337
  : displayName(s.principalId, orgMembers), org: s.principalType === "org" }), _jsx("span", { className: "flex-1 min-w-0 truncate", children: s.principalType === "org"
338
338
  ? s.principalId
339
- : displayName(s.principalId, orgMembers) }), canManage ? (_jsx(RoleSelect, { value: s.role, onChange: (r) => handleChangeRole(s, r), disabled: inFlight.has(keyOf(s)), plain: true })) : (_jsx("span", { className: "text-xs text-muted-foreground", children: cap(s.role) })), canManage ? (_jsx("button", { type: "button", "aria-label": "Remove", onClick: () => handleRemove(s), disabled: inFlight.has(keyOf(s)), className: BUTTON_GHOST_ICON, children: _jsx(IconTrash, { size: 14 }) })) : null] }, keyOf(s)))), !shares.length && !data?.ownerEmail ? (_jsx("li", { className: "px-1 py-1.5 text-sm text-muted-foreground", children: "No one has access yet." })) : null] }), _jsx("div", { className: "mb-2 text-sm font-semibold", children: "General access" }), _jsxs("div", { className: "mb-4 flex items-center gap-3", children: [_jsx("span", { "aria-hidden": true, className: "inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground", children: _jsx(meta.Icon, { size: 16, strokeWidth: 1.75 }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx(VisibilitySelect, { value: visibility, onChange: handleVisibility, disabled: !canManage, visibilityCopy: props.visibilityCopy }), _jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: meta.description })] })] }), props.accessNote ? (_jsx("div", { className: "mb-4 rounded-md border border-border bg-muted/35 p-3 text-xs text-muted-foreground", children: props.accessNote })) : null, props.shareUrl ? (_jsx(CopyLinkField, { value: props.shareUrl, label: props.shareUrlLabel, description: props.shareUrlDescription, unavailable: props.shareUrlRequiresPublic && visibility !== "public", unavailableDescription: props.shareUrlUnavailableDescription ??
340
- (canManage
341
- ? "Make general access public before copying this link."
342
- : "This link is not public. Ask an owner or admin to make it public."), unavailableActionLabel: canManage ? "Make public and copy" : "Not public", unavailableActionBusyLabel: "Making public...", onUnavailableAction: canManage ? () => onVisibilityChange("public") : undefined })) : null, _jsx("div", { className: "mt-2 flex justify-end", children: _jsx("button", { type: "button", onClick: handleDone, className: BUTTON_PRIMARY_SM, children: "Done" }) })] }));
339
+ : displayName(s.principalId, orgMembers) }), canManage ? (_jsx(RoleSelect, { value: s.role, onChange: (r) => handleChangeRole(s, r), disabled: inFlight.has(keyOf(s)), plain: true })) : (_jsx("span", { className: "text-xs text-muted-foreground", children: cap(s.role) })), canManage ? (_jsx("button", { type: "button", "aria-label": "Remove", onClick: () => handleRemove(s), disabled: inFlight.has(keyOf(s)), className: BUTTON_GHOST_ICON, children: _jsx(IconTrash, { size: 14 }) })) : null] }, keyOf(s)))), !shares.length && !data?.ownerEmail ? (_jsx("li", { className: "px-1 py-1.5 text-sm text-muted-foreground", children: "No one has access yet." })) : null] }), _jsx("div", { className: "mb-2 text-sm font-semibold", children: "General access" }), _jsxs("div", { className: "mb-4 flex items-center gap-3", children: [_jsx("span", { "aria-hidden": true, className: "inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground", children: _jsx(meta.Icon, { size: 16, strokeWidth: 1.75 }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx(VisibilitySelect, { value: visibility, onChange: handleVisibility, disabled: !canManage, visibilityCopy: props.visibilityCopy }), _jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: meta.description })] })] }), props.accessNote ? (_jsx("div", { className: "mb-4 rounded-md border border-border bg-muted/35 p-3 text-xs text-muted-foreground", children: props.accessNote })) : null, props.shareUrl ? (_jsx(CopyLinkField, { value: props.shareUrl, label: props.shareUrlLabel, description: props.shareUrlDescription })) : null, props.secondaryShareUrl ? (_jsx(CopyLinkField, { value: props.secondaryShareUrl, label: props.secondaryShareUrlLabel, description: props.secondaryShareUrlDescription })) : null, _jsx("div", { className: "mt-2 flex justify-end", children: _jsx("button", { type: "button", onClick: handleDone, className: BUTTON_PRIMARY_SM, children: "Done" }) })] }));
343
340
  }
344
- function CopyLinkField({ value, label = "Share link", description, unavailable = false, unavailableDescription, unavailableActionLabel = "Unavailable", unavailableActionBusyLabel = "Working...", onUnavailableAction, }) {
341
+ function CopyLinkField({ value, label = "Share link", description, }) {
345
342
  const [copied, setCopied] = useState(false);
346
- const [busy, setBusy] = useState(false);
347
343
  const resetRef = useRef(undefined);
348
344
  useEffect(() => {
349
345
  return () => {
@@ -351,52 +347,19 @@ function CopyLinkField({ value, label = "Share link", description, unavailable =
351
347
  clearTimeout(resetRef.current);
352
348
  };
353
349
  }, []);
354
- const markCopied = () => {
355
- setCopied(true);
356
- if (resetRef.current)
357
- clearTimeout(resetRef.current);
358
- resetRef.current = setTimeout(() => setCopied(false), 1400);
359
- };
360
- const copyValue = async () => {
361
- await navigator.clipboard.writeText(value);
362
- markCopied();
363
- };
364
350
  const handleCopy = async () => {
365
351
  try {
366
- await copyValue();
367
- }
368
- catch {
369
- setCopied(false);
370
- }
371
- };
372
- const handleUnavailableAction = async () => {
373
- if (!onUnavailableAction)
374
- return;
375
- setBusy(true);
376
- try {
377
- await onUnavailableAction();
378
- await copyValue();
352
+ await navigator.clipboard.writeText(value);
353
+ setCopied(true);
354
+ if (resetRef.current)
355
+ clearTimeout(resetRef.current);
356
+ resetRef.current = setTimeout(() => setCopied(false), 1400);
379
357
  }
380
358
  catch {
381
359
  setCopied(false);
382
360
  }
383
- finally {
384
- setBusy(false);
385
- }
386
361
  };
387
- const inputValue = unavailable
388
- ? "Link available after general access is Public"
389
- : value;
390
- return (_jsxs("div", { className: "mb-4", children: [_jsx("div", { className: "mb-2 text-sm font-semibold", children: label }), description ? (_jsx("div", { className: "mb-2 text-xs text-muted-foreground", children: description })) : null, unavailable && unavailableDescription ? (_jsx("div", { className: "mb-2 rounded-md border border-border bg-muted/35 px-3 py-2 text-xs text-muted-foreground", children: unavailableDescription })) : null, _jsxs("div", { className: "flex min-w-0 items-center gap-2", children: [_jsx("input", { readOnly: true, disabled: unavailable, value: inputValue, "aria-disabled": unavailable, className: cn("h-9 min-w-0 flex-1 rounded-md border border-input px-3 text-sm text-muted-foreground outline-none", unavailable ? "cursor-not-allowed bg-muted/40" : "bg-background"), onFocus: (event) => {
391
- if (!unavailable)
392
- event.currentTarget.select();
393
- } }), _jsxs("button", { type: "button", onClick: unavailable ? handleUnavailableAction : handleCopy, disabled: unavailable && !onUnavailableAction, className: "inline-flex h-9 shrink-0 items-center gap-2 rounded-md border border-input bg-background px-3 text-sm font-medium text-foreground hover:bg-accent", children: [copied ? _jsx(IconCheck, { size: 15 }) : _jsx(IconCopy, { size: 15 }), busy
394
- ? unavailableActionBusyLabel
395
- : unavailable
396
- ? unavailableActionLabel
397
- : copied
398
- ? "Copied"
399
- : "Copy"] })] })] }));
362
+ return (_jsxs("div", { className: "mb-4", children: [_jsx("div", { className: "mb-2 text-sm font-semibold", children: label }), description ? (_jsx("div", { className: "mb-2 text-xs text-muted-foreground", children: description })) : null, _jsxs("div", { className: "flex min-w-0 items-center gap-2", children: [_jsx("input", { readOnly: true, value: value, className: "h-9 min-w-0 flex-1 rounded-md border border-input bg-background px-3 text-sm text-muted-foreground outline-none", onFocus: (event) => event.currentTarget.select() }), _jsxs("button", { type: "button", onClick: handleCopy, className: "inline-flex h-9 shrink-0 items-center gap-2 rounded-md border border-input bg-background px-3 text-sm font-medium text-foreground hover:bg-accent", children: [copied ? _jsx(IconCheck, { size: 15 }) : _jsx(IconCopy, { size: 15 }), copied ? "Copied" : "Copy"] })] })] }));
400
363
  }
401
364
  // ---------------------------------------------------------------------------
402
365
  // Radix Select wrappers styled like shadcn Select (no native <select> anywhere)