Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

v2.5.0 batch 6: codex UI components (Sprint A #3 + C #8)

purple48035ee48af2
diff --git a/src/components/chat/AgentWorkspaceBadge.tsx b/src/components/chat/AgentWorkspaceBadge.tsx
new file mode 100644
index 00000000..44f9e5ec
--- /dev/null
+++ b/src/components/chat/AgentWorkspaceBadge.tsx
@@ -0,0 +1,79 @@
+import { useState } from 'react'
+import { Folder, Shield } from 'lucide-react'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import { useChatStore } from '../../stores/chatStore'
+import { AgentWorkspaceDialog } from './AgentWorkspaceDialog'
+import type { AgentWorkspace } from '../../types/agent-workspace'
+
+/**
+ * Tiny pill next to the agent toggle that shows where the active chat
+ * operates: "Sandbox" or the basename of the picked folder. Click to
+ * change — re-opens AgentWorkspaceDialog so the user can swap mid-chat.
+ *
+ * Renders nothing unless agent mode is enabled for the active chat AND
+ * a workspace has been chosen. The initial-choice flow is owned by
+ * AgentModeToggle.
+ */
+export function AgentWorkspaceBadge() {
+ const [dialogOpen, setDialogOpen] = useState(false)
+ const activeId = useChatStore((s) => s.activeConversationId)
+ const isActive = useAgentModeStore((s) =>
+ activeId ? s.agentModeActive[activeId] ?? false : false,
+ )
+ const workspace = useAgentModeStore((s) =>
+ activeId ? s.workspaces[activeId] : undefined,
+ )
+
+ if (!activeId || !isActive || !workspace) return null
+
+ const extras = workspace.kind === 'folder' ? workspace.extraPaths ?? [] : []
+ const label =
+ workspace.kind === 'folder'
+ ? extras.length > 0
+ ? `${basename(workspace.path)} +${extras.length}`
+ : basename(workspace.path)
+ : 'Sandbox'
+ const Icon = workspace.kind === 'folder' ? Folder : Shield
+ const tone =
+ workspace.kind === 'folder'
+ ? 'text-amber-500 border-amber-500/30'
+ : 'text-emerald-500 border-emerald-500/30'
+
+ const handleChoose = (next: AgentWorkspace) => {
+ useAgentModeStore.getState().setWorkspace(activeId, next)
+ setDialogOpen(false)
+ }
+
+ return (
+ <>
+ <button
+ onClick={() => setDialogOpen(true)}
+ title={
+ workspace.kind === 'folder'
+ ? `Agent working in ${workspace.path}. Click to change.`
+ : 'Agent working in isolated sandbox. Click to switch to a real folder.'
+ }
+ className={`flex items-center gap-1 px-1.5 py-0.5 rounded border transition-colors text-[0.55rem] bg-transparent hover:bg-white/5 ${tone}`}
+ >
+ <Icon size={10} />
+ <span className="font-mono max-w-[120px] truncate">{label}</span>
+ </button>
+
+ {dialogOpen && (
+ <AgentWorkspaceDialog
+ open={true}
+ conversationId={activeId}
+ onChoose={handleChoose}
+ onClose={() => setDialogOpen(false)}
+ />
+ )}
+ </>
+ )
+}
+
+function basename(p?: string): string {
+ if (!p) return 'folder'
+ const cleaned = p.replace(/[\\/]+$/, '')
+ const parts = cleaned.split(/[\\/]/)
+ return parts[parts.length - 1] || cleaned
+}
diff --git a/src/components/chat/AgentWorkspaceDialog.tsx b/src/components/chat/AgentWorkspaceDialog.tsx
new file mode 100644
index 00000000..7d051595
--- /dev/null
+++ b/src/components/chat/AgentWorkspaceDialog.tsx
@@ -0,0 +1,268 @@
+import { useState } from 'react'
+import { Folder, Shield, Check, Plus, X } from 'lucide-react'
+import { Modal } from '../ui/Modal'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { backendCall } from '../../api/backend'
+import type { AgentWorkspace } from '../../types/agent-workspace'
+
+interface Props {
+ open: boolean
+ conversationId: string
+ /** Called with the chosen workspace; parent persists + closes. */
+ onChoose: (workspace: AgentWorkspace) => void
+ onClose: () => void
+}
+
+/**
+ * Asks the user where this agent chat should operate on disk. Shown once
+ * per chat when agent mode is enabled and no workspace has been picked
+ * yet. Re-openable later from the agent-mode bar.
+ *
+ * Two phases:
+ * 1. Pick a workspace kind (Sandbox / Use last folder / Pick folder).
+ * 2. (Folder only) Optionally add more repos so the agent can sync
+ * multiple checkouts at once — primary stays the resolution anchor
+ * for relative paths; extras land in the system prompt as absolute
+ * paths the model can address directly.
+ */
+export function AgentWorkspaceDialog({
+ open,
+ conversationId,
+ onChoose,
+ onClose,
+}: Props) {
+ const lastFolder = useAgentModeStore((s) => s.lastFolder)
+ const [picking, setPicking] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const [draft, setDraft] = useState<AgentWorkspace | null>(null)
+ const [rememberAsDefault, setRememberAsDefault] = useState(false)
+
+ const handleSandbox = () => {
+ setError(null)
+ onChoose({ kind: 'sandbox' })
+ }
+
+ const handleUseLast = () => {
+ if (!lastFolder) return
+ setError(null)
+ setDraft({ kind: 'folder', path: lastFolder, extraPaths: [] })
+ }
+
+ const handlePick = async () => {
+ setPicking(true)
+ setError(null)
+ try {
+ const res = await backendCall<{ path?: string } | null>('pick_folder', {})
+ if (!res || !res.path) {
+ setPicking(false)
+ return
+ }
+ setDraft({ kind: 'folder', path: res.path, extraPaths: [] })
+ } catch (e) {
+ setError(
+ e instanceof Error ? e.message : 'Folder picker unavailable (bridge offline?)',
+ )
+ } finally {
+ setPicking(false)
+ }
+ }
+
+ const handleAddExtra = async () => {
+ setPicking(true)
+ setError(null)
+ try {
+ const res = await backendCall<{ path?: string } | null>('pick_folder', {})
+ if (!res || !res.path) {
+ setPicking(false)
+ return
+ }
+ setDraft((d) => {
+ if (!d || d.kind !== 'folder') return d
+ const extras = d.extraPaths ?? []
+ if (extras.includes(res.path!) || res.path === d.path) return d
+ return { ...d, extraPaths: [...extras, res.path!] }
+ })
+ } catch (e) {
+ setError(
+ e instanceof Error ? e.message : 'Folder picker unavailable (bridge offline?)',
+ )
+ } finally {
+ setPicking(false)
+ }
+ }
+
+ const handleRemoveExtra = (path: string) => {
+ setDraft((d) => {
+ if (!d || d.kind !== 'folder') return d
+ return { ...d, extraPaths: (d.extraPaths ?? []).filter((p) => p !== path) }
+ })
+ }
+
+ const handleSave = () => {
+ if (!draft) return
+ if (rememberAsDefault && draft.kind === 'folder' && draft.path) {
+ useSettingsStore.getState().updateSettings({ defaultWorkspace: draft })
+ }
+ onChoose(draft)
+ }
+
+ const phase: 'pick' | 'extras' = draft ? 'extras' : 'pick'
+
+ return (
+ <Modal open={open} onClose={onClose} title="">
+ <div className="space-y-4">
+ <div className="text-center space-y-1">
+ <h3 className="text-base font-semibold text-gray-900 dark:text-white">
+ {phase === 'pick' ? 'Where should the agent work?' : 'Add more repos?'}
+ </h3>
+ <p className="text-[0.7rem] text-gray-500">
+ {phase === 'pick'
+ ? 'Pick a folder to edit your real files, or use a sandbox to keep this chat isolated. You can change this later.'
+ : 'Primary anchors relative paths. Extras give the agent absolute access — perfect for "sync the API in repo-A with the client in repo-B".'}
+ </p>
+ </div>
+
+ {phase === 'pick' && (
+ <div className="space-y-2" data-testid="agent-workspace-options">
+ <WorkspaceOption
+ icon={<Shield size={16} className="text-emerald-500" />}
+ title="Sandbox"
+ body="Isolated workspace under ~/agent-workspace/. Nothing outside it can be touched."
+ onClick={handleSandbox}
+ disabled={picking}
+ />
+
+ {lastFolder && (
+ <WorkspaceOption
+ icon={<Check size={16} className="text-blue-500" />}
+ title="Use last folder"
+ body={lastFolder}
+ monoBody
+ onClick={handleUseLast}
+ disabled={picking}
+ />
+ )}
+
+ <WorkspaceOption
+ icon={<Folder size={16} className="text-amber-500" />}
+ title={picking ? 'Opening picker…' : 'Pick a folder…'}
+ body="Choose a real directory. The agent edits files in there directly — like Codex."
+ onClick={handlePick}
+ disabled={picking}
+ />
+ </div>
+ )}
+
+ {phase === 'extras' && draft?.kind === 'folder' && (
+ <div className="space-y-2" data-testid="agent-workspace-extras">
+ <div className="rounded-lg border border-amber-500/30 bg-amber-50/40 dark:bg-amber-500/[0.04] px-3 py-2">
+ <div className="text-[0.55rem] uppercase tracking-widest text-amber-700 dark:text-amber-300/80 mb-0.5">
+ Primary
+ </div>
+ <div className="text-[0.7rem] font-mono text-gray-800 dark:text-gray-200 truncate">
+ {draft.path}
+ </div>
+ </div>
+
+ {(draft.extraPaths ?? []).map((p) => (
+ <div
+ key={p}
+ className="flex items-center justify-between gap-2 rounded-lg border border-gray-200 dark:border-white/10 px-3 py-2"
+ >
+ <span className="text-[0.7rem] font-mono text-gray-700 dark:text-gray-300 truncate flex-1 min-w-0">
+ {p}
+ </span>
+ <button
+ onClick={() => handleRemoveExtra(p)}
+ title="Remove"
+ className="p-1 rounded hover:bg-red-500/10 text-red-500"
+ >
+ <X size={11} />
+ </button>
+ </div>
+ ))}
+
+ <button
+ onClick={handleAddExtra}
+ disabled={picking}
+ className="w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg border border-dashed border-gray-300 dark:border-white/10 text-[0.7rem] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-50 dark:hover:bg-white/[0.04] disabled:opacity-50"
+ data-testid="agent-workspace-add-extra"
+ >
+ <Plus size={11} /> {picking ? 'Opening picker…' : 'Add another repo'}
+ </button>
+
+ <label className="flex items-center gap-2 pt-1 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={rememberAsDefault}
+ onChange={(e) => setRememberAsDefault(e.target.checked)}
+ className="w-3 h-3"
+ data-testid="agent-workspace-remember-default"
+ />
+ <span className="text-[0.65rem] text-gray-600 dark:text-gray-400">
+ Remember as default — future chats open here without asking.
+ </span>
+ </label>
+ </div>
+ )}
+
+ {error && (
+ <p className="text-[0.65rem] text-red-500 text-center">{error}</p>
+ )}
+
+ <div className="flex items-center justify-end gap-2 pt-1">
+ <button
+ onClick={onClose}
+ className="px-3 py-1.5 rounded-lg text-[0.7rem] text-gray-500 hover:text-gray-800 dark:hover:text-white transition-colors"
+ data-conversation-id={conversationId}
+ >
+ Cancel
+ </button>
+ {phase === 'extras' && (
+ <button
+ onClick={handleSave}
+ className="px-3 py-1.5 rounded-lg text-[0.7rem] font-medium bg-emerald-500 hover:bg-emerald-600 text-white transition-colors"
+ data-testid="agent-workspace-save"
+ >
+ Save
+ </button>
+ )}
+ </div>
+ </div>
+ </Modal>
+ )
+}
+
+interface OptionProps {
+ icon: React.ReactNode
+ title: string
+ body: string
+ monoBody?: boolean
+ onClick: () => void
+ disabled?: boolean
+}
+
+function WorkspaceOption({ icon, title, body, monoBody, onClick, disabled }: OptionProps) {
+ return (
+ <button
+ onClick={onClick}
+ disabled={disabled}
+ className="w-full flex items-start gap-3 p-3 rounded-lg border border-gray-200 dark:border-white/10 bg-white dark:bg-white/[0.02] hover:bg-gray-50 dark:hover:bg-white/[0.04] transition-colors text-left disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <span className="mt-0.5 shrink-0">{icon}</span>
+ <span className="flex-1 min-w-0">
+ <span className="block text-[0.75rem] font-medium text-gray-900 dark:text-white">
+ {title}
+ </span>
+ <span
+ className={`block text-[0.65rem] text-gray-500 truncate ${
+ monoBody ? 'font-mono' : ''
+ }`}
+ >
+ {body}
+ </span>
+ </span>
+ </button>
+ )
+}
diff --git a/src/components/chat/DiffView.tsx b/src/components/chat/DiffView.tsx
new file mode 100644
index 00000000..eb86f16d
--- /dev/null
+++ b/src/components/chat/DiffView.tsx
@@ -0,0 +1,104 @@
+import { parseUnifiedDiff } from '../../lib/diff'
+
+interface Props {
+ /** Raw unified-diff string as produced by `computeUnifiedDiff`. */
+ diff: string
+ /**
+ * Cap on rendered lines. Long agent-driven refactors can produce a
+ * 2000-line diff that murders chat-scroll perf. Lines past the cap
+ * collapse into a "+N more" line.
+ */
+ maxLines?: number
+}
+
+/**
+ * Tiny syntax-free unified-diff renderer. Designed for the chat surface,
+ * not a full code editor — we colour add/remove/context lines and
+ * surface the per-hunk header so the user can see where edits landed.
+ */
+export function DiffView({ diff, maxLines = 200 }: Props) {
+ if (!diff) return null
+ const parsed = parseUnifiedDiff(diff)
+ const truncated = parsed.lines.length > maxLines
+ const lines = truncated ? parsed.lines.slice(0, maxLines) : parsed.lines
+ const hiddenCount = parsed.lines.length - lines.length
+
+ return (
+ <div className="rounded border border-white/10 bg-black/30 overflow-hidden">
+ {(parsed.added > 0 || parsed.removed > 0) && (
+ <div className="flex items-center justify-between px-2 py-1 border-b border-white/5 text-[0.55rem] font-mono">
+ <span className="text-gray-500 truncate">{parsed.path || 'diff'}</span>
+ <span className="flex gap-2 shrink-0">
+ {parsed.added > 0 && (
+ <span className="text-emerald-400">+{parsed.added}</span>
+ )}
+ {parsed.removed > 0 && (
+ <span className="text-red-400">-{parsed.removed}</span>
+ )}
+ </span>
+ </div>
+ )}
+ <pre className="text-[0.58rem] leading-relaxed font-mono overflow-auto scrollbar-thin max-h-[300px]">
+ {lines.map((l, i) => {
+ if (l.kind === 'header') {
+ return (
+ <div key={i} className="px-2 text-gray-600">
+ {l.text}
+ </div>
+ )
+ }
+ if (l.kind === 'hunk') {
+ return (
+ <div
+ key={i}
+ className="px-2 bg-blue-500/5 text-blue-300/70 border-y border-white/5"
+ >
+ {l.text}
+ </div>
+ )
+ }
+ if (l.kind === 'add') {
+ return (
+ <div key={i} className="px-2 bg-emerald-500/10 text-emerald-200">
+ {l.newLine !== undefined && (
+ <span className="inline-block w-8 text-right pr-2 text-emerald-500/50">
+ {l.newLine}
+ </span>
+ )}
+ <span>{`+${l.text}`}</span>
+ </div>
+ )
+ }
+ if (l.kind === 'remove') {
+ return (
+ <div key={i} className="px-2 bg-red-500/10 text-red-200">
+ {l.oldLine !== undefined && (
+ <span className="inline-block w-8 text-right pr-2 text-red-500/50">
+ {l.oldLine}
+ </span>
+ )}
+ <span>{`-${l.text}`}</span>
+ </div>
+ )
+ }
+ // context
+ return (
+ <div key={i} className="px-2 text-gray-400">
+ {l.newLine !== undefined && (
+ <span className="inline-block w-8 text-right pr-2 text-gray-700">
+ {l.newLine}
+ </span>
+ )}
+ <span>{` ${l.text}`}</span>
+ </div>
+ )
+ })}
+ {truncated && (
+ <div className="px-2 py-1 text-gray-600 italic">
+ … {hiddenCount} more lines
+ </div>
+ )}
+ </pre>
+ </div>
+ )
+}
diff --git a/src/components/chat/StagedChangesPanel.tsx b/src/components/chat/StagedChangesPanel.tsx
new file mode 100644
index 00000000..e75d3c50
--- /dev/null
+++ b/src/components/chat/StagedChangesPanel.tsx
@@ -0,0 +1,173 @@
+import { useState } from 'react'
+import { Check, X, ChevronDown, ChevronRight, FileText } from 'lucide-react'
+import { useStagedChangesStore, type StagedChange } from '../../stores/stagedChangesStore'
+import { useChatStore } from '../../stores/chatStore'
+import { toolRegistry } from '../../api/mcp'
+import { DiffView } from './DiffView'
+
+interface Props {
+ /** Active conversation id — the panel scopes itself to this chat. */
+ chatId: string | null
+}
+
+/**
+ * Right-sidebar panel that surfaces Codex's queued `file_write` calls when
+ * Stage-and-Approve is on. Each change shows its diff and offers per-row
+ * Apply/Reject; the footer offers Apply-all/Reject-all for big refactors.
+ *
+ * `Apply` calls the same `file_write` tool the executor would have called
+ * inline — the bridge sees an identical request, so the diff the user
+ * approved is exactly what lands on disk.
+ */
+// Module-scoped stable empty-array reference. Zustand selectors run on
+// every store update; returning a fresh `[]` literal (or any new object)
+// trips Object.is and re-renders forever. Reusing one frozen empty array
+// keeps the selector output identity-stable when this chat has no
+// staged changes yet.
+const EMPTY_CHANGES: readonly StagedChange[] = Object.freeze([])
+
+export function StagedChangesPanel({ chatId }: Props) {
+ const changes = useStagedChangesStore((s) =>
+ chatId ? s.byChat[chatId] ?? EMPTY_CHANGES : EMPTY_CHANGES,
+ ) as StagedChange[]
+ const remove = useStagedChangesStore((s) => s.remove)
+ const clear = useStagedChangesStore((s) => s.clear)
+ const [expanded, setExpanded] = useState(true)
+ const [applying, setApplying] = useState<Set<string>>(new Set())
+
+ if (!chatId || changes.length === 0) return null
+
+ async function applyOne(change: StagedChange) {
+ if (!chatId) return
+ setApplying((prev) => new Set(prev).add(change.id))
+ try {
+ await toolRegistry.execute('file_write', {
+ path: change.path,
+ content: change.newContent,
+ })
+ remove(chatId, change.id)
+ // Mirror the apply in the chat log so the user sees a confirmation
+ // in the main pane, not just the side-pane disappearing.
+ useChatStore.getState().addMessage(chatId, {
+ id: crypto.randomUUID(),
+ role: 'system',
+ content: `Applied staged change: ${change.path}`,
+ timestamp: Date.now(),
+ hidden: true,
+ })
+ } catch (e) {
+ // Apply failures leave the entry in the queue so the user can retry.
+ console.error('[StagedChangesPanel] apply failed', e)
+ } finally {
+ setApplying((prev) => {
+ const next = new Set(prev)
+ next.delete(change.id)
+ return next
+ })
+ }
+ }
+
+ async function applyAll() {
+ if (!chatId) return
+ for (const change of [...changes]) {
+ // eslint-disable-next-line no-await-in-loop
+ await applyOne(change)
+ }
+ }
+
+ function rejectOne(change: StagedChange) {
+ if (!chatId) return
+ remove(chatId, change.id)
+ }
+
+ function rejectAll() {
+ if (!chatId) return
+ clear(chatId)
+ }
+
+ return (
+ <div className="border-b border-gray-200 dark:border-white/[0.04] bg-amber-50/40 dark:bg-amber-500/[0.04]">
+ <button
+ onClick={() => setExpanded(!expanded)}
+ className="w-full flex items-center justify-between px-2 py-1.5 group hover:bg-amber-100/50 dark:hover:bg-amber-500/[0.08] transition-colors"
+ data-testid="staged-changes-header"
+ >
+ <span className="flex items-center gap-1.5">
+ {expanded ? (
+ <ChevronDown size={11} className="text-amber-700 dark:text-amber-400" />
+ ) : (
+ <ChevronRight size={11} className="text-amber-700 dark:text-amber-400" />
+ )}
+ <FileText size={10} className="text-amber-700 dark:text-amber-400" />
+ <span className="text-[0.6rem] font-semibold text-amber-900 dark:text-amber-300">
+ Pending ({changes.length})
+ </span>
+ </span>
+ </button>
+
+ {expanded && (
+ <div className="px-1.5 pb-2 space-y-1.5">
+ {changes.map((change) => {
+ const isApplying = applying.has(change.id)
+ return (
+ <div
+ key={change.id}
+ className="rounded border border-gray-200 dark:border-white/[0.08] bg-white dark:bg-black/20"
+ data-testid="staged-change"
+ >
+ <div className="flex items-center justify-between gap-1 px-1.5 py-1 border-b border-gray-100 dark:border-white/[0.04]">
+ <span
+ className="text-[0.55rem] font-mono truncate text-gray-700 dark:text-gray-300"
+ title={change.path}
+ >
+ {change.path}
+ </span>
+ <span className="flex items-center gap-0.5 shrink-0">
+ <button
+ onClick={() => applyOne(change)}
+ disabled={isApplying}
+ title="Apply"
+ className="p-0.5 rounded hover:bg-emerald-100 dark:hover:bg-emerald-500/20 text-emerald-600 disabled:opacity-50"
+ >
+ <Check size={10} />
+ </button>
+ <button
+ onClick={() => rejectOne(change)}
+ disabled={isApplying}
+ title="Reject"
+ className="p-0.5 rounded hover:bg-red-100 dark:hover:bg-red-500/20 text-red-500 disabled:opacity-50"
+ >
+ <X size={10} />
+ </button>
+ </span>
+ </div>
+ {change.diff && (
+ <div className="text-[0.5rem]">
+ <DiffView diff={change.diff} maxLines={40} />
+ </div>
+ )}
+ </div>
+ )
+ })}
+
+ <div className="flex items-center gap-1 pt-0.5">
+ <button
+ onClick={applyAll}
+ className="flex-1 px-1.5 py-1 rounded-md text-[0.55rem] font-medium bg-emerald-500 hover:bg-emerald-600 text-white transition-colors"
+ data-testid="apply-all"
+ >
+ Apply all
+ </button>
+ <button
+ onClick={rejectAll}
+ className="flex-1 px-1.5 py-1 rounded-md text-[0.55rem] font-medium bg-gray-200 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-white/15 text-gray-800 dark:text-gray-200 transition-colors"
+ data-testid="reject-all"
+ >
+ Reject all
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/src/lib/__tests__/diff.test.ts b/src/lib/__tests__/diff.test.ts
new file mode 100644
index 00000000..de3f6b56
--- /dev/null
+++ b/src/lib/__tests__/diff.test.ts
@@ -0,0 +1,94 @@
+import { describe, it, expect } from 'vitest'
+import { computeUnifiedDiff, parseUnifiedDiff } from '../diff'
+
+describe('computeUnifiedDiff', () => {
+ it('returns empty string when texts are identical', () => {
+ const a = 'one\ntwo\nthree'
+ expect(computeUnifiedDiff('f.ts', a, a)).toBe('')
+ })
+
+ it('emits a +++/--- header for changed files', () => {
+ const out = computeUnifiedDiff('src/a.ts', 'one\n', 'two\n')
+ expect(out.split('\n').slice(0, 2)).toEqual([
+ '--- a/src/a.ts',
+ '+++ b/src/a.ts',
+ ])
+ })
+
+ it('marks added + removed lines with leading sigils', () => {
+ const out = computeUnifiedDiff(
+ 'f',
+ 'alpha\nbeta\ngamma',
+ 'alpha\nBETA\ngamma',
+ )
+ expect(out).toMatch(/-beta/)
+ expect(out).toMatch(/\+BETA/)
+ expect(out).toMatch(/ alpha/)
+ expect(out).toMatch(/ gamma/)
+ })
+
+ it('produces a parseable hunk header with correct line counts', () => {
+ const out = computeUnifiedDiff(
+ 'f',
+ ['l1', 'l2', 'l3', 'l4', 'l5'].join('\n'),
+ ['l1', 'l2', 'l3-changed', 'l4', 'l5'].join('\n'),
+ )
+ const hunk = out.split('\n').find((l) => l.startsWith('@@'))!
+ expect(hunk).toMatch(/^@@ -1,\d+ \+1,\d+ @@$/)
+ })
+
+ it('handles pure inserts at the head', () => {
+ const out = computeUnifiedDiff('f', 'b\nc\n', 'a\nb\nc\n')
+ expect(out).toMatch(/\+a/)
+ // No content-line removals — the only `-` prefixes belong to the
+ // `--- a/` header.
+ const contentLines = out.split('\n').filter((l) => !l.startsWith('---'))
+ expect(contentLines.some((l) => l.startsWith('-'))).toBe(false)
+ })
+
+ it('handles pure deletes at the tail', () => {
+ const out = computeUnifiedDiff('f', 'a\nb\nc\n', 'a\nb\n')
+ expect(out).toMatch(/-c/)
+ })
+})
+
+describe('parseUnifiedDiff round-trip', () => {
+ it('classifies headers, hunks, context, add, remove', () => {
+ const diff = computeUnifiedDiff(
+ 'src/x.ts',
+ 'one\ntwo\nthree\nfour\n',
+ 'one\nTWO\nthree\nfour\nfive\n',
+ )
+ const parsed = parseUnifiedDiff(diff)
+ expect(parsed.path).toBe('src/x.ts')
+ expect(parsed.removed).toBe(1)
+ expect(parsed.added).toBe(2)
+ expect(parsed.lines.some((l) => l.kind === 'hunk')).toBe(true)
+ expect(parsed.lines.some((l) => l.kind === 'context')).toBe(true)
+ })
+
+ it('keeps line numbers monotonic in the parsed output', () => {
+ const diff = computeUnifiedDiff(
+ 'f',
+ ['a', 'b', 'c', 'd', 'e', 'f'].join('\n'),
+ ['a', 'B', 'c', 'd', 'e', 'f'].join('\n'),
+ )
+ const parsed = parseUnifiedDiff(diff)
+ const adds = parsed.lines.filter((l) => l.kind === 'add')
+ const removes = parsed.lines.filter((l) => l.kind === 'remove')
+ expect(adds[0].newLine).toBeDefined()
+ expect(removes[0].oldLine).toBeDefined()
+ // No NaN / undefined leaks.
+ for (const line of parsed.lines) {
+ if (line.oldLine !== undefined) expect(Number.isFinite(line.oldLine)).toBe(true)
+ if (line.newLine !== undefined) expect(Number.isFinite(line.newLine)).toBe(true)
+ }
+ })
+
+ it('survives empty old text (treats whole new file as add)', () => {
+ const diff = computeUnifiedDiff('new.txt', '', 'hello\nworld\n')
+ const parsed = parseUnifiedDiff(diff)
+ expect(parsed.added).toBeGreaterThan(0)
+ expect(parsed.removed).toBe(0)
+ })
+})
diff --git a/src/stores/__tests__/stagedChangesStore.test.ts b/src/stores/__tests__/stagedChangesStore.test.ts
new file mode 100644
index 00000000..64fafc0c
--- /dev/null
+++ b/src/stores/__tests__/stagedChangesStore.test.ts
@@ -0,0 +1,116 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useStagedChangesStore } from '../stagedChangesStore'
+
+describe('stagedChangesStore', () => {
+ beforeEach(() => {
+ useStagedChangesStore.setState({ byChat: {} })
+ })
+
+ it('starts empty', () => {
+ expect(useStagedChangesStore.getState().list('c1')).toEqual([])
+ })
+
+ it('stages a change and returns an id', () => {
+ const id = useStagedChangesStore.getState().stage('c1', {
+ path: 'src/a.ts',
+ oldContent: 'old',
+ newContent: 'new',
+ diff: 'diff body',
+ })
+ expect(typeof id).toBe('string')
+ const list = useStagedChangesStore.getState().list('c1')
+ expect(list).toHaveLength(1)
+ expect(list[0].path).toBe('src/a.ts')
+ expect(list[0].id).toBe(id)
+ expect(list[0].stagedAt).toBeGreaterThan(0)
+ })
+
+ it('staging the same path twice keeps only the latest (path-keyed dedupe)', () => {
+ useStagedChangesStore.getState().stage('c1', {
+ path: 'src/a.ts',
+ oldContent: 'old',
+ newContent: 'v1',
+ diff: 'd1',
+ })
+ useStagedChangesStore.getState().stage('c1', {
+ path: 'src/a.ts',
+ oldContent: 'old',
+ newContent: 'v2',
+ diff: 'd2',
+ })
+ const list = useStagedChangesStore.getState().list('c1')
+ expect(list).toHaveLength(1)
+ expect(list[0].newContent).toBe('v2')
+ })
+
+ it('queues across chats are isolated', () => {
+ useStagedChangesStore.getState().stage('c1', {
+ path: 'a',
+ oldContent: '',
+ newContent: 'x',
+ diff: '',
+ })
+ useStagedChangesStore.getState().stage('c2', {
+ path: 'b',
+ oldContent: '',
+ newContent: 'y',
+ diff: '',
+ })
+ expect(useStagedChangesStore.getState().list('c1').map((c) => c.path)).toEqual(['a'])
+ expect(useStagedChangesStore.getState().list('c2').map((c) => c.path)).toEqual(['b'])
+ })
+
+ it('remove drops a single entry and is a no-op for unknown ids', () => {
+ const id = useStagedChangesStore.getState().stage('c1', {
+ path: 'a',
+ oldContent: '',
+ newContent: 'x',
+ diff: '',
+ })
+ useStagedChangesStore.getState().remove('c1', 'nonexistent-id')
+ expect(useStagedChangesStore.getState().list('c1')).toHaveLength(1)
+ useStagedChangesStore.getState().remove('c1', id)
+ expect(useStagedChangesStore.getState().list('c1')).toEqual([])
+ })
+
+ it('clear empties a chat queue without touching others', () => {
+ useStagedChangesStore.getState().stage('c1', {
+ path: 'a',
+ oldContent: '',
+ newContent: 'x',
+ diff: '',
+ })
+ useStagedChangesStore.getState().stage('c2', {
+ path: 'b',
+ oldContent: '',
+ newContent: 'y',
+ diff: '',
+ })
+ useStagedChangesStore.getState().clear('c1')
+ expect(useStagedChangesStore.getState().list('c1')).toEqual([])
+ expect(useStagedChangesStore.getState().list('c2')).toHaveLength(1)
+ })
+
+ it('clearing the last entry deletes the chat key entirely', () => {
+ const id = useStagedChangesStore.getState().stage('c1', {
+ path: 'a',
+ oldContent: '',
+ newContent: 'x',
+ diff: '',
+ })
+ useStagedChangesStore.getState().remove('c1', id)
+ expect(useStagedChangesStore.getState().byChat['c1']).toBeUndefined()
+ })
+
+ it('get returns the entry by id', () => {
+ const id = useStagedChangesStore.getState().stage('c1', {
+ path: 'a',
+ oldContent: '',
+ newContent: 'x',
+ diff: '',
+ })
+ const found = useStagedChangesStore.getState().get('c1', id)
+ expect(found?.path).toBe('a')
+ expect(useStagedChangesStore.getState().get('c1', 'unknown')).toBeUndefined()
+ })
+})
diff --git a/src/stores/stagedChangesStore.ts b/src/stores/stagedChangesStore.ts
new file mode 100644
index 00000000..18dcffc2
--- /dev/null
+++ b/src/stores/stagedChangesStore.ts
@@ -0,0 +1,84 @@
+import { create } from 'zustand'
+import { v4 as uuid } from 'uuid'
+
+export interface StagedChange {
+ /** Stable id assigned at stage-time so the UI can key + remove safely. */
+ id: string
+ /** Path the model called `file_write` with — unresolved; the bridge resolves on apply. */
+ path: string
+ /** Full file content before the write — empty string when the target didn't exist. */
+ oldContent: string
+ /** Full file content the model wants to write. */
+ newContent: string
+ /** Pre-computed unified diff for snappy rendering — caller decides format. */
+ diff: string
+ /** Wall-clock when the model staged this change. */
+ stagedAt: number
+}
+
+interface StagedChangesState {
+ /** Per-conversation queue. Cleared on apply-all / reject-all / chat reset. */
+ byChat: Record<string, StagedChange[]>
+ /** Adds a change, returns the assigned id. Identical paths overwrite the prior entry — the model usually means the latest write to win. */
+ stage: (
+ chatId: string,
+ change: Omit<StagedChange, 'id' | 'stagedAt'>,
+ ) => string
+ /** Removes a single change from the queue. */
+ remove: (chatId: string, id: string) => void
+ /** Clears all staged changes for a chat. */
+ clear: (chatId: string) => void
+ /** Returns the queue for a chat (empty array if none). */
+ list: (chatId: string) => StagedChange[]
+ /** Looks up a single change by id. */
+ get: (chatId: string, id: string) => StagedChange | undefined
+}
+
+export const useStagedChangesStore = create<StagedChangesState>()((set, get) => ({
+ byChat: {},
+
+ stage: (chatId, change) => {
+ const id = uuid()
+ set((state) => {
+ const prev = state.byChat[chatId] ?? []
+ // Same path — replace, don't dupe. The diff carries the latest intent.
+ const without = prev.filter((c) => c.path !== change.path)
+ return {
+ byChat: {
+ ...state.byChat,
+ [chatId]: [
+ ...without,
+ { ...change, id, stagedAt: Date.now() },
+ ],
+ },
+ }
+ })
+ return id
+ },
+
+ remove: (chatId, id) =>
+ set((state) => {
+ const prev = state.byChat[chatId]
+ if (!prev) return state
+ const next = prev.filter((c) => c.id !== id)
+ const byChat = { ...state.byChat }
+ if (next.length === 0) {
+ delete byChat[chatId]
+ } else {
+ byChat[chatId] = next
+ }
+ return { byChat }
+ }),
+
+ clear: (chatId) =>
+ set((state) => {
+ if (!state.byChat[chatId]) return state
+ const byChat = { ...state.byChat }
+ delete byChat[chatId]
+ return { byChat }
+ }),
+
+ list: (chatId) => get().byChat[chatId] ?? [],
+
+ get: (chatId, id) => (get().byChat[chatId] ?? []).find((c) => c.id === id),
+}))