@athenaintel/react 0.25.0 → 0.26.0
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.
- package/README.md +6 -0
- package/dist/assets/AssetPanel.cjs +1 -1
- package/dist/assets/AssetPanel.cjs.map +1 -1
- package/dist/assets/AssetPanel.js +1 -1
- package/dist/assets/AssetPanel.js.map +1 -1
- package/dist/assets/AthenaAssetEmbed.cjs +1 -1
- package/dist/assets/AthenaAssetEmbed.cjs.map +1 -1
- package/dist/assets/AthenaAssetEmbed.js +1 -1
- package/dist/assets/AthenaAssetEmbed.js.map +1 -1
- package/dist/chat-ui/composer/run-input-rules-on-enter.cjs +14 -0
- package/dist/chat-ui/composer/run-input-rules-on-enter.cjs.map +1 -0
- package/dist/chat-ui/composer/run-input-rules-on-enter.d.ts +10 -0
- package/dist/chat-ui/composer/run-input-rules-on-enter.js +14 -0
- package/dist/chat-ui/composer/run-input-rules-on-enter.js.map +1 -0
- package/dist/chat-ui/composer/tiptap-composer.cjs +7 -4
- package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
- package/dist/chat-ui/composer/tiptap-composer.js +7 -4
- package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
- package/dist/chat-ui/markdown-storage.cjs +16 -0
- package/dist/chat-ui/markdown-storage.cjs.map +1 -0
- package/dist/chat-ui/markdown-storage.d.ts +21 -0
- package/dist/chat-ui/markdown-storage.js +16 -0
- package/dist/chat-ui/markdown-storage.js.map +1 -0
- package/dist/chat-ui/rich-text/chat-node-views.cjs.map +1 -1
- package/dist/chat-ui/rich-text/chat-node-views.js.map +1 -1
- package/dist/chat-ui/rich-text/chat-text-schema.cjs +15 -10
- package/dist/chat-ui/rich-text/chat-text-schema.cjs.map +1 -1
- package/dist/chat-ui/rich-text/chat-text-schema.js +11 -6
- package/dist/chat-ui/rich-text/chat-text-schema.js.map +1 -1
- package/dist/packages/agent-runtime/src/conversation-list.cjs +3 -0
- package/dist/packages/agent-runtime/src/conversation-list.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/conversation-list.js +3 -0
- package/dist/packages/agent-runtime/src/conversation-list.js.map +1 -1
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs +2 -2
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.js +2 -2
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
- package/dist/packages/agent-runtime/src/use-conversation-list.cjs +1 -0
- package/dist/packages/agent-runtime/src/use-conversation-list.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/use-conversation-list.js +1 -0
- package/dist/packages/agent-runtime/src/use-conversation-list.js.map +1 -1
- package/dist/packages/react/package.json.cjs +1 -1
- package/dist/packages/react/package.json.js +1 -1
- package/dist/runtime/statewire-run-config.cjs +1 -1
- package/dist/runtime/statewire-run-config.cjs.map +1 -1
- package/dist/runtime/statewire-run-config.d.ts +1 -1
- package/dist/runtime/statewire-run-config.js +1 -1
- package/dist/runtime/statewire-run-config.js.map +1 -1
- package/dist/threads/use-rest-conversation-history.d.ts +1 -0
- package/dist/threads/use-statewire-conversation-history.d.ts +2 -0
- package/dist/tools/append-document-tool-ui.cjs +5 -0
- package/dist/tools/append-document-tool-ui.cjs.map +1 -1
- package/dist/tools/append-document-tool-ui.js +5 -0
- package/dist/tools/append-document-tool-ui.js.map +1 -1
- package/package.json +13 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat-node-views.cjs","sources":["../../../src/chat-ui/rich-text/chat-node-views.tsx"],"sourcesContent":["import type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\nimport {\n NodeViewContent,\n NodeViewWrapper,\n type NodeViewProps,\n} from \"@tiptap/react\";\nimport { CheckIcon, CopyIcon, XIcon } from \"lucide-react\";\nimport { type ReactNode, useCallback, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport { MentionLink } from \"../mentions/mention-chip\";\nimport {\n makeMentionUrl,\n type MentionNodeAttrs,\n} from \"../mentions/mention-extension\";\n\nexport function ChatMention({\n node,\n interactive = true,\n}: {\n node: ProseMirrorNode;\n interactive?: boolean;\n}) {\n return (\n <span\n className=\"mention-chip\"\n data-mention=\"\"\n data-type={node.attrs.type}\n data-name={node.attrs.name}\n data-id={node.attrs.id}\n data-asset-type={node.attrs.assetType}\n data-display-as-preview={String(node.attrs.displayAsPreview === true)}\n >\n <MentionLink\n href={makeMentionUrl(node.attrs as MentionNodeAttrs)}\n interactive={interactive}\n >\n {node.attrs.name}\n </MentionLink>\n </span>\n );\n}\n\nexport function ChatMentionNodeView({ node, editor }: NodeViewProps) {\n return (\n <NodeViewWrapper as=\"span\">\n <ChatMention node={node} interactive={!editor.isEditable} />\n </NodeViewWrapper>\n );\n}\n\nconst COPIED_RESET_MS = 1500;\n\n/**\n * Copies the block's source. Reads `node.textContent` at click time so a\n * still-streaming block copies what is on screen, not a stale snapshot.\n */\nfunction CodeBlockCopyButton({ node }: { node: ProseMirrorNode }) {\n const [status, setStatus] = useState<\"idle\" | \"copied\" | \"failed\">(\"idle\");\n const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(\n () => () => {\n if (resetTimer.current) clearTimeout(resetTimer.current);\n },\n [],\n );\n const flash = useCallback((next: \"copied\" | \"failed\") => {\n setStatus(next);\n if (resetTimer.current) clearTimeout(resetTimer.current);\n resetTimer.current = setTimeout(() => setStatus(\"idle\"), COPIED_RESET_MS);\n }, []);\n const onCopy = useCallback(() => {\n // writeText rejects when clipboard-write is denied (permissions, an\n // embedding iframe without the allow attribute); surface that instead of\n // leaving an unhandled rejection and a button that looks like it worked.\n if (typeof navigator === \"undefined\" || !navigator.clipboard) {\n flash(\"failed\");\n return;\n }\n navigator.clipboard.writeText(node.textContent).then(\n () => flash(\"copied\"),\n () => flash(\"failed\"),\n );\n }, [node, flash]);\n const label =\n status === \"copied\" ? \"Copied\" : status === \"failed\" ? \"Copy failed\" : \"Copy code\";\n return (\n <button\n type=\"button\"\n title={label}\n aria-label={label}\n onClick={onCopy}\n className={cn(\n \"inline-flex size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground\",\n \"opacity-0 transition-opacity group-hover/code-block:opacity-100 focus-visible:opacity-100\",\n status !== \"idle\" && \"opacity-100\",\n status === \"failed\" && \"text-destructive\",\n )}\n >\n {status === \"copied\" ? (\n <CheckIcon className=\"size-3.5\" />\n ) : status === \"failed\" ? (\n <XIcon className=\"size-3.5\" />\n ) : (\n <CopyIcon className=\"size-3.5\" />\n )}\n </button>\n );\n}\n\n/** The frame both code renderings share: language label, an optional corner action, the `<pre>`. */\nfunction CodeBlockFrame({\n language,\n action,\n children,\n ...attributes\n}: {\n language: string | null | undefined;\n action?: ReactNode;\n children: ReactNode;\n \"data-chat-open-fence\"?: string;\n}) {\n return (\n <div\n className=\"not-prose group/code-block relative my-2 overflow-hidden rounded-lg border border-border bg-muted/30\"\n {...attributes}\n >\n {language && (\n <div className=\"border-b border-border bg-muted/50 px-3 py-1 text-[10px] font-medium text-muted-foreground\">\n {language}\n </div>\n )}\n {action && (\n <div className=\"absolute top-1 right-1\" contentEditable={false}>\n {action}\n </div>\n )}\n <pre className=\"overflow-x-auto p-3 pr-9 font-mono text-xs leading-relaxed text-foreground\">\n {children}\n </pre>\n </div>\n );\n}\n\nexport function ChatCodeBlock({\n node,\n children,\n}: {\n node: ProseMirrorNode;\n children: ReactNode;\n}) {\n return (\n <CodeBlockFrame\n language={node.attrs.language}\n action={<CodeBlockCopyButton node={node} />}\n >\n {children}\n </CodeBlockFrame>\n );\n}\n\n/**\n * A fenced block whose closing fence has not arrived: the same frame with the\n * code as plain text and no copy action (there is no settled source to copy\n * yet). Anything that decorates code — highlighting, a language pick — belongs\n * after the fence closes, when the block parses into a `codeBlock` node.\n */\nexport function StreamingCodeBlock({\n language,\n code,\n caret,\n}: {\n language: string;\n code: string;\n caret?: ReactNode;\n}) {\n return (\n <CodeBlockFrame language={language || null} data-chat-open-fence=\"\">\n <code>\n {code}\n {caret}\n </code>\n </CodeBlockFrame>\n );\n}\n\nexport function ChatCodeBlockNodeView({ node }: NodeViewProps) {\n return (\n <NodeViewWrapper>\n <ChatCodeBlock node={node}>\n <NodeViewContent as=\"code\" />\n </ChatCodeBlock>\n </NodeViewWrapper>\n );\n}\n"],"names":["jsx","MentionLink","makeMentionUrl","NodeViewWrapper","useState","useRef","useEffect","useCallback","cn","CheckIcon","XIcon","CopyIcon","jsxs","NodeViewContent"],"mappings":";;;;;;;;;AAeO,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA,cAAc;AAChB,GAGG;AACD,SACEA,2BAAAA;AAAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAU;AAAA,MACV,gBAAa;AAAA,MACb,aAAW,KAAK,MAAM;AAAA,MACtB,aAAW,KAAK,MAAM;AAAA,MACtB,WAAS,KAAK,MAAM;AAAA,MACpB,mBAAiB,KAAK,MAAM;AAAA,MAC5B,2BAAyB,OAAO,KAAK,MAAM,qBAAqB,IAAI;AAAA,MAEpE,UAAAA,2BAAAA;AAAAA,QAACC,YAAAA;AAAAA,QAAA;AAAA,UACC,MAAMC,iBAAAA,eAAe,KAAK,KAAyB;AAAA,UACnD;AAAA,UAEC,eAAK,MAAM;AAAA,QAAA;AAAA,MAAA;AAAA,IACd;AAAA,EAAA;AAGN;AAEO,SAAS,oBAAoB,EAAE,MAAM,UAAyB;AACnE,SACEF,2BAAAA,IAACG,MAAAA,iBAAA,EAAgB,IAAG,QAClB,UAAAH,2BAAAA,IAAC,aAAA,EAAY,MAAY,aAAa,CAAC,OAAO,WAAA,CAAY,EAAA,CAC5D;AAEJ;AAEA,MAAM,kBAAkB;AAMxB,SAAS,oBAAoB,EAAE,QAAmC;AAChE,QAAM,CAAC,QAAQ,SAAS,IAAII,QAAAA,SAAuC,MAAM;AACzE,QAAM,aAAaC,QAAAA,OAA6C,IAAI;AACpEC,UAAAA;AAA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AEH,UAAA;AAAA,QAAA,YACCZ,2BAAAA,IAAC,OAAA,EAAI,WAAU,8FACZ,UAAA,UACH;AAAA,QAED,UACCA,2BAAAA,IAAC,OAAA,EAAI,WAAU,0BAAyB,iBAAiB,OACtD,UAAA,QACH;AAAA,QAEFA,2BAAAA,IAAC,OAAA,EAAI,WAAU,8EACZ,SAAA,CACH;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA;AAGN;AAEO,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AACF,GAGG;AACD,SACEA,2BAAAA;AAAAA,IAAC;AAAA,IAAA;AAAA,MACC,UAAU,KAAK,MAAM;AAAA,MACrB,QAAQA,2BAAAA,IAAC,qBAAA,EAAoB,KAAA,CAAY;AAAA,MAExC;AAAA,IAAA;AAAA,EAAA;AAGP;AAQO,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,SACEA,2BAAAA,IAAC,kBAAe,UAAU,YAAY,MAAM,wBAAqB,IAC/D,0CAAC,QAAA,EACE,UAAA;AAAA,IAAA;AAAA,IACA;AAAA,EAAA,EAAA,CACH,EAAA,CACF;AAEJ;AAEO,SAAS,sBAAsB,EAAE,QAAuB;AAC7D,SACEA,2BAAAA,IAACG,MAAAA,iBAAA,EACC,UAAAH,2BAAAA,IAAC,eAAA,EAAc,MACb,yCAACa,MAAAA,iBAAA,
|
|
1
|
+
{"version":3,"file":"chat-node-views.cjs","sources":["../../../src/chat-ui/rich-text/chat-node-views.tsx"],"sourcesContent":["import type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\nimport {\n NodeViewContent,\n NodeViewWrapper,\n type NodeViewProps,\n} from \"@tiptap/react\";\nimport { CheckIcon, CopyIcon, XIcon } from \"lucide-react\";\nimport { type ReactNode, useCallback, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport { MentionLink } from \"../mentions/mention-chip\";\nimport {\n makeMentionUrl,\n type MentionNodeAttrs,\n} from \"../mentions/mention-extension\";\n\nexport function ChatMention({\n node,\n interactive = true,\n}: {\n node: ProseMirrorNode;\n interactive?: boolean;\n}) {\n return (\n <span\n className=\"mention-chip\"\n data-mention=\"\"\n data-type={node.attrs.type}\n data-name={node.attrs.name}\n data-id={node.attrs.id}\n data-asset-type={node.attrs.assetType}\n data-display-as-preview={String(node.attrs.displayAsPreview === true)}\n >\n <MentionLink\n href={makeMentionUrl(node.attrs as MentionNodeAttrs)}\n interactive={interactive}\n >\n {node.attrs.name}\n </MentionLink>\n </span>\n );\n}\n\nexport function ChatMentionNodeView({ node, editor }: NodeViewProps) {\n return (\n <NodeViewWrapper as=\"span\">\n <ChatMention node={node} interactive={!editor.isEditable} />\n </NodeViewWrapper>\n );\n}\n\nconst COPIED_RESET_MS = 1500;\n\n/**\n * Copies the block's source. Reads `node.textContent` at click time so a\n * still-streaming block copies what is on screen, not a stale snapshot.\n */\nfunction CodeBlockCopyButton({ node }: { node: ProseMirrorNode }) {\n const [status, setStatus] = useState<\"idle\" | \"copied\" | \"failed\">(\"idle\");\n const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(\n () => () => {\n if (resetTimer.current) clearTimeout(resetTimer.current);\n },\n [],\n );\n const flash = useCallback((next: \"copied\" | \"failed\") => {\n setStatus(next);\n if (resetTimer.current) clearTimeout(resetTimer.current);\n resetTimer.current = setTimeout(() => setStatus(\"idle\"), COPIED_RESET_MS);\n }, []);\n const onCopy = useCallback(() => {\n // writeText rejects when clipboard-write is denied (permissions, an\n // embedding iframe without the allow attribute); surface that instead of\n // leaving an unhandled rejection and a button that looks like it worked.\n if (typeof navigator === \"undefined\" || !navigator.clipboard) {\n flash(\"failed\");\n return;\n }\n navigator.clipboard.writeText(node.textContent).then(\n () => flash(\"copied\"),\n () => flash(\"failed\"),\n );\n }, [node, flash]);\n const label =\n status === \"copied\" ? \"Copied\" : status === \"failed\" ? \"Copy failed\" : \"Copy code\";\n return (\n <button\n type=\"button\"\n title={label}\n aria-label={label}\n onClick={onCopy}\n className={cn(\n \"inline-flex size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground\",\n \"opacity-0 transition-opacity group-hover/code-block:opacity-100 focus-visible:opacity-100\",\n status !== \"idle\" && \"opacity-100\",\n status === \"failed\" && \"text-destructive\",\n )}\n >\n {status === \"copied\" ? (\n <CheckIcon className=\"size-3.5\" />\n ) : status === \"failed\" ? (\n <XIcon className=\"size-3.5\" />\n ) : (\n <CopyIcon className=\"size-3.5\" />\n )}\n </button>\n );\n}\n\n/** The frame both code renderings share: language label, an optional corner action, the `<pre>`. */\nfunction CodeBlockFrame({\n language,\n action,\n children,\n ...attributes\n}: {\n language: string | null | undefined;\n action?: ReactNode;\n children: ReactNode;\n \"data-chat-open-fence\"?: string;\n}) {\n return (\n <div\n className=\"not-prose group/code-block relative my-2 overflow-hidden rounded-lg border border-border bg-muted/30\"\n {...attributes}\n >\n {language && (\n <div className=\"border-b border-border bg-muted/50 px-3 py-1 text-[10px] font-medium text-muted-foreground\">\n {language}\n </div>\n )}\n {action && (\n <div className=\"absolute top-1 right-1\" contentEditable={false}>\n {action}\n </div>\n )}\n <pre className=\"overflow-x-auto p-3 pr-9 font-mono text-xs leading-relaxed text-foreground\">\n {children}\n </pre>\n </div>\n );\n}\n\nexport function ChatCodeBlock({\n node,\n children,\n}: {\n node: ProseMirrorNode;\n children: ReactNode;\n}) {\n return (\n <CodeBlockFrame\n language={node.attrs.language}\n action={<CodeBlockCopyButton node={node} />}\n >\n {children}\n </CodeBlockFrame>\n );\n}\n\n/**\n * A fenced block whose closing fence has not arrived: the same frame with the\n * code as plain text and no copy action (there is no settled source to copy\n * yet). Anything that decorates code — highlighting, a language pick — belongs\n * after the fence closes, when the block parses into a `codeBlock` node.\n */\nexport function StreamingCodeBlock({\n language,\n code,\n caret,\n}: {\n language: string;\n code: string;\n caret?: ReactNode;\n}) {\n return (\n <CodeBlockFrame language={language || null} data-chat-open-fence=\"\">\n <code>\n {code}\n {caret}\n </code>\n </CodeBlockFrame>\n );\n}\n\nexport function ChatCodeBlockNodeView({ node }: NodeViewProps) {\n return (\n <NodeViewWrapper>\n <ChatCodeBlock node={node}>\n <NodeViewContent<\"code\"> as=\"code\" />\n </ChatCodeBlock>\n </NodeViewWrapper>\n );\n}\n"],"names":["jsx","MentionLink","makeMentionUrl","NodeViewWrapper","useState","useRef","useEffect","useCallback","cn","CheckIcon","XIcon","CopyIcon","jsxs","NodeViewContent"],"mappings":";;;;;;;;;AAeO,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA,cAAc;AAChB,GAGG;AACD,SACEA,2BAAAA;AAAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAU;AAAA,MACV,gBAAa;AAAA,MACb,aAAW,KAAK,MAAM;AAAA,MACtB,aAAW,KAAK,MAAM;AAAA,MACtB,WAAS,KAAK,MAAM;AAAA,MACpB,mBAAiB,KAAK,MAAM;AAAA,MAC5B,2BAAyB,OAAO,KAAK,MAAM,qBAAqB,IAAI;AAAA,MAEpE,UAAAA,2BAAAA;AAAAA,QAACC,YAAAA;AAAAA,QAAA;AAAA,UACC,MAAMC,iBAAAA,eAAe,KAAK,KAAyB;AAAA,UACnD;AAAA,UAEC,eAAK,MAAM;AAAA,QAAA;AAAA,MAAA;AAAA,IACd;AAAA,EAAA;AAGN;AAEO,SAAS,oBAAoB,EAAE,MAAM,UAAyB;AACnE,SACEF,2BAAAA,IAACG,MAAAA,iBAAA,EAAgB,IAAG,QAClB,UAAAH,2BAAAA,IAAC,aAAA,EAAY,MAAY,aAAa,CAAC,OAAO,WAAA,CAAY,EAAA,CAC5D;AAEJ;AAEA,MAAM,kBAAkB;AAMxB,SAAS,oBAAoB,EAAE,QAAmC;AAChE,QAAM,CAAC,QAAQ,SAAS,IAAII,QAAAA,SAAuC,MAAM;AACzE,QAAM,aAAaC,QAAAA,OAA6C,IAAI;AACpEC,UAAAA;AAAAA,IACE,MAAM,MAAM;AACV,UAAI,WAAW,QAAS,cAAa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A,EAAI,WAAU,8FACZ,UAAA,UACH;AAAA,QAED,UACCA,2BAAAA,IAAC,OAAA,EAAI,WAAU,0BAAyB,iBAAiB,OACtD,UAAA,QACH;AAAA,QAEFA,2BAAAA,IAAC,OAAA,EAAI,WAAU,8EACZ,SAAA,CACH;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA;AAGN;AAEO,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AACF,GAGG;AACD,SACEA,2BAAAA;AAAAA,IAAC;AAAA,IAAA;AAAA,MACC,UAAU,KAAK,MAAM;AAAA,MACrB,QAAQA,2BAAAA,IAAC,qBAAA,EAAoB,KAAA,CAAY;AAAA,MAExC;AAAA,IAAA;AAAA,EAAA;AAGP;AAQO,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,SACEA,2BAAAA,IAAC,kBAAe,UAAU,YAAY,MAAM,wBAAqB,IAC/D,0CAAC,QAAA,EACE,UAAA;AAAA,IAAA;AAAA,IACA;AAAA,EAAA,EAAA,CACH,EAAA,CACF;AAEJ;AAEO,SAAS,sBAAsB,EAAE,QAAuB;AAC7D,SACEA,2BAAAA,IAACG,MAAAA,iBAAA,EACC,UAAAH,2BAAAA,IAAC,eAAA,EAAc,MACb,yCAACa,MAAAA,iBAAA,EAAwB,IAAG,OAAA,CAAO,EAAA,CACrC,GACF;AAEJ;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat-node-views.js","sources":["../../../src/chat-ui/rich-text/chat-node-views.tsx"],"sourcesContent":["import type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\nimport {\n NodeViewContent,\n NodeViewWrapper,\n type NodeViewProps,\n} from \"@tiptap/react\";\nimport { CheckIcon, CopyIcon, XIcon } from \"lucide-react\";\nimport { type ReactNode, useCallback, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport { MentionLink } from \"../mentions/mention-chip\";\nimport {\n makeMentionUrl,\n type MentionNodeAttrs,\n} from \"../mentions/mention-extension\";\n\nexport function ChatMention({\n node,\n interactive = true,\n}: {\n node: ProseMirrorNode;\n interactive?: boolean;\n}) {\n return (\n <span\n className=\"mention-chip\"\n data-mention=\"\"\n data-type={node.attrs.type}\n data-name={node.attrs.name}\n data-id={node.attrs.id}\n data-asset-type={node.attrs.assetType}\n data-display-as-preview={String(node.attrs.displayAsPreview === true)}\n >\n <MentionLink\n href={makeMentionUrl(node.attrs as MentionNodeAttrs)}\n interactive={interactive}\n >\n {node.attrs.name}\n </MentionLink>\n </span>\n );\n}\n\nexport function ChatMentionNodeView({ node, editor }: NodeViewProps) {\n return (\n <NodeViewWrapper as=\"span\">\n <ChatMention node={node} interactive={!editor.isEditable} />\n </NodeViewWrapper>\n );\n}\n\nconst COPIED_RESET_MS = 1500;\n\n/**\n * Copies the block's source. Reads `node.textContent` at click time so a\n * still-streaming block copies what is on screen, not a stale snapshot.\n */\nfunction CodeBlockCopyButton({ node }: { node: ProseMirrorNode }) {\n const [status, setStatus] = useState<\"idle\" | \"copied\" | \"failed\">(\"idle\");\n const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(\n () => () => {\n if (resetTimer.current) clearTimeout(resetTimer.current);\n },\n [],\n );\n const flash = useCallback((next: \"copied\" | \"failed\") => {\n setStatus(next);\n if (resetTimer.current) clearTimeout(resetTimer.current);\n resetTimer.current = setTimeout(() => setStatus(\"idle\"), COPIED_RESET_MS);\n }, []);\n const onCopy = useCallback(() => {\n // writeText rejects when clipboard-write is denied (permissions, an\n // embedding iframe without the allow attribute); surface that instead of\n // leaving an unhandled rejection and a button that looks like it worked.\n if (typeof navigator === \"undefined\" || !navigator.clipboard) {\n flash(\"failed\");\n return;\n }\n navigator.clipboard.writeText(node.textContent).then(\n () => flash(\"copied\"),\n () => flash(\"failed\"),\n );\n }, [node, flash]);\n const label =\n status === \"copied\" ? \"Copied\" : status === \"failed\" ? \"Copy failed\" : \"Copy code\";\n return (\n <button\n type=\"button\"\n title={label}\n aria-label={label}\n onClick={onCopy}\n className={cn(\n \"inline-flex size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground\",\n \"opacity-0 transition-opacity group-hover/code-block:opacity-100 focus-visible:opacity-100\",\n status !== \"idle\" && \"opacity-100\",\n status === \"failed\" && \"text-destructive\",\n )}\n >\n {status === \"copied\" ? (\n <CheckIcon className=\"size-3.5\" />\n ) : status === \"failed\" ? (\n <XIcon className=\"size-3.5\" />\n ) : (\n <CopyIcon className=\"size-3.5\" />\n )}\n </button>\n );\n}\n\n/** The frame both code renderings share: language label, an optional corner action, the `<pre>`. */\nfunction CodeBlockFrame({\n language,\n action,\n children,\n ...attributes\n}: {\n language: string | null | undefined;\n action?: ReactNode;\n children: ReactNode;\n \"data-chat-open-fence\"?: string;\n}) {\n return (\n <div\n className=\"not-prose group/code-block relative my-2 overflow-hidden rounded-lg border border-border bg-muted/30\"\n {...attributes}\n >\n {language && (\n <div className=\"border-b border-border bg-muted/50 px-3 py-1 text-[10px] font-medium text-muted-foreground\">\n {language}\n </div>\n )}\n {action && (\n <div className=\"absolute top-1 right-1\" contentEditable={false}>\n {action}\n </div>\n )}\n <pre className=\"overflow-x-auto p-3 pr-9 font-mono text-xs leading-relaxed text-foreground\">\n {children}\n </pre>\n </div>\n );\n}\n\nexport function ChatCodeBlock({\n node,\n children,\n}: {\n node: ProseMirrorNode;\n children: ReactNode;\n}) {\n return (\n <CodeBlockFrame\n language={node.attrs.language}\n action={<CodeBlockCopyButton node={node} />}\n >\n {children}\n </CodeBlockFrame>\n );\n}\n\n/**\n * A fenced block whose closing fence has not arrived: the same frame with the\n * code as plain text and no copy action (there is no settled source to copy\n * yet). Anything that decorates code — highlighting, a language pick — belongs\n * after the fence closes, when the block parses into a `codeBlock` node.\n */\nexport function StreamingCodeBlock({\n language,\n code,\n caret,\n}: {\n language: string;\n code: string;\n caret?: ReactNode;\n}) {\n return (\n <CodeBlockFrame language={language || null} data-chat-open-fence=\"\">\n <code>\n {code}\n {caret}\n </code>\n </CodeBlockFrame>\n );\n}\n\nexport function ChatCodeBlockNodeView({ node }: NodeViewProps) {\n return (\n <NodeViewWrapper>\n <ChatCodeBlock node={node}>\n <NodeViewContent as=\"code\" />\n </ChatCodeBlock>\n </NodeViewWrapper>\n );\n}\n"],"names":[],"mappings":";;;;;;;AAeO,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA,cAAc;AAChB,GAGG;AACD,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAU;AAAA,MACV,gBAAa;AAAA,MACb,aAAW,KAAK,MAAM;AAAA,MACtB,aAAW,KAAK,MAAM;AAAA,MACtB,WAAS,KAAK,MAAM;AAAA,MACpB,mBAAiB,KAAK,MAAM;AAAA,MAC5B,2BAAyB,OAAO,KAAK,MAAM,qBAAqB,IAAI;AAAA,MAEpE,UAAA;AAAA,QAAC;AAAA,QAAA;AAAA,UACC,MAAM,eAAe,KAAK,KAAyB;AAAA,UACnD;AAAA,UAEC,eAAK,MAAM;AAAA,QAAA;AAAA,MAAA;AAAA,IACd;AAAA,EAAA;AAGN;AAEO,SAAS,oBAAoB,EAAE,MAAM,UAAyB;AACnE,SACE,oBAAC,iBAAA,EAAgB,IAAG,QAClB,UAAA,oBAAC,aAAA,EAAY,MAAY,aAAa,CAAC,OAAO,WAAA,CAAY,EAAA,CAC5D;AAEJ;AAEA,MAAM,kBAAkB;AAMxB,SAAS,oBAAoB,EAAE,QAAmC;AAChE,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAuC,MAAM;AACzE,QAAM,aAAa,OAA6C,IAAI;AACpE;AAAA,IACE,MAAM,MAAM;AACV,UAAI,WAAW,QAAS,cAAa,WAAW,OAAO;AAAA,IACzD;AAAA,IACA,CAAA;AAAA,EAAC;AAEH,QAAM,QAAQ,YAAY,CAAC,SAA8B;AACvD,cAAU,IAAI;AACd,QAAI,WAAW,QAAS,cAAa,WAAW,OAAO;AACvD,eAAW,UAAU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ACD,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,UAAU,KAAK,MAAM;AAAA,MACrB,QAAQ,oBAAC,qBAAA,EAAoB,KAAA,CAAY;AAAA,MAExC;AAAA,IAAA;AAAA,EAAA;AAGP;AAQO,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,SACE,oBAAC,kBAAe,UAAU,YAAY,MAAM,wBAAqB,IAC/D,+BAAC,QAAA,EACE,UAAA;AAAA,IAAA;AAAA,IACA;AAAA,EAAA,EAAA,CACH,EAAA,CACF;AAEJ;AAEO,SAAS,sBAAsB,EAAE,QAAuB;AAC7D,SACE,oBAAC,iBAAA,EACC,UAAA,oBAAC,eAAA,EAAc,MACb,8BAAC,iBAAA,
|
|
1
|
+
{"version":3,"file":"chat-node-views.js","sources":["../../../src/chat-ui/rich-text/chat-node-views.tsx"],"sourcesContent":["import type { Node as ProseMirrorNode } from \"@tiptap/pm/model\";\nimport {\n NodeViewContent,\n NodeViewWrapper,\n type NodeViewProps,\n} from \"@tiptap/react\";\nimport { CheckIcon, CopyIcon, XIcon } from \"lucide-react\";\nimport { type ReactNode, useCallback, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport { MentionLink } from \"../mentions/mention-chip\";\nimport {\n makeMentionUrl,\n type MentionNodeAttrs,\n} from \"../mentions/mention-extension\";\n\nexport function ChatMention({\n node,\n interactive = true,\n}: {\n node: ProseMirrorNode;\n interactive?: boolean;\n}) {\n return (\n <span\n className=\"mention-chip\"\n data-mention=\"\"\n data-type={node.attrs.type}\n data-name={node.attrs.name}\n data-id={node.attrs.id}\n data-asset-type={node.attrs.assetType}\n data-display-as-preview={String(node.attrs.displayAsPreview === true)}\n >\n <MentionLink\n href={makeMentionUrl(node.attrs as MentionNodeAttrs)}\n interactive={interactive}\n >\n {node.attrs.name}\n </MentionLink>\n </span>\n );\n}\n\nexport function ChatMentionNodeView({ node, editor }: NodeViewProps) {\n return (\n <NodeViewWrapper as=\"span\">\n <ChatMention node={node} interactive={!editor.isEditable} />\n </NodeViewWrapper>\n );\n}\n\nconst COPIED_RESET_MS = 1500;\n\n/**\n * Copies the block's source. Reads `node.textContent` at click time so a\n * still-streaming block copies what is on screen, not a stale snapshot.\n */\nfunction CodeBlockCopyButton({ node }: { node: ProseMirrorNode }) {\n const [status, setStatus] = useState<\"idle\" | \"copied\" | \"failed\">(\"idle\");\n const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(\n () => () => {\n if (resetTimer.current) clearTimeout(resetTimer.current);\n },\n [],\n );\n const flash = useCallback((next: \"copied\" | \"failed\") => {\n setStatus(next);\n if (resetTimer.current) clearTimeout(resetTimer.current);\n resetTimer.current = setTimeout(() => setStatus(\"idle\"), COPIED_RESET_MS);\n }, []);\n const onCopy = useCallback(() => {\n // writeText rejects when clipboard-write is denied (permissions, an\n // embedding iframe without the allow attribute); surface that instead of\n // leaving an unhandled rejection and a button that looks like it worked.\n if (typeof navigator === \"undefined\" || !navigator.clipboard) {\n flash(\"failed\");\n return;\n }\n navigator.clipboard.writeText(node.textContent).then(\n () => flash(\"copied\"),\n () => flash(\"failed\"),\n );\n }, [node, flash]);\n const label =\n status === \"copied\" ? \"Copied\" : status === \"failed\" ? \"Copy failed\" : \"Copy code\";\n return (\n <button\n type=\"button\"\n title={label}\n aria-label={label}\n onClick={onCopy}\n className={cn(\n \"inline-flex size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground\",\n \"opacity-0 transition-opacity group-hover/code-block:opacity-100 focus-visible:opacity-100\",\n status !== \"idle\" && \"opacity-100\",\n status === \"failed\" && \"text-destructive\",\n )}\n >\n {status === \"copied\" ? (\n <CheckIcon className=\"size-3.5\" />\n ) : status === \"failed\" ? (\n <XIcon className=\"size-3.5\" />\n ) : (\n <CopyIcon className=\"size-3.5\" />\n )}\n </button>\n );\n}\n\n/** The frame both code renderings share: language label, an optional corner action, the `<pre>`. */\nfunction CodeBlockFrame({\n language,\n action,\n children,\n ...attributes\n}: {\n language: string | null | undefined;\n action?: ReactNode;\n children: ReactNode;\n \"data-chat-open-fence\"?: string;\n}) {\n return (\n <div\n className=\"not-prose group/code-block relative my-2 overflow-hidden rounded-lg border border-border bg-muted/30\"\n {...attributes}\n >\n {language && (\n <div className=\"border-b border-border bg-muted/50 px-3 py-1 text-[10px] font-medium text-muted-foreground\">\n {language}\n </div>\n )}\n {action && (\n <div className=\"absolute top-1 right-1\" contentEditable={false}>\n {action}\n </div>\n )}\n <pre className=\"overflow-x-auto p-3 pr-9 font-mono text-xs leading-relaxed text-foreground\">\n {children}\n </pre>\n </div>\n );\n}\n\nexport function ChatCodeBlock({\n node,\n children,\n}: {\n node: ProseMirrorNode;\n children: ReactNode;\n}) {\n return (\n <CodeBlockFrame\n language={node.attrs.language}\n action={<CodeBlockCopyButton node={node} />}\n >\n {children}\n </CodeBlockFrame>\n );\n}\n\n/**\n * A fenced block whose closing fence has not arrived: the same frame with the\n * code as plain text and no copy action (there is no settled source to copy\n * yet). Anything that decorates code — highlighting, a language pick — belongs\n * after the fence closes, when the block parses into a `codeBlock` node.\n */\nexport function StreamingCodeBlock({\n language,\n code,\n caret,\n}: {\n language: string;\n code: string;\n caret?: ReactNode;\n}) {\n return (\n <CodeBlockFrame language={language || null} data-chat-open-fence=\"\">\n <code>\n {code}\n {caret}\n </code>\n </CodeBlockFrame>\n );\n}\n\nexport function ChatCodeBlockNodeView({ node }: NodeViewProps) {\n return (\n <NodeViewWrapper>\n <ChatCodeBlock node={node}>\n <NodeViewContent<\"code\"> as=\"code\" />\n </ChatCodeBlock>\n </NodeViewWrapper>\n );\n}\n"],"names":[],"mappings":";;;;;;;AAeO,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA,cAAc;AAChB,GAGG;AACD,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAU;AAAA,MACV,gBAAa;AAAA,MACb,aAAW,KAAK,MAAM;AAAA,MACtB,aAA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7D,SACE,oBAAC,iBAAA,EACC,UAAA,oBAAC,eAAA,EAAc,MACb,8BAAC,iBAAA,EAAwB,IAAG,OAAA,CAAO,EAAA,CACrC,GACF;AAEJ;"}
|
|
@@ -7,13 +7,11 @@ const CodeBlock = require("@tiptap/extension-code-block");
|
|
|
7
7
|
const react = require("@tiptap/react");
|
|
8
8
|
const Link = require("@tiptap/extension-link");
|
|
9
9
|
const Image = require("@tiptap/extension-image");
|
|
10
|
-
const
|
|
11
|
-
const TableRow = require("@tiptap/extension-table-row");
|
|
12
|
-
const TableCell = require("@tiptap/extension-table-cell");
|
|
13
|
-
const TableHeader = require("@tiptap/extension-table-header");
|
|
10
|
+
const extensionTable = require("@tiptap/extension-table");
|
|
14
11
|
const TaskList = require("@tiptap/extension-task-list");
|
|
15
12
|
const TaskItem = require("@tiptap/extension-task-item");
|
|
16
13
|
const tiptapMarkdown = require("tiptap-markdown");
|
|
14
|
+
const markdownStorage = require("../markdown-storage.cjs");
|
|
17
15
|
const mentionExtension = require("../mentions/mention-extension.cjs");
|
|
18
16
|
const chatNodeViews = require("./chat-node-views.cjs");
|
|
19
17
|
const citationAnchors = require("./citation-anchors.cjs");
|
|
@@ -38,7 +36,14 @@ const ChatLinkExtension = Link.extend({
|
|
|
38
36
|
});
|
|
39
37
|
function createChatTextExtensions() {
|
|
40
38
|
return [
|
|
41
|
-
StarterKit.configure({
|
|
39
|
+
StarterKit.configure({
|
|
40
|
+
codeBlock: false,
|
|
41
|
+
// Tiptap 3 StarterKit also bundles these; chat text registers its own link and never had the rest.
|
|
42
|
+
link: false,
|
|
43
|
+
underline: false,
|
|
44
|
+
listKeymap: false,
|
|
45
|
+
trailingNode: false
|
|
46
|
+
}),
|
|
42
47
|
ChatCodeBlockExtension,
|
|
43
48
|
ChatLinkExtension.configure({
|
|
44
49
|
openOnClick: false,
|
|
@@ -48,10 +53,10 @@ function createChatTextExtensions() {
|
|
|
48
53
|
isAllowedUri: (url) => citationAnchors.isAllowedChatHref(url)
|
|
49
54
|
}),
|
|
50
55
|
Image.configure({ inline: true }),
|
|
51
|
-
Table.configure({ resizable: false }),
|
|
52
|
-
TableRow,
|
|
53
|
-
TableCell,
|
|
54
|
-
TableHeader,
|
|
56
|
+
extensionTable.Table.configure({ resizable: false }),
|
|
57
|
+
extensionTable.TableRow,
|
|
58
|
+
extensionTable.TableCell,
|
|
59
|
+
extensionTable.TableHeader,
|
|
55
60
|
TaskList,
|
|
56
61
|
TaskItem.configure({ nested: true }),
|
|
57
62
|
tiptapMarkdown.Markdown.configure({
|
|
@@ -74,7 +79,7 @@ function parseChatText(markdown) {
|
|
|
74
79
|
content: "",
|
|
75
80
|
editable: false
|
|
76
81
|
}));
|
|
77
|
-
const html = parserEditor.
|
|
82
|
+
const html = markdownStorage.getMarkdownStorage(parserEditor).parser.parse(markdown);
|
|
78
83
|
const body = new window.DOMParser().parseFromString(html, "text/html").body;
|
|
79
84
|
citationAnchors.normalizeCitationAnchors(body);
|
|
80
85
|
return model.DOMParser.fromSchema(parserEditor.schema).parse(body);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat-text-schema.cjs","sources":["../../../src/chat-ui/rich-text/chat-text-schema.tsx"],"sourcesContent":["import { Editor, type Extensions } from \"@tiptap/core\";\nimport { DOMParser as ProseMirrorDOMParser } from \"@tiptap/pm/model\";\nimport StarterKit from \"@tiptap/starter-kit\";\nimport CodeBlock from \"@tiptap/extension-code-block\";\nimport { ReactNodeViewRenderer } from \"@tiptap/react\";\nimport Link from \"@tiptap/extension-link\";\nimport Image from \"@tiptap/extension-image\";\nimport Table
|
|
1
|
+
{"version":3,"file":"chat-text-schema.cjs","sources":["../../../src/chat-ui/rich-text/chat-text-schema.tsx"],"sourcesContent":["import { Editor, type Extensions } from \"@tiptap/core\";\nimport { DOMParser as ProseMirrorDOMParser } from \"@tiptap/pm/model\";\nimport StarterKit from \"@tiptap/starter-kit\";\nimport CodeBlock from \"@tiptap/extension-code-block\";\nimport { ReactNodeViewRenderer } from \"@tiptap/react\";\nimport Link from \"@tiptap/extension-link\";\nimport Image from \"@tiptap/extension-image\";\nimport { Table, TableCell, TableHeader, TableRow } from \"@tiptap/extension-table\";\nimport TaskList from \"@tiptap/extension-task-list\";\nimport TaskItem from \"@tiptap/extension-task-item\";\nimport { Markdown } from \"tiptap-markdown\";\nimport { getMarkdownStorage } from \"../markdown-storage\";\nimport { MentionExtension } from \"../mentions/mention-extension\";\nimport { ChatCodeBlockNodeView, ChatMentionNodeView } from \"./chat-node-views\";\nimport { isAllowedChatHref, normalizeCitationAnchors } from \"./citation-anchors\";\n\nconst ChatMentionExtension = MentionExtension.extend({\n addNodeView: () => ReactNodeViewRenderer(ChatMentionNodeView, { as: \"span\" }),\n});\n/** Fenced code rendered through `ChatCodeBlock` (language label + copy button). */\nexport const ChatCodeBlockExtension = CodeBlock.extend({\n addNodeView: () => ReactNodeViewRenderer(ChatCodeBlockNodeView),\n});\n\n/**\n * The Link mark with the excerpt a citation carries (`data-excerpt`, the\n * source chip's tooltip and scroll-to-text target) and an href allow-list\n * narrower than tiptap's default: `http(s):`, `mailto:`, the screen-point\n * protocol and app-relative Spaces paths pass; every other scheme\n * (`javascript:`, `ftp:`, `data:`, protocol-relative `//host`) is dropped and\n * its label kept as text. The same rule governs the composer's autolink.\n */\nexport const ChatLinkExtension = Link.extend({\n addAttributes() {\n return {\n ...this.parent?.(),\n excerpt: {\n default: null,\n parseHTML: (element: HTMLElement) => element.getAttribute(\"data-excerpt\"),\n renderHTML: (attributes: Record<string, unknown>) =>\n typeof attributes.excerpt === \"string\" && attributes.excerpt\n ? { \"data-excerpt\": attributes.excerpt }\n : {},\n },\n };\n },\n});\n\n/** Both the editable draft and the static message body use this schema and parser. */\nexport function createChatTextExtensions(): Extensions {\n return [\n StarterKit.configure({\n codeBlock: false,\n // Tiptap 3 StarterKit also bundles these; chat text registers its own link and never had the rest.\n link: false,\n underline: false,\n listKeymap: false,\n trailingNode: false,\n }),\n ChatCodeBlockExtension,\n ChatLinkExtension.configure({\n openOnClick: false,\n autolink: true,\n linkOnPaste: true,\n protocols: [\"athena-point\"],\n isAllowedUri: (url) => isAllowedChatHref(url),\n }),\n Image.configure({ inline: true }),\n Table.configure({ resizable: false }),\n TableRow,\n TableCell,\n TableHeader,\n TaskList,\n TaskItem.configure({ nested: true }),\n Markdown.configure({\n html: true,\n tightLists: true,\n tightListClass: \"tight\",\n bulletListMarker: \"-\",\n linkify: true,\n breaks: true,\n transformPastedText: true,\n transformCopiedText: false,\n }),\n ChatMentionExtension,\n ];\n}\n\nlet parserEditor: Editor | undefined;\n\n/**\n * A single detached parser per browser tab, never an editor per message.\n * Markdown → HTML (markdown-it, with bare URLs linkified and inline HTML kept)\n * → agora's citation anchors given their hrefs → the schema's document.\n */\nexport function parseChatText(markdown: string) {\n parserEditor ??= new Editor({\n extensions: createChatTextExtensions(),\n content: \"\",\n editable: false,\n });\n const html: string = getMarkdownStorage(parserEditor).parser.parse(markdown);\n const body = new window.DOMParser().parseFromString(html, \"text/html\").body;\n normalizeCitationAnchors(body);\n return ProseMirrorDOMParser.fromSchema(parserEditor.schema).parse(body);\n}\n\n/** Typography is shared; the composer supplies only its padding and scroll boundary. */\nexport const CHAT_TEXT_CLASS =\n \"aui-md prose prose-sm max-w-none min-w-0 break-words text-sm leading-snug text-foreground prose-p:my-1.5 prose-p:leading-snug prose-headings:mt-3 prose-headings:mb-1.5 prose-headings:font-semibold prose-h1:text-sm prose-h2:text-sm prose-h3:text-xs prose-ul:my-1.5 prose-ol:my-1.5 prose-li:my-0.5 prose-blockquote:border-l-2 prose-blockquote:border-border prose-blockquote:text-muted-foreground prose-code:rounded prose-code:bg-muted prose-code:px-1 prose-code:py-0.5 prose-code:text-xs prose-code:font-mono prose-code:before:content-none prose-code:after:content-none prose-pre:my-2 prose-pre:overflow-x-auto prose-pre:rounded-lg prose-pre:border prose-pre:border-border prose-pre:bg-muted/30 prose-pre:p-3 prose-a:text-primary prose-a:underline prose-a:decoration-primary/40 prose-a:underline-offset-2 hover:prose-a:decoration-primary prose-strong:font-semibold prose-hr:border-border [&>:first-child]:mt-0 [&>:last-child]:mb-0 [&_table]:block [&_table]:overflow-x-auto [&_td]:border [&_td]:border-border [&_td]:px-2 [&_th]:border [&_th]:border-border [&_th]:px-2 [&_ul[data-type=taskList]]:list-none [&_ul[data-type=taskList]]:pl-0 [&_li[data-type=taskItem]]:flex [&_li[data-type=taskItem]]:gap-2\";\n"],"names":["MentionExtension","ReactNodeViewRenderer","ChatMentionNodeView","ChatCodeBlockNodeView","isAllowedChatHref","Table","TableRow","TableCell","TableHeader","Markdown","Editor","getMarkdownStorage","normalizeCitationAnchors","ProseMirrorDOMParser"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,MAAM,uBAAuBA,iBAAAA,iBAAiB,OAAO;AAAA,EACnD,aAAa,MAAMC,MAAAA,sBAAsBC,cAAAA,qBAAqB,EAAE,IAAI,QAAQ;AAC9E,CAAC;AAEM,MAAM,yBAAyB,UAAU,OAAO;AAAA,EACrD,aAAa,MAAMD,MAAAA,sBAAsBE,cAAAA,qBAAqB;AAChE,CAAC;AAUM,MAAM,oBAAoB,KAAK,OAAO;AAAA,EAC3C,gBAAgB;;AACd,WAAO;AAAA,MACL,IAAG,UAAK,WAAL;AAAA,MACH,SAAS;AAAA,QACP,SAAS;AAAA,QACT,WAAW,CAAC,YAAyB,QAAQ,aAAa,cAAc;AAAA,QACxE,YAAY,CAAC,eACX,OAAO,WAAW,YAAY,YAAY,WAAW,UACjD,EAAE,gBAAgB,WAAW,QAAA,IAC7B,CAAA;AAAA,MAAC;AAAA,IACT;AAAA,EAEJ;AACF,CAAC;AAGM,SAAS,2BAAuC;AACrD,SAAO;AAAA,IACL,WAAW,UAAU;AAAA,MACnB,WAAW;AAAA;AAAA,MAEX,MAAM;AAAA,MACN,WAAW;AAAA,MACX,YAAY;AAAA,MACZ,cAAc;AAAA,IAAA,CACf;AAAA,IACD;AAAA,IACA,kBAAkB,UAAU;AAAA,MAC1B,aAAa;AAAA,MACb,UAAU;AAAA,MACV,aAAa;AAAA,MACb,WAAW,CAAC,cAAc;AAAA,MAC1B,cAAc,CAAC,QAAQC,gBAAAA,kBAAkB,GAAG;AAAA,IAAA,CAC7C;AAAA,IACD,MAAM,UAAU,EAAE,QAAQ,MAAM;AAAA,IAChCC,eAAAA,MAAM,UAAU,EAAE,WAAW,OAAO;AAAA,IACpCC,eAAAA;AAAAA,IACAC,eAAAA;AAAAA,IACAC,eAAAA;AAAAA,IACA;AAAA,IACA,SAAS,UAAU,EAAE,QAAQ,MAAM;AAAA,IACnCC,eAAAA,SAAS,UAAU;AAAA,MACjB,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,gBAAgB;AAAA,MAChB,kBAAkB;AAAA,MAClB,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,qBAAqB;AAAA,MACrB,qBAAqB;AAAA,IAAA,CACtB;AAAA,IACD;AAAA,EAAA;AAEJ;AAEA,IAAI;AAOG,SAAS,cAAc,UAAkB;AAC9C,kCAAiB,IAAIC,KAAAA,OAAO;AAAA,IAC1B,YAAY,yBAAA;AAAA,IACZ,SAAS;AAAA,IACT,UAAU;AAAA,EAAA,CACX;AACD,QAAM,OAAeC,gBAAAA,mBAAmB,YAAY,EAAE,OAAO,MAAM,QAAQ;AAC3E,QAAM,OAAO,IAAI,OAAO,UAAA,EAAY,gBAAgB,MAAM,WAAW,EAAE;AACvEC,kBAAAA,yBAAyB,IAAI;AAC7B,SAAOC,MAAAA,UAAqB,WAAW,aAAa,MAAM,EAAE,MAAM,IAAI;AACxE;AAGO,MAAM,kBACX;;;;;;"}
|
|
@@ -5,13 +5,11 @@ import CodeBlock from "@tiptap/extension-code-block";
|
|
|
5
5
|
import { ReactNodeViewRenderer } from "@tiptap/react";
|
|
6
6
|
import Link from "@tiptap/extension-link";
|
|
7
7
|
import Image from "@tiptap/extension-image";
|
|
8
|
-
import Table from "@tiptap/extension-table";
|
|
9
|
-
import TableRow from "@tiptap/extension-table-row";
|
|
10
|
-
import TableCell from "@tiptap/extension-table-cell";
|
|
11
|
-
import TableHeader from "@tiptap/extension-table-header";
|
|
8
|
+
import { TableRow, TableCell, TableHeader, Table } from "@tiptap/extension-table";
|
|
12
9
|
import TaskList from "@tiptap/extension-task-list";
|
|
13
10
|
import TaskItem from "@tiptap/extension-task-item";
|
|
14
11
|
import { Markdown } from "tiptap-markdown";
|
|
12
|
+
import { getMarkdownStorage } from "../markdown-storage.js";
|
|
15
13
|
import { MentionExtension } from "../mentions/mention-extension.js";
|
|
16
14
|
import { ChatCodeBlockNodeView, ChatMentionNodeView } from "./chat-node-views.js";
|
|
17
15
|
import { isAllowedChatHref, normalizeCitationAnchors } from "./citation-anchors.js";
|
|
@@ -36,7 +34,14 @@ const ChatLinkExtension = Link.extend({
|
|
|
36
34
|
});
|
|
37
35
|
function createChatTextExtensions() {
|
|
38
36
|
return [
|
|
39
|
-
StarterKit.configure({
|
|
37
|
+
StarterKit.configure({
|
|
38
|
+
codeBlock: false,
|
|
39
|
+
// Tiptap 3 StarterKit also bundles these; chat text registers its own link and never had the rest.
|
|
40
|
+
link: false,
|
|
41
|
+
underline: false,
|
|
42
|
+
listKeymap: false,
|
|
43
|
+
trailingNode: false
|
|
44
|
+
}),
|
|
40
45
|
ChatCodeBlockExtension,
|
|
41
46
|
ChatLinkExtension.configure({
|
|
42
47
|
openOnClick: false,
|
|
@@ -72,7 +77,7 @@ function parseChatText(markdown) {
|
|
|
72
77
|
content: "",
|
|
73
78
|
editable: false
|
|
74
79
|
}));
|
|
75
|
-
const html = parserEditor.
|
|
80
|
+
const html = getMarkdownStorage(parserEditor).parser.parse(markdown);
|
|
76
81
|
const body = new window.DOMParser().parseFromString(html, "text/html").body;
|
|
77
82
|
normalizeCitationAnchors(body);
|
|
78
83
|
return DOMParser.fromSchema(parserEditor.schema).parse(body);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat-text-schema.js","sources":["../../../src/chat-ui/rich-text/chat-text-schema.tsx"],"sourcesContent":["import { Editor, type Extensions } from \"@tiptap/core\";\nimport { DOMParser as ProseMirrorDOMParser } from \"@tiptap/pm/model\";\nimport StarterKit from \"@tiptap/starter-kit\";\nimport CodeBlock from \"@tiptap/extension-code-block\";\nimport { ReactNodeViewRenderer } from \"@tiptap/react\";\nimport Link from \"@tiptap/extension-link\";\nimport Image from \"@tiptap/extension-image\";\nimport Table
|
|
1
|
+
{"version":3,"file":"chat-text-schema.js","sources":["../../../src/chat-ui/rich-text/chat-text-schema.tsx"],"sourcesContent":["import { Editor, type Extensions } from \"@tiptap/core\";\nimport { DOMParser as ProseMirrorDOMParser } from \"@tiptap/pm/model\";\nimport StarterKit from \"@tiptap/starter-kit\";\nimport CodeBlock from \"@tiptap/extension-code-block\";\nimport { ReactNodeViewRenderer } from \"@tiptap/react\";\nimport Link from \"@tiptap/extension-link\";\nimport Image from \"@tiptap/extension-image\";\nimport { Table, TableCell, TableHeader, TableRow } from \"@tiptap/extension-table\";\nimport TaskList from \"@tiptap/extension-task-list\";\nimport TaskItem from \"@tiptap/extension-task-item\";\nimport { Markdown } from \"tiptap-markdown\";\nimport { getMarkdownStorage } from \"../markdown-storage\";\nimport { MentionExtension } from \"../mentions/mention-extension\";\nimport { ChatCodeBlockNodeView, ChatMentionNodeView } from \"./chat-node-views\";\nimport { isAllowedChatHref, normalizeCitationAnchors } from \"./citation-anchors\";\n\nconst ChatMentionExtension = MentionExtension.extend({\n addNodeView: () => ReactNodeViewRenderer(ChatMentionNodeView, { as: \"span\" }),\n});\n/** Fenced code rendered through `ChatCodeBlock` (language label + copy button). */\nexport const ChatCodeBlockExtension = CodeBlock.extend({\n addNodeView: () => ReactNodeViewRenderer(ChatCodeBlockNodeView),\n});\n\n/**\n * The Link mark with the excerpt a citation carries (`data-excerpt`, the\n * source chip's tooltip and scroll-to-text target) and an href allow-list\n * narrower than tiptap's default: `http(s):`, `mailto:`, the screen-point\n * protocol and app-relative Spaces paths pass; every other scheme\n * (`javascript:`, `ftp:`, `data:`, protocol-relative `//host`) is dropped and\n * its label kept as text. The same rule governs the composer's autolink.\n */\nexport const ChatLinkExtension = Link.extend({\n addAttributes() {\n return {\n ...this.parent?.(),\n excerpt: {\n default: null,\n parseHTML: (element: HTMLElement) => element.getAttribute(\"data-excerpt\"),\n renderHTML: (attributes: Record<string, unknown>) =>\n typeof attributes.excerpt === \"string\" && attributes.excerpt\n ? { \"data-excerpt\": attributes.excerpt }\n : {},\n },\n };\n },\n});\n\n/** Both the editable draft and the static message body use this schema and parser. */\nexport function createChatTextExtensions(): Extensions {\n return [\n StarterKit.configure({\n codeBlock: false,\n // Tiptap 3 StarterKit also bundles these; chat text registers its own link and never had the rest.\n link: false,\n underline: false,\n listKeymap: false,\n trailingNode: false,\n }),\n ChatCodeBlockExtension,\n ChatLinkExtension.configure({\n openOnClick: false,\n autolink: true,\n linkOnPaste: true,\n protocols: [\"athena-point\"],\n isAllowedUri: (url) => isAllowedChatHref(url),\n }),\n Image.configure({ inline: true }),\n Table.configure({ resizable: false }),\n TableRow,\n TableCell,\n TableHeader,\n TaskList,\n TaskItem.configure({ nested: true }),\n Markdown.configure({\n html: true,\n tightLists: true,\n tightListClass: \"tight\",\n bulletListMarker: \"-\",\n linkify: true,\n breaks: true,\n transformPastedText: true,\n transformCopiedText: false,\n }),\n ChatMentionExtension,\n ];\n}\n\nlet parserEditor: Editor | undefined;\n\n/**\n * A single detached parser per browser tab, never an editor per message.\n * Markdown → HTML (markdown-it, with bare URLs linkified and inline HTML kept)\n * → agora's citation anchors given their hrefs → the schema's document.\n */\nexport function parseChatText(markdown: string) {\n parserEditor ??= new Editor({\n extensions: createChatTextExtensions(),\n content: \"\",\n editable: false,\n });\n const html: string = getMarkdownStorage(parserEditor).parser.parse(markdown);\n const body = new window.DOMParser().parseFromString(html, \"text/html\").body;\n normalizeCitationAnchors(body);\n return ProseMirrorDOMParser.fromSchema(parserEditor.schema).parse(body);\n}\n\n/** Typography is shared; the composer supplies only its padding and scroll boundary. */\nexport const CHAT_TEXT_CLASS =\n \"aui-md prose prose-sm max-w-none min-w-0 break-words text-sm leading-snug text-foreground prose-p:my-1.5 prose-p:leading-snug prose-headings:mt-3 prose-headings:mb-1.5 prose-headings:font-semibold prose-h1:text-sm prose-h2:text-sm prose-h3:text-xs prose-ul:my-1.5 prose-ol:my-1.5 prose-li:my-0.5 prose-blockquote:border-l-2 prose-blockquote:border-border prose-blockquote:text-muted-foreground prose-code:rounded prose-code:bg-muted prose-code:px-1 prose-code:py-0.5 prose-code:text-xs prose-code:font-mono prose-code:before:content-none prose-code:after:content-none prose-pre:my-2 prose-pre:overflow-x-auto prose-pre:rounded-lg prose-pre:border prose-pre:border-border prose-pre:bg-muted/30 prose-pre:p-3 prose-a:text-primary prose-a:underline prose-a:decoration-primary/40 prose-a:underline-offset-2 hover:prose-a:decoration-primary prose-strong:font-semibold prose-hr:border-border [&>:first-child]:mt-0 [&>:last-child]:mb-0 [&_table]:block [&_table]:overflow-x-auto [&_td]:border [&_td]:border-border [&_td]:px-2 [&_th]:border [&_th]:border-border [&_th]:px-2 [&_ul[data-type=taskList]]:list-none [&_ul[data-type=taskList]]:pl-0 [&_li[data-type=taskItem]]:flex [&_li[data-type=taskItem]]:gap-2\";\n"],"names":["ProseMirrorDOMParser"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAM,uBAAuB,iBAAiB,OAAO;AAAA,EACnD,aAAa,MAAM,sBAAsB,qBAAqB,EAAE,IAAI,QAAQ;AAC9E,CAAC;AAEM,MAAM,yBAAyB,UAAU,OAAO;AAAA,EACrD,aAAa,MAAM,sBAAsB,qBAAqB;AAChE,CAAC;AAUM,MAAM,oBAAoB,KAAK,OAAO;AAAA,EAC3C,gBAAgB;;AACd,WAAO;AAAA,MACL,IAAG,UAAK,WAAL;AAAA,MACH,SAAS;AAAA,QACP,SAAS;AAAA,QACT,WAAW,CAAC,YAAyB,QAAQ,aAAa,cAAc;AAAA,QACxE,YAAY,CAAC,eACX,OAAO,WAAW,YAA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@@ -25,6 +25,7 @@ function normalizeConversationListFilter(filter) {
|
|
|
25
25
|
normalized.excludeSourceChannels = [...filter.excludeSourceChannels].sort();
|
|
26
26
|
}
|
|
27
27
|
if (filter.computerAssetId) normalized.computerAssetId = filter.computerAssetId;
|
|
28
|
+
if (filter.parentSessionId) normalized.parentSessionId = filter.parentSessionId;
|
|
28
29
|
if (filter.states && filter.states.length > 0) {
|
|
29
30
|
normalized.states = [...filter.states].sort();
|
|
30
31
|
}
|
|
@@ -117,6 +118,8 @@ function summaryFromConversationIndexEntry(entry, previous) {
|
|
|
117
118
|
assetType: entry.asset_type,
|
|
118
119
|
assetId: entry.asset_id ?? (previous == null ? void 0 : previous.assetId) ?? null,
|
|
119
120
|
computerAssetId: (previous == null ? void 0 : previous.computerAssetId) ?? null,
|
|
121
|
+
parentSessionId: previous == null ? void 0 : previous.parentSessionId,
|
|
122
|
+
subSessionCount: previous == null ? void 0 : previous.subSessionCount,
|
|
120
123
|
appId: entry.app_id,
|
|
121
124
|
triggerType: entry.trigger_type,
|
|
122
125
|
preview: entry.last_message_preview,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-list.cjs","sources":["../../../../../agent-runtime/src/conversation-list.ts"],"sourcesContent":["import type { InfiniteData, QueryClient } from '@tanstack/react-query';\nimport type { ConversationIndexEntry } from './conversation-index';\n\n/**\n * What a session asks of the viewer, derived server-side from the run, the\n * parked interrupt, the pull requests it opened, its termination and its last\n * wake (the Devin-style session list). `needs_you` is the only state that\n * demands the viewer act; `working` is live; `ready` finished with something\n * to look at; `watching` waits on an external party (a review, a check);\n * `done` and `error` are terminal. A backend newer than this client may report\n * a value outside the union — render it as \"no attention\" rather than failing.\n */\nexport type ConversationAttention =\n | 'needs_you'\n | 'working'\n | 'ready'\n | 'watching'\n | 'done'\n | 'error';\n\nexport const CONVERSATION_ATTENTIONS: readonly ConversationAttention[] = [\n 'needs_you',\n 'working',\n 'ready',\n 'watching',\n 'done',\n 'error',\n];\n\n/** Which signal produced the attention state (and the `nextAction` copy). */\nexport type ConversationAttentionSource =\n | 'interrupt'\n | 'run'\n | 'pull_request'\n | 'termination'\n | 'wake'\n | 'handoff'\n | 'follow_up';\n\n/** The last event that woke a resting session (a GitHub webhook, a schedule, a handoff). */\nexport interface ConversationWake {\n source: string | null;\n reason: string | null;\n /** ISO 8601 timestamp of the wake. */\n at: string | null;\n}\n\n/**\n * Live GitHub state of a pull request the session opened, read by the server\n * when the list renders. Never pushed by the conversation index — it comes\n * from the list fetch only, so a fold keeps the fetched value.\n */\nexport interface ConversationPullRequest {\n /** `owner/repo` the pull request lives in. */\n repoFullName: string;\n number: number;\n url: string;\n title: string;\n state: 'OPEN' | 'CLOSED' | 'MERGED';\n isDraft: boolean;\n /** GitHub's review decision (APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED) or null. */\n reviewDecision: string | null;\n /** Combined state of the checks on the head commit. */\n checksState: 'SUCCESS' | 'FAILURE' | 'PENDING' | 'NONE';\n /** ISO 8601 timestamp of the pull request's last update on GitHub. */\n updatedAt: string;\n}\n\n/**\n * Shared conversation/thread LIST contract (chat-stack unification —\n * thread-list-contract-convergence).\n *\n * Every chat surface lists \"my conversations\" against the same underlying\n * session assets, but historically each declared its own row shape, paging\n * model, and filter set (Olympus GraphQL `listConversations`, the SDK/Chrome\n * REST `/api/conversations/threads/list`, mobile's `/api/v0/sessions`). This\n * module is the ONE contract those surfaces converge on:\n *\n * - **Row shape**: {@link ConversationSummary} — the canonical camelCase\n * superset. Fields a transport cannot supply are `null`, never invented.\n * - **Ordering**: newest first by `updatedAt`, always. Ordering is part of the\n * contract, not a parameter — no surface sorts any other way.\n * - **Paging**: offset/limit with a LIVE newest page and explicitly-fetched\n * frozen history pages (see `useConversationList`). `hasMore` continues the\n * scan; `totalCount` is advisory and may be `null` for transports that do\n * not count.\n * - **Filtering**: {@link ConversationListFilter}. `appId` follows\n * `docs/SESSION_APP_ID_GUIDE.md`: exact match when set (legacy `null`\n * sessions excluded), no filter when unset. A fetcher that cannot express a\n * requested filter field MUST throw rather than silently ignore it — a\n * dropped filter returns wrong rows under a cache key that claims otherwise.\n * - **Freshness**: the per-user conversation-index statewire\n * (`conversation-index.ts`) is the push signal; these queries are the data\n * source. Push handlers call {@link invalidateConversationListCaches}.\n */\nexport interface ConversationSummary {\n /** LangGraph thread id — the cross-surface conversation identity. */\n threadId: string;\n title: string;\n /** ISO 8601 timestamp of last update (the contract's sort key). */\n updatedAt: string;\n /** ISO 8601 creation timestamp, when the transport reports it. */\n createdAt: string | null;\n /** Session lifecycle state from athena_metadata (e.g. running, completed). */\n state: string | null;\n /** Agent runtime marker (e.g. 'athena_deep_agent'), when reported. */\n runtime: string | null;\n /** Channel the session was started from (e.g. agent_email, web). */\n sourceChannel: string | null;\n /** Asset type (session, video_session, desktop_session, mobile_session). */\n assetType: string | null;\n /** Session asset id (`asset_<uuid>`), when the transport reports it. */\n assetId: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Computer asset whose sandbox started the session (`sourceChannel` 'computer'); omitted by surfaces that don't carry it. */\n computerAssetId?: string | null;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Last-message preview used when a legacy session has no useful title. */\n preview: string | null;\n messageCount: number | null;\n /** Per-user unread flag derived server-side from the read receipt. */\n isUnread: boolean;\n /**\n * Canonical session status (status_v2: idle | active | needs_input | error),\n * or null when the transport does not report it.\n */\n sessionStatus: string | null;\n /**\n * Canonical status of the session's current run (status_v2: scheduled |\n * queued | running | needs_input | completed | failed | canceled). Null when\n * the transport does not report it — {@link isConversationRunning} then\n * falls back to the legacy `state`. Running badges on every surface derive\n * from this one helper so they cannot disagree.\n */\n runStatus: string | null;\n /**\n * Server-derived attention state. `undefined` when the transport (or an\n * older server) does not report it — {@link deriveConversationAttention}\n * then falls back to the status planes; `null` when the server reports none.\n */\n attention?: ConversationAttention | null;\n /** One line (≤ 80 chars) of what the viewer should do next, when the server derives one. */\n nextAction?: string | null;\n /** Which signal produced `attention` / `nextAction`. */\n attentionSource?: ConversationAttentionSource | null;\n /** Whether the viewer pinned (favorited) the session; `undefined` when not reported. */\n isFavorited?: boolean;\n /** The last wake of a resting session; `undefined` when not reported. */\n lastWake?: ConversationWake | null;\n /**\n * Pull requests the session opened with their live GitHub state. `[]` when\n * it opened none, `null` when the state could not be read right now,\n * `undefined` when the transport did not ask for (or report) it.\n */\n pullRequests?: ConversationPullRequest[] | null;\n}\n\n/**\n * The canonical filter set. Semantics are defined here once; each fetcher\n * translates the fields its transport supports and throws on the rest.\n */\nexport interface ConversationListFilter {\n /** Exact-match client app filter; unset = all apps (SESSION_APP_ID_GUIDE). */\n appId?: string;\n /** Asset types to include (e.g. ['session']); unset = all session types. */\n assetTypes?: readonly string[];\n /** Case-insensitive title search. */\n search?: string;\n /** Hide triggered/background sessions (REST thread list only today). */\n excludeTriggered?: boolean;\n /** Start-channel filter (v0 sessions / REST thread list only today). */\n sourceChannels?: readonly string[];\n /** Start channels to hide (e.g. ['api']); GraphQL `listConversations` only today. */\n excludeSourceChannels?: readonly string[];\n /** Exact computer asset whose sandbox started the session; GraphQL `listConversations` only today. */\n computerAssetId?: string;\n /**\n * Lifecycle-state filter (e.g. ['running'], ['completed']). Transports match\n * it with the shared status_v2 rule (running carries a 12-hour recency cutoff).\n */\n states?: readonly string[];\n /** Restrict to sessions run by any of these agents (athena_metadata.agent). */\n agentIds?: readonly string[];\n /**\n * Include branched sub-sessions and orchestration children, which every list\n * hides by default because they belong under their parent thread.\n */\n includeSubSessions?: boolean;\n}\n\nexport interface ConversationListPage {\n /** Rows in contract order (updatedAt desc). */\n items: ConversationSummary[];\n /** Whether another `offset + limit` scan would return more rows. */\n hasMore: boolean;\n /** Total matching rows, or null when the transport does not count. */\n totalCount: number | null;\n}\n\nexport interface ConversationListFetchParams {\n limit: number;\n offset: number;\n filter: ConversationListFilter;\n signal?: AbortSignal;\n}\n\n/**\n * One page fetch against some transport (GraphQL `listConversations`, the\n * REST thread list, …). Must reject on filter fields it cannot express.\n */\nexport type ConversationListFetcher = (\n params: ConversationListFetchParams\n) => Promise<ConversationListPage>;\n\n/** Root of every conversation-list query key (all surfaces, all filters). */\nexport const CONVERSATION_LIST_QUERY_KEY_ROOT = 'athena-conversation-list';\n\n/**\n * Scope used by `useConversationList` when the caller passes no `scopeKey`.\n * Exported so cache seeders (e.g. Olympus's spacesBootstrap adoption) can\n * address the exact keys default-scoped hooks read from.\n */\nexport const CONVERSATION_LIST_DEFAULT_SCOPE_KEY = 'default';\n\n/**\n * Normalize a filter to its semantic content: unset/empty fields are dropped\n * (so `{}` and `{ appId: undefined }` are the same filter) and array order is\n * canonicalized. Fetchers receive the normalized form, so what a cache entry\n * claims to hold is exactly what was fetched.\n */\nexport function normalizeConversationListFilter(\n filter: ConversationListFilter\n): ConversationListFilter {\n const normalized: ConversationListFilter = {};\n if (filter.appId) normalized.appId = filter.appId;\n if (filter.assetTypes && filter.assetTypes.length > 0) {\n normalized.assetTypes = [...filter.assetTypes].sort();\n }\n if (filter.search) normalized.search = filter.search;\n if (filter.excludeTriggered !== undefined) normalized.excludeTriggered = filter.excludeTriggered;\n if (filter.sourceChannels && filter.sourceChannels.length > 0) {\n normalized.sourceChannels = [...filter.sourceChannels].sort();\n }\n if (filter.excludeSourceChannels && filter.excludeSourceChannels.length > 0) {\n normalized.excludeSourceChannels = [...filter.excludeSourceChannels].sort();\n }\n if (filter.computerAssetId) normalized.computerAssetId = filter.computerAssetId;\n if (filter.states && filter.states.length > 0) {\n normalized.states = [...filter.states].sort();\n }\n if (filter.agentIds && filter.agentIds.length > 0) {\n normalized.agentIds = [...filter.agentIds].sort();\n }\n if (filter.includeSubSessions) normalized.includeSubSessions = true;\n return normalized;\n}\n\n/** status_v2 run statuses during which a session is actively working. */\nconst RUNNING_RUN_STATUSES: ReadonlySet<string> = new Set(['queued', 'running']);\n\n/**\n * THE running rule for every conversation-list surface (sidebar pane, recent\n * dropdown, workspace section, pushed index rows): the canonical status_v2 run\n * status when the transport reports one, else the legacy `state`. A session\n * paused on a human gate (`needs_input`) is not running.\n */\nexport function isConversationRunning(summary: {\n runStatus?: string | null;\n state?: string | null;\n}): boolean {\n if (summary.runStatus !== null && summary.runStatus !== undefined) {\n return RUNNING_RUN_STATUSES.has(summary.runStatus);\n }\n return summary.state === 'running';\n}\n\nconst KNOWN_ATTENTIONS: ReadonlySet<string> = new Set(CONVERSATION_ATTENTIONS);\n\n/**\n * THE attention rule for every session-list surface: the server-derived\n * `attention` when the transport reports one it knows, else a client fallback\n * from the status planes so an older server still yields the two states a\n * list cannot do without — a human gate reads as `needs_you`, a live run as\n * `working`, a failed run as `error`. `null` when nothing applies.\n */\nexport function deriveConversationAttention(\n summary: Pick<ConversationSummary, 'attention' | 'runStatus' | 'sessionStatus' | 'state'>\n): ConversationAttention | null {\n if (typeof summary.attention === 'string' && KNOWN_ATTENTIONS.has(summary.attention)) {\n return summary.attention;\n }\n if (summary.runStatus === 'needs_input' || summary.sessionStatus === 'needs_input') {\n return 'needs_you';\n }\n if (isConversationRunning(summary)) return 'working';\n if (summary.runStatus === 'failed' || summary.sessionStatus === 'error') return 'error';\n return null;\n}\n\n/**\n * Stable cache identity for a filter: the normalized fields serialized in\n * sorted key order, so semantically equal filters share one cache entry.\n */\nexport function conversationListFilterKey(filter: ConversationListFilter): string {\n const normalized = normalizeConversationListFilter(filter) as Record<string, unknown>;\n return JSON.stringify(\n Object.keys(normalized)\n .sort()\n .map((key) => [key, normalized[key]])\n );\n}\n\n/**\n * Query keys for the two-tier pager. `scopeKey` isolates caches beyond the\n * filter — surfaces MUST include everything that changes whose list this is\n * (principal/user id, backend base URL) so a credential swap can never read\n * another identity's rows out of the cache.\n *\n * `pageSize` is part of the key because it is baked into every cached page's\n * offset boundaries: two hooks sharing a scope and filter but paging by\n * different sizes would otherwise reuse each other's incompatible boundaries\n * and skip or duplicate rows.\n */\nexport const conversationListQueryKeys = {\n root: [CONVERSATION_LIST_QUERY_KEY_ROOT] as const,\n scope: (scopeKey: string) => [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey] as const,\n firstPage: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'first-page'] as const,\n history: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'history'] as const,\n};\n\n/**\n * Flatten pages into one newest-first list, deduplicating by `threadId`.\n * The live first page wins over retained history copies of the same thread.\n */\nexport function mergeConversationPages(\n pages: readonly ConversationListPage[]\n): ConversationSummary[] {\n const seen = new Set<string>();\n const items: ConversationSummary[] = [];\n for (const page of pages) {\n for (const item of page.items) {\n if (seen.has(item.threadId)) continue;\n seen.add(item.threadId);\n items.push(item);\n }\n }\n return items;\n}\n\n/**\n * Prepend a conversation to a page unless its thread is already present\n * (optimistic \"new thread appears at the top\" write). Identity-preserving\n * no-op when present, so equal writes never notify subscribers.\n */\nexport function prependConversationToPage(\n page: ConversationListPage,\n item: ConversationSummary\n): ConversationListPage {\n if (page.items.some((existing) => existing.threadId === item.threadId)) return page;\n return {\n ...page,\n items: [item, ...page.items],\n totalCount: page.totalCount === null ? null : page.totalCount + 1,\n };\n}\n\n/** Remove a thread's row from a page; identity-preserving when absent. */\nexport function removeConversationFromPage(\n page: ConversationListPage,\n threadId: string\n): ConversationListPage {\n if (!page.items.some((item) => item.threadId === threadId)) return page;\n return { ...page, items: page.items.filter((item) => item.threadId !== threadId) };\n}\n\n/**\n * Patch every row matching `match`; identity-preserving when nothing matches\n * so cache writes cannot cause spurious re-renders.\n */\nexport function patchConversationsInPage(\n page: ConversationListPage,\n match: (item: ConversationSummary) => boolean,\n patch: Partial<ConversationSummary>\n): ConversationListPage {\n let changed = false;\n const items = page.items.map((item) => {\n if (!match(item)) return item;\n changed = true;\n return { ...item, ...patch };\n });\n return changed ? { ...page, items } : page;\n}\n\ntype CachedConversationList =\n | ConversationListPage\n | InfiniteData<ConversationListPage, number>\n | undefined;\n\nfunction isInfinitePages(\n data: ConversationListPage | InfiniteData<ConversationListPage, number>\n): data is InfiniteData<ConversationListPage, number> {\n return 'pages' in data;\n}\n\nfunction mapCachedPages(\n data: CachedConversationList,\n transform: (page: ConversationListPage) => ConversationListPage\n): CachedConversationList {\n if (!data) return data;\n if (isInfinitePages(data)) {\n let changed = false;\n const pages = data.pages.map((page) => {\n const next = transform(page);\n if (next !== page) changed = true;\n return next;\n });\n return changed ? { ...data, pages } : data;\n }\n return transform(data);\n}\n\ninterface ConversationListCacheScope {\n /** Restrict to one scope; omitted = every conversation-list cache. */\n scopeKey?: string;\n}\n\nfunction scopedKey(options?: ConversationListCacheScope): readonly string[] {\n return options?.scopeKey !== undefined\n ? conversationListQueryKeys.scope(options.scopeKey)\n : conversationListQueryKeys.root;\n}\n\n/**\n * Invalidate conversation-list caches (all filters, first page + history).\n * This is the hook for push signals — the conversation-index statewire, a\n * finished run, an archive/restore — anything that changed the server list.\n */\nexport function invalidateConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.invalidateQueries({ queryKey: scopedKey(options) });\n}\n\n/** Cancel in-flight list fetches so an optimistic write cannot be overwritten. */\nexport function cancelConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.cancelQueries({ queryKey: scopedKey(options) });\n}\n\n/**\n * Patch matching rows in every cached conversation list (first pages, history\n * pages, searches) so per-row state (read receipts, titles) flips in the same\n * frame as the interaction instead of after the next refetch.\n */\nexport function patchConversationListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & {\n match: (item: ConversationSummary) => boolean;\n patch: Partial<ConversationSummary>;\n }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => patchConversationsInPage(page, options.match, options.patch))\n );\n}\n\n/** Remove a thread's row from every cached conversation list in scope. */\nexport function removeConversationFromListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & { threadId: string }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => removeConversationFromPage(page, options.threadId))\n );\n}\n\nfunction timestampMs(value: string): number {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\nfunction sameSummary(a: ConversationSummary, b: ConversationSummary): boolean {\n return (\n a.threadId === b.threadId &&\n a.title === b.title &&\n a.updatedAt === b.updatedAt &&\n a.createdAt === b.createdAt &&\n a.state === b.state &&\n a.runtime === b.runtime &&\n a.sourceChannel === b.sourceChannel &&\n a.assetType === b.assetType &&\n a.assetId === b.assetId &&\n a.appId === b.appId &&\n a.triggerType === b.triggerType &&\n a.preview === b.preview &&\n a.messageCount === b.messageCount &&\n a.isUnread === b.isUnread &&\n a.sessionStatus === b.sessionStatus &&\n a.runStatus === b.runStatus &&\n a.attention === b.attention &&\n a.nextAction === b.nextAction &&\n a.attentionSource === b.attentionSource &&\n a.isFavorited === b.isFavorited &&\n // Never pushed by the index, so a fold carries the previous references\n // through unchanged; identity is the equality that matters here.\n a.lastWake === b.lastWake &&\n a.pullRequests === b.pullRequests\n );\n}\n\n/**\n * Project one replicated conversation-index row onto the shared summary shape.\n * Fields the index never carries (`createdAt`) and viewer-specific fields a\n * lifecycle publish cannot know (`is_unread: null`) keep the row's previous\n * value. Canonical status is taken from the entry when the publishing pod\n * reports it; a snapshot from a pod that predates the fields falls back to the\n * legacy `state` (null status) rather than keeping a stale run status.\n *\n * Attention fields (`attention`, `next_action`, `attention_source`,\n * `is_favorited`) are taken from the entry when the publishing pod reports\n * them, so a live push flips a row to \"needs you\" the way it renames it; a\n * pod that predates them leaves the row's previous values. Pull-request state\n * and the last wake are never pushed and always keep the fetched value.\n */\nexport function summaryFromConversationIndexEntry(\n entry: ConversationIndexEntry,\n previous?: ConversationSummary\n): ConversationSummary {\n const carriesStatus = entry.run_status !== undefined || entry.session_status !== undefined;\n return {\n threadId: entry.thread_id,\n title: entry.title,\n updatedAt: entry.updated_at,\n createdAt: previous?.createdAt ?? null,\n state: entry.state,\n runtime: entry.runtime,\n sourceChannel: entry.start_channel,\n assetType: entry.asset_type,\n assetId: entry.asset_id ?? previous?.assetId ?? null,\n computerAssetId: previous?.computerAssetId ?? null,\n appId: entry.app_id,\n triggerType: entry.trigger_type,\n preview: entry.last_message_preview,\n messageCount: entry.message_count,\n isUnread: entry.is_unread ?? previous?.isUnread ?? false,\n sessionStatus: carriesStatus ? (entry.session_status ?? null) : null,\n runStatus: carriesStatus ? (entry.run_status ?? null) : null,\n attention: entry.attention !== undefined ? entry.attention : previous?.attention,\n nextAction: entry.next_action !== undefined ? entry.next_action : previous?.nextAction,\n attentionSource:\n entry.attention_source !== undefined ? entry.attention_source : previous?.attentionSource,\n isFavorited: entry.is_favorited ?? previous?.isFavorited,\n lastWake: previous?.lastWake,\n pullRequests: previous?.pullRequests,\n };\n}\n\n/**\n * Fold the user's replicated conversation index (the newest-page window the\n * per-user statewire pushes) into a cached live first page, so a thread\n * created, renamed, finished, or read anywhere updates every list surface in\n * the same frame — without refetching the page.\n *\n * - Rows in the window are upserted (new threads appear, existing rows take\n * the pushed fields, see {@link summaryFromConversationIndexEntry}).\n * - Rows NOT in the window but at least as new as the window's oldest row\n * should have been in it, so they left the list (archived, hidden, shared\n * away) and are dropped. Older rows are beyond the window and are kept.\n * - When the index reports no further rows (`indexHasMore === false`) the\n * window IS the whole list, so every row outside it is dropped.\n *\n * Newest-first ordering is restored and the page identity is preserved when\n * nothing changed, so an equal push never notifies subscribers.\n */\nexport function mergeConversationIndexIntoPage(\n page: ConversationListPage,\n entries: readonly ConversationIndexEntry[],\n options: { indexHasMore: boolean }\n): ConversationListPage {\n const previousByThread = new Map(page.items.map((item) => [item.threadId, item]));\n const inWindow = new Set(entries.map((entry) => entry.thread_id));\n const windowTailMs =\n entries.length > 0 ? Math.min(...entries.map((entry) => timestampMs(entry.updated_at))) : null;\n\n const merged: ConversationSummary[] = entries.map((entry) => {\n const previous = previousByThread.get(entry.thread_id);\n const next = summaryFromConversationIndexEntry(entry, previous);\n return previous && sameSummary(previous, next) ? previous : next;\n });\n\n for (const item of page.items) {\n if (inWindow.has(item.threadId)) continue;\n if (!options.indexHasMore) continue;\n if (windowTailMs !== null && timestampMs(item.updatedAt) >= windowTailMs) continue;\n merged.push(item);\n }\n\n merged.sort((a, b) => timestampMs(b.updatedAt) - timestampMs(a.updatedAt));\n\n const unchanged =\n merged.length === page.items.length &&\n merged.every((item, index) => item === page.items[index]);\n if (unchanged) return page;\n\n return { ...page, items: merged };\n}\n"],"names":[],"mappings":";;AAoBO,MAAM,0BAA4D;AAAA,EACvE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8LO,MAAM,mCAAmC;AAOzC,MAAM,sCAAsC;AAQ5C,SAAS,gCACd,QACwB;AACxB,QAAM,aAAqC,CAAA;AAC3C,MAAI,OAAO,MAAO,YAAW,QAAQ,OAAO;AAC5C,MAAI,OAAO,cAAc,OAAO,WAAW,SAAS,GAAG;AACrD,eAAW,aAAa,CAAC,GAAG,OAAO,UAAU,EAAE,KAAA;AAAA,EACjD;AACA,MAAI,OAAO,OAAQ,YAAW,SAAS,OAAO;AAC9C,MAAI,OAAO,qBAAqB,OAAW,YAAW,mBAAmB,OAAO;AAChF,MAAI,OAAO,kBAAkB,OAAO,eAAe,SAAS,GAAG;AAC7D,eAAW,iBAAiB,CAAC,GAAG,OAAO,cAAc,EAAE,KAAA;AAAA,EACzD;AACA,MAAI,OAAO,yBAAyB,OAAO,sBAAsB,SAAS,GAAG;AAC3E,eAAW,wBAAwB,CAAC,GAAG,OAAO,qBAAqB,EAAE,KAAA;AAAA,EACvE;AACA,MAAI,OAAO,gBAAiB,YAAW,kBAAkB,OAAO;AAChE,MAAI,OAAO,UAAU,OAAO,OAAO,SAAS,GAAG;AAC7C,eAAW,SA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AG;AACvE;AAqFO,SAAS,kCACd,OACA,UACqB;AACrB,QAAM,gBAAgB,MAAM,eAAe,UAAa,MAAM,mBAAmB;AACjF,SAAO;AAAA,IACL,UAAU,MAAM;AAAA,IAChB,OAAO,MAAM;AAAA,IACb,WAAW,MAAM;AAAA,IACjB,YAAW,qCAAU,cAAa;AAAA,IAClC,OAAO,MAAM;AAAA,IACb,SAAS,MAAM;AAAA,IACf,eAAe,MAAM;AAAA,IACrB,WAAW,MAAM;AAAA,IACjB,SAAS,MAAM,aAAY,qCAAU,YAAW;AAAA,IAChD,kBAAiB,qCAAU,oBAAmB;AAAA,IAC9C,OAAO,MAAM;AAAA,IACb,aAAa,MAAM;AAAA,IACnB,SAAS,MAAM;AAAA,IACf,cAAc,MAAM;AAAA,IACpB,UAAU,MAAM,cAAa,qCAAU,aAAY;AAAA,IACnD,eAAe,gBAAiB,MAAM,kBAAkB,OAAQ;AAAA,IAChE,WAAW,gBAAiB,MAAM,cAAc,OAAQ;AAAA,IACxD,WAAW,MAAM,cAAc,SAAY,MAAM,YAAY,qCAAU;AAAA,IACvE,YAAY,MAAM,gBAAgB,SAAY,MAAM,cAAc,qCAAU;AAAA,IAC5E,iBACE,MAAM,qBAAqB,SAAY,MAAM,mBAAmB,qCAAU;AAAA,IAC5E,aAAa,MAAM,iBAAgB,qCAAU;AAAA,IAC7C,UAAU,qCAAU;AAAA,IACpB,cAAc,qCAAU;AAAA,EAAA;AAE5B;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"conversation-list.cjs","sources":["../../../../../agent-runtime/src/conversation-list.ts"],"sourcesContent":["import type { InfiniteData, QueryClient } from '@tanstack/react-query';\nimport type { ConversationIndexEntry } from './conversation-index';\n\n/**\n * What a session asks of the viewer, derived server-side from the run, the\n * parked interrupt, the pull requests it opened, its termination and its last\n * wake (the Devin-style session list). `needs_you` is the only state that\n * demands the viewer act; `working` is live; `ready` finished with something\n * to look at; `watching` waits on an external party (a review, a check);\n * `done` and `error` are terminal. A backend newer than this client may report\n * a value outside the union — render it as \"no attention\" rather than failing.\n */\nexport type ConversationAttention =\n | 'needs_you'\n | 'working'\n | 'ready'\n | 'watching'\n | 'done'\n | 'error';\n\nexport const CONVERSATION_ATTENTIONS: readonly ConversationAttention[] = [\n 'needs_you',\n 'working',\n 'ready',\n 'watching',\n 'done',\n 'error',\n];\n\n/** Which signal produced the attention state (and the `nextAction` copy). */\nexport type ConversationAttentionSource =\n | 'interrupt'\n | 'run'\n | 'pull_request'\n | 'termination'\n | 'wake'\n | 'handoff'\n | 'follow_up';\n\n/** The last event that woke a resting session (a GitHub webhook, a schedule, a handoff). */\nexport interface ConversationWake {\n source: string | null;\n reason: string | null;\n /** ISO 8601 timestamp of the wake. */\n at: string | null;\n}\n\n/**\n * Live GitHub state of a pull request the session opened, read by the server\n * when the list renders. Never pushed by the conversation index — it comes\n * from the list fetch only, so a fold keeps the fetched value.\n */\nexport interface ConversationPullRequest {\n /** `owner/repo` the pull request lives in. */\n repoFullName: string;\n number: number;\n url: string;\n title: string;\n state: 'OPEN' | 'CLOSED' | 'MERGED';\n isDraft: boolean;\n /** GitHub's review decision (APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED) or null. */\n reviewDecision: string | null;\n /** Combined state of the checks on the head commit. */\n checksState: 'SUCCESS' | 'FAILURE' | 'PENDING' | 'NONE';\n /** ISO 8601 timestamp of the pull request's last update on GitHub. */\n updatedAt: string;\n}\n\n/**\n * Shared conversation/thread LIST contract (chat-stack unification —\n * thread-list-contract-convergence).\n *\n * Every chat surface lists \"my conversations\" against the same underlying\n * session assets, but historically each declared its own row shape, paging\n * model, and filter set (Olympus GraphQL `listConversations`, the SDK/Chrome\n * REST `/api/conversations/threads/list`, mobile's `/api/v0/sessions`). This\n * module is the ONE contract those surfaces converge on:\n *\n * - **Row shape**: {@link ConversationSummary} — the canonical camelCase\n * superset. Fields a transport cannot supply are `null`, never invented.\n * - **Ordering**: newest first by `updatedAt`, always. Ordering is part of the\n * contract, not a parameter — no surface sorts any other way.\n * - **Paging**: offset/limit with a LIVE newest page and explicitly-fetched\n * frozen history pages (see `useConversationList`). `hasMore` continues the\n * scan; `totalCount` is advisory and may be `null` for transports that do\n * not count.\n * - **Filtering**: {@link ConversationListFilter}. `appId` follows\n * `docs/SESSION_APP_ID_GUIDE.md`: exact match when set (legacy `null`\n * sessions excluded), no filter when unset. A fetcher that cannot express a\n * requested filter field MUST throw rather than silently ignore it — a\n * dropped filter returns wrong rows under a cache key that claims otherwise.\n * - **Freshness**: the per-user conversation-index statewire\n * (`conversation-index.ts`) is the push signal; these queries are the data\n * source. Push handlers call {@link invalidateConversationListCaches}.\n */\nexport interface ConversationSummary {\n /** LangGraph thread id — the cross-surface conversation identity. */\n threadId: string;\n title: string;\n /** ISO 8601 timestamp of last update (the contract's sort key). */\n updatedAt: string;\n /** ISO 8601 creation timestamp, when the transport reports it. */\n createdAt: string | null;\n /** Session lifecycle state from athena_metadata (e.g. running, completed). */\n state: string | null;\n /** Agent runtime marker (e.g. 'athena_deep_agent'), when reported. */\n runtime: string | null;\n /** Channel the session was started from (e.g. agent_email, web). */\n sourceChannel: string | null;\n /** Asset type (session, video_session, desktop_session, mobile_session). */\n assetType: string | null;\n /** Session asset id (`asset_<uuid>`), when the transport reports it. */\n assetId: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Computer asset whose sandbox started the session (`sourceChannel` 'computer'); omitted by surfaces that don't carry it. */\n computerAssetId?: string | null;\n /** Session asset id this row is a sub-session of; omitted by surfaces that don't carry it. */\n parentSessionId?: string | null;\n /** Sub-sessions of this row the viewer can see; omitted by surfaces that don't carry it. */\n subSessionCount?: number;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Last-message preview used when a legacy session has no useful title. */\n preview: string | null;\n messageCount: number | null;\n /** Per-user unread flag derived server-side from the read receipt. */\n isUnread: boolean;\n /**\n * Canonical session status (status_v2: idle | active | needs_input | error),\n * or null when the transport does not report it.\n */\n sessionStatus: string | null;\n /**\n * Canonical status of the session's current run (status_v2: scheduled |\n * queued | running | needs_input | completed | failed | canceled). Null when\n * the transport does not report it — {@link isConversationRunning} then\n * falls back to the legacy `state`. Running badges on every surface derive\n * from this one helper so they cannot disagree.\n */\n runStatus: string | null;\n /**\n * Server-derived attention state. `undefined` when the transport (or an\n * older server) does not report it — {@link deriveConversationAttention}\n * then falls back to the status planes; `null` when the server reports none.\n */\n attention?: ConversationAttention | null;\n /** One line (≤ 80 chars) of what the viewer should do next, when the server derives one. */\n nextAction?: string | null;\n /** Which signal produced `attention` / `nextAction`. */\n attentionSource?: ConversationAttentionSource | null;\n /** Whether the viewer pinned (favorited) the session; `undefined` when not reported. */\n isFavorited?: boolean;\n /** The last wake of a resting session; `undefined` when not reported. */\n lastWake?: ConversationWake | null;\n /**\n * Pull requests the session opened with their live GitHub state. `[]` when\n * it opened none, `null` when the state could not be read right now,\n * `undefined` when the transport did not ask for (or report) it.\n */\n pullRequests?: ConversationPullRequest[] | null;\n}\n\n/**\n * The canonical filter set. Semantics are defined here once; each fetcher\n * translates the fields its transport supports and throws on the rest.\n */\nexport interface ConversationListFilter {\n /** Exact-match client app filter; unset = all apps (SESSION_APP_ID_GUIDE). */\n appId?: string;\n /** Asset types to include (e.g. ['session']); unset = all session types. */\n assetTypes?: readonly string[];\n /** Case-insensitive title search. */\n search?: string;\n /** Hide triggered/background sessions (REST thread list only today). */\n excludeTriggered?: boolean;\n /** Start-channel filter (v0 sessions / REST thread list only today). */\n sourceChannels?: readonly string[];\n /** Start channels to hide (e.g. ['api']); GraphQL `listConversations` only today. */\n excludeSourceChannels?: readonly string[];\n /** Exact computer asset whose sandbox started the session; GraphQL `listConversations` only today. */\n computerAssetId?: string;\n /** Only the sub-sessions of this session asset id; GraphQL `listConversations` only today. */\n parentSessionId?: string;\n /**\n * Lifecycle-state filter (e.g. ['running'], ['completed']). Transports match\n * it with the shared status_v2 rule (running carries a 12-hour recency cutoff).\n */\n states?: readonly string[];\n /** Restrict to sessions run by any of these agents (athena_metadata.agent). */\n agentIds?: readonly string[];\n /**\n * Include branched sub-sessions and orchestration children, which every list\n * hides by default because they belong under their parent thread.\n */\n includeSubSessions?: boolean;\n}\n\nexport interface ConversationListPage {\n /** Rows in contract order (updatedAt desc). */\n items: ConversationSummary[];\n /** Whether another `offset + limit` scan would return more rows. */\n hasMore: boolean;\n /** Total matching rows, or null when the transport does not count. */\n totalCount: number | null;\n}\n\nexport interface ConversationListFetchParams {\n limit: number;\n offset: number;\n filter: ConversationListFilter;\n signal?: AbortSignal;\n}\n\n/**\n * One page fetch against some transport (GraphQL `listConversations`, the\n * REST thread list, …). Must reject on filter fields it cannot express.\n */\nexport type ConversationListFetcher = (\n params: ConversationListFetchParams\n) => Promise<ConversationListPage>;\n\n/** Root of every conversation-list query key (all surfaces, all filters). */\nexport const CONVERSATION_LIST_QUERY_KEY_ROOT = 'athena-conversation-list';\n\n/**\n * Scope used by `useConversationList` when the caller passes no `scopeKey`.\n * Exported so cache seeders (e.g. Olympus's spacesBootstrap adoption) can\n * address the exact keys default-scoped hooks read from.\n */\nexport const CONVERSATION_LIST_DEFAULT_SCOPE_KEY = 'default';\n\n/**\n * Normalize a filter to its semantic content: unset/empty fields are dropped\n * (so `{}` and `{ appId: undefined }` are the same filter) and array order is\n * canonicalized. Fetchers receive the normalized form, so what a cache entry\n * claims to hold is exactly what was fetched.\n */\nexport function normalizeConversationListFilter(\n filter: ConversationListFilter\n): ConversationListFilter {\n const normalized: ConversationListFilter = {};\n if (filter.appId) normalized.appId = filter.appId;\n if (filter.assetTypes && filter.assetTypes.length > 0) {\n normalized.assetTypes = [...filter.assetTypes].sort();\n }\n if (filter.search) normalized.search = filter.search;\n if (filter.excludeTriggered !== undefined) normalized.excludeTriggered = filter.excludeTriggered;\n if (filter.sourceChannels && filter.sourceChannels.length > 0) {\n normalized.sourceChannels = [...filter.sourceChannels].sort();\n }\n if (filter.excludeSourceChannels && filter.excludeSourceChannels.length > 0) {\n normalized.excludeSourceChannels = [...filter.excludeSourceChannels].sort();\n }\n if (filter.computerAssetId) normalized.computerAssetId = filter.computerAssetId;\n if (filter.parentSessionId) normalized.parentSessionId = filter.parentSessionId;\n if (filter.states && filter.states.length > 0) {\n normalized.states = [...filter.states].sort();\n }\n if (filter.agentIds && filter.agentIds.length > 0) {\n normalized.agentIds = [...filter.agentIds].sort();\n }\n if (filter.includeSubSessions) normalized.includeSubSessions = true;\n return normalized;\n}\n\n/** status_v2 run statuses during which a session is actively working. */\nconst RUNNING_RUN_STATUSES: ReadonlySet<string> = new Set(['queued', 'running']);\n\n/**\n * THE running rule for every conversation-list surface (sidebar pane, recent\n * dropdown, workspace section, pushed index rows): the canonical status_v2 run\n * status when the transport reports one, else the legacy `state`. A session\n * paused on a human gate (`needs_input`) is not running.\n */\nexport function isConversationRunning(summary: {\n runStatus?: string | null;\n state?: string | null;\n}): boolean {\n if (summary.runStatus !== null && summary.runStatus !== undefined) {\n return RUNNING_RUN_STATUSES.has(summary.runStatus);\n }\n return summary.state === 'running';\n}\n\nconst KNOWN_ATTENTIONS: ReadonlySet<string> = new Set(CONVERSATION_ATTENTIONS);\n\n/**\n * THE attention rule for every session-list surface: the server-derived\n * `attention` when the transport reports one it knows, else a client fallback\n * from the status planes so an older server still yields the two states a\n * list cannot do without — a human gate reads as `needs_you`, a live run as\n * `working`, a failed run as `error`. `null` when nothing applies.\n */\nexport function deriveConversationAttention(\n summary: Pick<ConversationSummary, 'attention' | 'runStatus' | 'sessionStatus' | 'state'>\n): ConversationAttention | null {\n if (typeof summary.attention === 'string' && KNOWN_ATTENTIONS.has(summary.attention)) {\n return summary.attention;\n }\n if (summary.runStatus === 'needs_input' || summary.sessionStatus === 'needs_input') {\n return 'needs_you';\n }\n if (isConversationRunning(summary)) return 'working';\n if (summary.runStatus === 'failed' || summary.sessionStatus === 'error') return 'error';\n return null;\n}\n\n/**\n * Stable cache identity for a filter: the normalized fields serialized in\n * sorted key order, so semantically equal filters share one cache entry.\n */\nexport function conversationListFilterKey(filter: ConversationListFilter): string {\n const normalized = normalizeConversationListFilter(filter) as Record<string, unknown>;\n return JSON.stringify(\n Object.keys(normalized)\n .sort()\n .map((key) => [key, normalized[key]])\n );\n}\n\n/**\n * Query keys for the two-tier pager. `scopeKey` isolates caches beyond the\n * filter — surfaces MUST include everything that changes whose list this is\n * (principal/user id, backend base URL) so a credential swap can never read\n * another identity's rows out of the cache.\n *\n * `pageSize` is part of the key because it is baked into every cached page's\n * offset boundaries: two hooks sharing a scope and filter but paging by\n * different sizes would otherwise reuse each other's incompatible boundaries\n * and skip or duplicate rows.\n */\nexport const conversationListQueryKeys = {\n root: [CONVERSATION_LIST_QUERY_KEY_ROOT] as const,\n scope: (scopeKey: string) => [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey] as const,\n firstPage: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'first-page'] as const,\n history: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'history'] as const,\n};\n\n/**\n * Flatten pages into one newest-first list, deduplicating by `threadId`.\n * The live first page wins over retained history copies of the same thread.\n */\nexport function mergeConversationPages(\n pages: readonly ConversationListPage[]\n): ConversationSummary[] {\n const seen = new Set<string>();\n const items: ConversationSummary[] = [];\n for (const page of pages) {\n for (const item of page.items) {\n if (seen.has(item.threadId)) continue;\n seen.add(item.threadId);\n items.push(item);\n }\n }\n return items;\n}\n\n/**\n * Prepend a conversation to a page unless its thread is already present\n * (optimistic \"new thread appears at the top\" write). Identity-preserving\n * no-op when present, so equal writes never notify subscribers.\n */\nexport function prependConversationToPage(\n page: ConversationListPage,\n item: ConversationSummary\n): ConversationListPage {\n if (page.items.some((existing) => existing.threadId === item.threadId)) return page;\n return {\n ...page,\n items: [item, ...page.items],\n totalCount: page.totalCount === null ? null : page.totalCount + 1,\n };\n}\n\n/** Remove a thread's row from a page; identity-preserving when absent. */\nexport function removeConversationFromPage(\n page: ConversationListPage,\n threadId: string\n): ConversationListPage {\n if (!page.items.some((item) => item.threadId === threadId)) return page;\n return { ...page, items: page.items.filter((item) => item.threadId !== threadId) };\n}\n\n/**\n * Patch every row matching `match`; identity-preserving when nothing matches\n * so cache writes cannot cause spurious re-renders.\n */\nexport function patchConversationsInPage(\n page: ConversationListPage,\n match: (item: ConversationSummary) => boolean,\n patch: Partial<ConversationSummary>\n): ConversationListPage {\n let changed = false;\n const items = page.items.map((item) => {\n if (!match(item)) return item;\n changed = true;\n return { ...item, ...patch };\n });\n return changed ? { ...page, items } : page;\n}\n\ntype CachedConversationList =\n | ConversationListPage\n | InfiniteData<ConversationListPage, number>\n | undefined;\n\nfunction isInfinitePages(\n data: ConversationListPage | InfiniteData<ConversationListPage, number>\n): data is InfiniteData<ConversationListPage, number> {\n return 'pages' in data;\n}\n\nfunction mapCachedPages(\n data: CachedConversationList,\n transform: (page: ConversationListPage) => ConversationListPage\n): CachedConversationList {\n if (!data) return data;\n if (isInfinitePages(data)) {\n let changed = false;\n const pages = data.pages.map((page) => {\n const next = transform(page);\n if (next !== page) changed = true;\n return next;\n });\n return changed ? { ...data, pages } : data;\n }\n return transform(data);\n}\n\ninterface ConversationListCacheScope {\n /** Restrict to one scope; omitted = every conversation-list cache. */\n scopeKey?: string;\n}\n\nfunction scopedKey(options?: ConversationListCacheScope): readonly string[] {\n return options?.scopeKey !== undefined\n ? conversationListQueryKeys.scope(options.scopeKey)\n : conversationListQueryKeys.root;\n}\n\n/**\n * Invalidate conversation-list caches (all filters, first page + history).\n * This is the hook for push signals — the conversation-index statewire, a\n * finished run, an archive/restore — anything that changed the server list.\n */\nexport function invalidateConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.invalidateQueries({ queryKey: scopedKey(options) });\n}\n\n/** Cancel in-flight list fetches so an optimistic write cannot be overwritten. */\nexport function cancelConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.cancelQueries({ queryKey: scopedKey(options) });\n}\n\n/**\n * Patch matching rows in every cached conversation list (first pages, history\n * pages, searches) so per-row state (read receipts, titles) flips in the same\n * frame as the interaction instead of after the next refetch.\n */\nexport function patchConversationListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & {\n match: (item: ConversationSummary) => boolean;\n patch: Partial<ConversationSummary>;\n }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => patchConversationsInPage(page, options.match, options.patch))\n );\n}\n\n/** Remove a thread's row from every cached conversation list in scope. */\nexport function removeConversationFromListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & { threadId: string }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => removeConversationFromPage(page, options.threadId))\n );\n}\n\nfunction timestampMs(value: string): number {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\nfunction sameSummary(a: ConversationSummary, b: ConversationSummary): boolean {\n return (\n a.threadId === b.threadId &&\n a.title === b.title &&\n a.updatedAt === b.updatedAt &&\n a.createdAt === b.createdAt &&\n a.state === b.state &&\n a.runtime === b.runtime &&\n a.sourceChannel === b.sourceChannel &&\n a.assetType === b.assetType &&\n a.assetId === b.assetId &&\n a.appId === b.appId &&\n a.triggerType === b.triggerType &&\n a.preview === b.preview &&\n a.messageCount === b.messageCount &&\n a.isUnread === b.isUnread &&\n a.sessionStatus === b.sessionStatus &&\n a.runStatus === b.runStatus &&\n a.attention === b.attention &&\n a.nextAction === b.nextAction &&\n a.attentionSource === b.attentionSource &&\n a.isFavorited === b.isFavorited &&\n // Never pushed by the index, so a fold carries the previous references\n // through unchanged; identity is the equality that matters here.\n a.lastWake === b.lastWake &&\n a.pullRequests === b.pullRequests\n );\n}\n\n/**\n * Project one replicated conversation-index row onto the shared summary shape.\n * Fields the index never carries (`createdAt`) and viewer-specific fields a\n * lifecycle publish cannot know (`is_unread: null`) keep the row's previous\n * value. Canonical status is taken from the entry when the publishing pod\n * reports it; a snapshot from a pod that predates the fields falls back to the\n * legacy `state` (null status) rather than keeping a stale run status.\n *\n * Attention fields (`attention`, `next_action`, `attention_source`,\n * `is_favorited`) are taken from the entry when the publishing pod reports\n * them, so a live push flips a row to \"needs you\" the way it renames it; a\n * pod that predates them leaves the row's previous values. Pull-request state\n * and the last wake are never pushed and always keep the fetched value.\n */\nexport function summaryFromConversationIndexEntry(\n entry: ConversationIndexEntry,\n previous?: ConversationSummary\n): ConversationSummary {\n const carriesStatus = entry.run_status !== undefined || entry.session_status !== undefined;\n return {\n threadId: entry.thread_id,\n title: entry.title,\n updatedAt: entry.updated_at,\n createdAt: previous?.createdAt ?? null,\n state: entry.state,\n runtime: entry.runtime,\n sourceChannel: entry.start_channel,\n assetType: entry.asset_type,\n assetId: entry.asset_id ?? previous?.assetId ?? null,\n computerAssetId: previous?.computerAssetId ?? null,\n parentSessionId: previous?.parentSessionId,\n subSessionCount: previous?.subSessionCount,\n appId: entry.app_id,\n triggerType: entry.trigger_type,\n preview: entry.last_message_preview,\n messageCount: entry.message_count,\n isUnread: entry.is_unread ?? previous?.isUnread ?? false,\n sessionStatus: carriesStatus ? (entry.session_status ?? null) : null,\n runStatus: carriesStatus ? (entry.run_status ?? null) : null,\n attention: entry.attention !== undefined ? entry.attention : previous?.attention,\n nextAction: entry.next_action !== undefined ? entry.next_action : previous?.nextAction,\n attentionSource:\n entry.attention_source !== undefined ? entry.attention_source : previous?.attentionSource,\n isFavorited: entry.is_favorited ?? previous?.isFavorited,\n lastWake: previous?.lastWake,\n pullRequests: previous?.pullRequests,\n };\n}\n\n/**\n * Fold the user's replicated conversation index (the newest-page window the\n * per-user statewire pushes) into a cached live first page, so a thread\n * created, renamed, finished, or read anywhere updates every list surface in\n * the same frame — without refetching the page.\n *\n * - Rows in the window are upserted (new threads appear, existing rows take\n * the pushed fields, see {@link summaryFromConversationIndexEntry}).\n * - Rows NOT in the window but at least as new as the window's oldest row\n * should have been in it, so they left the list (archived, hidden, shared\n * away) and are dropped. Older rows are beyond the window and are kept.\n * - When the index reports no further rows (`indexHasMore === false`) the\n * window IS the whole list, so every row outside it is dropped.\n *\n * Newest-first ordering is restored and the page identity is preserved when\n * nothing changed, so an equal push never notifies subscribers.\n */\nexport function mergeConversationIndexIntoPage(\n page: ConversationListPage,\n entries: readonly ConversationIndexEntry[],\n options: { indexHasMore: boolean }\n): ConversationListPage {\n const previousByThread = new Map(page.items.map((item) => [item.threadId, item]));\n const inWindow = new Set(entries.map((entry) => entry.thread_id));\n const windowTailMs =\n entries.length > 0 ? Math.min(...entries.map((entry) => timestampMs(entry.updated_at))) : null;\n\n const merged: ConversationSummary[] = entries.map((entry) => {\n const previous = previousByThread.get(entry.thread_id);\n const next = summaryFromConversationIndexEntry(entry, previous);\n return previous && sameSummary(previous, next) ? previous : next;\n });\n\n for (const item of page.items) {\n if (inWindow.has(item.threadId)) continue;\n if (!options.indexHasMore) continue;\n if (windowTailMs !== null && timestampMs(item.updatedAt) >= windowTailMs) continue;\n merged.push(item);\n }\n\n merged.sort((a, b) => timestampMs(b.updatedAt) - timestampMs(a.updatedAt));\n\n const unchanged =\n merged.length === page.items.length &&\n merged.every((item, index) => item === page.items[index]);\n if (unchanged) return page;\n\n return { ...page, items: merged };\n}\n"],"names":[],"mappings":";;AAoBO,MAAM,0BAA4D;AAAA,EACvE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAoMO,MAAM,mCAAmC;AAOzC,MAAM,sCAAsC;AAQ5C,SAAS,gCACd,QACwB;AACxB,QAAM,aAAqC,CAAA;AAC3C,MAAI,OAAO,MAAO,YAAW,QAAQ,OAAO;AAC5C,MAAI,OAAO,cAAc,OAAO,WAAW,SAAS,GAAG;AACrD,eAAW,aAAa,CAAC,GA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Ac,SAAY,MAAM,YAAY,qCAAU;AAAA,IACvE,YAAY,MAAM,gBAAgB,SAAY,MAAM,cAAc,qCAAU;AAAA,IAC5E,iBACE,MAAM,qBAAqB,SAAY,MAAM,mBAAmB,qCAAU;AAAA,IAC5E,aAAa,MAAM,iBAAgB,qCAAU;AAAA,IAC7C,UAAU,qCAAU;AAAA,IACpB,cAAc,qCAAU;AAAA,EAAA;AAE5B;;;;;;;;;;;;;;;"}
|
|
@@ -23,6 +23,7 @@ function normalizeConversationListFilter(filter) {
|
|
|
23
23
|
normalized.excludeSourceChannels = [...filter.excludeSourceChannels].sort();
|
|
24
24
|
}
|
|
25
25
|
if (filter.computerAssetId) normalized.computerAssetId = filter.computerAssetId;
|
|
26
|
+
if (filter.parentSessionId) normalized.parentSessionId = filter.parentSessionId;
|
|
26
27
|
if (filter.states && filter.states.length > 0) {
|
|
27
28
|
normalized.states = [...filter.states].sort();
|
|
28
29
|
}
|
|
@@ -115,6 +116,8 @@ function summaryFromConversationIndexEntry(entry, previous) {
|
|
|
115
116
|
assetType: entry.asset_type,
|
|
116
117
|
assetId: entry.asset_id ?? (previous == null ? void 0 : previous.assetId) ?? null,
|
|
117
118
|
computerAssetId: (previous == null ? void 0 : previous.computerAssetId) ?? null,
|
|
119
|
+
parentSessionId: previous == null ? void 0 : previous.parentSessionId,
|
|
120
|
+
subSessionCount: previous == null ? void 0 : previous.subSessionCount,
|
|
118
121
|
appId: entry.app_id,
|
|
119
122
|
triggerType: entry.trigger_type,
|
|
120
123
|
preview: entry.last_message_preview,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-list.js","sources":["../../../../../agent-runtime/src/conversation-list.ts"],"sourcesContent":["import type { InfiniteData, QueryClient } from '@tanstack/react-query';\nimport type { ConversationIndexEntry } from './conversation-index';\n\n/**\n * What a session asks of the viewer, derived server-side from the run, the\n * parked interrupt, the pull requests it opened, its termination and its last\n * wake (the Devin-style session list). `needs_you` is the only state that\n * demands the viewer act; `working` is live; `ready` finished with something\n * to look at; `watching` waits on an external party (a review, a check);\n * `done` and `error` are terminal. A backend newer than this client may report\n * a value outside the union — render it as \"no attention\" rather than failing.\n */\nexport type ConversationAttention =\n | 'needs_you'\n | 'working'\n | 'ready'\n | 'watching'\n | 'done'\n | 'error';\n\nexport const CONVERSATION_ATTENTIONS: readonly ConversationAttention[] = [\n 'needs_you',\n 'working',\n 'ready',\n 'watching',\n 'done',\n 'error',\n];\n\n/** Which signal produced the attention state (and the `nextAction` copy). */\nexport type ConversationAttentionSource =\n | 'interrupt'\n | 'run'\n | 'pull_request'\n | 'termination'\n | 'wake'\n | 'handoff'\n | 'follow_up';\n\n/** The last event that woke a resting session (a GitHub webhook, a schedule, a handoff). */\nexport interface ConversationWake {\n source: string | null;\n reason: string | null;\n /** ISO 8601 timestamp of the wake. */\n at: string | null;\n}\n\n/**\n * Live GitHub state of a pull request the session opened, read by the server\n * when the list renders. Never pushed by the conversation index — it comes\n * from the list fetch only, so a fold keeps the fetched value.\n */\nexport interface ConversationPullRequest {\n /** `owner/repo` the pull request lives in. */\n repoFullName: string;\n number: number;\n url: string;\n title: string;\n state: 'OPEN' | 'CLOSED' | 'MERGED';\n isDraft: boolean;\n /** GitHub's review decision (APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED) or null. */\n reviewDecision: string | null;\n /** Combined state of the checks on the head commit. */\n checksState: 'SUCCESS' | 'FAILURE' | 'PENDING' | 'NONE';\n /** ISO 8601 timestamp of the pull request's last update on GitHub. */\n updatedAt: string;\n}\n\n/**\n * Shared conversation/thread LIST contract (chat-stack unification —\n * thread-list-contract-convergence).\n *\n * Every chat surface lists \"my conversations\" against the same underlying\n * session assets, but historically each declared its own row shape, paging\n * model, and filter set (Olympus GraphQL `listConversations`, the SDK/Chrome\n * REST `/api/conversations/threads/list`, mobile's `/api/v0/sessions`). This\n * module is the ONE contract those surfaces converge on:\n *\n * - **Row shape**: {@link ConversationSummary} — the canonical camelCase\n * superset. Fields a transport cannot supply are `null`, never invented.\n * - **Ordering**: newest first by `updatedAt`, always. Ordering is part of the\n * contract, not a parameter — no surface sorts any other way.\n * - **Paging**: offset/limit with a LIVE newest page and explicitly-fetched\n * frozen history pages (see `useConversationList`). `hasMore` continues the\n * scan; `totalCount` is advisory and may be `null` for transports that do\n * not count.\n * - **Filtering**: {@link ConversationListFilter}. `appId` follows\n * `docs/SESSION_APP_ID_GUIDE.md`: exact match when set (legacy `null`\n * sessions excluded), no filter when unset. A fetcher that cannot express a\n * requested filter field MUST throw rather than silently ignore it — a\n * dropped filter returns wrong rows under a cache key that claims otherwise.\n * - **Freshness**: the per-user conversation-index statewire\n * (`conversation-index.ts`) is the push signal; these queries are the data\n * source. Push handlers call {@link invalidateConversationListCaches}.\n */\nexport interface ConversationSummary {\n /** LangGraph thread id — the cross-surface conversation identity. */\n threadId: string;\n title: string;\n /** ISO 8601 timestamp of last update (the contract's sort key). */\n updatedAt: string;\n /** ISO 8601 creation timestamp, when the transport reports it. */\n createdAt: string | null;\n /** Session lifecycle state from athena_metadata (e.g. running, completed). */\n state: string | null;\n /** Agent runtime marker (e.g. 'athena_deep_agent'), when reported. */\n runtime: string | null;\n /** Channel the session was started from (e.g. agent_email, web). */\n sourceChannel: string | null;\n /** Asset type (session, video_session, desktop_session, mobile_session). */\n assetType: string | null;\n /** Session asset id (`asset_<uuid>`), when the transport reports it. */\n assetId: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Computer asset whose sandbox started the session (`sourceChannel` 'computer'); omitted by surfaces that don't carry it. */\n computerAssetId?: string | null;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Last-message preview used when a legacy session has no useful title. */\n preview: string | null;\n messageCount: number | null;\n /** Per-user unread flag derived server-side from the read receipt. */\n isUnread: boolean;\n /**\n * Canonical session status (status_v2: idle | active | needs_input | error),\n * or null when the transport does not report it.\n */\n sessionStatus: string | null;\n /**\n * Canonical status of the session's current run (status_v2: scheduled |\n * queued | running | needs_input | completed | failed | canceled). Null when\n * the transport does not report it — {@link isConversationRunning} then\n * falls back to the legacy `state`. Running badges on every surface derive\n * from this one helper so they cannot disagree.\n */\n runStatus: string | null;\n /**\n * Server-derived attention state. `undefined` when the transport (or an\n * older server) does not report it — {@link deriveConversationAttention}\n * then falls back to the status planes; `null` when the server reports none.\n */\n attention?: ConversationAttention | null;\n /** One line (≤ 80 chars) of what the viewer should do next, when the server derives one. */\n nextAction?: string | null;\n /** Which signal produced `attention` / `nextAction`. */\n attentionSource?: ConversationAttentionSource | null;\n /** Whether the viewer pinned (favorited) the session; `undefined` when not reported. */\n isFavorited?: boolean;\n /** The last wake of a resting session; `undefined` when not reported. */\n lastWake?: ConversationWake | null;\n /**\n * Pull requests the session opened with their live GitHub state. `[]` when\n * it opened none, `null` when the state could not be read right now,\n * `undefined` when the transport did not ask for (or report) it.\n */\n pullRequests?: ConversationPullRequest[] | null;\n}\n\n/**\n * The canonical filter set. Semantics are defined here once; each fetcher\n * translates the fields its transport supports and throws on the rest.\n */\nexport interface ConversationListFilter {\n /** Exact-match client app filter; unset = all apps (SESSION_APP_ID_GUIDE). */\n appId?: string;\n /** Asset types to include (e.g. ['session']); unset = all session types. */\n assetTypes?: readonly string[];\n /** Case-insensitive title search. */\n search?: string;\n /** Hide triggered/background sessions (REST thread list only today). */\n excludeTriggered?: boolean;\n /** Start-channel filter (v0 sessions / REST thread list only today). */\n sourceChannels?: readonly string[];\n /** Start channels to hide (e.g. ['api']); GraphQL `listConversations` only today. */\n excludeSourceChannels?: readonly string[];\n /** Exact computer asset whose sandbox started the session; GraphQL `listConversations` only today. */\n computerAssetId?: string;\n /**\n * Lifecycle-state filter (e.g. ['running'], ['completed']). Transports match\n * it with the shared status_v2 rule (running carries a 12-hour recency cutoff).\n */\n states?: readonly string[];\n /** Restrict to sessions run by any of these agents (athena_metadata.agent). */\n agentIds?: readonly string[];\n /**\n * Include branched sub-sessions and orchestration children, which every list\n * hides by default because they belong under their parent thread.\n */\n includeSubSessions?: boolean;\n}\n\nexport interface ConversationListPage {\n /** Rows in contract order (updatedAt desc). */\n items: ConversationSummary[];\n /** Whether another `offset + limit` scan would return more rows. */\n hasMore: boolean;\n /** Total matching rows, or null when the transport does not count. */\n totalCount: number | null;\n}\n\nexport interface ConversationListFetchParams {\n limit: number;\n offset: number;\n filter: ConversationListFilter;\n signal?: AbortSignal;\n}\n\n/**\n * One page fetch against some transport (GraphQL `listConversations`, the\n * REST thread list, …). Must reject on filter fields it cannot express.\n */\nexport type ConversationListFetcher = (\n params: ConversationListFetchParams\n) => Promise<ConversationListPage>;\n\n/** Root of every conversation-list query key (all surfaces, all filters). */\nexport const CONVERSATION_LIST_QUERY_KEY_ROOT = 'athena-conversation-list';\n\n/**\n * Scope used by `useConversationList` when the caller passes no `scopeKey`.\n * Exported so cache seeders (e.g. Olympus's spacesBootstrap adoption) can\n * address the exact keys default-scoped hooks read from.\n */\nexport const CONVERSATION_LIST_DEFAULT_SCOPE_KEY = 'default';\n\n/**\n * Normalize a filter to its semantic content: unset/empty fields are dropped\n * (so `{}` and `{ appId: undefined }` are the same filter) and array order is\n * canonicalized. Fetchers receive the normalized form, so what a cache entry\n * claims to hold is exactly what was fetched.\n */\nexport function normalizeConversationListFilter(\n filter: ConversationListFilter\n): ConversationListFilter {\n const normalized: ConversationListFilter = {};\n if (filter.appId) normalized.appId = filter.appId;\n if (filter.assetTypes && filter.assetTypes.length > 0) {\n normalized.assetTypes = [...filter.assetTypes].sort();\n }\n if (filter.search) normalized.search = filter.search;\n if (filter.excludeTriggered !== undefined) normalized.excludeTriggered = filter.excludeTriggered;\n if (filter.sourceChannels && filter.sourceChannels.length > 0) {\n normalized.sourceChannels = [...filter.sourceChannels].sort();\n }\n if (filter.excludeSourceChannels && filter.excludeSourceChannels.length > 0) {\n normalized.excludeSourceChannels = [...filter.excludeSourceChannels].sort();\n }\n if (filter.computerAssetId) normalized.computerAssetId = filter.computerAssetId;\n if (filter.states && filter.states.length > 0) {\n normalized.states = [...filter.states].sort();\n }\n if (filter.agentIds && filter.agentIds.length > 0) {\n normalized.agentIds = [...filter.agentIds].sort();\n }\n if (filter.includeSubSessions) normalized.includeSubSessions = true;\n return normalized;\n}\n\n/** status_v2 run statuses during which a session is actively working. */\nconst RUNNING_RUN_STATUSES: ReadonlySet<string> = new Set(['queued', 'running']);\n\n/**\n * THE running rule for every conversation-list surface (sidebar pane, recent\n * dropdown, workspace section, pushed index rows): the canonical status_v2 run\n * status when the transport reports one, else the legacy `state`. A session\n * paused on a human gate (`needs_input`) is not running.\n */\nexport function isConversationRunning(summary: {\n runStatus?: string | null;\n state?: string | null;\n}): boolean {\n if (summary.runStatus !== null && summary.runStatus !== undefined) {\n return RUNNING_RUN_STATUSES.has(summary.runStatus);\n }\n return summary.state === 'running';\n}\n\nconst KNOWN_ATTENTIONS: ReadonlySet<string> = new Set(CONVERSATION_ATTENTIONS);\n\n/**\n * THE attention rule for every session-list surface: the server-derived\n * `attention` when the transport reports one it knows, else a client fallback\n * from the status planes so an older server still yields the two states a\n * list cannot do without — a human gate reads as `needs_you`, a live run as\n * `working`, a failed run as `error`. `null` when nothing applies.\n */\nexport function deriveConversationAttention(\n summary: Pick<ConversationSummary, 'attention' | 'runStatus' | 'sessionStatus' | 'state'>\n): ConversationAttention | null {\n if (typeof summary.attention === 'string' && KNOWN_ATTENTIONS.has(summary.attention)) {\n return summary.attention;\n }\n if (summary.runStatus === 'needs_input' || summary.sessionStatus === 'needs_input') {\n return 'needs_you';\n }\n if (isConversationRunning(summary)) return 'working';\n if (summary.runStatus === 'failed' || summary.sessionStatus === 'error') return 'error';\n return null;\n}\n\n/**\n * Stable cache identity for a filter: the normalized fields serialized in\n * sorted key order, so semantically equal filters share one cache entry.\n */\nexport function conversationListFilterKey(filter: ConversationListFilter): string {\n const normalized = normalizeConversationListFilter(filter) as Record<string, unknown>;\n return JSON.stringify(\n Object.keys(normalized)\n .sort()\n .map((key) => [key, normalized[key]])\n );\n}\n\n/**\n * Query keys for the two-tier pager. `scopeKey` isolates caches beyond the\n * filter — surfaces MUST include everything that changes whose list this is\n * (principal/user id, backend base URL) so a credential swap can never read\n * another identity's rows out of the cache.\n *\n * `pageSize` is part of the key because it is baked into every cached page's\n * offset boundaries: two hooks sharing a scope and filter but paging by\n * different sizes would otherwise reuse each other's incompatible boundaries\n * and skip or duplicate rows.\n */\nexport const conversationListQueryKeys = {\n root: [CONVERSATION_LIST_QUERY_KEY_ROOT] as const,\n scope: (scopeKey: string) => [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey] as const,\n firstPage: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'first-page'] as const,\n history: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'history'] as const,\n};\n\n/**\n * Flatten pages into one newest-first list, deduplicating by `threadId`.\n * The live first page wins over retained history copies of the same thread.\n */\nexport function mergeConversationPages(\n pages: readonly ConversationListPage[]\n): ConversationSummary[] {\n const seen = new Set<string>();\n const items: ConversationSummary[] = [];\n for (const page of pages) {\n for (const item of page.items) {\n if (seen.has(item.threadId)) continue;\n seen.add(item.threadId);\n items.push(item);\n }\n }\n return items;\n}\n\n/**\n * Prepend a conversation to a page unless its thread is already present\n * (optimistic \"new thread appears at the top\" write). Identity-preserving\n * no-op when present, so equal writes never notify subscribers.\n */\nexport function prependConversationToPage(\n page: ConversationListPage,\n item: ConversationSummary\n): ConversationListPage {\n if (page.items.some((existing) => existing.threadId === item.threadId)) return page;\n return {\n ...page,\n items: [item, ...page.items],\n totalCount: page.totalCount === null ? null : page.totalCount + 1,\n };\n}\n\n/** Remove a thread's row from a page; identity-preserving when absent. */\nexport function removeConversationFromPage(\n page: ConversationListPage,\n threadId: string\n): ConversationListPage {\n if (!page.items.some((item) => item.threadId === threadId)) return page;\n return { ...page, items: page.items.filter((item) => item.threadId !== threadId) };\n}\n\n/**\n * Patch every row matching `match`; identity-preserving when nothing matches\n * so cache writes cannot cause spurious re-renders.\n */\nexport function patchConversationsInPage(\n page: ConversationListPage,\n match: (item: ConversationSummary) => boolean,\n patch: Partial<ConversationSummary>\n): ConversationListPage {\n let changed = false;\n const items = page.items.map((item) => {\n if (!match(item)) return item;\n changed = true;\n return { ...item, ...patch };\n });\n return changed ? { ...page, items } : page;\n}\n\ntype CachedConversationList =\n | ConversationListPage\n | InfiniteData<ConversationListPage, number>\n | undefined;\n\nfunction isInfinitePages(\n data: ConversationListPage | InfiniteData<ConversationListPage, number>\n): data is InfiniteData<ConversationListPage, number> {\n return 'pages' in data;\n}\n\nfunction mapCachedPages(\n data: CachedConversationList,\n transform: (page: ConversationListPage) => ConversationListPage\n): CachedConversationList {\n if (!data) return data;\n if (isInfinitePages(data)) {\n let changed = false;\n const pages = data.pages.map((page) => {\n const next = transform(page);\n if (next !== page) changed = true;\n return next;\n });\n return changed ? { ...data, pages } : data;\n }\n return transform(data);\n}\n\ninterface ConversationListCacheScope {\n /** Restrict to one scope; omitted = every conversation-list cache. */\n scopeKey?: string;\n}\n\nfunction scopedKey(options?: ConversationListCacheScope): readonly string[] {\n return options?.scopeKey !== undefined\n ? conversationListQueryKeys.scope(options.scopeKey)\n : conversationListQueryKeys.root;\n}\n\n/**\n * Invalidate conversation-list caches (all filters, first page + history).\n * This is the hook for push signals — the conversation-index statewire, a\n * finished run, an archive/restore — anything that changed the server list.\n */\nexport function invalidateConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.invalidateQueries({ queryKey: scopedKey(options) });\n}\n\n/** Cancel in-flight list fetches so an optimistic write cannot be overwritten. */\nexport function cancelConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.cancelQueries({ queryKey: scopedKey(options) });\n}\n\n/**\n * Patch matching rows in every cached conversation list (first pages, history\n * pages, searches) so per-row state (read receipts, titles) flips in the same\n * frame as the interaction instead of after the next refetch.\n */\nexport function patchConversationListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & {\n match: (item: ConversationSummary) => boolean;\n patch: Partial<ConversationSummary>;\n }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => patchConversationsInPage(page, options.match, options.patch))\n );\n}\n\n/** Remove a thread's row from every cached conversation list in scope. */\nexport function removeConversationFromListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & { threadId: string }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => removeConversationFromPage(page, options.threadId))\n );\n}\n\nfunction timestampMs(value: string): number {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\nfunction sameSummary(a: ConversationSummary, b: ConversationSummary): boolean {\n return (\n a.threadId === b.threadId &&\n a.title === b.title &&\n a.updatedAt === b.updatedAt &&\n a.createdAt === b.createdAt &&\n a.state === b.state &&\n a.runtime === b.runtime &&\n a.sourceChannel === b.sourceChannel &&\n a.assetType === b.assetType &&\n a.assetId === b.assetId &&\n a.appId === b.appId &&\n a.triggerType === b.triggerType &&\n a.preview === b.preview &&\n a.messageCount === b.messageCount &&\n a.isUnread === b.isUnread &&\n a.sessionStatus === b.sessionStatus &&\n a.runStatus === b.runStatus &&\n a.attention === b.attention &&\n a.nextAction === b.nextAction &&\n a.attentionSource === b.attentionSource &&\n a.isFavorited === b.isFavorited &&\n // Never pushed by the index, so a fold carries the previous references\n // through unchanged; identity is the equality that matters here.\n a.lastWake === b.lastWake &&\n a.pullRequests === b.pullRequests\n );\n}\n\n/**\n * Project one replicated conversation-index row onto the shared summary shape.\n * Fields the index never carries (`createdAt`) and viewer-specific fields a\n * lifecycle publish cannot know (`is_unread: null`) keep the row's previous\n * value. Canonical status is taken from the entry when the publishing pod\n * reports it; a snapshot from a pod that predates the fields falls back to the\n * legacy `state` (null status) rather than keeping a stale run status.\n *\n * Attention fields (`attention`, `next_action`, `attention_source`,\n * `is_favorited`) are taken from the entry when the publishing pod reports\n * them, so a live push flips a row to \"needs you\" the way it renames it; a\n * pod that predates them leaves the row's previous values. Pull-request state\n * and the last wake are never pushed and always keep the fetched value.\n */\nexport function summaryFromConversationIndexEntry(\n entry: ConversationIndexEntry,\n previous?: ConversationSummary\n): ConversationSummary {\n const carriesStatus = entry.run_status !== undefined || entry.session_status !== undefined;\n return {\n threadId: entry.thread_id,\n title: entry.title,\n updatedAt: entry.updated_at,\n createdAt: previous?.createdAt ?? null,\n state: entry.state,\n runtime: entry.runtime,\n sourceChannel: entry.start_channel,\n assetType: entry.asset_type,\n assetId: entry.asset_id ?? previous?.assetId ?? null,\n computerAssetId: previous?.computerAssetId ?? null,\n appId: entry.app_id,\n triggerType: entry.trigger_type,\n preview: entry.last_message_preview,\n messageCount: entry.message_count,\n isUnread: entry.is_unread ?? previous?.isUnread ?? false,\n sessionStatus: carriesStatus ? (entry.session_status ?? null) : null,\n runStatus: carriesStatus ? (entry.run_status ?? null) : null,\n attention: entry.attention !== undefined ? entry.attention : previous?.attention,\n nextAction: entry.next_action !== undefined ? entry.next_action : previous?.nextAction,\n attentionSource:\n entry.attention_source !== undefined ? entry.attention_source : previous?.attentionSource,\n isFavorited: entry.is_favorited ?? previous?.isFavorited,\n lastWake: previous?.lastWake,\n pullRequests: previous?.pullRequests,\n };\n}\n\n/**\n * Fold the user's replicated conversation index (the newest-page window the\n * per-user statewire pushes) into a cached live first page, so a thread\n * created, renamed, finished, or read anywhere updates every list surface in\n * the same frame — without refetching the page.\n *\n * - Rows in the window are upserted (new threads appear, existing rows take\n * the pushed fields, see {@link summaryFromConversationIndexEntry}).\n * - Rows NOT in the window but at least as new as the window's oldest row\n * should have been in it, so they left the list (archived, hidden, shared\n * away) and are dropped. Older rows are beyond the window and are kept.\n * - When the index reports no further rows (`indexHasMore === false`) the\n * window IS the whole list, so every row outside it is dropped.\n *\n * Newest-first ordering is restored and the page identity is preserved when\n * nothing changed, so an equal push never notifies subscribers.\n */\nexport function mergeConversationIndexIntoPage(\n page: ConversationListPage,\n entries: readonly ConversationIndexEntry[],\n options: { indexHasMore: boolean }\n): ConversationListPage {\n const previousByThread = new Map(page.items.map((item) => [item.threadId, item]));\n const inWindow = new Set(entries.map((entry) => entry.thread_id));\n const windowTailMs =\n entries.length > 0 ? Math.min(...entries.map((entry) => timestampMs(entry.updated_at))) : null;\n\n const merged: ConversationSummary[] = entries.map((entry) => {\n const previous = previousByThread.get(entry.thread_id);\n const next = summaryFromConversationIndexEntry(entry, previous);\n return previous && sameSummary(previous, next) ? previous : next;\n });\n\n for (const item of page.items) {\n if (inWindow.has(item.threadId)) continue;\n if (!options.indexHasMore) continue;\n if (windowTailMs !== null && timestampMs(item.updatedAt) >= windowTailMs) continue;\n merged.push(item);\n }\n\n merged.sort((a, b) => timestampMs(b.updatedAt) - timestampMs(a.updatedAt));\n\n const unchanged =\n merged.length === page.items.length &&\n merged.every((item, index) => item === page.items[index]);\n if (unchanged) return page;\n\n return { ...page, items: merged };\n}\n"],"names":[],"mappings":"AAoBO,MAAM,0BAA4D;AAAA,EACvE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8LO,MAAM,mCAAmC;AAOzC,MAAM,sCAAsC;AAQ5C,SAAS,gCACd,QACwB;AACxB,QAAM,aAAqC,CAAA;AAC3C,MAAI,OAAO,MAAO,YAAW,QAAQ,OAAO;AAC5C,MAAI,OAAO,cAAc,OAAO,WAAW,SAAS,GAAG;AACrD,eAAW,aAAa,CAAC,GAAG,OAAO,UAAU,EAAE,KAAA;AAAA,EACjD;AACA,MAAI,OAAO,OAAQ,YAAW,SAAS,OAAO;AAC9C,MAAI,OAAO,qBAAqB,OAAW,YAAW,mBAAmB,OAAO;AAChF,MAAI,OAAO,kBAAkB,OAAO,eAAe,SAAS,GAAG;AAC7D,eAAW,iBAAiB,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time/src/conversation-list.ts"],"sourcesContent":["import type { InfiniteData, QueryClient } from '@tanstack/react-query';\nimport type { ConversationIndexEntry } from './conversation-index';\n\n/**\n * What a session asks of the viewer, derived server-side from the run, the\n * parked interrupt, the pull requests it opened, its termination and its last\n * wake (the Devin-style session list). `needs_you` is the only state that\n * demands the viewer act; `working` is live; `ready` finished with something\n * to look at; `watching` waits on an external party (a review, a check);\n * `done` and `error` are terminal. A backend newer than this client may report\n * a value outside the union — render it as \"no attention\" rather than failing.\n */\nexport type ConversationAttention =\n | 'needs_you'\n | 'working'\n | 'ready'\n | 'watching'\n | 'done'\n | 'error';\n\nexport const CONVERSATION_ATTENTIONS: readonly ConversationAttention[] = [\n 'needs_you',\n 'working',\n 'ready',\n 'watching',\n 'done',\n 'error',\n];\n\n/** Which signal produced the attention state (and the `nextAction` copy). */\nexport type ConversationAttentionSource =\n | 'interrupt'\n | 'run'\n | 'pull_request'\n | 'termination'\n | 'wake'\n | 'handoff'\n | 'follow_up';\n\n/** The last event that woke a resting session (a GitHub webhook, a schedule, a handoff). */\nexport interface ConversationWake {\n source: string | null;\n reason: string | null;\n /** ISO 8601 timestamp of the wake. */\n at: string | null;\n}\n\n/**\n * Live GitHub state of a pull request the session opened, read by the server\n * when the list renders. Never pushed by the conversation index — it comes\n * from the list fetch only, so a fold keeps the fetched value.\n */\nexport interface ConversationPullRequest {\n /** `owner/repo` the pull request lives in. */\n repoFullName: string;\n number: number;\n url: string;\n title: string;\n state: 'OPEN' | 'CLOSED' | 'MERGED';\n isDraft: boolean;\n /** GitHub's review decision (APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED) or null. */\n reviewDecision: string | null;\n /** Combined state of the checks on the head commit. */\n checksState: 'SUCCESS' | 'FAILURE' | 'PENDING' | 'NONE';\n /** ISO 8601 timestamp of the pull request's last update on GitHub. */\n updatedAt: string;\n}\n\n/**\n * Shared conversation/thread LIST contract (chat-stack unification —\n * thread-list-contract-convergence).\n *\n * Every chat surface lists \"my conversations\" against the same underlying\n * session assets, but historically each declared its own row shape, paging\n * model, and filter set (Olympus GraphQL `listConversations`, the SDK/Chrome\n * REST `/api/conversations/threads/list`, mobile's `/api/v0/sessions`). This\n * module is the ONE contract those surfaces converge on:\n *\n * - **Row shape**: {@link ConversationSummary} — the canonical camelCase\n * superset. Fields a transport cannot supply are `null`, never invented.\n * - **Ordering**: newest first by `updatedAt`, always. Ordering is part of the\n * contract, not a parameter — no surface sorts any other way.\n * - **Paging**: offset/limit with a LIVE newest page and explicitly-fetched\n * frozen history pages (see `useConversationList`). `hasMore` continues the\n * scan; `totalCount` is advisory and may be `null` for transports that do\n * not count.\n * - **Filtering**: {@link ConversationListFilter}. `appId` follows\n * `docs/SESSION_APP_ID_GUIDE.md`: exact match when set (legacy `null`\n * sessions excluded), no filter when unset. A fetcher that cannot express a\n * requested filter field MUST throw rather than silently ignore it — a\n * dropped filter returns wrong rows under a cache key that claims otherwise.\n * - **Freshness**: the per-user conversation-index statewire\n * (`conversation-index.ts`) is the push signal; these queries are the data\n * source. Push handlers call {@link invalidateConversationListCaches}.\n */\nexport interface ConversationSummary {\n /** LangGraph thread id — the cross-surface conversation identity. */\n threadId: string;\n title: string;\n /** ISO 8601 timestamp of last update (the contract's sort key). */\n updatedAt: string;\n /** ISO 8601 creation timestamp, when the transport reports it. */\n createdAt: string | null;\n /** Session lifecycle state from athena_metadata (e.g. running, completed). */\n state: string | null;\n /** Agent runtime marker (e.g. 'athena_deep_agent'), when reported. */\n runtime: string | null;\n /** Channel the session was started from (e.g. agent_email, web). */\n sourceChannel: string | null;\n /** Asset type (session, video_session, desktop_session, mobile_session). */\n assetType: string | null;\n /** Session asset id (`asset_<uuid>`), when the transport reports it. */\n assetId: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Computer asset whose sandbox started the session (`sourceChannel` 'computer'); omitted by surfaces that don't carry it. */\n computerAssetId?: string | null;\n /** Session asset id this row is a sub-session of; omitted by surfaces that don't carry it. */\n parentSessionId?: string | null;\n /** Sub-sessions of this row the viewer can see; omitted by surfaces that don't carry it. */\n subSessionCount?: number;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Last-message preview used when a legacy session has no useful title. */\n preview: string | null;\n messageCount: number | null;\n /** Per-user unread flag derived server-side from the read receipt. */\n isUnread: boolean;\n /**\n * Canonical session status (status_v2: idle | active | needs_input | error),\n * or null when the transport does not report it.\n */\n sessionStatus: string | null;\n /**\n * Canonical status of the session's current run (status_v2: scheduled |\n * queued | running | needs_input | completed | failed | canceled). Null when\n * the transport does not report it — {@link isConversationRunning} then\n * falls back to the legacy `state`. Running badges on every surface derive\n * from this one helper so they cannot disagree.\n */\n runStatus: string | null;\n /**\n * Server-derived attention state. `undefined` when the transport (or an\n * older server) does not report it — {@link deriveConversationAttention}\n * then falls back to the status planes; `null` when the server reports none.\n */\n attention?: ConversationAttention | null;\n /** One line (≤ 80 chars) of what the viewer should do next, when the server derives one. */\n nextAction?: string | null;\n /** Which signal produced `attention` / `nextAction`. */\n attentionSource?: ConversationAttentionSource | null;\n /** Whether the viewer pinned (favorited) the session; `undefined` when not reported. */\n isFavorited?: boolean;\n /** The last wake of a resting session; `undefined` when not reported. */\n lastWake?: ConversationWake | null;\n /**\n * Pull requests the session opened with their live GitHub state. `[]` when\n * it opened none, `null` when the state could not be read right now,\n * `undefined` when the transport did not ask for (or report) it.\n */\n pullRequests?: ConversationPullRequest[] | null;\n}\n\n/**\n * The canonical filter set. Semantics are defined here once; each fetcher\n * translates the fields its transport supports and throws on the rest.\n */\nexport interface ConversationListFilter {\n /** Exact-match client app filter; unset = all apps (SESSION_APP_ID_GUIDE). */\n appId?: string;\n /** Asset types to include (e.g. ['session']); unset = all session types. */\n assetTypes?: readonly string[];\n /** Case-insensitive title search. */\n search?: string;\n /** Hide triggered/background sessions (REST thread list only today). */\n excludeTriggered?: boolean;\n /** Start-channel filter (v0 sessions / REST thread list only today). */\n sourceChannels?: readonly string[];\n /** Start channels to hide (e.g. ['api']); GraphQL `listConversations` only today. */\n excludeSourceChannels?: readonly string[];\n /** Exact computer asset whose sandbox started the session; GraphQL `listConversations` only today. */\n computerAssetId?: string;\n /** Only the sub-sessions of this session asset id; GraphQL `listConversations` only today. */\n parentSessionId?: string;\n /**\n * Lifecycle-state filter (e.g. ['running'], ['completed']). Transports match\n * it with the shared status_v2 rule (running carries a 12-hour recency cutoff).\n */\n states?: readonly string[];\n /** Restrict to sessions run by any of these agents (athena_metadata.agent). */\n agentIds?: readonly string[];\n /**\n * Include branched sub-sessions and orchestration children, which every list\n * hides by default because they belong under their parent thread.\n */\n includeSubSessions?: boolean;\n}\n\nexport interface ConversationListPage {\n /** Rows in contract order (updatedAt desc). */\n items: ConversationSummary[];\n /** Whether another `offset + limit` scan would return more rows. */\n hasMore: boolean;\n /** Total matching rows, or null when the transport does not count. */\n totalCount: number | null;\n}\n\nexport interface ConversationListFetchParams {\n limit: number;\n offset: number;\n filter: ConversationListFilter;\n signal?: AbortSignal;\n}\n\n/**\n * One page fetch against some transport (GraphQL `listConversations`, the\n * REST thread list, …). Must reject on filter fields it cannot express.\n */\nexport type ConversationListFetcher = (\n params: ConversationListFetchParams\n) => Promise<ConversationListPage>;\n\n/** Root of every conversation-list query key (all surfaces, all filters). */\nexport const CONVERSATION_LIST_QUERY_KEY_ROOT = 'athena-conversation-list';\n\n/**\n * Scope used by `useConversationList` when the caller passes no `scopeKey`.\n * Exported so cache seeders (e.g. Olympus's spacesBootstrap adoption) can\n * address the exact keys default-scoped hooks read from.\n */\nexport const CONVERSATION_LIST_DEFAULT_SCOPE_KEY = 'default';\n\n/**\n * Normalize a filter to its semantic content: unset/empty fields are dropped\n * (so `{}` and `{ appId: undefined }` are the same filter) and array order is\n * canonicalized. Fetchers receive the normalized form, so what a cache entry\n * claims to hold is exactly what was fetched.\n */\nexport function normalizeConversationListFilter(\n filter: ConversationListFilter\n): ConversationListFilter {\n const normalized: ConversationListFilter = {};\n if (filter.appId) normalized.appId = filter.appId;\n if (filter.assetTypes && filter.assetTypes.length > 0) {\n normalized.assetTypes = [...filter.assetTypes].sort();\n }\n if (filter.search) normalized.search = filter.search;\n if (filter.excludeTriggered !== undefined) normalized.excludeTriggered = filter.excludeTriggered;\n if (filter.sourceChannels && filter.sourceChannels.length > 0) {\n normalized.sourceChannels = [...filter.sourceChannels].sort();\n }\n if (filter.excludeSourceChannels && filter.excludeSourceChannels.length > 0) {\n normalized.excludeSourceChannels = [...filter.excludeSourceChannels].sort();\n }\n if (filter.computerAssetId) normalized.computerAssetId = filter.computerAssetId;\n if (filter.parentSessionId) normalized.parentSessionId = filter.parentSessionId;\n if (filter.states && filter.states.length > 0) {\n normalized.states = [...filter.states].sort();\n }\n if (filter.agentIds && filter.agentIds.length > 0) {\n normalized.agentIds = [...filter.agentIds].sort();\n }\n if (filter.includeSubSessions) normalized.includeSubSessions = true;\n return normalized;\n}\n\n/** status_v2 run statuses during which a session is actively working. */\nconst RUNNING_RUN_STATUSES: ReadonlySet<string> = new Set(['queued', 'running']);\n\n/**\n * THE running rule for every conversation-list surface (sidebar pane, recent\n * dropdown, workspace section, pushed index rows): the canonical status_v2 run\n * status when the transport reports one, else the legacy `state`. A session\n * paused on a human gate (`needs_input`) is not running.\n */\nexport function isConversationRunning(summary: {\n runStatus?: string | null;\n state?: string | null;\n}): boolean {\n if (summary.runStatus !== null && summary.runStatus !== undefined) {\n return RUNNING_RUN_STATUSES.has(summary.runStatus);\n }\n return summary.state === 'running';\n}\n\nconst KNOWN_ATTENTIONS: ReadonlySet<string> = new Set(CONVERSATION_ATTENTIONS);\n\n/**\n * THE attention rule for every session-list surface: the server-derived\n * `attention` when the transport reports one it knows, else a client fallback\n * from the status planes so an older server still yields the two states a\n * list cannot do without — a human gate reads as `needs_you`, a live run as\n * `working`, a failed run as `error`. `null` when nothing applies.\n */\nexport function deriveConversationAttention(\n summary: Pick<ConversationSummary, 'attention' | 'runStatus' | 'sessionStatus' | 'state'>\n): ConversationAttention | null {\n if (typeof summary.attention === 'string' && KNOWN_ATTENTIONS.has(summary.attention)) {\n return summary.attention;\n }\n if (summary.runStatus === 'needs_input' || summary.sessionStatus === 'needs_input') {\n return 'needs_you';\n }\n if (isConversationRunning(summary)) return 'working';\n if (summary.runStatus === 'failed' || summary.sessionStatus === 'error') return 'error';\n return null;\n}\n\n/**\n * Stable cache identity for a filter: the normalized fields serialized in\n * sorted key order, so semantically equal filters share one cache entry.\n */\nexport function conversationListFilterKey(filter: ConversationListFilter): string {\n const normalized = normalizeConversationListFilter(filter) as Record<string, unknown>;\n return JSON.stringify(\n Object.keys(normalized)\n .sort()\n .map((key) => [key, normalized[key]])\n );\n}\n\n/**\n * Query keys for the two-tier pager. `scopeKey` isolates caches beyond the\n * filter — surfaces MUST include everything that changes whose list this is\n * (principal/user id, backend base URL) so a credential swap can never read\n * another identity's rows out of the cache.\n *\n * `pageSize` is part of the key because it is baked into every cached page's\n * offset boundaries: two hooks sharing a scope and filter but paging by\n * different sizes would otherwise reuse each other's incompatible boundaries\n * and skip or duplicate rows.\n */\nexport const conversationListQueryKeys = {\n root: [CONVERSATION_LIST_QUERY_KEY_ROOT] as const,\n scope: (scopeKey: string) => [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey] as const,\n firstPage: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'first-page'] as const,\n history: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'history'] as const,\n};\n\n/**\n * Flatten pages into one newest-first list, deduplicating by `threadId`.\n * The live first page wins over retained history copies of the same thread.\n */\nexport function mergeConversationPages(\n pages: readonly ConversationListPage[]\n): ConversationSummary[] {\n const seen = new Set<string>();\n const items: ConversationSummary[] = [];\n for (const page of pages) {\n for (const item of page.items) {\n if (seen.has(item.threadId)) continue;\n seen.add(item.threadId);\n items.push(item);\n }\n }\n return items;\n}\n\n/**\n * Prepend a conversation to a page unless its thread is already present\n * (optimistic \"new thread appears at the top\" write). Identity-preserving\n * no-op when present, so equal writes never notify subscribers.\n */\nexport function prependConversationToPage(\n page: ConversationListPage,\n item: ConversationSummary\n): ConversationListPage {\n if (page.items.some((existing) => existing.threadId === item.threadId)) return page;\n return {\n ...page,\n items: [item, ...page.items],\n totalCount: page.totalCount === null ? null : page.totalCount + 1,\n };\n}\n\n/** Remove a thread's row from a page; identity-preserving when absent. */\nexport function removeConversationFromPage(\n page: ConversationListPage,\n threadId: string\n): ConversationListPage {\n if (!page.items.some((item) => item.threadId === threadId)) return page;\n return { ...page, items: page.items.filter((item) => item.threadId !== threadId) };\n}\n\n/**\n * Patch every row matching `match`; identity-preserving when nothing matches\n * so cache writes cannot cause spurious re-renders.\n */\nexport function patchConversationsInPage(\n page: ConversationListPage,\n match: (item: ConversationSummary) => boolean,\n patch: Partial<ConversationSummary>\n): ConversationListPage {\n let changed = false;\n const items = page.items.map((item) => {\n if (!match(item)) return item;\n changed = true;\n return { ...item, ...patch };\n });\n return changed ? { ...page, items } : page;\n}\n\ntype CachedConversationList =\n | ConversationListPage\n | InfiniteData<ConversationListPage, number>\n | undefined;\n\nfunction isInfinitePages(\n data: ConversationListPage | InfiniteData<ConversationListPage, number>\n): data is InfiniteData<ConversationListPage, number> {\n return 'pages' in data;\n}\n\nfunction mapCachedPages(\n data: CachedConversationList,\n transform: (page: ConversationListPage) => ConversationListPage\n): CachedConversationList {\n if (!data) return data;\n if (isInfinitePages(data)) {\n let changed = false;\n const pages = data.pages.map((page) => {\n const next = transform(page);\n if (next !== page) changed = true;\n return next;\n });\n return changed ? { ...data, pages } : data;\n }\n return transform(data);\n}\n\ninterface ConversationListCacheScope {\n /** Restrict to one scope; omitted = every conversation-list cache. */\n scopeKey?: string;\n}\n\nfunction scopedKey(options?: ConversationListCacheScope): readonly string[] {\n return options?.scopeKey !== undefined\n ? conversationListQueryKeys.scope(options.scopeKey)\n : conversationListQueryKeys.root;\n}\n\n/**\n * Invalidate conversation-list caches (all filters, first page + history).\n * This is the hook for push signals — the conversation-index statewire, a\n * finished run, an archive/restore — anything that changed the server list.\n */\nexport function invalidateConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.invalidateQueries({ queryKey: scopedKey(options) });\n}\n\n/** Cancel in-flight list fetches so an optimistic write cannot be overwritten. */\nexport function cancelConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.cancelQueries({ queryKey: scopedKey(options) });\n}\n\n/**\n * Patch matching rows in every cached conversation list (first pages, history\n * pages, searches) so per-row state (read receipts, titles) flips in the same\n * frame as the interaction instead of after the next refetch.\n */\nexport function patchConversationListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & {\n match: (item: ConversationSummary) => boolean;\n patch: Partial<ConversationSummary>;\n }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => patchConversationsInPage(page, options.match, options.patch))\n );\n}\n\n/** Remove a thread's row from every cached conversation list in scope. */\nexport function removeConversationFromListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & { threadId: string }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => removeConversationFromPage(page, options.threadId))\n );\n}\n\nfunction timestampMs(value: string): number {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\nfunction sameSummary(a: ConversationSummary, b: ConversationSummary): boolean {\n return (\n a.threadId === b.threadId &&\n a.title === b.title &&\n a.updatedAt === b.updatedAt &&\n a.createdAt === b.createdAt &&\n a.state === b.state &&\n a.runtime === b.runtime &&\n a.sourceChannel === b.sourceChannel &&\n a.assetType === b.assetType &&\n a.assetId === b.assetId &&\n a.appId === b.appId &&\n a.triggerType === b.triggerType &&\n a.preview === b.preview &&\n a.messageCount === b.messageCount &&\n a.isUnread === b.isUnread &&\n a.sessionStatus === b.sessionStatus &&\n a.runStatus === b.runStatus &&\n a.attention === b.attention &&\n a.nextAction === b.nextAction &&\n a.attentionSource === b.attentionSource &&\n a.isFavorited === b.isFavorited &&\n // Never pushed by the index, so a fold carries the previous references\n // through unchanged; identity is the equality that matters here.\n a.lastWake === b.lastWake &&\n a.pullRequests === b.pullRequests\n );\n}\n\n/**\n * Project one replicated conversation-index row onto the shared summary shape.\n * Fields the index never carries (`createdAt`) and viewer-specific fields a\n * lifecycle publish cannot know (`is_unread: null`) keep the row's previous\n * value. Canonical status is taken from the entry when the publishing pod\n * reports it; a snapshot from a pod that predates the fields falls back to the\n * legacy `state` (null status) rather than keeping a stale run status.\n *\n * Attention fields (`attention`, `next_action`, `attention_source`,\n * `is_favorited`) are taken from the entry when the publishing pod reports\n * them, so a live push flips a row to \"needs you\" the way it renames it; a\n * pod that predates them leaves the row's previous values. Pull-request state\n * and the last wake are never pushed and always keep the fetched value.\n */\nexport function summaryFromConversationIndexEntry(\n entry: ConversationIndexEntry,\n previous?: ConversationSummary\n): ConversationSummary {\n const carriesStatus = entry.run_status !== undefined || entry.session_status !== undefined;\n return {\n threadId: entry.thread_id,\n title: entry.title,\n updatedAt: entry.updated_at,\n createdAt: previous?.createdAt ?? null,\n state: entry.state,\n runtime: entry.runtime,\n sourceChannel: entry.start_channel,\n assetType: entry.asset_type,\n assetId: entry.asset_id ?? previous?.assetId ?? null,\n computerAssetId: previous?.computerAssetId ?? null,\n parentSessionId: previous?.parentSessionId,\n subSessionCount: previous?.subSessionCount,\n appId: entry.app_id,\n triggerType: entry.trigger_type,\n preview: entry.last_message_preview,\n messageCount: entry.message_count,\n isUnread: entry.is_unread ?? previous?.isUnread ?? false,\n sessionStatus: carriesStatus ? (entry.session_status ?? null) : null,\n runStatus: carriesStatus ? (entry.run_status ?? null) : null,\n attention: entry.attention !== undefined ? entry.attention : previous?.attention,\n nextAction: entry.next_action !== undefined ? entry.next_action : previous?.nextAction,\n attentionSource:\n entry.attention_source !== undefined ? entry.attention_source : previous?.attentionSource,\n isFavorited: entry.is_favorited ?? previous?.isFavorited,\n lastWake: previous?.lastWake,\n pullRequests: previous?.pullRequests,\n };\n}\n\n/**\n * Fold the user's replicated conversation index (the newest-page window the\n * per-user statewire pushes) into a cached live first page, so a thread\n * created, renamed, finished, or read anywhere updates every list surface in\n * the same frame — without refetching the page.\n *\n * - Rows in the window are upserted (new threads appear, existing rows take\n * the pushed fields, see {@link summaryFromConversationIndexEntry}).\n * - Rows NOT in the window but at least as new as the window's oldest row\n * should have been in it, so they left the list (archived, hidden, shared\n * away) and are dropped. Older rows are beyond the window and are kept.\n * - When the index reports no further rows (`indexHasMore === false`) the\n * window IS the whole list, so every row outside it is dropped.\n *\n * Newest-first ordering is restored and the page identity is preserved when\n * nothing changed, so an equal push never notifies subscribers.\n */\nexport function mergeConversationIndexIntoPage(\n page: ConversationListPage,\n entries: readonly ConversationIndexEntry[],\n options: { indexHasMore: boolean }\n): ConversationListPage {\n const previousByThread = new Map(page.items.map((item) => [item.threadId, item]));\n const inWindow = new Set(entries.map((entry) => entry.thread_id));\n const windowTailMs =\n entries.length > 0 ? Math.min(...entries.map((entry) => timestampMs(entry.updated_at))) : null;\n\n const merged: ConversationSummary[] = entries.map((entry) => {\n const previous = previousByThread.get(entry.thread_id);\n const next = summaryFromConversationIndexEntry(entry, previous);\n return previous && sameSummary(previous, next) ? previous : next;\n });\n\n for (const item of page.items) {\n if (inWindow.has(item.threadId)) continue;\n if (!options.indexHasMore) continue;\n if (windowTailMs !== null && timestampMs(item.updatedAt) >= windowTailMs) continue;\n merged.push(item);\n }\n\n merged.sort((a, b) => timestampMs(b.updatedAt) - timestampMs(a.updatedAt));\n\n const unchanged =\n merged.length === page.items.length &&\n merged.every((item, index) => item === page.items[index]);\n if (unchanged) return page;\n\n return { ...page, items: merged };\n}\n"],"names":[],"mappings":"AAoBO,MAAM,0BAA4D;AAAA,EACvE;AAAA,EACA;AA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