Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cowork): port the pure transcript, artifact and preview helpers
Akarshan Biswasb8f38b8ac111
diff --git a/web-app/src/lib/__tests__/codeArtifacts.test.ts b/web-app/src/lib/__tests__/codeArtifacts.test.tsnew file mode 100644index 000000000..7b7ed4e0d--- /dev/null+++ b/web-app/src/lib/__tests__/codeArtifacts.test.ts@@ -0,0 +1,268 @@+import { describe, it, expect } from 'vitest'+import {+ artifactFor,+ bashArtifactPaths,+ isArtifactPath,+ artifactsFromParts,+ artifactsFromTurns,+} from '@/lib/codeArtifacts'+import type { CodeTurn } from '@/hooks/useCodeSessions'++const write = (path: string, state = 'output-available', output = `Created ${path} (10 bytes)`) => ({+ type: 'tool-write',+ input: { path },+ state,+ output,+})++describe('isArtifactPath', () => {+ it('accepts things a user would call a deliverable', () => {+ expect(isArtifactPath('index.html')).toBe(true)+ expect(isArtifactPath('a/logo.svg')).toBe(true)+ expect(isArtifactPath('shot.PNG')).toBe(true)+ expect(isArtifactPath('report.pdf')).toBe(true)+ expect(isArtifactPath('notes.md')).toBe(true)+ })++ it('rejects the project scaffolding a run also writes', () => {+ // These are the reason the list is an allowlist: otherwise every run+ // fills it with noise. They stay visible in the diff panel (#285).+ expect(isArtifactPath('package.json')).toBe(false)+ expect(isArtifactPath('yarn.lock')).toBe(false)+ expect(isArtifactPath('.gitignore')).toBe(false)+ expect(isArtifactPath('src/main.rs')).toBe(false)+ expect(isArtifactPath('tsconfig.json')).toBe(false)+ })+})++describe('artifactFor', () => {+ it('titles from the basename without the extension', () => {+ expect(artifactFor('games/flappy-bird.html')).toEqual({+ path: 'games/flappy-bird.html',+ title: 'flappy-bird',+ group: 'Code',+ label: 'HTML',+ })+ })++ it('groups by kind and upper-cases the label', () => {+ expect(artifactFor('a.png')?.group).toBe('Image')+ expect(artifactFor('a.docx')?.group).toBe('Document')+ expect(artifactFor('a.svg')?.label).toBe('SVG')+ expect(artifactFor('clip.mp4')?.group).toBe('Video')+ expect(artifactFor('track.mp3')?.group).toBe('Audio')+ expect(artifactFor('track.flac')?.label).toBe('FLAC')+ })++ it('keeps dots inside a filename', () => {+ expect(artifactFor('report.v2.final.pdf')?.title).toBe('report.v2.final')+ })++ it('returns null for a non-artifact', () => {+ expect(artifactFor('package.json')).toBeNull()+ })+})++describe('artifactsFromParts', () => {+ it('reads artifacts off a message own write/edit parts', () => {+ const parts = [+ { type: 'text', text: 'done' },+ write('index.html'),+ write('package.json'), // not an artifact+ ]+ expect(artifactsFromParts(parts)).toEqual([+ { path: 'index.html', title: 'index', group: 'Code', label: 'HTML' },+ ])+ })++ it('ignores edit entirely — it only ever touches an existing file', () => {+ const parts = [+ write('a.html'),+ { type: 'tool-edit', input: { path: 'b.html' }, state: 'output-available', output: 'ok' },+ ]+ expect(artifactsFromParts(parts).map((a) => a.path)).toEqual(['a.html'])+ })++ it('ignores a write that overwrote an existing file', () => {+ // The codebase case: rewriting README.md or an icon is not a deliverable.+ expect(+ artifactsFromParts([write('README.md', 'output-available', 'Overwrote README.md (20 bytes)')])+ ).toEqual([])+ })++ it('ignores a call that failed or never completed', () => {+ expect(artifactsFromParts([write('a.html', 'output-error')])).toEqual([])+ expect(artifactsFromParts([write('a.html', 'input-streaming')])).toEqual([])+ })++ it('ignores non-write tools and malformed input', () => {+ expect(+ artifactsFromParts([+ { type: 'tool-read', input: { path: 'a.html' }, state: 'output-available' },+ { type: 'tool-write', input: {}, state: 'output-available' },+ { type: 'tool-write', input: { path: 42 }, state: 'output-available' },+ ])+ ).toEqual([])+ })++ it('is empty for no parts', () => {+ expect(artifactsFromParts(undefined)).toEqual([])+ expect(artifactsFromParts([])).toEqual([])+ })++ it('preserves first-seen order', () => {+ const got = artifactsFromParts([write('b.md'), write('a.html')])+ expect(got.map((a) => a.path)).toEqual(['b.md', 'a.html'])+ })+})++describe('artifactsFromTurns', () => {+ const toolTurn = (name: string, path: string, extra: Partial<CodeTurn> = {}) =>+ ({+ role: 'tool',+ content: '',+ name,+ args: { path },+ status: 'done',+ result: `Created ${path} (10 bytes)`,+ ...extra,+ }) as CodeTurn++ it('reads write/edit artifacts straight off session turns', () => {+ const turns = [+ { role: 'user', content: 'go' },+ toolTurn('write', 'index.html'),+ toolTurn('write', 'package.json'),+ toolTurn('read', 'index.html'),+ ] as CodeTurn[]+ expect(artifactsFromTurns(turns).map((a) => a.path)).toEqual(['index.html'])+ })++ it('counts a file created then rewritten once', () => {+ // Regression: the library showed one card per rewrite.+ const turns = [+ toolTurn('write', 'a.html'),+ toolTurn('edit', 'a.html'),+ toolTurn('write', 'a.html', { result: 'Overwrote a.html (12 bytes)' }),+ ]+ expect(artifactsFromTurns(turns)).toHaveLength(1)+ })++ it('excludes files it only modified — the real-codebase case', () => {+ // A repo of thousands of files: editing docs and assets must not flood+ // the library just because .md/.svg are on the allowlist.+ const turns = [+ toolTurn('write', 'README.md', { result: 'Overwrote README.md (99 bytes)' }),+ toolTurn('edit', 'docs/guide.md'),+ toolTurn('write', 'assets/icon.svg', { result: 'Overwrote assets/icon.svg (30 bytes)' }),+ toolTurn('write', 'report.html'), // genuinely new+ ]+ expect(artifactsFromTurns(turns).map((a) => a.path)).toEqual(['report.html'])+ })++ it('treats the legacy "Wrote N bytes" result as a creation', () => {+ // Pre-existing sessions have no create/modify distinction; dropping them+ // would silently empty an existing library.+ expect(+ artifactsFromTurns([+ toolTurn('write', 'a.html', { result: 'Wrote 8000 bytes to /p/a.html' }),+ ])+ ).toHaveLength(1)+ })++ it('ignores errored and still-running calls', () => {+ expect(artifactsFromTurns([toolTurn('write', 'a.html', { isError: true })])).toEqual([])+ expect(artifactsFromTurns([toolTurn('write', 'a.html', { status: 'running' })])).toEqual([])+ })++ it('is empty for no turns', () => {+ expect(artifactsFromTurns(undefined)).toEqual([])+ expect(artifactsFromTurns([])).toEqual([])+ })++ it('recovers an mp4 a bash download produced (quoted spaces in the name)', () => {+ const turns = [+ {+ role: 'tool',+ content: '',+ name: 'bash',+ args: {+ command:+ 'cd /Users/thinhlpg/Desktop && yt-dlp -f "bv*+ba/b" -o "%(title)s.%(ext)s" "https://youtu.be/x" 2>&1 | tail -30',+ },+ status: 'done',+ isError: false,+ result:+ '[download] Destination: /Users/thinhlpg/Desktop/Rick Astley - Never Gonna Give You Up.mp4\n[download] 100% of 11MiB',+ } as CodeTurn,+ ]+ const artifacts = artifactsFromTurns(turns, '/Users/thinhlpg/Desktop')+ expect(artifacts).toHaveLength(1)+ expect(artifacts[0]!.group).toBe('Video')+ expect(artifacts[0]!.title).toContain('Rick Astley')+ })++ it('recovers a relative mp4 from ls -lh in the bash result', () => {+ const turns = [+ {+ role: 'tool',+ content: '',+ name: 'bash',+ args: { command: 'cd /p && python3 make.py && ls -lh cat_video.mp4' },+ status: 'done',+ isError: false,+ result: '-rw-r--r--@ 1 u staff 144K Aug 6 11:50 cat_video.mp4',+ } as CodeTurn,+ ]+ const artifacts = artifactsFromTurns(turns, '/p')+ expect(artifacts).toHaveLength(1)+ expect(artifacts[0]!.path).toBe('/p/cat_video.mp4')+ })++ it('tracks a file across an absolute mv target', () => {+ const turns = [+ {+ role: 'tool',+ content: '',+ name: 'bash',+ args: { command: 'cd /p/src && mv cat_video.mp4 /p/cat_video.mp4 && ls -lh /p/cat_video.mp4' },+ status: 'done',+ isError: false,+ result: '-rw-r--r--@ 1 u staff 144K Aug 6 11:50 /p/cat_video.mp4',+ } as CodeTurn,+ ]+ const artifacts = artifactsFromTurns(turns, '/p')+ expect(artifacts).toHaveLength(1)+ expect(artifacts[0]!.path).toBe('/p/cat_video.mp4')+ })++ it('ignores probes and globs that list no real file', () => {+ const turns = [+ {+ role: 'tool',+ content: '',+ name: 'bash',+ args: { command: 'which yt-dlp ffmpeg; ls *.mp4' },+ status: 'done',+ isError: false,+ result: '/opt/homebrew/bin/yt-dlp\n/opt/homebrew/bin/ffmpeg',+ } as CodeTurn,+ ]+ expect(artifactsFromTurns(turns, '/p')).toEqual([])+ })++ it('ignores errored bash calls', () => {+ const turns = [+ {+ role: 'tool',+ content: '',+ name: 'bash',+ args: { command: 'python3 make.py 2>&1 && ls -lh out.mp4' },+ status: 'done',+ isError: true,+ result: "can't open file 'make.py': No such file",+ } as CodeTurn,+ ]+ expect(artifactsFromTurns(turns, '/p')).toEqual([])+ })+})diff --git a/web-app/src/lib/__tests__/codeDiffs.test.ts b/web-app/src/lib/__tests__/codeDiffs.test.tsnew file mode 100644index 000000000..1ea87cefe--- /dev/null+++ b/web-app/src/lib/__tests__/codeDiffs.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from 'vitest'+import { collectCodeFileDiffs } from '@/lib/codeDiffs'+import type { CodeTurn, SubagentRun } from '@/hooks/useCodeSessions'++const edit = (+ path: unknown,+ diff: string,+ extra: Partial<CodeTurn> = {}+): CodeTurn => ({+ role: 'tool',+ content: '',+ name: 'edit',+ args: { path },+ diff,+ status: 'done',+ ...extra,+})++describe('collectCodeFileDiffs', () => {+ it('groups repeated main-agent operations by path and preserves first-seen file order', () => {+ const files = collectCodeFileDiffs(+ [+ edit('src/a.ts', '- 1 | old\n+ 1 | new'),+ edit('src/b.ts', '+ 1 | b'),+ edit('src/a.ts', '@@ edit 1/1 @@\n+ 2 | next'),+ ],+ []+ )++ expect(files.map((file) => file.path)).toEqual(['src/a.ts', 'src/b.ts'])+ expect(files[0]).toMatchObject({+ path: 'src/a.ts',+ additions: 2,+ deletions: 1,+ })+ expect(files[0].operations).toEqual([+ { diff: '- 1 | old\n+ 1 | new', source: 'main' },+ { diff: '@@ edit 1/1 @@\n+ 2 | next', source: 'main' },+ ])+ })+ it('includes only write/edit tool diffs and ignores path-bearing bash output', () => {+ const files = collectCodeFileDiffs(+ [+ edit('src/edit.ts', '+ 1 | edit'),+ edit('src/write.ts', '+ 1 | write', { name: 'write' }),+ edit('src/bash.ts', '+ 1 | ignored bash diff', { name: 'bash' }),+ edit('src/assistant.ts', '+ 1 | ignored assistant diff', {+ role: 'assistant',+ }),+ ],+ []+ )++ expect(files.map((file) => file.path)).toEqual([+ 'src/edit.ts',+ 'src/write.ts',+ ])+ expect(+ files.flatMap((file) =>+ file.operations.map((operation) => operation.diff)+ )+ ).toEqual([+ '+ 1 | edit',+ '+ 1 | write',+ ])+ })++ it('keeps main trace first, then subagents in current run order', () => {+ const subagents = [+ {+ runId: 'r1',+ name: 'TestsScout',+ status: 'done',+ startedAt: 1,+ endedAt: 2,+ turns: [edit('src/a.ts', '+ 3 | scout')],+ },+ {+ runId: 'r2',+ name: 'DocsScout',+ status: 'done',+ startedAt: 3,+ endedAt: 4,+ turns: [edit('src/a.ts', '- 4 | docs')],+ },+ ] satisfies SubagentRun[]++ expect(+ collectCodeFileDiffs(+ [edit('src/a.ts', '+ 1 | main')],+ subagents+ )[0].operations+ ).toEqual([+ { diff: '+ 1 | main', source: 'main' },+ { diff: '+ 3 | scout', source: 'subagent', sourceName: 'TestsScout' },+ { diff: '- 4 | docs', source: 'subagent', sourceName: 'DocsScout' },+ ])+ })++ it('ignores failed, running, malformed, pathless, and empty-diff turns', () => {+ expect(+ collectCodeFileDiffs(+ [+ edit('src/a.ts', '+ 1 | ignored', { isError: true }),+ edit('src/a.ts', '+ 1 | ignored', { status: 'running' }),+ edit('src/a.ts', ''),+ edit(42, '+ 1 | ignored'),+ edit('', '+ 1 | ignored'),+ {+ role: 'tool',+ content: '',+ name: 'edit',+ args: 'bad',+ diff: '+ 1 | ignored',+ status: 'done',+ },+ ],+ []+ )+ ).toEqual([])+ })++ it('counts only focused diff lines that start with plus-space or minus-space', () => {+ expect(+ collectCodeFileDiffs(+ [+ edit(+ 'src/a.ts',+ '+++ b/src/a.ts\n+ 1 | focused\n+not focused\n- 2 | removed\n--- a/src/a.ts\n-not focused'+ ),+ ],+ []+ )[0]+ ).toMatchObject({ additions: 1, deletions: 1 })+ })+})diff --git a/web-app/src/lib/__tests__/codePreview.test.ts b/web-app/src/lib/__tests__/codePreview.test.tsnew file mode 100644index 000000000..2696f90cc--- /dev/null+++ b/web-app/src/lib/__tests__/codePreview.test.ts@@ -0,0 +1,128 @@+import { describe, it, expect } from 'vitest'+import {+ previewKindFor,+ extensionOf,+ basenameOf,+ isAssetKind,+ unresolvedRefs,+ resolveInRoot,+} from '@/lib/codePreview'++describe('previewKindFor', () => {+ it('maps the renderable types', () => {+ expect(previewKindFor('a/index.html')).toBe('html')+ expect(previewKindFor('a/logo.svg')).toBe('svg')+ expect(previewKindFor('README.md')).toBe('markdown')+ expect(previewKindFor('shot.PNG')).toBe('image')+ expect(previewKindFor('clip.mp4')).toBe('video')+ expect(previewKindFor('track.mp3')).toBe('audio')+ expect(previewKindFor('main.rs')).toBe('text')+ })++ it('falls back to a file card for unknown and binary types', () => {+ // These must not be rendered as text — `read_file_sync` is+ // `read_to_string` and would fail on them anyway.+ expect(previewKindFor('deck.pptx')).toBe('file')+ expect(previewKindFor('report.pdf')).toBe('file')+ expect(previewKindFor('archive.zip')).toBe('file')+ expect(previewKindFor('bin/tool')).toBe('file')+ })++ it('treats a dotfile as having no extension, not an extension', () => {+ expect(extensionOf('.gitignore')).toBe('')+ expect(previewKindFor('.gitignore')).toBe('file')+ })++ it('reads the extension from the basename, not an earlier path segment', () => {+ expect(extensionOf('my.dir/file')).toBe('')+ expect(previewKindFor('v1.2/notes.md')).toBe('markdown')+ })++ it('handles windows separators', () => {+ expect(basenameOf('a\\b\\index.html')).toBe('index.html')+ expect(previewKindFor('a\\b\\index.html')).toBe('html')+ })++ it('routes only image/video through the asset protocol', () => {+ expect(isAssetKind('image')).toBe(true)+ expect(isAssetKind('video')).toBe(true)+ expect(isAssetKind('html')).toBe(false)+ expect(isAssetKind('text')).toBe(false)+ })+})++describe('unresolvedRefs', () => {+ // The pane renders into an opaque-origin sandbox with no base URL, so these+ // silently fail to load. Counting them is what lets us say so.+ it('counts relative src/href that the sandbox cannot resolve', () => {+ expect(unresolvedRefs('<img src="./logo.png">')).toBe(1)+ expect(unresolvedRefs('<link href="style.css"><script src="app.js">')).toBe(2)+ expect(unresolvedRefs("<img src='sub/dir/a.png'>")).toBe(1)+ })++ it('does not count anything that resolves on its own', () => {+ expect(unresolvedRefs('<img src="data:image/png;base64,AAA">')).toBe(0)+ expect(unresolvedRefs('<script src="https://cdn.example/x.js">')).toBe(0)+ expect(unresolvedRefs('<img src="//cdn.example/x.png">')).toBe(0)+ expect(unresolvedRefs('<a href="#section">x</a>')).toBe(0)+ expect(unresolvedRefs('<img src="blob:abc">')).toBe(0)+ })++ it('is zero for a self-contained page, which is the common generated case', () => {+ const page = `<html><style>body{color:red}</style><script>1</script></html>`+ expect(unresolvedRefs(page)).toBe(0)+ })++ it('ignores empty values', () => {+ expect(unresolvedRefs('<img src="">')).toBe(0)+ })+})++describe('resolveInRoot', () => {+ const root = '/Users/me/proj'++ it('resolves a relative path', () => {+ expect(resolveInRoot(root, 'index.html')).toBe('/Users/me/proj/index.html')+ expect(resolveInRoot(root, 'a/b.md')).toBe('/Users/me/proj/a/b.md')+ })++ it('accepts an absolute path inside the root', () => {+ // Regression: the agent reports absolute paths for some writes and+ // relative for others; refusing absolute rejected in-project files.+ expect(resolveInRoot(root, '/Users/me/proj/flappy.html')).toBe(+ '/Users/me/proj/flappy.html'+ )+ })++ it('refuses anything that lands outside the root', () => {+ expect(resolveInRoot(root, '../secrets.env')).toBeNull()+ expect(resolveInRoot(root, 'a/../../etc/passwd')).toBeNull()+ expect(resolveInRoot(root, '/etc/passwd')).toBeNull()+ // Sibling dir sharing a name prefix must not pass the prefix check.+ expect(resolveInRoot(root, '/Users/me/proj-other/x')).toBeNull()+ })++ it('collapses . and trailing slashes', () => {+ expect(resolveInRoot(root + '/', './a.md')).toBe('/Users/me/proj/a.md')+ expect(resolveInRoot(root, 'a/./b/../c.md')).toBe('/Users/me/proj/a/c.md')+ })++ it('handles windows paths', () => {+ expect(resolveInRoot('C:\\proj', 'a\\b.html')).toBe('C:/proj/a/b.html')+ expect(resolveInRoot('C:\\proj', 'C:\\other\\x')).toBeNull()+ })++ it('compares containment case-insensitively (Windows/macOS volumes are)', () => {+ expect(resolveInRoot('/Users/me/Proj', '/users/me/proj/a.html')).toBe(+ '/users/me/proj/a.html'+ )+ expect(resolveInRoot('c:/proj', 'C:/Proj/a.html')).toBe('C:/Proj/a.html')+ // Still refuses a genuinely different directory.+ expect(resolveInRoot('/Users/me/Proj', '/Users/me/Other/a.html')).toBeNull()+ })++ it('is null on empty input', () => {+ expect(resolveInRoot(root, '')).toBeNull()+ expect(resolveInRoot('', 'a.md')).toBeNull()+ })+})diff --git a/web-app/src/lib/__tests__/htmlAssets.test.ts b/web-app/src/lib/__tests__/htmlAssets.test.tsnew file mode 100644index 000000000..40b5f2354--- /dev/null+++ b/web-app/src/lib/__tests__/htmlAssets.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest'+import { countUnresolvedAssetRefs } from '../htmlAssets'++describe('countUnresolvedAssetRefs', () => {+ it('returns 0 for empty input', () => {+ expect(countUnresolvedAssetRefs('')).toBe(0)+ })++ it('ignores absolute http(s) refs', () => {+ const html = '<img src="https://cdn.example.com/logo.png"><a href="http://x.dev/page">x</a>'+ expect(countUnresolvedAssetRefs(html)).toBe(0)+ })++ it('ignores inline data and blob refs', () => {+ const html = '<img src="data:image/png;base64,AAAA"><link href="blob:abc123">'+ expect(countUnresolvedAssetRefs(html)).toBe(0)+ })++ it('ignores same-document anchors', () => {+ expect(countUnresolvedAssetRefs('<a href="#section">jump</a>')).toBe(0)+ })++ it('counts relative refs that cannot resolve in the sandbox', () => {+ const html = '<img src="./logo.png"><link href="style.css"><script src="app.js"></script>'+ expect(countUnresolvedAssetRefs(html)).toBe(3)+ })++ it('counts protocol-relative and root-absolute refs as unresolved', () => {+ const html = '<img src="//cdn.example.com/x.png"><script src="/vendor.js"></script>'+ expect(countUnresolvedAssetRefs(html)).toBe(2)+ })++ it('counts duplicates individually', () => {+ expect(countUnresolvedAssetRefs('<img src="a.png"><img src="a.png">')).toBe(2)+ })++ it('handles single and double quoted attributes', () => {+ const html = "<img src='a.png'><img src=\"b.png\">"+ expect(countUnresolvedAssetRefs(html)).toBe(2)+ })++ it('ignores empty attribute values', () => {+ expect(countUnresolvedAssetRefs('<img src=""><a href="">x</a>')).toBe(0)+ })+})diff --git a/web-app/src/lib/__tests__/previewInspector.test.ts b/web-app/src/lib/__tests__/previewInspector.test.tsnew file mode 100644index 000000000..e253ffbb1--- /dev/null+++ b/web-app/src/lib/__tests__/previewInspector.test.ts@@ -0,0 +1,273 @@+import { describe, it, expect, beforeAll, afterEach } from 'vitest'+import { PREVIEW_INSPECTOR_SCRIPT } from '../previewInspector'++/**+ * The inspector is an IIFE that runs inside the preview iframe's own document.+ * Vitest's jsdom document stands in for that document: evaluate the script+ * once, then drive it with synthetic pointer events.+ */+const runInspector = () => {+ const fn = new Function(PREVIEW_INSPECTOR_SCRIPT)+ fn()+ // If the document reported itself as still loading, mount waited for+ // DOMContentLoaded (which may already have fired in the test env).+ if (document.querySelectorAll('[data-jan-inspector="1"]').length < 3) {+ document.dispatchEvent(new Event('DOMContentLoaded'))+ }+}++const overlays = () =>+ [...document.querySelectorAll<HTMLDivElement>('[data-jan-inspector="1"]')]++const fire = (type: string, target: Element) => {+ const Ctor =+ typeof PointerEvent !== 'undefined' ? PointerEvent : MouseEvent+ target.dispatchEvent(new Ctor(type, { bubbles: true, cancelable: true }))+}++const visible = (el: HTMLDivElement) => el.style.display === 'block'++describe('PREVIEW_INSPECTOR_SCRIPT', () => {+ beforeAll(() => {+ // jsdom has no layout engine: derive rects from inline styles so the+ // inspector's getBoundingClientRect calls produce meaningful values.+ Element.prototype.getBoundingClientRect = function (this: Element): DOMRect {+ const num = (v: string | undefined) => {+ const n = parseFloat(v ?? '')+ return Number.isFinite(n) ? n : 0+ }+ const st = this.style as CSSStyleDeclaration+ const left = num(st.left)+ const top = num(st.top)+ const width = num(st.width)+ const height = num(st.height)+ return {+ left,+ top,+ width,+ height,+ right: left + width,+ bottom: top + height,+ x: left,+ y: top,+ toJSON: () => ({}),+ } as DOMRect+ }+ runInspector()+ })++ afterEach(() => {+ // Clear the pin and hover box, then drop every node the tests added while+ // keeping the inspector's own overlay divs (children of body).+ fire('pointerdown', document.body)+ for (const el of overlays()) el.style.display = 'none'+ for (const el of document.body.querySelectorAll(':not([data-jan-inspector])')) {+ el.remove()+ }+ const main = document.createElement('main')+ document.body.appendChild(main)+ })++ it('installs three overlay nodes (hover box, pin box, label)', () => {+ expect(overlays().length).toBe(3)+ for (const el of overlays()) {+ expect(el.style.pointerEvents).toBe('none')+ expect(el.style.position).toBe('fixed')+ expect(el.style.display).toBe('none')+ }+ })++ it('shows a dashed hover outline on pointerover and hides it on pointerout', () => {+ const main = document.querySelector('main')!+ main.style.width = '200px'+ main.style.height = '100px'+ const [hoverBox] = overlays()++ fire('pointerover', main)+ expect(visible(hoverBox)).toBe(true)+ // Hover uses dotted to visually distinguish from user annotations+ expect(hoverBox.style.border).toContain('dotted')+ expect(hoverBox.style.width).toBe('200px')+ expect(hoverBox.style.height).toBe('100px')++ fire('pointerout', main)+ expect(visible(hoverBox)).toBe(false)+ })++ it('ignores hover on the document background', () => {+ const [hoverBox] = overlays()+ fire('pointerover', document.body)+ expect(visible(hoverBox)).toBe(false)+ })++ it('pins a dashed bbox with a label on click', () => {+ const main = document.querySelector('main')!+ main.id = 'main'+ main.className = 'card active'+ main.style.width = '120px'+ main.style.height = '60px'+ const [, pinBox, pinLabel] = overlays()++ fire('pointerdown', main)+ expect(visible(pinBox)).toBe(true)+ // Pin uses dashed to distinguish from user annotations (which are solid)+ expect(pinBox.style.border).toContain('dashed')+ expect(pinBox.style.width).toBe('120px')+ expect(pinLabel.textContent).toBe('main#main.card.active')+ })++ it('posts the pinned bbox rect and selector to the parent', () => {+ const spy = vi.spyOn(window, 'postMessage').mockImplementation(() => {})+ const main = document.querySelector('main')!+ main.style.width = '120px'+ main.style.height = '60px'++ fire('pointerdown', main)+ expect(spy).toHaveBeenCalledWith(+ {+ source: 'jan-preview-inspector',+ type: 'pin',+ label: 'main',+ rect: { x: 0, y: 0, width: 120, height: 60 },+ },+ '*'+ )+ spy.mockRestore()+ })++ it('posts clear when the pin is dismissed', () => {+ const spy = vi.spyOn(window, 'postMessage').mockImplementation(() => {})+ const main = document.querySelector('main')!+ main.style.width = '80px'+ main.style.height = '40px'++ fire('pointerdown', main)+ fire('pointerdown', document.body)+ const calls = spy.mock.calls.map((c) => (c[0] as { type?: string }).type)+ expect(calls).toContain('pin')+ expect(calls).toContain('clear')+ spy.mockRestore()+ })++ it('labels svg-style elements with lowercase tags', () => {+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'rect')+ svg.setAttribute('class', 'plot bar')+ svg.setAttribute('width', '10')+ svg.setAttribute('height', '10')+ document.querySelector('main')!.appendChild(svg)+ const [, , pinLabel] = overlays()++ fire('pointerdown', svg)+ expect(pinLabel.textContent).toBe('rect.plot.bar')+ })++ it('truncates very long labels', () => {+ const el = document.createElement('div')+ el.className =+ 'a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9'+ document.querySelector('main')!.appendChild(el)+ const [, , pinLabel] = overlays()++ fire('pointerdown', el)+ expect((pinLabel.textContent ?? '').length).toBe(60)+ expect(pinLabel.textContent?.endsWith('…')).toBe(true)+ })++ it('clears the pin when clicking the background', () => {+ const main = document.querySelector('main')!+ const [, pinBox, pinLabel] = overlays()++ fire('pointerdown', main)+ expect(visible(pinBox)).toBe(true)++ fire('pointerdown', document.body)+ expect(visible(pinBox)).toBe(false)+ expect(visible(pinLabel)).toBe(false)+ })++ it('clears the pin on Escape', () => {+ const main = document.querySelector('main')!+ const [, pinBox] = overlays()++ fire('pointerdown', main)+ expect(visible(pinBox)).toBe(true)++ document.dispatchEvent(+ new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })+ )+ expect(visible(pinBox)).toBe(false)+ })++ it('keeps the pin aligned after a scroll', () => {+ const main = document.querySelector('main')!+ main.style.width = '80px'+ main.style.height = '40px'+ const [, pinBox] = overlays()++ fire('pointerdown', main)+ expect(pinBox.style.left).toBe('0px')++ main.style.left = '50px'+ main.style.top = '25px'+ window.dispatchEvent(new Event('scroll'))+ expect(pinBox.style.left).toBe('50px')+ expect(pinBox.style.top).toBe('25px')+ })++ it('treats a viewport-covering wrapper as background (click clears)', () => {+ const main = document.querySelector('main')!+ const [, pinBox] = overlays()+ // jsdom default viewport is 1024x768; a wrapper covering ~all of it must+ // deselect instead of pinning the full-page container.+ main.style.width = '1100px'+ main.style.height = '800px'++ fire('pointerdown', main)+ expect(visible(pinBox)).toBe(false)+ })++ it('posts the pinned bbox rect and selector to the parent', () => {+ const spy = vi.spyOn(window, 'postMessage').mockImplementation(() => {})+ const main = document.querySelector('main')!+ main.style.width = '120px'+ main.style.height = '60px'++ fire('pointerdown', main)+ expect(spy).toHaveBeenCalledWith(+ {+ source: 'jan-preview-inspector',+ type: 'pin',+ label: 'main',+ rect: { x: 0, y: 0, width: 120, height: 60 },+ },+ '*'+ )+ spy.mockRestore()+ })++ it('posts clear when the pin is dismissed', () => {+ const spy = vi.spyOn(window, 'postMessage').mockImplementation(() => {})+ const main = document.querySelector('main')!+ main.style.width = '80px'+ main.style.height = '40px'++ fire('pointerdown', main)+ fire('pointerdown', document.body)+ const calls = spy.mock.calls.map((c) => (c[0] as { type?: string }).type)+ expect(calls).toContain('pin')+ expect(calls).toContain('clear')+ spy.mockRestore()+ })++ it('clears the pin when the pinned element leaves the DOM', () => {+ const main = document.querySelector('main')!+ const [, pinBox] = overlays()++ fire('pointerdown', main)+ expect(visible(pinBox)).toBe(true)++ main.remove()+ window.dispatchEvent(new Event('scroll'))+ expect(visible(pinBox)).toBe(false)+ })+})diff --git a/web-app/src/lib/__tests__/todoLabels.test.ts b/web-app/src/lib/__tests__/todoLabels.test.tsnew file mode 100644index 000000000..64822f913--- /dev/null+++ b/web-app/src/lib/__tests__/todoLabels.test.ts@@ -0,0 +1,36 @@+import { describe, it, expect } from 'vitest'+import { cleanTaskLabel } from '@/lib/todoLabels'++describe('cleanTaskLabel', () => {+ it('strips a model-written status marker so it does not double up with the row icon', () => {+ expect(cleanTaskLabel('✅ Launch 3 parallel subagents')).toBe(+ 'Launch 3 parallel subagents'+ )+ expect(cleanTaskLabel('☐ Collect all 3 reports')).toBe('Collect all 3 reports')+ expect(cleanTaskLabel('[x] Run validation script')).toBe('Run validation script')+ expect(cleanTaskLabel('[ ] Run validation script')).toBe('Run validation script')+ expect(cleanTaskLabel('- Open the final file')).toBe('Open the final file')+ expect(cleanTaskLabel('• Open the final file')).toBe('Open the final file')+ })++ it('only strips one leading marker, never mid-label content', () => {+ expect(cleanTaskLabel('Visual QA via PDF→images')).toBe('Visual QA via PDF→images')+ // A marker that is part of the sentence stays put.+ expect(cleanTaskLabel('Check the ✅ column renders')).toBe('Check the ✅ column renders')+ // Nested markers: only the outermost one goes.+ expect(cleanTaskLabel('- [x] Ship it')).toBe('[x] Ship it')+ })++ it('never returns an empty label', () => {+ // A label that is nothing but a marker would otherwise render as a blank+ // row, which reads as a rendering bug rather than a bare task.+ expect(cleanTaskLabel('✅')).toBe('✅')+ expect(cleanTaskLabel(' ')).toBe('')+ })++ it('leaves an ordinary label untouched', () => {+ expect(cleanTaskLabel('Write pptxgenjs script for 5-slide deck')).toBe(+ 'Write pptxgenjs script for 5-slide deck'+ )+ })+})diff --git a/web-app/src/lib/agentActivity.test.ts b/web-app/src/lib/agentActivity.test.tsnew file mode 100644index 000000000..d777446ae--- /dev/null+++ b/web-app/src/lib/agentActivity.test.ts@@ -0,0 +1,199 @@+import { describe, it, expect } from 'vitest'+import {+ toolActivityText,+ completedToolLabel,+ usedSkillNames,+ activeToolPart,+ subagentActivityLabel,+} from './agentActivity'+import type { SubagentRun } from '@/hooks/useCodeSessions'++describe('toolActivityText', () => {+ it('formats write with basename only', () => {+ expect(toolActivityText('write', { path: '/a/b/report.html' })).toBe(+ 'Writing report.html'+ )+ })++ it('formats edit with basename only', () => {+ expect(toolActivityText('edit', { path: 'src/config.ts' })).toBe(+ 'Editing config.ts'+ )+ })+ it('formats write with Windows-style path basename only', () => {+ expect(+ toolActivityText('write', { path: 'C:\\Users\\x\\report.html' })+ ).toBe('Writing report.html')+ })++ it('formats bash with truncated command', () => {+ expect(toolActivityText('bash', { command: 'ls -la' })).toBe(+ 'Running ls -la'+ )+ })++ it('truncates long bash commands to 60 chars', () => {+ const long = 'echo ' + 'x'.repeat(100)+ const text = toolActivityText('bash', { command: long })+ expect(text.startsWith('Running echo ')).toBe(true)+ expect(text.length).toBeLessThanOrEqual('Running '.length + 60)+ })++ it('formats read/ls/find/grep with basename', () => {+ expect(toolActivityText('read', { path: '/x/y.md' })).toBe('Reading y.md')+ expect(toolActivityText('ls', { path: '/x' })).toBe('Listing x')+ expect(toolActivityText('find', { path: '/x' })).toBe('Finding x')+ expect(toolActivityText('grep', { path: '/x' })).toBe('Searching x')+ })++ it('formats memory tools without a path', () => {+ expect(toolActivityText('memory_write', {})).toBe('Saving memory')+ expect(toolActivityText('memory_read', {})).toBe('Reading memory')+ expect(toolActivityText('memory_list', {})).toBe('Reading memory')+ })++ it('names the skill being read', () => {+ expect(toolActivityText('skill_read', { name: 'pptx' })).toBe(+ 'Reading pptx'+ )+ expect(+ completedToolLabel('skill_read', { name: 'pptx' }, 'output-available')+ ).toBe('Used pptx')+ })++ it('falls back to humanized tool name for unknown tools', () => {+ expect(toolActivityText('web_search', { query: 'x' })).toBe('Web search')+ })++ it('falls back gracefully when path/command arg is missing', () => {+ expect(toolActivityText('write', {})).toBe('Writing')+ expect(toolActivityText('bash', {})).toBe('Running')+ })+})++describe('usedSkillNames', () => {+ it('returns unique successfully loaded skill names only', () => {+ expect(+ usedSkillNames([+ {+ type: 'tool-skill_read',+ state: 'output-available',+ input: { name: 'pptx' },+ },+ {+ type: 'tool-skill_read',+ state: 'output-available',+ input: { name: 'pptx' },+ },+ {+ type: 'tool-skill_read',+ state: 'output-error',+ input: { name: 'broken' },+ },+ ])+ ).toEqual(['pptx'])+ })+})++describe('activeToolPart', () => {+ it('returns null when no part is pending', () => {+ const parts = [+ { type: 'text', state: undefined },+ {+ type: 'tool-write',+ state: 'output-available',+ toolCallId: 'c1',+ input: { path: 'a.ts' },+ },+ ]+ expect(activeToolPart(parts)).toBeNull()+ })++ it('returns the pending tool part text and id', () => {+ const parts = [+ {+ type: 'tool-write',+ state: 'input-available',+ toolCallId: 'c1',+ input: { path: 'report.html' },+ },+ ]+ expect(activeToolPart(parts)).toEqual({+ toolCallId: 'c1',+ toolName: 'write',+ text: 'Writing report.html',+ })+ })++ it('ignores non-tool parts', () => {+ const parts = [{ type: 'text', state: 'input-available' }]+ expect(activeToolPart(parts)).toBeNull()+ })+})++describe('subagentActivityLabel', () => {+ it('returns null when no subagent is running', () => {+ const subagents: SubagentRun[] = [+ {+ runId: 'r1',+ name: 'Researcher',+ status: 'done',+ startedAt: 1,+ turns: [],+ },+ ]+ expect(subagentActivityLabel(subagents)).toBeNull()+ })++ it('labels a single running subagent with its own tool activity', () => {+ const subagents: SubagentRun[] = [+ {+ runId: 'r1',+ name: 'Researcher',+ status: 'running',+ startedAt: 1000,+ turns: [+ {+ role: 'tool',+ content: '',+ name: 'write',+ args: { path: 'notes.md' },+ status: 'running',+ },+ ],+ },+ ]+ expect(subagentActivityLabel(subagents)).toEqual({+ text: 'Researcher: Writing notes.md',+ startedAt: 1000,+ })+ })++ it('labels a single running subagent with "working" when it has no tool turn', () => {+ const subagents: SubagentRun[] = [+ {+ runId: 'r1',+ name: 'Researcher',+ status: 'running',+ startedAt: 1000,+ turns: [],+ },+ ]+ expect(subagentActivityLabel(subagents)).toEqual({+ text: 'Researcher: working',+ startedAt: 1000,+ })+ })++ it('labels multiple running subagents with a count and earliest startedAt', () => {+ const subagents: SubagentRun[] = [+ { runId: 'r1', name: 'A', status: 'running', startedAt: 2000, turns: [] },+ { runId: 'r2', name: 'B', status: 'running', startedAt: 1000, turns: [] },+ { runId: 'r3', name: 'C', status: 'done', startedAt: 500, turns: [] },+ ]+ expect(subagentActivityLabel(subagents)).toEqual({+ text: '2 subagents working',+ startedAt: 1000,+ })+ })+})diff --git a/web-app/src/lib/agentActivity.ts b/web-app/src/lib/agentActivity.tsnew file mode 100644index 000000000..b7a45493b--- /dev/null+++ b/web-app/src/lib/agentActivity.ts@@ -0,0 +1,142 @@+import type { CodeTurn, SubagentRun } from '@/types/codeSession'++export type ActivityLabel = { text: string; startedAt: number } | null++const MAX_COMMAND_LEN = 60++function basename(path: string): string {+ const normalized = path.replace(/\\/g, '/').replace(/\/+$/, '')+ const idx = normalized.lastIndexOf('/')+ return idx === -1 ? normalized : normalized.slice(idx + 1) || normalized+}++function truncate(text: string, max: number): string {+ return text.length > max ? `${text.slice(0, max - 1)}…` : text+}++function stringArg(input: unknown, key: string): string | undefined {+ if (!input || typeof input !== 'object') return undefined+ const value = (input as Record<string, unknown>)[key]+ return typeof value === 'string' && value.length > 0 ? value : undefined+}++function humanizeToolName(name: string): string {+ const spaced = name.replace(/[_-]+/g, ' ').trim()+ if (!spaced) return 'tool'+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)+}++const VERB_BY_TOOL: Record<string, string> = {+ write: 'Writing',+ edit: 'Editing',+ bash: 'Running',+ read: 'Reading',+ ls: 'Listing',+ find: 'Finding',+ grep: 'Searching',+}++const NO_DETAIL_TOOLS: Record<string, string> = {+ memory_write: 'Saving memory',+ memory_read: 'Reading memory',+ memory_list: 'Reading memory',+}++/** Text for one tool call, given its name and args. Pure formatting, no timestamp. */+export function toolActivityText(toolName: string, input: unknown): string {+ const fixed = NO_DETAIL_TOOLS[toolName]+ if (fixed) return fixed++ if (toolName === 'skill_read') {+ const name = stringArg(input, 'name')+ return name ? `Reading ${name}` : 'Reading skill'+ }++ const verb = VERB_BY_TOOL[toolName]+ if (!verb) return humanizeToolName(toolName)++ if (toolName === 'bash') {+ const command = stringArg(input, 'command')+ return command ? `${verb} ${truncate(command, MAX_COMMAND_LEN)}` : verb+ }++ const path = stringArg(input, 'path')+ return path ? `${verb} ${basename(path)}` : verb+}++export function completedToolLabel(+ toolName: string,+ input: unknown,+ state: string+): string {+ if (toolName === 'skill_read' && state === 'output-available') {+ const name = stringArg(input, 'name')+ return name ? `Used ${name}` : 'Used skill'+ }+ return toolActivityText(toolName, input)+}++type ToolPartLike = {+ type: string+ state?: string+ toolCallId?: string+ input?: unknown+}++const PENDING_STATES = new Set(['input-available', 'submitted'])++/** Finds the first pending tool part; returns its id, name, and activity text. */+export function activeToolPart(+ parts: ToolPartLike[]+): { toolCallId: string; toolName: string; text: string } | null {+ for (const part of parts) {+ if (!part.type.startsWith('tool-')) continue+ if (!part.state || !PENDING_STATES.has(part.state)) continue+ if (!part.toolCallId) continue+ const toolName = part.type.slice('tool-'.length)+ return {+ toolCallId: part.toolCallId,+ toolName,+ text: toolActivityText(toolName, part.input),+ }+ }+ return null+}++export function usedSkillNames(parts: ToolPartLike[]): string[] {+ const names = new Set<string>()+ for (const part of parts) {+ if (part.type !== 'tool-skill_read' || part.state !== 'output-available') {+ continue+ }+ const name = stringArg(part.input, 'name')+ if (name) names.add(name)+ }+ return [...names]+}++function lastRunningToolTurn(turns: CodeTurn[]): CodeTurn | undefined {+ for (let i = turns.length - 1; i >= 0; i--) {+ const turn = turns[i]+ if (turn.role === 'tool' && turn.status === 'running') return turn+ }+ return undefined+}++/** null if no subagent is running; else a combined label + earliest startedAt. */+export function subagentActivityLabel(subagents: SubagentRun[]): ActivityLabel {+ const running = subagents.filter((s) => s.status === 'running')+ if (running.length === 0) return null++ if (running.length === 1) {+ const run = running[0]+ const activeTurn = lastRunningToolTurn(run.turns)+ const detail = activeTurn+ ? toolActivityText(activeTurn.name ?? 'tool', activeTurn.args)+ : 'working'+ return { text: `${run.name}: ${detail}`, startedAt: run.startedAt }+ }++ const startedAt = Math.min(...running.map((s) => s.startedAt))+ return { text: `${running.length} subagents working`, startedAt }+}diff --git a/web-app/src/lib/codeArtifacts.ts b/web-app/src/lib/codeArtifacts.tsnew file mode 100644index 000000000..b60caa195--- /dev/null+++ b/web-app/src/lib/codeArtifacts.ts@@ -0,0 +1,260 @@+import { AudioLines, Code2, FileText, ImageIcon, Video } from 'lucide-react'+import { basenameOf, extensionOf, resolveInRoot } from '@/lib/codePreview'+import type { CodeTurn } from '@/types/codeSession'++/**+ * Artifacts a run produced, derived from its `write`/`edit` tool calls+ * (jan-internal #242 / #304).+ *+ * Two filters, because either alone is wrong:+ *+ * 1. The path must look like a deliverable (see the extension allowlist).+ * 2. The agent must have **created** the file, not modified an existing one.+ *+ * (2) is what makes this usable on a real codebase. On an empty folder the+ * allowlist alone is fine, but in a repo of thousands of files `.md`, `.svg`,+ * `.html`, `.csv` and images *are* the codebase — editing READMEs or icons+ * would otherwise flood the library with source assets. A file the agent+ * brought into existence is a deliverable; one it edited was already yours.+ *+ * Modifications remain visible in the diff panel (#285), which is the right+ * surface for "what did the agent change".+ */+export type CodeArtifact = {+ /** Project-relative path, as the tool reported it. */+ path: string+ /** Display name — the basename without its extension. */+ title: string+ /** Coarse grouping shown on the card, e.g. `Code · HTML`. */+ group: 'Code' | 'Image' | 'Document' | 'Video' | 'Audio'+ /** Upper-cased extension, e.g. `HTML`. */+ label: string+}++/** Extension → grouping. Anything absent is not an artifact. */+const ARTIFACT_GROUPS: Record<string, CodeArtifact['group']> = {+ html: 'Code',+ htm: 'Code',+ svg: 'Code',+ png: 'Image',+ jpg: 'Image',+ jpeg: 'Image',+ gif: 'Image',+ webp: 'Image',+ md: 'Document',+ pdf: 'Document',+ docx: 'Document',+ xlsx: 'Document',+ pptx: 'Document',+ csv: 'Document',+ mp4: 'Video',+ webm: 'Video',+ mov: 'Video',+ mkv: 'Video',+ avi: 'Video',+ m4v: 'Video',+ mp3: 'Audio',+ wav: 'Audio',+ ogg: 'Audio',+ flac: 'Audio',+ m4a: 'Audio',+ aac: 'Audio',+ opus: 'Audio',+}++export function isArtifactPath(path: string): boolean {+ return extensionOf(path) in ARTIFACT_GROUPS+}++export function artifactFor(path: string): CodeArtifact | null {+ const ext = extensionOf(path)+ const group = ARTIFACT_GROUPS[ext]+ if (!group) return null+ const base = basenameOf(path)+ const dot = base.lastIndexOf('.')+ return {+ path,+ title: dot > 0 ? base.slice(0, dot) : base,+ group,+ label: ext.toUpperCase(),+ }+}++/** Icon per group, shared by the transcript card and the artifacts library. */+export const ARTIFACT_ICON = {+ Code: Code2,+ Image: ImageIcon,+ Document: FileText,+ Video: Video,+ Audio: AudioLines,+} as const++export const ARTIFACT_GROUP_NAMES = ['Code', 'Image', 'Document', 'Video', 'Audio'] as const++/**+ * Did this write bring a new file into existence?+ *+ * `write` reports `Created <path> (<n> bytes)` or `Overwrote <path> (...)`+ * (handlers.rs), and its diff is headed `@@ created file @@` for a new file.+ * On a UIMessage part the diff is prepended to the result, so the marker is not+ * at position 0 — hence `includes` rather than `startsWith`.+ *+ * Sessions written before the tool reported this said `Wrote N bytes to <path>`+ * with no create/modify distinction. Those are treated as creations: they are+ * historical, and dropping them would silently empty an existing library.+ */+export function createdNewFile(value: unknown): boolean {+ // A UIMessagePart's `output` is typed `unknown`, so narrow here rather than+ // casting at every call site.+ const text = typeof value === 'string' ? value : ''+ if (!text) return false+ if (text.includes('Overwrote ')) return false+ return (+ text.includes('Created ') ||+ text.includes('@@ created file @@') ||+ text.includes('Wrote ') // legacy format, no distinction available+ )+}++type PartLike = {+ type?: string+ input?: unknown+ state?: string+ output?: unknown+}++const pathFromInput = (input: unknown): string | undefined => {+ if (input && typeof input === 'object' && 'path' in input) {+ const v = (input as Record<string, unknown>).path+ return typeof v === 'string' ? v : undefined+ }+ return undefined+}++/** A path-shaped token, quoted or bare, e.g. `cat_video.mp4` or `"Rick ....mp4"`. */+const PATH_TOKEN_RE = /"([^"]+)"|'([^']+)'|(\S+)/g++/**+ * Artifact paths a `bash` turn produced, recovered from its command and output.+ *+ * `write` results name their file directly; `bash` does not. Two signals, one+ * rule:+ *+ * 1. A path the command names explicitly (yt-dlp `-o out.mp4`, `ls -lh+ * cat_video.mp4`, `mv a.mp4 b.mp4`) that the output confirms exists — the+ * basename reappears in the tool output, so the file is real after the run.+ * 2. A `Destination: <path>` line in the output (yt-dlp / wget / curl `-o`),+ * which declares the file being written even when the command used a+ * format template (`-o "%(title)s.%(ext)s"`).+ *+ * Probes and directory listings are filtered out: `which ffmpeg` names no+ * artifact path, and `ls *.mp4` names no literal file — the output lists real+ * names but the command token `*.mp4` never reappears verbatim, so nothing is+ * confirmed.+ *+ * Absolute paths pass through; relative paths resolve against `root`.+ */+export function bashArtifactPaths(+ command: unknown,+ output: unknown,+ root: string | null | undefined+): CodeArtifact[] {+ const cmd = typeof command === 'string' ? command : ''+ const out = typeof output === 'string' ? output : ''+ if (!out) return []+ const seen = new Set<string>()+ const found: CodeArtifact[] = []+ const consider = (raw: string) => {+ const token = raw.trim()+ if (!token || seen.has(token) || !isArtifactPath(token)) return+ seen.add(token)+ const path = root ? (resolveInRoot(root, token) ?? token) : token+ const artifact = artifactFor(path)+ if (artifact) found.push(artifact)+ }+ // 1. Command-named paths, confirmed by their basename reappearing in the+ // output. Quoted paths with spaces survive as one token.+ for (const m of (cmd || '').matchAll(PATH_TOKEN_RE)) {+ const token = (m[1] ?? m[2] ?? m[3] ?? '').trim()+ if (token && isArtifactPath(token) && out.includes(basenameOf(token))) {+ consider(token)+ }+ }+ // 2. `Destination: <path>` in the output — yt-dlp-style writers declare the+ // file even when the command only carried a format template.+ for (const m of out.matchAll(/Destination:\s*([^\n\r]+)/gi)) {+ consider(m[1] ?? '')+ }+ return found+}++/**+ * Artifacts attributable to one message, read off its own `write`/`edit` tool+ * parts. Keeping the association message-local is what lets the card render+ * inline in the transcript without `MessageItem` needing to know about+ * artifacts at all.+ *+ * Deduplicated by path, keeping first-seen order: a run that writes then edits+ * the same file produced one artifact, not two.+ */+export function artifactsFromParts(parts: PartLike[] | undefined): CodeArtifact[] {+ if (!parts?.length) return []+ const out: CodeArtifact[] = []+ const seen = new Set<string>()+ for (const part of parts) {+ // `edit` targets a file that already existed, so it never creates one.+ if (part.type !== 'tool-write') continue+ // Only a call that actually completed produced a file.+ if (part.state && part.state !== 'output-available') continue+ if (!createdNewFile(part.output)) continue+ const path = pathFromInput(part.input)+ if (!path || seen.has(path)) continue+ const artifact = artifactFor(path)+ if (!artifact) continue+ seen.add(path)+ out.push(artifact)+ }+ return out+}++/**+ * Artifacts a whole session produced, read straight off its turns.+ *+ * Deliberately not `codeTurnsToUIMessages` + {@link artifactsFromParts}: that+ * builds the full message tree (markdown parts, reasoning splitting, tool+ * grouping) for every session just to recover a handful of paths. The library+ * lists every session at once, so that cost is paid per render.+ *+ * Deduplicated by path — a session that rewrites a file across turns produced+ * one artifact, not one per rewrite.+ */+export function artifactsFromTurns(+ turns: CodeTurn[] | undefined,+ root?: string | null+): CodeArtifact[] {+ if (!turns?.length) return []+ const byPath = new Map<string, CodeArtifact>()+ for (const turn of turns) {+ if (turn.role !== 'tool') continue+ // Only a completed, non-error call produced a file.+ if (turn.isError || turn.status === 'running') continue+ if (turn.name === 'write') {+ if (!createdNewFile(turn.result ?? turn.content)) continue+ const path = pathFromInput(turn.args)+ if (!path) continue+ const artifact = artifactFor(path)+ if (artifact) byPath.set(path, artifact)+ } else if (turn.name === 'bash') {+ // Files made by shell commands (downloads, ffmpeg renders) carry no+ // `write` result; recover them from the command + output pair.+ const command =+ turn.args && typeof turn.args === 'object'+ ? (turn.args as Record<string, unknown>).command+ : undefined+ for (const artifact of bashArtifactPaths(command, turn.result ?? turn.content, root)) {+ byPath.set(artifact.path, artifact)+ }+ }+ }+ return [...byPath.values()]+}diff --git a/web-app/src/lib/codeDiffs.ts b/web-app/src/lib/codeDiffs.tsnew file mode 100644index 000000000..1ee4c98a5--- /dev/null+++ b/web-app/src/lib/codeDiffs.ts@@ -0,0 +1,71 @@+import type { CodeTurn, SubagentRun } from '@/types/codeSession'++export type CodeDiffOperation = {+ diff: string+ source: 'main' | 'subagent'+ sourceName?: string+}++export type CodeFileDiff = {+ path: string+ additions: number+ deletions: number+ operations: CodeDiffOperation[]+}++function addOperation(+ files: Map<string, CodeFileDiff>,+ turn: CodeTurn,+ source: 'main' | 'subagent',+ sourceName?: string+) {+ if (+ turn.role !== 'tool' ||+ (turn.name !== 'write' && turn.name !== 'edit') ||+ turn.isError ||+ turn.status === 'running' ||+ !turn.diff+ ) {+ return+ }+ if (!turn.args || typeof turn.args !== 'object') return++ const path = (turn.args as Record<string, unknown>).path+ if (typeof path !== 'string' || !path.trim()) return++ const lines = turn.diff.split('\n')+ const additions = lines.filter((line) => line.startsWith('+ ')).length+ const deletions = lines.filter((line) => line.startsWith('- ')).length+ const operation: CodeDiffOperation = sourceName+ ? { diff: turn.diff, source, sourceName }+ : { diff: turn.diff, source }+ const current = files.get(path)++ if (current) {+ current.additions += additions+ current.deletions += deletions+ current.operations.push(operation)+ return+ }++ files.set(path, { path, additions, deletions, operations: [operation] })+}++export function collectCodeFileDiffs(+ turns: CodeTurn[],+ subagents: SubagentRun[]+): CodeFileDiff[] {+ const files = new Map<string, CodeFileDiff>()++ for (const turn of turns) {+ addOperation(files, turn, 'main')+ }++ for (const run of subagents) {+ for (const turn of run.turns) {+ addOperation(files, turn, 'subagent', run.name)+ }+ }++ return [...files.values()]+}diff --git a/web-app/src/lib/codePreview.ts b/web-app/src/lib/codePreview.tsnew file mode 100644index 000000000..d0b9d1116--- /dev/null+++ b/web-app/src/lib/codePreview.ts@@ -0,0 +1,155 @@+// Renderer selection and load-state modelling for the Cowork preview pane+// (jan-internal #242). Kept pure and separate from the component so the state+// machine and the security checks are testable without a DOM.++/** How a given file should be shown. `file` is the fallback card. */+export type PreviewKind = 'html' | 'svg' | 'markdown' | 'image' | 'video' | 'audio' | 'text' | 'file'++/**+ * Preview FSM, shared with the artifacts library (#304) so both surfaces behave+ * identically.+ *+ * `idle → loading → ready | unsupported | failed`, and `reload` re-enters+ * `loading`. `changedOnDisk` is a flag on `ready` rather than an auto-reload:+ * swapping content under someone mid-interaction (playing a game, scrolled into+ * a document) is worse than offering them the reload.+ */+export type PreviewState =+ | { status: 'idle' }+ | { status: 'loading'; path: string }+ | {+ status: 'ready'+ path: string+ kind: Exclude<PreviewKind, 'file'>+ content?: string+ assetUrl?: string+ /** Relative refs the sandbox cannot resolve — see `unresolvedRefs`. */+ unresolvedRefs?: number+ }+ | { status: 'unsupported'; path: string }+ | { status: 'failed'; path: string; reason: string }++const EXT_KIND: Record<string, PreviewKind> = {+ html: 'html',+ htm: 'html',+ svg: 'svg',+ md: 'markdown',+ markdown: 'markdown',+ png: 'image',+ jpg: 'image',+ jpeg: 'image',+ gif: 'image',+ webp: 'image',+ bmp: 'image',+ ico: 'image',+ mp4: 'video',+ webm: 'video',+ mov: 'video',+ mkv: 'video',+ avi: 'video',+ m4v: 'video',+ mp3: 'audio',+ wav: 'audio',+ ogg: 'audio',+ flac: 'audio',+ m4a: 'audio',+ aac: 'audio',+ opus: 'audio',+ txt: 'text',+ json: 'text',+ css: 'text',+ js: 'text',+ jsx: 'text',+ ts: 'text',+ tsx: 'text',+ py: 'text',+ rs: 'text',+ toml: 'text',+ yml: 'text',+ yaml: 'text',+ sh: 'text',+ csv: 'text',+}++export function extensionOf(path: string): string {+ const base = path.split(/[/\\]/).pop() ?? ''+ const dot = base.lastIndexOf('.')+ // A leading dot is a dotfile, not an extension (`.gitignore`).+ return dot > 0 ? base.slice(dot + 1).toLowerCase() : ''+}++/** Which renderer a path maps to. Unknown/binary types fall back to `file`. */+export function previewKindFor(path: string): PreviewKind {+ return EXT_KIND[extensionOf(path)] ?? 'file'+}++/** `image`, `video` and `audio` stream from disk via the asset protocol, not a read. */+export function isAssetKind(kind: PreviewKind): boolean {+ return kind === 'image' || kind === 'video' || kind === 'audio'+}++export function basenameOf(path: string): string {+ return path.split(/[/\\]/).pop() || path+}++/**+ * `HtmlArtifact` renders into an opaque-origin sandbox via `srcDoc`, so there is+ * no base URL: a relative `src`/`href` cannot resolve and the asset silently+ * fails to load. Count those so the pane can say so instead of presenting a+ * visibly broken page as if it were correct.+ *+ * Absolute URLs, `data:`/`blob:`, protocol-relative URLs, anchors and inline+ * handlers are all fine and not counted.+ */+export function unresolvedRefs(html: string): number {+ let count = 0+ for (const m of html.matchAll(/\b(?:src|href)\s*=\s*("([^"]*)"|'([^']*)')/gi)) {+ const value = (m[2] ?? m[3] ?? '').trim()+ if (!value) continue+ if (+ /^[a-z][a-z0-9+.-]*:/i.test(value) || // any scheme: http:, data:, mailto:+ value.startsWith('//') || // protocol-relative+ value.startsWith('#') // in-page anchor+ ) {+ continue+ }+ count += 1+ }+ return count+}++/**+ * Absolute path for `path` if it lands inside `root`, else null.+ *+ * Accepts relative *or* absolute input: the agent reports either, sometimes+ * both within one session, so refusing absolute outright rejected files that+ * were in the project all along. `..` is collapsed first, so traversal cannot+ * sneak past by ending up inside the root string.+ */+export function resolveInRoot(root: string, path: string): string | null {+ const slash = (p: string) => p.replace(/\\/g, '/')+ const trim = (p: string) => slash(p).replace(/\/+$/, '')+ const r = trim(root)+ if (!r || !path) return null+ const raw = slash(path)+ const isAbs = raw.startsWith('/') || /^[a-z]:\//i.test(raw)+ const joined = isAbs ? raw : `${r}/${raw.replace(/^\/+/, '')}`++ const parts: string[] = []+ for (const seg of joined.split('/')) {+ if (!seg || seg === '.') continue+ if (seg === '..') parts.pop()+ else parts.push(seg)+ }+ const abs = (joined.startsWith('/') ? '/' : '') + parts.join('/')+ // Containment compared case-insensitively: Windows and default macOS volumes+ // are case-insensitive, so `/Users/me/Proj` and `/users/me/proj` are the same+ // directory and a case-sensitive check would refuse an in-project file. The+ // returned path keeps its original casing for the actual read.+ const inRoot = abs.toLowerCase() === r.toLowerCase() ||+ abs.toLowerCase().startsWith(`${r.toLowerCase()}/`)+ return inRoot ? abs : null+}++/** Guard before reading, so an oversized file fails fast instead of hanging. */+export const MAX_PREVIEW_BYTES = 2 * 1024 * 1024diff --git a/web-app/src/lib/codeTurns.ts b/web-app/src/lib/codeTurns.tsindex 0f2e2d0ee..0feb66c62 100644--- a/web-app/src/lib/codeTurns.ts+++ b/web-app/src/lib/codeTurns.ts@@ -1,6 +1,6 @@/* eslint-disable @typescript-eslint/no-explicit-any */import type { UIMessage } from 'ai'-import type { CodeTurn } from '@/hooks/useCodeSessions'+import type { CodeTurn } from '@/types/codeSession'import { reasoningPartsFromText } from '@/lib/messages'/**diff --git a/web-app/src/lib/htmlAssets.ts b/web-app/src/lib/htmlAssets.tsnew file mode 100644index 000000000..868a41bab--- /dev/null+++ b/web-app/src/lib/htmlAssets.ts@@ -0,0 +1,44 @@+/**+ * Detect asset references in generated HTML that cannot resolve inside the+ * artifact iframe's opaque-origin sandbox.+ *+ * The preview mounts model HTML in an iframe with no allow-same-origin, so a+ * relative reference (`./logo.png`, `style.css`, `app.js`) has no base URL to+ * resolve against and fails silently — the page renders visibly broken with no+ * explanation. We scan `src`/`href` attributes for values that are neither+ * absolute (http/https), inline (data:/blob:), nor page-internal anchors, and+ * surface the count so the user knows the page is missing assets instead of+ * staring at a blank spot.+ */++/** URL schemes that resolve without a base URL. */+const RESOLVABLE_SCHEME_RE = /^(?:data|blob|https?|mailto|tel|ftp):/i++/** src/href attribute value, e.g. `./logo.png`, `style.css`, `#section`. */+const ATTR_VALUE_RE = /(?:src|href)\s*=\s*("([^"]*)"|'([^']*)')/gi++function isResolvable(value: string): boolean {+ const trimmed = value.trim()+ if (!trimmed) return true+ if (RESOLVABLE_SCHEME_RE.test(trimmed)) return true+ // Same-document anchor: no network fetch, resolves in the sandbox.+ if (trimmed.startsWith('#')) return true+ // Protocol-relative, absolute-path, or relative refs need a base URL the+ // opaque-origin iframe does not have.+ return false+}++/**+ * Count of src/href values in `html` that cannot resolve in the sandboxed+ * artifact iframe. Returns 0 for empty or non-HTML input; duplicates count+ * (each reference is a separate failed fetch).+ */+export function countUnresolvedAssetRefs(html: string): number {+ if (!html) return 0+ let count = 0+ for (const match of html.matchAll(ATTR_VALUE_RE)) {+ const value = match[2] ?? match[3] ?? ''+ if (!isResolvable(value)) count += 1+ }+ return count+}diff --git a/web-app/src/lib/previewInspector.ts b/web-app/src/lib/previewInspector.tsnew file mode 100644index 000000000..2665909ae--- /dev/null+++ b/web-app/src/lib/previewInspector.ts@@ -0,0 +1,229 @@+/**+ * Element-inspector script injected into artifact preview iframes (Cursor+ * browser / Claude artifacts style). Runs inside the sandboxed srcdoc document+ * itself, so it can inspect the DOM even though the opaque origin makes the+ * parent page unable to reach it.+ *+ * Behavior:+ * - Hover: thin dashed outline + (on click) a pinned solid bounding box and a+ * label chip (`div#main.card.active`, truncated) following the element.+ * - Click an element: pin its bbox + label. Click the background (html/body)+ * or press Escape: clear the pin. Scrolling/resizing keeps the pin aligned.+ * - Every pin/clear posts a `{source:'jan-preview-inspector', type:'pin'|+ * 'clear'}` message to the parent so the annotation overlay can anchor its+ * inline note box at the selected element (see AnnotationOverlay).+ *+ * Kept dependency-free and CSP-safe: inlined via `script-src 'unsafe-inline'`,+ * only DOM/style APIs, no network. The string must never contain the literal+ * `</script` (it would terminate the inline tag early), hence concatenation+ * style and no HTML in here.+ */+export const PREVIEW_INSPECTOR_SCRIPT = `(function () {+ 'use strict'+ if (window.__janPreviewInspector) return+ window.__janPreviewInspector = true++ var HOVER = '#94a3b8' // slate-400 - subtle gray for hover+ var PIN = '#64748b' // slate-500 - darker gray for pinned+ var hoverBox = null+ var pinBox = null+ var pinLabel = null+ var pinnedEl = null++ function makeBox() {+ var el = document.createElement('div')+ el.setAttribute('data-jan-inspector', '1')+ el.style.cssText =+ 'position:fixed;pointer-events:none;z-index:2147483647;display:none;' ++ 'box-sizing:border-box;margin:0;padding:0'+ return el+ }++ function makeLabel() {+ var el = document.createElement('div')+ el.setAttribute('data-jan-inspector', '1')+ el.style.cssText =+ 'position:fixed;pointer-events:none;z-index:2147483647;display:none;' ++ 'max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;' ++ 'padding:1px 6px;border-radius:3px;' ++ 'font:11px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;' ++ 'color:#fff;background:' + HOVER+ return el+ }++ function labelFor(el) {+ var out = (el.tagName || 'div').toLowerCase()+ if (el.id) out += '#' + el.id+ if (el.classList && el.classList.length) {+ var cls = []+ for (var i = 0; i < el.classList.length; i++) cls.push(el.classList[i])+ out += '.' + cls.join('.')+ }+ return out.length > 60 ? out.slice(0, 59) + '…' : out+ }++ function placeBox(box, el, color, width, dashed) {+ var r = el.getBoundingClientRect()+ // Inspector uses dots for hover, short dashes for pin - clearly different+ // from user annotations which use solid lines or long dashes (6px dash, 4px gap).+ var dashStyle = dashed ? '1px dotted' : '2px dashed'+ box.style.border = dashStyle + ' ' + color+ box.style.left = r.left + 'px'+ box.style.top = r.top + 'px'+ box.style.width = r.width + 'px'+ box.style.height = r.height + 'px'+ box.style.display = 'block'+ return r+ }++ function placeLabel(r) {+ var top = r.top - 22+ if (top < 2) top = r.bottom + 4+ pinLabel.style.left = r.left + 'px'+ pinLabel.style.top = top + 'px'+ pinLabel.style.display = 'block'+ }++ function isBackground(t) {+ return !t || t === document.documentElement || t === document.body+ }++ // The parent (annotation overlay) anchors its inline note box at the pinned+ // element, so it needs the bbox. postMessage works across the sandbox; the+ // opaque origin forces targetOrigin '*'.+ function sendPin(r, label) {+ try {+ window.parent.postMessage(+ {+ source: 'jan-preview-inspector',+ type: 'pin',+ label: label,+ rect: { x: r.left, y: r.top, width: r.width, height: r.height }+ },+ '*'+ )+ } catch (e) {+ /* parent may be gone or block cross-frame messaging */+ }+ }++ function sendClear() {+ try {+ window.parent.postMessage(+ { source: 'jan-preview-inspector', type: 'clear' },+ '*'+ )+ } catch (e) {+ /* see sendPin */+ }+ }++ // Clicking whitespace should deselect, not pin the full-page wrapper that+ // usually covers the whole viewport.+ function coversViewport(el) {+ var r = el.getBoundingClientRect()+ return (+ r.width >= window.innerWidth * 0.98 &&+ r.height >= window.innerHeight * 0.98+ )+ }++ function clearPin() {+ pinnedEl = null+ if (pinBox) pinBox.style.display = 'none'+ if (pinLabel) pinLabel.style.display = 'none'+ sendClear()+ }++ function refreshPin() {+ if (!pinnedEl) return+ if (!pinnedEl.isConnected) {+ clearPin()+ return+ }+ var r = placeBox(pinBox, pinnedEl, PIN, 2, false)+ placeLabel(r)+ // Re-post so the parent's pin chip tracks the element while the page+ // scrolls or resizes; the overlay dedupes an unchanged rect.+ sendPin(r, pinLabel.textContent)+ }++ document.addEventListener(+ 'pointerover',+ function (e) {+ if (!hoverBox) return+ var t = e.target+ if (+ !t ||+ t.nodeType !== 1 ||+ isBackground(t) ||+ coversViewport(t) ||+ t === pinnedEl+ ) {+ hoverBox.style.display = 'none'+ return+ }+ placeBox(hoverBox, t, HOVER, 1, true)+ },+ true+ )++ document.addEventListener(+ 'pointerout',+ function () {+ if (hoverBox) hoverBox.style.display = 'none'+ },+ true+ )++ document.addEventListener(+ 'pointerdown',+ function (e) {+ var t = e.target+ if (!t || t.nodeType !== 1 || isBackground(t) || coversViewport(t)) {+ clearPin()+ return+ }+ pinnedEl = t+ pinLabel.textContent = labelFor(t)+ var r = placeBox(pinBox, t, PIN, 2, false)+ placeLabel(r)+ sendPin(r, pinLabel.textContent)+ },+ true+ )++ document.addEventListener('keydown', function (e) {+ if (e.key === 'Escape') clearPin()+ })++ // The annotation overlay drops the pin when it leaves the select tool, so a+ // stale bbox never sits underneath the strokes the user is drawing.+ window.addEventListener('message', function (e) {+ var d = e.data+ if (d && d.source === 'jan-annotation-overlay' && d.type === 'clear') {+ clearPin()+ // The hover outline sticks too: once the overlay captures the pointer,+ // this frame never sees the pointerout that would have hidden it.+ if (hoverBox) hoverBox.style.display = 'none'+ }+ })++ window.addEventListener('scroll', refreshPin, true)+ window.addEventListener('resize', refreshPin)++ function mount() {+ hoverBox = makeBox()+ pinBox = makeBox()+ pinLabel = makeLabel()+ document.body.appendChild(hoverBox)+ document.body.appendChild(pinBox)+ document.body.appendChild(pinLabel)+ }++ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', mount)+ } else {+ mount()+ }+})()`diff --git a/web-app/src/lib/todoLabels.ts b/web-app/src/lib/todoLabels.tsnew file mode 100644index 000000000..9d3135f4a--- /dev/null+++ b/web-app/src/lib/todoLabels.ts@@ -0,0 +1,17 @@+// Models often prefix a task label with their own status marker ("✅ Ship it",+// "[x] Ship it", "- Ship it"). The todo panel already renders status as an+// icon, so showing the marker too gives every task two competing indicators.+//+// The marker set is single code points each allowed one trailing variation+// selector (`✔` + U+FE0F is one grapheme but two code points, so listing the+// composed form inside a character class would match its halves separately).+const LEADING_MARKER = /^\s*(?:[✅✓✔☑❌✗☐🔲🔳⬜◻]️?|\[[ xX~-]?\]|[-*•])\s+/u++/**+ * Drop a single leading status marker from a model-written task label. Anything+ * else — including a marker used mid-sentence — is left exactly as written, and+ * a label made up of nothing but a marker is kept rather than blanked out.+ */+export function cleanTaskLabel(content: string): string {+ return content.replace(LEADING_MARKER, '').trim() || content.trim()+}diff --git a/web-app/src/types/codeSession.ts b/web-app/src/types/codeSession.tsnew file mode 100644index 000000000..1108ae1d1--- /dev/null+++ b/web-app/src/types/codeSession.ts@@ -0,0 +1,105 @@+/**+ * Shared Cowork session types, kept free of any store so the presentation layer+ * can be built and tested without pulling in zustand or the run driver.+ *+ * The shapes mirroring Rust structs keep snake_case field names verbatim: the+ * same JSON crosses the tool boundary in both directions, and renaming here+ * would mean a translation layer on every hop.+ */++/** A single visible transcript entry. `tool` rows are display-only and carry the+ * structured call/result so the UI can render a tool card. */+export type CodeTurn = {+ role: 'user' | 'assistant' | 'tool'+ content: string+ /** User-row only: data URLs of images attached via paste/file picker. */+ images?: string[]+ callId?: string+ name?: string+ args?: unknown+ /** Raw JSON argument text accumulated while the call streams, so the tool card+ * shows a live preview. Superseded once the parsed `args` land. */+ argsLive?: string+ result?: string+ isError?: boolean+ diff?: string+ status?: 'running' | 'done'+}++/** Mirrors the Rust `Usage` struct (events.rs). */+export type Usage = {+ prompt_tokens?: number+ completion_tokens?: number+ total_tokens?: number+}++/**+ * One subagent run, bucketed by its own run id so concurrent subagents never+ * share a transcript lane. Lives transiently in the run store while running,+ * then the finished set is committed onto its session.+ */+export type SubagentRun = {+ runId: string+ name: string+ status: 'queued' | 'running' | 'done'+ startedAt: number+ endedAt?: number+ /** 1-based FIFO queue position while `queued`; cleared on start. */+ waiting?: number+ /** The subagent's own trace. The final answer is in `finalOutput`, not here. */+ turns: CodeTurn[]+ finalOutput?: string+ usage?: Usage+}++/** Mirrors the Rust `TodoItem`/`TodoPhase`/`TodoList` structs (todo.rs). */+export type TodoStatus = 'pending' | 'in_progress' | 'completed' | 'abandoned'++export type TodoItem = {+ content: string+ status: TodoStatus+}++export type TodoPhase = {+ name: string+ tasks: TodoItem[]+}++export type TodoList = {+ phases: TodoPhase[]+}++/** `/goal` state: set by `/goal <condition>`, checked after each turn completes,+ * cleared by `/goal clear` or once the evaluator reports it met. */+export type CodeGoal = {+ condition: string+ turns: number+ status: 'active' | 'achieved'+ lastReason: string+}++/** Mirrors the Rust `OptionItem`/`Question`/`AskRequest` structs (interaction.rs). */+export type AskOption = {+ label: string+ description?: string+}++export type AskQuestion = {+ id: string+ question: string+ options: AskOption[]+ multi?: boolean+ recommended?: number+}++export type AskRequestPayload = {+ questions: AskQuestion[]+}++/** Mirrors `QuestionResult` (interaction.rs): one answer per question, either+ * selected option label(s) or free-text `custom_input` — never both. */+export type AskAnswer = {+ id: string+ selected: string[]+ custom_input?: string+}