Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(cowork): rebuild the Code surface on the new loop, without permissions

Akarshan Biswas05c4521e5f4f
diff --git a/web-app/src/containers/CodeArtifactCard.tsx b/web-app/src/containers/CodeArtifactCard.tsx
new file mode 100644
index 000000000..58f583a5e
--- /dev/null
+++ b/web-app/src/containers/CodeArtifactCard.tsx
@@ -0,0 +1,91 @@
+import { ChevronDown, FolderOpen, SquareArrowOutUpRight } from 'lucide-react'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
+import { Card } from '@/components/ui/card'
+import { useServiceHub } from '@/hooks/useServiceHub'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { resolveInRoot } from '@/lib/codePreview'
+import { ARTIFACT_ICON, type CodeArtifact } from '@/lib/codeArtifacts'
+
+/**
+ * Inline card for something the agent produced (jan-internal #242).
+ *
+ * Rendered by the Cowork transcript itself rather than by `MessageItem`, which
+ * is shared with the chat surface — the association is derived from a message's
+ * own write/edit parts, so nothing shared needs to know artifacts exist.
+ *
+ * Card body opens the in-app preview; the split button hands the file to the OS.
+ */
+export function CodeArtifactCard({
+ artifact,
+ root,
+ onPreview,
+}: {
+ artifact: CodeArtifact
+ root: string | null
+ onPreview: (path: string) => void
+}) {
+ const { t } = useTranslation()
+ const serviceHub = useServiceHub()
+ const Icon = ARTIFACT_ICON[artifact.group]
+ const abs = root ? resolveInRoot(root, artifact.path) : null
+
+ return (
+ <Card className="my-3 flex items-center gap-3 p-3">
+ <button
+ type="button"
+ onClick={() => onPreview(artifact.path)}
+ title={t('common:artifactOpenPreview')}
+ className="flex min-w-0 flex-1 items-center gap-3 text-left"
+ >
+ <span className="flex size-10 shrink-0 items-center justify-center rounded-md border">
+ <Icon size={18} className="text-muted-foreground" />
+ </span>
+ <span className="min-w-0">
+ <span className="block truncate text-sm font-medium">{artifact.title}</span>
+ <span className="block truncate text-xs text-muted-foreground">
+ {artifact.group} · {artifact.label}
+ </span>
+ </span>
+ </button>
+
+ {abs && (
+ <div className="flex shrink-0 items-center rounded-md border">
+ <button
+ type="button"
+ onClick={() => void serviceHub.opener().openPath(abs)}
+ className="flex items-center gap-1.5 rounded-l-md px-2.5 py-1.5 text-xs hover:bg-accent"
+ >
+ <SquareArrowOutUpRight size={13} className="text-muted-foreground" />
+ {t('common:artifactOpenExternal')}
+ </button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={t('common:artifactMoreActions')}
+ className="rounded-r-md border-l px-1.5 py-1.5 hover:bg-accent"
+ >
+ <ChevronDown size={13} className="text-muted-foreground" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => void serviceHub.opener().openPath(abs)}>
+ <SquareArrowOutUpRight size={14} />
+ {t('common:artifactOpenExternal')}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => void serviceHub.opener().revealItemInDir(abs)}>
+ <FolderOpen size={14} />
+ {t('common:artifactShowInFolder')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
+ </Card>
+ )
+}
diff --git a/web-app/src/containers/CodeAskCard.tsx b/web-app/src/containers/CodeAskCard.tsx
new file mode 100644
index 000000000..b7ae80c3a
Binary files /dev/null and b/web-app/src/containers/CodeAskCard.tsx differ
diff --git a/web-app/src/containers/CodeDiffPanel.tsx b/web-app/src/containers/CodeDiffPanel.tsx
new file mode 100644
index 000000000..f7a30c9f6
--- /dev/null
+++ b/web-app/src/containers/CodeDiffPanel.tsx
@@ -0,0 +1,121 @@
+import { useState } from 'react'
+import { ChevronDown, GitBranch } from 'lucide-react'
+import { cn } from '@/lib/utils'
+import { DiffView } from '@/components/DiffView'
+import { CodeSidePanel } from '@/containers/CodeSidePanel'
+import type { CodeFileDiff } from '@/lib/codeDiffs'
+
+export function CodeDiffPanel({
+ files,
+ folderName,
+ gitBranch,
+ onClose,
+}: {
+ files: CodeFileDiff[]
+ folderName?: string
+ gitBranch: string | null
+ onClose: () => void
+}): React.ReactElement {
+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set())
+ const additions = files.reduce((sum, file) => sum + file.additions, 0)
+ const deletions = files.reduce((sum, file) => sum + file.deletions, 0)
+
+ const toggleFile = (path: string) => {
+ setExpanded((current) => {
+ const next = new Set(current)
+ if (next.has(path)) {
+ next.delete(path)
+ } else {
+ next.add(path)
+ }
+ return next
+ })
+ }
+
+ return (
+ <CodeSidePanel
+ title="Agent changes"
+ summary={
+ <span className="shrink-0 text-xs font-mono text-main-view-fg/60">
+ +{additions} -{deletions}
+ </span>
+ }
+ onClose={onClose}
+ >
+ <div className="h-full overflow-y-auto">
+ <div className="flex flex-col gap-2 border-b p-3 text-xs text-main-view-fg/60">
+ <div className="truncate" title={folderName}>
+ {folderName ?? 'No folder selected'}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ {gitBranch ? (
+ <span className="inline-flex items-center gap-1 rounded-full bg-muted px-1.5 py-0.5 font-mono">
+ <GitBranch size={10} />
+ {gitBranch}
+ </span>
+ ) : null}
+ <span>{files.length} files</span>
+ <span className="font-mono text-green-600">+{additions}</span>
+ <span className="font-mono text-red-600">-{deletions}</span>
+ </div>
+ </div>
+
+ {files.length === 0 ? (
+ <p className="px-4 py-8 text-center text-sm text-main-view-fg/50">
+ Successful agent write and edit changes will appear here.
+ </p>
+ ) : (
+ <div className="divide-y">
+ {files.map((file) => {
+ const isExpanded = expanded.has(file.path)
+ return (
+ <div key={file.path}>
+ <button
+ type="button"
+ onClick={() => toggleFile(file.path)}
+ aria-expanded={isExpanded}
+ className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-muted/50"
+ >
+ <ChevronDown
+ size={14}
+ className={cn(
+ 'shrink-0 text-main-view-fg/50 transition-transform',
+ !isExpanded && '-rotate-90'
+ )}
+ />
+ <span className="min-w-0 flex-1 truncate text-xs font-medium">
+ {file.path}
+ </span>
+ <span className="shrink-0 font-mono text-xs text-green-600">
+ +{file.additions}
+ </span>
+ <span className="shrink-0 font-mono text-xs text-red-600">
+ -{file.deletions}
+ </span>
+ </button>
+ {isExpanded ? (
+ <div className="border-t bg-background">
+ {file.operations.map((operation, index) => (
+ <div key={`${file.path}-${index}`} className="border-b last:border-b-0">
+ {operation.source === 'subagent' && operation.sourceName ? (
+ <p className="px-3 pt-2 text-xs text-muted-foreground">
+ {operation.sourceName}
+ </p>
+ ) : null}
+ <DiffView
+ diff={operation.diff}
+ className="max-h-none rounded-none border-0"
+ />
+ </div>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ </CodeSidePanel>
+ )
+}
diff --git a/web-app/src/containers/CodeSidePanel.tsx b/web-app/src/containers/CodeSidePanel.tsx
new file mode 100644
index 000000000..717f1cd6e
--- /dev/null
+++ b/web-app/src/containers/CodeSidePanel.tsx
@@ -0,0 +1,95 @@
+import { useCallback, useRef, useState, type ReactNode } from 'react'
+import { Maximize2, Minimize2, X } from 'lucide-react'
+import { cn } from '@/lib/utils'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+
+type CodeSidePanelProps = {
+ title: ReactNode
+ leading?: ReactNode
+ summary?: ReactNode
+ children: ReactNode
+ onClose: () => void
+}
+
+const PANEL_MIN_W = 240
+const PANEL_MAX_W = 640
+const PANEL_DEFAULT_W = 320
+
+export function CodeSidePanel({
+ title,
+ leading,
+ summary,
+ children,
+ onClose,
+}: CodeSidePanelProps): React.ReactElement {
+ const { t } = useTranslation()
+ const [expanded, setExpanded] = useState(false)
+ const [width, setWidth] = useState(PANEL_DEFAULT_W)
+ const dragging = useRef(false)
+ const startX = useRef(0)
+ const startW = useRef(0)
+
+ const onMouseDown = useCallback(
+ (e: React.MouseEvent) => {
+ e.preventDefault()
+ dragging.current = true
+ startX.current = e.clientX
+ startW.current = expanded ? PANEL_MAX_W : width
+ const onMove = (ev: MouseEvent) => {
+ if (!dragging.current) return
+ const delta = startX.current - ev.clientX // left edge -> drag left = wider
+ const next = Math.min(PANEL_MAX_W, Math.max(PANEL_MIN_W, startW.current + delta))
+ setWidth(next)
+ }
+ const onUp = () => {
+ dragging.current = false
+ window.removeEventListener('mousemove', onMove)
+ window.removeEventListener('mouseup', onUp)
+ }
+ window.addEventListener('mousemove', onMove)
+ window.addEventListener('mouseup', onUp)
+ },
+ [expanded, width]
+ )
+
+ return (
+ <aside
+ className={cn(
+ 'relative flex h-full shrink-0 flex-col border-l bg-main-view',
+ expanded ? 'w-[32rem] max-w-[60%]' : ''
+ )}
+ style={expanded ? undefined : { width: `${width}px` }}
+ >
+ {/* Resize handle – thin invisible strip on the left edge. */}
+ <div
+ role="separator"
+ aria-orientation="vertical"
+ onMouseDown={onMouseDown}
+ className="absolute inset-y-0 left-0 z-10 w-1 cursor-col-resize bg-main-view-fg/0 transition-colors hover:bg-main-view-fg/20"
+ />
+ <div className="flex h-11 shrink-0 items-center gap-2 border-b px-3">
+ {leading}
+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{title}</span>
+ {summary}
+ <button
+ type="button"
+ onClick={() => setExpanded((value) => !value)}
+ aria-label={expanded ? t('common:collapse') : t('common:expand')}
+ title={expanded ? t('common:collapse') : t('common:expand')}
+ className="text-main-view-fg/60 hover:text-main-view-fg"
+ >
+ {expanded ? <Minimize2 size={16} /> : <Maximize2 size={16} />}
+ </button>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label={t('common:close')}
+ className="text-main-view-fg/60 hover:text-main-view-fg"
+ >
+ <X size={18} />
+ </button>
+ </div>
+ <div className="min-h-0 flex-1">{children}</div>
+ </aside>
+ )
+}
diff --git a/web-app/src/containers/CodeTodoPanel.tsx b/web-app/src/containers/CodeTodoPanel.tsx
new file mode 100644
index 000000000..4a4639eb5
--- /dev/null
+++ b/web-app/src/containers/CodeTodoPanel.tsx
@@ -0,0 +1,155 @@
+import { useState } from 'react'
+import { Check, ChevronDown, Loader2, Minus } from 'lucide-react'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { cn } from '@/lib/utils'
+import type { TodoList, TodoStatus } from '@/types/codeSession'
+import { CodeSidePanel } from '@/containers/CodeSidePanel'
+import { cleanTaskLabel } from '@/lib/todoLabels'
+
+/** Status dot: filled when resolved, hollow while still open. */
+function StatusDot({ status }: { status: TodoStatus }) {
+ const base = 'mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full'
+ if (status === 'completed') {
+ return (
+ <span className={cn(base, 'bg-primary text-primary-foreground')}>
+ <Check size={11} strokeWidth={3} />
+ </span>
+ )
+ }
+ if (status === 'abandoned') {
+ return (
+ <span className={cn(base, 'bg-main-view-fg/20 text-main-view-fg/70')}>
+ <Minus size={11} strokeWidth={3} />
+ </span>
+ )
+ }
+ if (status === 'in_progress') {
+ return (
+ <span className={cn(base, 'text-primary')}>
+ <Loader2 size={13} className="animate-spin" />
+ </span>
+ )
+ }
+ return <span className={cn(base, 'border-[1.5px] border-main-view-fg/25')} />
+}
+
+/**
+ * Session todo list panel, mirroring the agent core's canonical todo tool
+ * (see todo.rs) the TUI already renders as a HUD. Read-only: the model owns
+ * mutations via the `todo` tool; this just projects the current snapshot.
+ */
+export function CodeTodoPanel({
+ todos,
+ onClose,
+}: {
+ todos: TodoList | undefined
+ onClose: () => void
+}): React.ReactElement {
+ const { t } = useTranslation()
+ const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set())
+ const phases = todos?.phases ?? []
+ const tasks = phases.flatMap((p) => p.tasks)
+ const done = tasks.filter(
+ (task) => task.status === 'completed' || task.status === 'abandoned'
+ ).length
+ const pct = tasks.length > 0 ? Math.round((done / tasks.length) * 100) : 0
+
+ const togglePhase = (name: string) =>
+ setCollapsed((current) => {
+ const next = new Set(current)
+ if (next.has(name)) next.delete(name)
+ else next.add(name)
+ return next
+ })
+
+ return (
+ <CodeSidePanel
+ title={t('common:todoPanelTitle')}
+ summary={
+ tasks.length > 0 ? (
+ <span className="shrink-0 font-mono text-xs tabular-nums text-main-view-fg/60">
+ {done}/{tasks.length}
+ </span>
+ ) : null
+ }
+ onClose={onClose}
+ >
+ <div className="flex h-full flex-col">
+ {tasks.length > 0 && (
+ // Thin progress bar under the header, so overall completion reads at
+ // a glance without parsing the list.
+ <div className="h-0.5 shrink-0 bg-main-view-fg/10">
+ <div
+ className="h-full bg-primary transition-[width] duration-300"
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ )}
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 py-2.5">
+ {phases.length === 0 ? (
+ <p className="text-sm text-main-view-fg/50">{t('common:todoPanelEmpty')}</p>
+ ) : (
+ phases.map((phase, phaseIdx) => {
+ const isCollapsed = collapsed.has(phase.name)
+ const phaseDone = phase.tasks.filter(
+ (task) => task.status === 'completed' || task.status === 'abandoned'
+ ).length
+ return (
+ <section key={phase.name} className={cn(phaseIdx > 0 && 'mt-3.5')}>
+ {/* A flat single-phase list has no meaningful phase name to
+ show, so the header is skipped entirely there. */}
+ {phase.name && (
+ <button
+ type="button"
+ onClick={() => togglePhase(phase.name)}
+ className="group mb-1 flex w-full items-center gap-1 text-left"
+ >
+ <ChevronDown
+ size={11}
+ className={cn(
+ 'shrink-0 text-main-view-fg/40 transition-transform',
+ isCollapsed && '-rotate-90'
+ )}
+ />
+ <span className="truncate text-[11px] font-semibold uppercase tracking-wider text-main-view-fg/50">
+ {phase.name}
+ </span>
+ <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums text-main-view-fg/35">
+ {phaseDone}/{phase.tasks.length}
+ </span>
+ </button>
+ )}
+ {!isCollapsed && (
+ <ul className="space-y-1">
+ {phase.tasks.map((task, i) => {
+ const resolved =
+ task.status === 'completed' || task.status === 'abandoned'
+ return (
+ <li
+ key={`${phase.name}-${i}`}
+ className="flex items-start gap-2 pl-0.5"
+ >
+ <StatusDot status={task.status} />
+ <span
+ className={cn(
+ 'text-[13px] leading-5',
+ resolved && 'text-main-view-fg/40 line-through',
+ task.status === 'in_progress' && 'font-medium'
+ )}
+ >
+ {cleanTaskLabel(task.content)}
+ </span>
+ </li>
+ )
+ })}
+ </ul>
+ )}
+ </section>
+ )
+ })
+ )}
+ </div>
+ </div>
+ </CodeSidePanel>
+ )
+}
diff --git a/web-app/src/containers/CoworkBudgetNotice.tsx b/web-app/src/containers/CoworkBudgetNotice.tsx
new file mode 100644
index 000000000..ae368601a
--- /dev/null
+++ b/web-app/src/containers/CoworkBudgetNotice.tsx
@@ -0,0 +1,61 @@
+import { CircleSlash } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+
+type Props =
+ | { kind: 'steps'; max: number; onContinue: () => void }
+ | { kind: 'tokens'; onCompact: () => void; onNewSession: () => void }
+
+/**
+ * Why a run stopped short of an answer.
+ *
+ * Deliberately not styled as an error: hitting a step cap is routine on a long
+ * task, and colouring it red trains people to read a normal event as a failure
+ * — after which they stop reading the ones that matter.
+ */
+export function CoworkBudgetNotice(props: Props) {
+ const { t } = useTranslation()
+
+ return (
+ <div
+ role="status"
+ data-testid="cowork-budget-notice"
+ className="mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground"
+ >
+ <CircleSlash size={14} aria-hidden className="shrink-0" />
+ {props.kind === 'steps' ? (
+ <>
+ <span>{t('common:budget.stoppedSteps', { max: props.max })}</span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7"
+ onClick={props.onContinue}
+ >
+ {t('common:budget.keepGoing')}
+ </Button>
+ </>
+ ) : (
+ <>
+ <span>{t('common:budget.stoppedTokens')}</span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7"
+ onClick={props.onCompact}
+ >
+ {t('common:budget.compact')}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7"
+ onClick={props.onNewSession}
+ >
+ {t('common:budget.newSession')}
+ </Button>
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/web-app/src/containers/CoworkPlanToggle.tsx b/web-app/src/containers/CoworkPlanToggle.tsx
new file mode 100644
index 000000000..6a8580925
--- /dev/null
+++ b/web-app/src/containers/CoworkPlanToggle.tsx
@@ -0,0 +1,69 @@
+import { Diamond } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/ui/tooltip'
+import { cn } from '@/lib/utils'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+
+type Props = {
+ planMode: boolean
+ onChange: (planMode: boolean) => void
+}
+
+/**
+ * A pressed-state button, not a Switch: a Switch reads as a settings control
+ * and is too tall for the 28px dock row, and this is a mode flipped mid-
+ * conversation.
+ *
+ * The visual cues are deliberately quiet — a filled glyph here, a placeholder
+ * swap and one hairline on the composer. Tinting the composer made every
+ * plan-mode session look like an error state.
+ */
+export function CoworkPlanToggle({ planMode, onChange }: Props) {
+ const { t } = useTranslation()
+
+ return (
+ <>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant={planMode ? 'secondary' : 'outline'}
+ size="sm"
+ aria-pressed={planMode}
+ onClick={() => onChange(!planMode)}
+ className={cn(
+ 'h-7 gap-1.5 rounded-full shrink-0',
+ planMode && 'border-primary/40'
+ )}
+ >
+ <Diamond
+ size={13}
+ aria-hidden
+ className={cn(
+ 'shrink-0',
+ planMode
+ ? 'fill-current text-primary'
+ : 'text-muted-foreground'
+ )}
+ />
+ <span className={planMode ? undefined : 'text-muted-foreground'}>
+ {t('common:planMode.label')}
+ </span>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {planMode
+ ? t('common:planMode.tooltipOn')
+ : t('common:planMode.tooltipOff')}
+ </TooltipContent>
+ </Tooltip>
+ {/* The cues are subtle by design, so the change itself is announced. */}
+ <span aria-live="polite" className="sr-only">
+ {planMode ? t('common:planMode.onAnnounce') : ''}
+ </span>
+ </>
+ )
+}
diff --git a/web-app/src/containers/CoworkSandboxChip.tsx b/web-app/src/containers/CoworkSandboxChip.tsx
new file mode 100644
index 000000000..b43d94a3d
--- /dev/null
+++ b/web-app/src/containers/CoworkSandboxChip.tsx
@@ -0,0 +1,89 @@
+import { useCallback, useEffect, useState } from 'react'
+import { TriangleAlert } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '@/components/ui/popover'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { getSandboxStatus, refreshSandboxStatus } from '@/lib/agentTools'
+
+/** Per-OS remedy. Never shown the raw `backend` value, which is `"none"` here. */
+function fixKeyFor(platform: string): string {
+ if (platform.includes('mac') || platform.includes('darwin')) {
+ return 'common:sandbox.fixMac'
+ }
+ if (platform.includes('win')) return 'common:sandbox.fixWindows'
+ return 'common:sandbox.fixLinux'
+}
+
+/**
+ * Shown only when no OS sandbox can confine a shell, in which case `bash` is
+ * withheld entirely rather than run unconfined. Without this the capability
+ * just silently isn't offered, which reads as a broken agent.
+ */
+export function CoworkSandboxChip() {
+ const { t } = useTranslation()
+ const [enforces, setEnforces] = useState<boolean | null>(null)
+ const [checking, setChecking] = useState(false)
+
+ useEffect(() => {
+ let alive = true
+ void getSandboxStatus().then((s) => {
+ if (alive) setEnforces(s.enforces)
+ })
+ return () => {
+ alive = false
+ }
+ }, [])
+
+ const recheck = useCallback(() => {
+ setChecking(true)
+ void refreshSandboxStatus()
+ .then((s) => setEnforces(s.enforces))
+ .finally(() => setChecking(false))
+ }, [])
+
+ // null while probing: stay out of the way rather than flash a warning.
+ if (enforces !== false) return null
+
+ const platform =
+ typeof navigator === 'undefined' ? '' : navigator.platform.toLowerCase()
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 gap-1.5 rounded-full bg-amber-500/10 text-amber-600 shrink-0 hover:bg-amber-500/20 dark:text-amber-400"
+ aria-label={t('common:sandbox.a11y')}
+ >
+ <TriangleAlert size={12} className="shrink-0" />
+ <span>{t('common:sandbox.noTerminal')}</span>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-80 p-3">
+ <h3 className="text-sm font-medium">{t('common:sandbox.title')}</h3>
+ <p className="mt-1.5 text-xs text-muted-foreground">
+ {t('common:sandbox.body')}
+ </p>
+ <p className="mt-2 text-xs text-muted-foreground">
+ {t(fixKeyFor(platform))}
+ </p>
+ <div className="mt-3 flex">
+ <Button
+ variant="outline"
+ size="sm"
+ className="ml-auto"
+ disabled={checking}
+ onClick={recheck}
+ >
+ {t('common:sandbox.recheck')}
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/web-app/src/containers/CoworkWorkspacePill.tsx b/web-app/src/containers/CoworkWorkspacePill.tsx
new file mode 100644
index 000000000..9f2a592f2
--- /dev/null
+++ b/web-app/src/containers/CoworkWorkspacePill.tsx
@@ -0,0 +1,188 @@
+import { Folder, GitBranch, HardDrive, Lock } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '@/components/ui/popover'
+import { Separator } from '@/components/ui/separator'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { useServiceHub } from '@/hooks/useServiceHub'
+import { basenameOf } from '@/lib/codePreview'
+import { truncateMiddle } from '@/lib/utils'
+
+type Props = {
+ /** Attached project folder, or null when the session is sandbox-only. */
+ folder: string | null
+ /** Absolute path of this session's sandbox — where every write lands. */
+ sandboxPath: string | null
+ gitBranch?: string | null
+ onAttach: () => void
+ onDetach: () => void
+}
+
+/**
+ * Names both halves of the session's filesystem: the read-only folder it reads
+ * from, and the sandbox it writes to.
+ *
+ * The two headings carry the whole point. A single "folder" control would imply
+ * the agent edits your project, which it cannot — so the direction is stated
+ * structurally rather than in a warning the user learns to skip.
+ */
+export function CoworkWorkspacePill({
+ folder,
+ sandboxPath,
+ gitBranch,
+ onAttach,
+ onDetach,
+}: Props) {
+ const { t } = useTranslation()
+ const serviceHub = useServiceHub()
+ const folderName = folder ? basenameOf(folder) : null
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1.5 rounded-full shrink-0"
+ aria-label={
+ folderName
+ ? t('common:workspace.a11yWithFolder', { folder: folderName })
+ : t('common:workspace.a11ySandboxOnly')
+ }
+ >
+ {folderName ? (
+ <>
+ <Folder size={14} className="text-muted-foreground shrink-0" />
+ <span className="truncate max-w-[120px]">{folderName}</span>
+ <span className="text-muted-foreground/80 text-xs">
+ {t('common:workspace.readOnly')}
+ </span>
+ <span aria-hidden className="text-muted-foreground/60">
+ →
+ </span>
+ </>
+ ) : null}
+ <HardDrive size={14} className="text-muted-foreground shrink-0" />
+ <span>{t('common:workspace.sandbox')}</span>
+ </Button>
+ </PopoverTrigger>
+
+ <PopoverContent align="start" className="w-80 p-3">
+ {folder ? (
+ <>
+ <p className="text-xs font-medium text-muted-foreground">
+ {t('common:workspace.readsFrom')}
+ </p>
+ <div className="mt-1 flex items-center gap-2">
+ <Folder size={14} className="shrink-0 text-muted-foreground" />
+ <span className="truncate text-sm font-medium">{folderName}</span>
+ <span className="ml-auto inline-flex shrink-0 items-center gap-1 rounded-full bg-muted px-1.5 py-0.5 text-xs font-mono text-muted-foreground">
+ <Lock size={10} />
+ {t('common:workspace.readOnly')}
+ </span>
+ </div>
+ <p
+ className="mt-0.5 font-mono text-xs text-muted-foreground"
+ title={folder}
+ >
+ {truncateMiddle(folder, 44)}
+ </p>
+ <div className="mt-1.5 flex items-center gap-2">
+ {gitBranch && (
+ <span className="inline-flex items-center gap-1 rounded-full bg-muted px-1.5 py-0.5 text-xs font-mono text-muted-foreground">
+ <GitBranch size={10} />
+ {gitBranch}
+ </span>
+ )}
+ <Button
+ variant="ghost"
+ size="sm"
+ className="ml-auto h-7"
+ onClick={() => void serviceHub.opener().openPath(folder)}
+ >
+ {t('common:workspace.open')}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7"
+ onClick={() =>
+ void serviceHub.opener().revealItemInDir(folder)
+ }
+ >
+ {t('common:workspace.reveal')}
+ </Button>
+ </div>
+ <Separator className="my-3" />
+ </>
+ ) : null}
+
+ <p className="text-xs font-medium text-muted-foreground">
+ {t('common:workspace.writesTo')}
+ </p>
+ <div className="mt-1 flex items-center gap-2">
+ <HardDrive size={14} className="shrink-0 text-muted-foreground" />
+ <span className="truncate text-sm font-medium">
+ {t('common:workspace.sandboxForSession')}
+ </span>
+ {sandboxPath && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="ml-auto h-7 shrink-0"
+ onClick={() => void serviceHub.opener().openPath(sandboxPath)}
+ >
+ {t('common:workspace.open')}
+ </Button>
+ )}
+ </div>
+ {sandboxPath && (
+ <p
+ className="mt-0.5 font-mono text-xs text-muted-foreground"
+ title={sandboxPath}
+ >
+ {truncateMiddle(sandboxPath, 44)}
+ </p>
+ )}
+
+ <Separator className="my-3" />
+
+ <p className="text-xs text-muted-foreground">
+ {folder
+ ? t('common:workspace.footnote')
+ : t('common:workspace.footnoteEmpty')}
+ </p>
+
+ <div className="mt-3 flex items-center gap-2">
+ {folder ? (
+ <>
+ <Button variant="ghost" size="sm" onClick={onDetach}>
+ {t('common:workspace.detach')}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="ml-auto"
+ onClick={onAttach}
+ >
+ {t('common:workspace.change')}
+ </Button>
+ </>
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ className="ml-auto"
+ onClick={onAttach}
+ >
+ {t('common:workspace.attach')}
+ </Button>
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/web-app/src/containers/__tests__/CodeAskCard.test.tsx b/web-app/src/containers/__tests__/CodeAskCard.test.tsx
new file mode 100644
index 000000000..3c18a771c
--- /dev/null
+++ b/web-app/src/containers/__tests__/CodeAskCard.test.tsx
@@ -0,0 +1,143 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import '@testing-library/jest-dom'
+import { CodeAskCard } from '@/containers/CodeAskCard'
+import type { AskRequestPayload } from '@/hooks/useCodeRun'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (key: string, vars?: Record<string, unknown>) =>
+ vars && 'count' in vars ? `${vars.count} selected` : key,
+ }),
+}))
+
+const single: AskRequestPayload = {
+ questions: [
+ {
+ id: 'scope',
+ question: 'Which scope?',
+ options: [{ label: 'Small' }, { label: 'Large' }],
+ },
+ ],
+}
+
+const multi: AskRequestPayload = {
+ questions: [
+ {
+ id: 'who',
+ question: 'Who reads it?',
+ multi: true,
+ options: [{ label: 'Team' }, { label: 'Public' }],
+ },
+ ],
+}
+
+const twoQuestions: AskRequestPayload = {
+ questions: [
+ { id: 'a', question: 'First?', options: [{ label: 'A1' }, { label: 'A2' }] },
+ { id: 'b', question: 'Second?', options: [{ label: 'B1' }, { label: 'B2' }] },
+ ],
+}
+
+let onRespond: ReturnType<typeof vi.fn>
+beforeEach(() => {
+ onRespond = vi.fn()
+})
+
+const submitButton = () => screen.getByLabelText('common:submit')
+
+describe('CodeAskCard', () => {
+ it('renders nothing when there is no pending request', () => {
+ const { container } = render(
+ <CodeAskCard requestId={null} request={null} onRespond={onRespond} />
+ )
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('submits the selected option label', () => {
+ render(<CodeAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText('Small'))
+ fireEvent.click(submitButton())
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [{ id: 'scope', selected: ['Small'] }])
+ })
+
+ it('single-select replaces the previous pick rather than accumulating', () => {
+ render(<CodeAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText('Small'))
+ fireEvent.click(screen.getByText('Large'))
+ fireEvent.click(submitButton())
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [{ id: 'scope', selected: ['Large'] }])
+ })
+
+ it('multi-select accumulates', () => {
+ render(<CodeAskCard requestId="ask-1" request={multi} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText('Team'))
+ fireEvent.click(screen.getByText('Public'))
+ fireEvent.click(submitButton())
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [
+ { id: 'who', selected: ['Team', 'Public'] },
+ ])
+ })
+
+ it('free text and options are mutually exclusive, per the QuestionResult contract', () => {
+ render(<CodeAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText('Small'))
+ fireEvent.click(screen.getByText('common:askSomethingElse'))
+ fireEvent.change(screen.getByPlaceholderText('common:askSomethingElsePlaceholder'), {
+ target: { value: 'neither' },
+ })
+ fireEvent.click(submitButton())
+ // `selected` empty, custom_input set — never both.
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [
+ { id: 'scope', selected: [], custom_input: 'neither' },
+ ])
+ })
+
+ it('cannot submit on empty free text', () => {
+ render(<CodeAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText('common:askSomethingElse'))
+ expect(submitButton()).toBeDisabled()
+ fireEvent.change(screen.getByPlaceholderText('common:askSomethingElsePlaceholder'), {
+ target: { value: ' ' },
+ })
+ expect(submitButton()).toBeDisabled()
+ })
+
+ it('requires every question answered before submitting, since the core rejects partial responses', () => {
+ render(<CodeAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)
+ // Answer only the first, then page to the last.
+ fireEvent.click(screen.getByText('A1'))
+ fireEvent.click(screen.getByLabelText('common:askNext'))
+ expect(screen.getByText('Second?')).toBeInTheDocument()
+ expect(submitButton()).toBeDisabled()
+
+ fireEvent.click(screen.getByText('B1'))
+ fireEvent.click(submitButton())
+ expect(onRespond).toHaveBeenCalledWith('ask-1', [
+ { id: 'a', selected: ['A1'] },
+ { id: 'b', selected: ['B1'] },
+ ])
+ })
+
+ it('Skip declines the whole request (the core has no per-question skip)', () => {
+ render(<CodeAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)
+ fireEvent.click(screen.getByText('common:skip'))
+ expect(onRespond).toHaveBeenCalledWith('ask-1', null)
+ })
+
+ it('dismissing declines too, so a paused run never hangs silently', () => {
+ render(<CodeAskCard requestId="ask-1" request={single} onRespond={onRespond} />)
+ fireEvent.click(screen.getByLabelText('common:close'))
+ expect(onRespond).toHaveBeenCalledWith('ask-1', null)
+ })
+
+ it('resets state when a new request arrives', () => {
+ const { rerender } = render(
+ <CodeAskCard requestId="ask-1" request={single} onRespond={onRespond} />
+ )
+ fireEvent.click(screen.getByText('Small'))
+ // A second request must not inherit the first one's pick.
+ rerender(<CodeAskCard requestId="ask-2" request={single} onRespond={onRespond} />)
+ expect(submitButton()).toBeDisabled()
+ })
+})
diff --git a/web-app/src/containers/__tests__/CoworkBudgetNotice.test.tsx b/web-app/src/containers/__tests__/CoworkBudgetNotice.test.tsx
new file mode 100644
index 000000000..24eee2e15
--- /dev/null
+++ b/web-app/src/containers/__tests__/CoworkBudgetNotice.test.tsx
@@ -0,0 +1,51 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (k: string, opts?: Record<string, unknown>) =>
+ opts ? `${k} ${Object.values(opts).join(' ')}` : k,
+ }),
+}))
+
+import { CoworkBudgetNotice } from '../CoworkBudgetNotice'
+
+describe('CoworkBudgetNotice', () => {
+ it('offers Keep going when the step cap is hit', async () => {
+ const onContinue = vi.fn()
+ render(
+ <CoworkBudgetNotice kind="steps" max={100} onContinue={onContinue} />
+ )
+ expect(
+ screen.getByText('common:budget.stoppedSteps 100')
+ ).toBeInTheDocument()
+ await userEvent.click(screen.getByText('common:budget.keepGoing'))
+ expect(onContinue).toHaveBeenCalled()
+ })
+
+ it('offers Compact and New session when the token budget is hit', async () => {
+ const onCompact = vi.fn()
+ const onNewSession = vi.fn()
+ render(
+ <CoworkBudgetNotice
+ kind="tokens"
+ onCompact={onCompact}
+ onNewSession={onNewSession}
+ />
+ )
+ await userEvent.click(screen.getByText('common:budget.compact'))
+ expect(onCompact).toHaveBeenCalled()
+ await userEvent.click(screen.getByText('common:budget.newSession'))
+ expect(onNewSession).toHaveBeenCalled()
+ })
+
+ // Routine, not a failure: a destructive/red treatment would teach users to
+ // ignore the notices that do matter.
+ it('is a status, not an alert', () => {
+ render(<CoworkBudgetNotice kind="steps" max={30} onContinue={vi.fn()} />)
+ const el = screen.getByTestId('cowork-budget-notice')
+ expect(el).toHaveAttribute('role', 'status')
+ expect(el.className).not.toMatch(/destructive|text-red/)
+ })
+})
diff --git a/web-app/src/containers/__tests__/CoworkPlanToggle.test.tsx b/web-app/src/containers/__tests__/CoworkPlanToggle.test.tsx
new file mode 100644
index 000000000..2f781e087
--- /dev/null
+++ b/web-app/src/containers/__tests__/CoworkPlanToggle.test.tsx
@@ -0,0 +1,49 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({ t: (k: string) => k }),
+}))
+
+import { CoworkPlanToggle } from '../CoworkPlanToggle'
+
+describe('CoworkPlanToggle', () => {
+ // aria-pressed, not aria-checked: this is a mode button, not a checkbox. The
+ // visual cues are intentionally subtle, so the accessible state is the only
+ // unambiguous signal.
+ it('exposes its state through aria-pressed', () => {
+ const { rerender } = render(
+ <CoworkPlanToggle planMode={false} onChange={vi.fn()} />
+ )
+ expect(screen.getByRole('button')).toHaveAttribute('aria-pressed', 'false')
+
+ rerender(<CoworkPlanToggle planMode onChange={vi.fn()} />)
+ expect(screen.getByRole('button')).toHaveAttribute('aria-pressed', 'true')
+ })
+
+ it('toggles both ways', async () => {
+ const onChange = vi.fn()
+ const { rerender } = render(
+ <CoworkPlanToggle planMode={false} onChange={onChange} />
+ )
+ await userEvent.click(screen.getByRole('button'))
+ expect(onChange).toHaveBeenCalledWith(true)
+
+ onChange.mockReset()
+ rerender(<CoworkPlanToggle planMode onChange={onChange} />)
+ await userEvent.click(screen.getByRole('button'))
+ expect(onChange).toHaveBeenCalledWith(false)
+ })
+
+ it('announces only while plan mode is on', () => {
+ const { rerender } = render(
+ <CoworkPlanToggle planMode={false} onChange={vi.fn()} />
+ )
+ expect(document.querySelector('[aria-live="polite"]')).toHaveTextContent('')
+ rerender(<CoworkPlanToggle planMode onChange={vi.fn()} />)
+ expect(document.querySelector('[aria-live="polite"]')).toHaveTextContent(
+ 'common:planMode.onAnnounce'
+ )
+ })
+})
diff --git a/web-app/src/containers/__tests__/CoworkSandboxChip.test.tsx b/web-app/src/containers/__tests__/CoworkSandboxChip.test.tsx
new file mode 100644
index 000000000..6f7deb5a9
--- /dev/null
+++ b/web-app/src/containers/__tests__/CoworkSandboxChip.test.tsx
@@ -0,0 +1,62 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({ t: (k: string) => k }),
+}))
+
+const { getSandboxStatus, refreshSandboxStatus } = vi.hoisted(() => ({
+ getSandboxStatus: vi.fn(),
+ refreshSandboxStatus: vi.fn(),
+}))
+vi.mock('@/lib/agentTools', () => ({ getSandboxStatus, refreshSandboxStatus }))
+
+import { CoworkSandboxChip } from '../CoworkSandboxChip'
+
+describe('CoworkSandboxChip', () => {
+ beforeEach(() => {
+ getSandboxStatus.mockReset()
+ refreshSandboxStatus.mockReset()
+ })
+
+ // The whole point: an enforcing sandbox is the normal case and must be
+ // invisible. A chip that always showed would be permanent furniture.
+ it('renders nothing when a sandbox enforces', async () => {
+ getSandboxStatus.mockResolvedValue({ backend: 'bubblewrap', enforces: true })
+ const { container } = render(<CoworkSandboxChip />)
+ await waitFor(() => expect(getSandboxStatus).toHaveBeenCalled())
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('stays hidden while the probe is still in flight', () => {
+ getSandboxStatus.mockReturnValue(new Promise(() => {}))
+ const { container } = render(<CoworkSandboxChip />)
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('explains the degradation and never shows the raw backend value', async () => {
+ getSandboxStatus.mockResolvedValue({ backend: 'none', enforces: false })
+ render(<CoworkSandboxChip />)
+ const chip = await screen.findByRole('button')
+ await userEvent.click(chip)
+
+ expect(screen.getByText('common:sandbox.title')).toBeInTheDocument()
+ expect(screen.getByText('common:sandbox.body')).toBeInTheDocument()
+ expect(document.body.textContent).not.toContain('none')
+ })
+
+ it('re-probes on Check again and hides itself once a backend appears', async () => {
+ getSandboxStatus.mockResolvedValue({ backend: 'none', enforces: false })
+ refreshSandboxStatus.mockResolvedValue({
+ backend: 'bubblewrap',
+ enforces: true,
+ })
+ const { container } = render(<CoworkSandboxChip />)
+ await userEvent.click(await screen.findByRole('button'))
+ await userEvent.click(screen.getByText('common:sandbox.recheck'))
+
+ await waitFor(() => expect(container).toBeEmptyDOMElement())
+ expect(refreshSandboxStatus).toHaveBeenCalled()
+ })
+})
diff --git a/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsx b/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsx
new file mode 100644
index 000000000..280ab104c
--- /dev/null
+++ b/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsx
@@ -0,0 +1,102 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (k: string, opts?: Record<string, unknown>) =>
+ opts ? `${k} ${Object.values(opts).join(' ')}` : k,
+ }),
+}))
+
+const openPath = vi.fn()
+const revealItemInDir = vi.fn()
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceHub: () => ({ opener: () => ({ openPath, revealItemInDir }) }),
+}))
+
+import { CoworkWorkspacePill } from '../CoworkWorkspacePill'
+
+const SANDBOX = '/home/u/.jan/agent-workspace/sessions/4f2a'
+
+describe('CoworkWorkspacePill', () => {
+ beforeEach(() => {
+ openPath.mockReset()
+ revealItemInDir.mockReset()
+ })
+
+ it('names only the sandbox when no folder is attached', async () => {
+ render(
+ <CoworkWorkspacePill
+ folder={null}
+ sandboxPath={SANDBOX}
+ onAttach={vi.fn()}
+ onDetach={vi.fn()}
+ />
+ )
+ await userEvent.click(screen.getByRole('button'))
+
+ expect(screen.getByText('common:workspace.writesTo')).toBeInTheDocument()
+ expect(screen.queryByText('common:workspace.readsFrom')).toBeNull()
+ // No folder means nothing to detach.
+ expect(screen.queryByText('common:workspace.detach')).toBeNull()
+ expect(screen.getByText('common:workspace.attach')).toBeInTheDocument()
+ })
+
+ // The honesty requirement: whenever a folder is attached, the popover must
+ // state both directions and mark the folder read-only. A regression here
+ // would have the UI implying the agent edits the user's project.
+ it('states both directions and marks the folder read-only', async () => {
+ render(
+ <CoworkWorkspacePill
+ folder="/home/u/Projects/jan-app"
+ sandboxPath={SANDBOX}
+ gitBranch="dev"
+ onAttach={vi.fn()}
+ onDetach={vi.fn()}
+ />
+ )
+ await userEvent.click(screen.getByRole('button', { name: /a11yWithFolder/ }))
+
+ expect(screen.getByText('common:workspace.readsFrom')).toBeInTheDocument()
+ expect(screen.getByText('common:workspace.writesTo')).toBeInTheDocument()
+ expect(
+ screen.getAllByText('common:workspace.readOnly').length
+ ).toBeGreaterThan(0)
+ expect(screen.getByText('dev')).toBeInTheDocument()
+ expect(screen.getByText('common:workspace.footnote')).toBeInTheDocument()
+ })
+
+ it('opens the folder and reveals it through the right opener calls', async () => {
+ render(
+ <CoworkWorkspacePill
+ folder="/home/u/Projects/jan-app"
+ sandboxPath={SANDBOX}
+ onAttach={vi.fn()}
+ onDetach={vi.fn()}
+ />
+ )
+ await userEvent.click(screen.getByRole('button', { name: /a11yWithFolder/ }))
+
+ await userEvent.click(screen.getAllByText('common:workspace.open')[0])
+ expect(openPath).toHaveBeenCalledWith('/home/u/Projects/jan-app')
+
+ await userEvent.click(screen.getByText('common:workspace.reveal'))
+ expect(revealItemInDir).toHaveBeenCalledWith('/home/u/Projects/jan-app')
+ })
+
+ it('detaches the folder', async () => {
+ const onDetach = vi.fn()
+ render(
+ <CoworkWorkspacePill
+ folder="/home/u/Projects/jan-app"
+ sandboxPath={SANDBOX}
+ onAttach={vi.fn()}
+ onDetach={onDetach}
+ />
+ )
+ await userEvent.click(screen.getByRole('button', { name: /a11yWithFolder/ }))
+ await userEvent.click(screen.getByText('common:workspace.detach'))
+ expect(onDetach).toHaveBeenCalled()
+ })
+})
diff --git a/web-app/src/containers/dialogs/CodePermissionDialog.tsx b/web-app/src/containers/dialogs/CodePermissionDialog.tsx
deleted file mode 100644
index 33188ff23..000000000
--- a/web-app/src/containers/dialogs/CodePermissionDialog.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import { useTranslation } from '@/i18n/react-i18next-compat'
-import { DiffView } from '@/components/DiffView'
-import {
- ToolApprovalDialog,
- type ApprovalDecision,
-} from '@/containers/dialogs/ToolApprovalDialog'
-
-export type PermissionDecision = 'allow_once' | 'allow_always' | 'deny'
-
-/** A gated tool call awaiting the user's approval, mirrors the Rust
- * `permission_request` StreamEvent (see events.rs). */
-export type PendingPermission = {
- requestId: string
- toolName: string
- capability: string
- path?: string
- command?: string
- diff?: string
- promptKind: string
- offersAlways: boolean
-}
-
-// The shared dialog speaks hyphenated decisions; the Rust command
-// (`agent_permission_respond`) expects the snake_case wire values.
-const WIRE: Record<ApprovalDecision, PermissionDecision> = {
- 'allow-once': 'allow_once',
- 'allow-always': 'allow_always',
- deny: 'deny',
-}
-
-/**
- * Approval dialog for a single gated agent tool call. A thin wrapper over the
- * shared `ToolApprovalDialog`: it maps the head of the pending-permission queue
- * onto the shared shell and injects the command/path/diff body. Closing the
- * dialog counts as a deny so the agent never proceeds without an explicit allow.
- */
-export default function CodePermissionDialog({
- request,
- onRespond,
-}: {
- request: PendingPermission | null
- onRespond: (requestId: string, decision: PermissionDecision) => void
-}) {
- const { t } = useTranslation()
- if (!request) return null
-
- const { requestId, toolName, capability, path, command, diff, offersAlways } =
- request
-
- return (
- <ToolApprovalDialog
- open={!!request}
- toolName={toolName}
- offersAlways={offersAlways}
- description={
- <>
- {t('tools:toolApproval.description')}{' '}
- <span className="font-semibold">{toolName}</span>
- {capability ? ` (${capability})` : ''}.
- </>
- }
- onDecision={(decision) => onRespond(requestId, WIRE[decision])}
- >
- {command && (
- <pre className="rounded-md bg-sidebar-foreground/5 px-2 py-1.5 text-xs font-mono break-all whitespace-pre-wrap">
- {command}
- </pre>
- )}
- {path && !command && (
- <pre className="rounded-md bg-sidebar-foreground/5 px-2 py-1.5 text-xs font-mono break-all">
- {path}
- </pre>
- )}
- {diff && <DiffView diff={diff} className="mt-1" />}
- </ToolApprovalDialog>
- )
-}
diff --git a/web-app/src/containers/dialogs/ToolApprovalDialog.tsx b/web-app/src/containers/dialogs/ToolApprovalDialog.tsx
index e6951e462..e2bea5bc0 100644
--- a/web-app/src/containers/dialogs/ToolApprovalDialog.tsx
+++ b/web-app/src/containers/dialogs/ToolApprovalDialog.tsx
@@ -15,7 +15,7 @@ export type ApprovalDecision = 'allow-once' | 'allow-always' | 'deny'
/**
* Presentational approval dialog shared by the chat MCP tool-approval flow
- * (`ToolApproval`) and the code agent's permission prompt (`CodePermissionDialog`).
+ * (`ToolApproval`).
*
* It owns only the shell — the shared `tools:toolApproval.*` copy, the
* deny / allow-once / allow-always footer, and close-as-deny semantics (Esc or
diff --git a/web-app/src/hooks/__tests__/useCodeRun.test.ts b/web-app/src/hooks/__tests__/useCodeRun.test.ts
new file mode 100644
index 000000000..4b574488b
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useCodeRun.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useCodeRun } from '../useCodeRun'
+
+// Covers only the llamacpp-attribution slice (llamacppRuns/pendingLlamacppError)
+// added for Cowork's model-load/OOM feedback parity with regular chat — see
+// LlamacppOomListener.test.tsx for how a Tauri event actually drives these.
+describe('useCodeRun - llamacpp attribution', () => {
+ beforeEach(() => {
+ useCodeRun.setState({
+ llamacppRuns: {},
+ pendingLlamacppError: {},
+ runId: {},
+ loadingModels: {},
+ modelLoadProgress: {},
+ })
+ })
+
+ it('tracks and clears which session is running which model', () => {
+ useCodeRun.getState().setLlamacppRun('session-a', 'model-1')
+ expect(useCodeRun.getState().llamacppRuns).toEqual({ 'session-a': 'model-1' })
+
+ useCodeRun.getState().clearLlamacppRun('session-a')
+ expect(useCodeRun.getState().llamacppRuns).toEqual({})
+ })
+
+ it('clearLlamacppRun on an untracked session is a no-op, not a crash', () => {
+ expect(() => useCodeRun.getState().clearLlamacppRun('nobody')).not.toThrow()
+ expect(useCodeRun.getState().llamacppRuns).toEqual({})
+ })
+
+ it('takePendingLlamacppError reads and clears in one step', () => {
+ useCodeRun.getState().setPendingLlamacppError('session-a', 'oom')
+
+ expect(useCodeRun.getState().takePendingLlamacppError('session-a')).toBe('oom')
+ // Consumed — a second take (e.g. a duplicate finally-block run) must not
+ // re-apply the same message twice.
+ expect(useCodeRun.getState().takePendingLlamacppError('session-a')).toBeUndefined()
+ expect(useCodeRun.getState().pendingLlamacppError).toEqual({})
+ })
+
+ it('takePendingLlamacppError on a session with nothing pending returns undefined', () => {
+ expect(useCodeRun.getState().takePendingLlamacppError('idle-session')).toBeUndefined()
+ })
+
+ it('does not cross-attribute between two sessions running different models', () => {
+ useCodeRun.getState().setLlamacppRun('session-a', 'model-1')
+ useCodeRun.getState().setLlamacppRun('session-b', 'model-2')
+ useCodeRun.getState().setPendingLlamacppError('session-a', 'oom')
+
+ expect(useCodeRun.getState().llamacppRuns).toEqual({
+ 'session-a': 'model-1',
+ 'session-b': 'model-2',
+ })
+ expect(useCodeRun.getState().takePendingLlamacppError('session-b')).toBeUndefined()
+ expect(useCodeRun.getState().takePendingLlamacppError('session-a')).toBe('oom')
+ })
+
+ it('clearCodeRun sweeps up llamacppRuns and pendingLlamacppError for that session too', () => {
+ useCodeRun.getState().setLlamacppRun('session-a', 'model-1')
+ useCodeRun.getState().setPendingLlamacppError('session-a', 'oom')
+
+ useCodeRun.getState().clearCodeRun('session-a')
+
+ expect(useCodeRun.getState().llamacppRuns).toEqual({})
+ expect(useCodeRun.getState().pendingLlamacppError).toEqual({})
+ })
+})
+
+describe('useCodeRun - per-session loading state', () => {
+ beforeEach(() => {
+ useCodeRun.setState({ loadingModels: {}, modelLoadProgress: {} })
+ })
+
+ it('sets and unsets the loading flag per session', () => {
+ useCodeRun.getState().setSessionLoadingModel('session-a', true)
+ expect(useCodeRun.getState().loadingModels).toEqual({ 'session-a': true })
+
+ useCodeRun.getState().setSessionLoadingModel('session-a', false)
+ // Absent, not `false` — mirrors useAppState's own loadingModels
+ // convention (key presence, not a boolean value, is the signal).
+ expect(useCodeRun.getState().loadingModels).toEqual({})
+ })
+
+ it('sets and clears load progress per session', () => {
+ useCodeRun
+ .getState()
+ .setSessionModelLoadProgress('session-a', { modelId: 'model-1', value: 0.4 })
+ expect(useCodeRun.getState().modelLoadProgress['session-a']).toEqual({
+ modelId: 'model-1',
+ value: 0.4,
+ })
+
+ useCodeRun.getState().setSessionModelLoadProgress('session-a', undefined)
+ expect(useCodeRun.getState().modelLoadProgress).toEqual({})
+ })
+
+ it('keeps two sessions\' loading state independent', () => {
+ useCodeRun.getState().setSessionLoadingModel('session-a', true)
+ useCodeRun.getState().setSessionLoadingModel('session-b', true)
+
+ useCodeRun.getState().setSessionLoadingModel('session-a', false)
+
+ expect(useCodeRun.getState().loadingModels).toEqual({ 'session-b': true })
+ })
+
+ it('clearCodeRun sweeps up per-session loading state too', () => {
+ useCodeRun.getState().setSessionLoadingModel('session-a', true)
+ useCodeRun
+ .getState()
+ .setSessionModelLoadProgress('session-a', { modelId: 'model-1', value: 0.4 })
+
+ useCodeRun.getState().clearCodeRun('session-a')
+
+ expect(useCodeRun.getState().loadingModels).toEqual({})
+ expect(useCodeRun.getState().modelLoadProgress).toEqual({})
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useCodeSessions.test.ts b/web-app/src/hooks/__tests__/useCodeSessions.test.ts
new file mode 100644
index 000000000..9bd821530
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useCodeSessions.test.ts
@@ -0,0 +1,146 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+
+vi.mock('@/lib/backendStorage', () => ({
+ backendStorage: {
+ getItem: vi.fn().mockResolvedValue(null),
+ setItem: vi.fn().mockResolvedValue(undefined),
+ removeItem: vi.fn().mockResolvedValue(undefined),
+ },
+}))
+
+import { useCodeSessions } from '../useCodeSessions'
+import type { CodeTurn, SubagentRun } from '@/types/codeSession'
+
+const reset = () => useCodeSessions.setState({ sessions: [], currentId: null })
+
+const sub = (runId: string, name: string): SubagentRun => ({
+ runId,
+ name,
+ status: 'done',
+ startedAt: 0,
+ turns: [],
+})
+
+describe('useCodeSessions', () => {
+ beforeEach(reset)
+
+ it('starts a session with an empty message list', () => {
+ const id = useCodeSessions.getState().createSession()
+ const s = useCodeSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.messages).toEqual([])
+ expect(s.folder).toBeNull()
+ })
+
+ it('appends turns and replaces the message list on commit', () => {
+ const id = useCodeSessions.getState().createSession()
+ const turn: CodeTurn = { role: 'user', content: 'hi' }
+ const msgs = [{ id: 'm1', role: 'user', parts: [] }] as never
+ useCodeSessions.getState().commitTurns(id, [turn], msgs, [])
+ useCodeSessions.getState().commitTurns(id, [turn], msgs, [])
+ const s = useCodeSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.turns).toHaveLength(2)
+ expect(s.messages).toHaveLength(1)
+ })
+
+ // A later run that dispatches no subagents must not erase what an earlier
+ // run in the same session already finished.
+ it('merges subagents by runId across runs instead of replacing', () => {
+ const id = useCodeSessions.getState().createSession()
+ useCodeSessions.getState().commitTurns(id, [], [], [sub('r1', 'alpha')])
+ useCodeSessions.getState().commitTurns(id, [], [], [])
+ let s = useCodeSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.subagents?.map((r) => r.runId)).toEqual(['r1'])
+
+ useCodeSessions.getState().commitTurns(id, [], [], [sub('r1', 'renamed')])
+ s = useCodeSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.subagents).toHaveLength(1)
+ expect(s.subagents?.[0].name).toBe('renamed')
+ })
+
+ it('keeps the last usage when a run reports none', () => {
+ const id = useCodeSessions.getState().createSession()
+ useCodeSessions.getState().commitTurns(id, [], [], [], { total_tokens: 42 })
+ useCodeSessions.getState().commitTurns(id, [], [], [])
+ const s = useCodeSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.lastUsage?.total_tokens).toBe(42)
+ })
+
+ it('clears the transcript, messages and subagents together', () => {
+ const id = useCodeSessions.getState().createSession()
+ useCodeSessions
+ .getState()
+ .commitTurns(
+ id,
+ [{ role: 'user', content: 'hi' }],
+ [{ id: 'm1', role: 'user', parts: [] }] as never,
+ [sub('r1', 'alpha')],
+ { total_tokens: 1 }
+ )
+ useCodeSessions.getState().clearSession(id)
+ const s = useCodeSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.turns).toEqual([])
+ expect(s.messages).toEqual([])
+ expect(s.subagents).toEqual([])
+ expect(s.lastUsage).toBeUndefined()
+ })
+
+ it('toggles plan mode and detaches a folder', () => {
+ const id = useCodeSessions.getState().createSession()
+ useCodeSessions.getState().setPlanMode(id, true)
+ useCodeSessions.getState().setFolder(id, '/tmp/project')
+ let s = useCodeSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.planMode).toBe(true)
+ expect(s.folder).toBe('/tmp/project')
+
+ useCodeSessions.getState().setFolder(id, null)
+ s = useCodeSessions.getState().sessions.find((x) => x.id === id)!
+ expect(s.folder).toBeNull()
+ })
+})
+
+describe('useCodeSessions persist migration', () => {
+ // v0 sessions carry `turns` but no `messages`. Losing the tool turns on
+ // upgrade would leave the agent replaying a conversation with holes in it.
+ it('rebuilds messages from turns for a v0 session', () => {
+ const migrate = useCodeSessions.persist.getOptions().migrate!
+ const out = migrate(
+ {
+ sessions: [
+ {
+ id: 's1',
+ turns: [
+ { role: 'user', content: 'build it' },
+ {
+ role: 'tool',
+ content: '',
+ name: 'write',
+ callId: 'c1',
+ args: { path: 'a.txt' },
+ result: 'Created a.txt (3 bytes)',
+ status: 'done',
+ },
+ ],
+ },
+ ],
+ },
+ 0
+ ) as { sessions: Array<{ messages: unknown[] }> }
+
+ const parts = (out.sessions[0].messages as never[]).flatMap(
+ (m: { parts?: unknown[] }) => m.parts ?? []
+ )
+ expect(out.sessions[0].messages.length).toBeGreaterThan(0)
+ expect(
+ parts.some((p: { type?: string }) => p.type === 'tool-write')
+ ).toBe(true)
+ })
+
+ it('leaves an already-migrated session alone', () => {
+ const migrate = useCodeSessions.persist.getOptions().migrate!
+ const existing = [{ id: 's1', turns: [], messages: [{ id: 'keep' }] }]
+ const out = migrate({ sessions: existing }, 1) as {
+ sessions: Array<{ messages: Array<{ id: string }> }>
+ }
+ expect(out.sessions[0].messages[0].id).toBe('keep')
+ })
+})
diff --git a/web-app/src/hooks/useCodeRun.ts b/web-app/src/hooks/useCodeRun.ts
new file mode 100644
index 000000000..65e441b81
--- /dev/null
+++ b/web-app/src/hooks/useCodeRun.ts
@@ -0,0 +1,449 @@
+import { create } from 'zustand'
+import type {
+ CodeTurn,
+ SubagentRun,
+ Usage,
+ TodoList,
+ AskRequestPayload,
+} from '@/types/codeSession'
+import type { ModelLoadProgress } from '@/hooks/useAppState'
+
+// The ask shapes live in the store-free types module; re-exported here because
+// this store is where the pending-ask queue lives.
+export type {
+ AskOption,
+ AskQuestion,
+ AskRequestPayload,
+ AskAnswer,
+} from '@/types/codeSession'
+
+// StreamEvent shapes emitted by the Rust agent loop (events.rs, tag = "type").
+// Owned here because this store is what consumes/dispatches them.
+export type StreamEvent =
+ | { type: 'token'; text: string }
+ | { type: 'step'; index: number; max: number }
+ | { type: 'tool_call_started'; id: string; name: string }
+ | { type: 'tool_call_args_delta'; id: string; delta: string }
+ | { type: 'tool_call'; id: string; name: string; args: unknown }
+ | { type: 'tool_result'; id: string; content: string; is_error: boolean; diff?: string }
+ | { type: 'done'; stop_reason: string; usage: Usage | null }
+ | { type: 'error'; code: string; message: string }
+ | { type: 'todo_update'; list: TodoList }
+ | { type: 'ask_request'; request_id: string; request: AskRequestPayload }
+ | { type: 'subagent_queued'; run_id: string; name: string; waiting: number }
+ | { type: 'subagent_start'; run_id: string; name: string }
+ | { type: 'subagent_end'; run_id: string; name: string; usage: Usage | null }
+ | { type: 'turn_usage'; usage: Usage }
+ | { type: 'subagent'; run_id: string; name: string; event: StreamEvent }
+
+// Append a streamed token to the last assistant turn, or start a new one.
+// Shared by the main stream (appendToken) and a subagent's wrapped stream
+// (applyInnerToTurns) — same merge, different turn lane.
+function appendAssistantToken(turns: CodeTurn[], text: string): CodeTurn[] {
+ const last = turns[turns.length - 1]
+ if (last && last.role === 'assistant')
+ return [...turns.slice(0, -1), { ...last, content: last.content + text }]
+ return [...turns, { role: 'assistant', content: text }]
+}
+
+// A freshly-dispatched tool call's turn. Shared by the main stream's
+// pushToolTurn call site (code.tsx) and a subagent's wrapped tool_call.
+export function makeToolCallTurn(ev: {
+ id: string
+ name: string
+ args: unknown
+}): CodeTurn {
+ return {
+ role: 'tool',
+ content: '',
+ callId: ev.id,
+ name: ev.name,
+ args: ev.args,
+ status: 'running',
+ }
+}
+
+// Find the tool turn by callId and merge patch onto it; returns the same
+// array reference (no-op) when there's no match, so callers can cheaply
+// detect "nothing changed". Shared by updateToolTurn and applyInnerToTurns.
+function mergeToolResult(
+ turns: CodeTurn[],
+ callId: string,
+ patch: Partial<CodeTurn>
+): CodeTurn[] {
+ const idx = turns.findIndex((tn) => tn.role === 'tool' && tn.callId === callId)
+ if (idx === -1) return turns
+ return [...turns.slice(0, idx), { ...turns[idx], ...patch }, ...turns.slice(idx + 1)]
+}
+
+// Apply one wrapped inner subagent event to that subagent's own turn lane
+// (token append / tool_call push / tool_result merge). Pure.
+function applyInnerToTurns(turns: CodeTurn[], inner: StreamEvent): CodeTurn[] {
+ switch (inner.type) {
+ case 'token':
+ return appendAssistantToken(turns, inner.text)
+ case 'tool_call_started': {
+ if (turns.some((tn) => tn.role === 'tool' && tn.callId === inner.id)) return turns
+ return [
+ ...turns,
+ { role: 'tool', content: '', callId: inner.id, name: inner.name, args: null, argsLive: '', status: 'running' },
+ ]
+ }
+ case 'tool_call_args_delta': {
+ const idx = turns.findIndex((tn) => tn.role === 'tool' && tn.callId === inner.id)
+ if (idx === -1) return turns
+ const prev = turns[idx].argsLive ?? ''
+ return [...turns.slice(0, idx), { ...turns[idx], argsLive: prev + inner.delta }, ...turns.slice(idx + 1)]
+ }
+ case 'tool_call':
+ return [...turns, makeToolCallTurn(inner)]
+ case 'tool_result':
+ return mergeToolResult(turns, inner.id, {
+ result: inner.content,
+ isError: inner.is_error,
+ diff: inner.diff,
+ status: 'done',
+ })
+ default:
+ return turns // step / anything else: no visible turn
+ }
+}
+
+function omitKey<T>(map: Record<string, T>, key: string): Record<string, T> {
+ if (!(key in map)) return map
+ const next = { ...map }
+ delete next[key]
+ return next
+}
+
+// Transient (non-persisted) run state for the Code UI, keyed by session id —
+// mirroring useAppState's per-thread Record<id, T> maps. This is what lets a run
+// keep updating a background session while another is viewed: every stream write
+// targets the session id captured at submit, and rendering reads the viewed id.
+//
+// No separate `running` flag: a session is running iff it has a runId, so
+// that's read directly (runId[sid] != null) instead of a second map that
+// would need to be kept in sync with it.
+type CodeRunState = {
+ liveTurns: Record<string, CodeTurn[]>
+ subagents: Record<string, SubagentRun[]>
+ runId: Record<string, string>
+ // In-flight `ask` tool questions per session. A subagent's wrapped ask is
+ // attributed to the parent session the same way.
+ pendingAsks: Record<string, { requestId: string; request: AskRequestPayload }[]>
+ // Usage from the latest `done` event, per session. Set once per run (the
+ // terminal event); untouched by a `null` usage so a provider that doesn't
+ // report it on a given turn doesn't blank out the last known value.
+ usage: Record<string, Usage>
+ /** Set by the artifacts library so Cowork opens that file on mount. */
+ pendingPreview: { sessionId: string; path: string } | null
+ // Session ids currently talking to the llamacpp provider, mapped to the
+ // model id in flight. Cowork sessions aren't chat threads, so they're
+ // invisible to the chat-only signals the global OOM/backend-error listener
+ // otherwise keys off; this is how that listener (mounted outside Cowork's
+ // component tree, so it still sees a session running in the background)
+ // finds the right session(s) to attribute a router-level failure to, and
+ // matches load-progress events by model id rather than "whichever session
+ // ran most recently".
+ llamacppRuns: Record<string, string>
+ // A friendlier failure message the listener stashes when the router itself
+ // reports why (OOM / backend crash) — submitTurn prefers this over whatever
+ // generic message the resulting connection failure produced.
+ pendingLlamacppError: Record<string, string>
+ // Cowork's own mirror of useAppState's thread-keyed loadingModels /
+ // modelLoadProgressByThread, keyed by session id instead of chat thread id.
+ // Kept as an entirely separate Record rather than sharing chat's — several
+ // chat-side functions (hasActiveLlamacppRequest, clearActiveWork) scan
+ // useAppState.loadingModels' *keys* as their "is a real chat thread active"
+ // signal; writing Cowork session ids into that same Record would make a
+ // Cowork-only model load/failure look like chat activity to those checks.
+ loadingModels: Record<string, boolean>
+ modelLoadProgress: Record<string, ModelLoadProgress>
+
+ beginRun: (sid: string, runId: string, userText: string, images?: string[]) => void
+ appendToken: (sid: string, text: string) => void
+ pushToolTurn: (sid: string, turn: CodeTurn) => void
+ updateToolTurn: (sid: string, callId: string, patch: Partial<CodeTurn>) => void
+ // `tool_call_started`: open a live tool row before any args exist, so the
+ // card shows a spot the user can watch fill as the arguments stream.
+ announceToolCall: (sid: string, id: string, name: string) => void
+ // `tool_call_args_delta`: append raw JSON argument text to the running row.
+ appendToolArgs: (sid: string, id: string, delta: string) => void
+ startSubagent: (sid: string, runId: string, name: string) => void
+ // `subagent_queued`: mark a child as waiting for a concurrency slot.
+ queueSubagent: (sid: string, runId: string, name: string, waiting: number) => void
+ endSubagent: (sid: string, runId: string, usage?: Usage | null) => void
+ routeIntoSubagent: (sid: string, runId: string, inner: StreamEvent) => void
+ attachSubagentOutput: (sid: string, runId: string, content: string) => void
+ setUsage: (sid: string, usage: Usage | null) => void
+ requestPreview: (sessionId: string, path: string) => void
+ clearPendingPreview: () => void
+ setLlamacppRun: (sid: string, modelId: string) => void
+ clearLlamacppRun: (sid: string) => void
+ setPendingLlamacppError: (sid: string, message: string) => void
+ /** Reads and clears in one step, so a message can't be applied twice. */
+ takePendingLlamacppError: (sid: string) => string | undefined
+ setSessionLoadingModel: (sid: string, loading: boolean) => void
+ setSessionModelLoadProgress: (
+ sid: string,
+ progress: ModelLoadProgress | undefined
+ ) => void
+ addPendingAsk: (sid: string, requestId: string, request: AskRequestPayload) => void
+ removePendingAsk: (sid: string, requestId: string) => void
+ // Mark running tool turns + subagents done (interrupted). Leaves
+ // liveTurns/subagents in place and returns the final values so the caller
+ // can commit them before clearCodeRun without a second round of store
+ // reads. Run-level failure is surfaced separately via `useMessageErrors`,
+ // not through this function.
+ finalizeRun: (sid: string) => { turns: CodeTurn[]; subagents: SubagentRun[] }
+ clearCodeRun: (sid: string) => void
+}
+
+export const useCodeRun = create<CodeRunState>()((set, get) => ({
+ liveTurns: {},
+ subagents: {},
+ runId: {},
+ pendingAsks: {},
+ usage: {},
+ pendingPreview: null,
+ llamacppRuns: {},
+ pendingLlamacppError: {},
+ loadingModels: {},
+ modelLoadProgress: {},
+
+ beginRun: (sid, runId, userText, images) =>
+ set((s) => ({
+ runId: { ...s.runId, [sid]: runId },
+ liveTurns: {
+ ...s.liveTurns,
+ [sid]: [{ role: 'user', content: userText, images }],
+ },
+ subagents: { ...s.subagents, [sid]: [] },
+ pendingAsks: { ...s.pendingAsks, [sid]: [] },
+ })),
+
+ appendToken: (sid, text) =>
+ set((s) => ({
+ liveTurns: {
+ ...s.liveTurns,
+ [sid]: appendAssistantToken(s.liveTurns[sid] ?? [], text),
+ },
+ })),
+
+ pushToolTurn: (sid, turn) =>
+ set((s) => ({
+ liveTurns: { ...s.liveTurns, [sid]: [...(s.liveTurns[sid] ?? []), turn] },
+ })),
+
+ updateToolTurn: (sid, callId, patch) =>
+ set((s) => {
+ const turns = s.liveTurns[sid] ?? []
+ const next = mergeToolResult(turns, callId, patch)
+ return next === turns ? {} : { liveTurns: { ...s.liveTurns, [sid]: next } }
+ }),
+
+ announceToolCall: (sid, id, name) =>
+ set((s) => {
+ const turns = s.liveTurns[sid] ?? []
+ if (turns.some((tn) => tn.role === 'tool' && tn.callId === id)) return {}
+ return {
+ liveTurns: {
+ ...s.liveTurns,
+ [sid]: [
+ ...turns,
+ { role: 'tool', content: '', callId: id, name, args: null, argsLive: '', status: 'running' },
+ ],
+ },
+ }
+ }),
+
+ appendToolArgs: (sid, id, delta) =>
+ set((s) => {
+ const turns = s.liveTurns[sid] ?? []
+ const idx = turns.findIndex((tn) => tn.role === 'tool' && tn.callId === id)
+ if (idx === -1) return {}
+ const prev = turns[idx].argsLive ?? ''
+ return {
+ liveTurns: {
+ ...s.liveTurns,
+ [sid]: [...turns.slice(0, idx), { ...turns[idx], argsLive: prev + delta }, ...turns.slice(idx + 1)],
+ },
+ }
+ }),
+
+ startSubagent: (sid, runId, name) =>
+ set((s) => {
+ const runs = s.subagents[sid] ?? []
+ // Promote a queued child the moment its slot frees; otherwise create it.
+ const idx = runs.findIndex((r) => r.runId === runId)
+ if (idx !== -1) {
+ const existing = runs[idx]
+ if (existing.status === 'queued') {
+ return {
+ subagents: {
+ ...s.subagents,
+ [sid]: [
+ ...runs.slice(0, idx),
+ { ...existing, status: 'running' as const, waiting: undefined, startedAt: Date.now() },
+ ...runs.slice(idx + 1),
+ ],
+ },
+ }
+ }
+ return {}
+ }
+ return {
+ subagents: {
+ ...s.subagents,
+ [sid]: [
+ ...runs,
+ { runId, name, status: 'running', startedAt: Date.now(), turns: [] },
+ ],
+ },
+ }
+ }),
+
+ queueSubagent: (sid, runId, name, waiting) =>
+ set((s) => {
+ const runs = s.subagents[sid] ?? []
+ if (runs.some((r) => r.runId === runId)) return {}
+ return {
+ subagents: {
+ ...s.subagents,
+ [sid]: [
+ ...runs,
+ { runId, name, status: 'queued', waiting, startedAt: Date.now(), turns: [] },
+ ],
+ },
+ }
+ }),
+
+
+ endSubagent: (sid, runId, usage) =>
+ set((s) => ({
+ subagents: {
+ ...s.subagents,
+ [sid]: (s.subagents[sid] ?? []).map((r) =>
+ r.runId === runId && r.status !== 'done'
+ ? {
+ ...r,
+ status: 'done' as const,
+ endedAt: Date.now(),
+ usage: usage ?? undefined,
+ }
+ : r
+ ),
+ },
+ })),
+
+ routeIntoSubagent: (sid, runId, inner) =>
+ set((s) => ({
+ subagents: {
+ ...s.subagents,
+ [sid]: (s.subagents[sid] ?? []).map((r) =>
+ r.runId === runId ? { ...r, turns: applyInnerToTurns(r.turns, inner) } : r
+ ),
+ },
+ })),
+
+ attachSubagentOutput: (sid, runId, content) =>
+ set((s) => ({
+ subagents: {
+ ...s.subagents,
+ [sid]: (s.subagents[sid] ?? []).map((r) =>
+ r.runId === runId && r.finalOutput == null ? { ...r, finalOutput: content } : r
+ ),
+ },
+ })),
+
+ setUsage: (sid, usage) =>
+ set((s) => (usage ? { usage: { ...s.usage, [sid]: usage } } : {})),
+
+ requestPreview: (sessionId, path) => set({ pendingPreview: { sessionId, path } }),
+ clearPendingPreview: () => set({ pendingPreview: null }),
+
+ setLlamacppRun: (sid, modelId) =>
+ set((s) => ({ llamacppRuns: { ...s.llamacppRuns, [sid]: modelId } })),
+ clearLlamacppRun: (sid) =>
+ set((s) => ({ llamacppRuns: omitKey(s.llamacppRuns, sid) })),
+ setPendingLlamacppError: (sid, message) =>
+ set((s) => ({
+ pendingLlamacppError: { ...s.pendingLlamacppError, [sid]: message },
+ })),
+ takePendingLlamacppError: (sid) => {
+ const message = get().pendingLlamacppError[sid]
+ if (message !== undefined) {
+ set((s) => ({ pendingLlamacppError: omitKey(s.pendingLlamacppError, sid) }))
+ }
+ return message
+ },
+ setSessionLoadingModel: (sid, loading) =>
+ set((s) => {
+ const next = { ...s.loadingModels }
+ if (loading) next[sid] = true
+ else delete next[sid]
+ return { loadingModels: next }
+ }),
+ setSessionModelLoadProgress: (sid, progress) =>
+ set((s) => {
+ const next = { ...s.modelLoadProgress }
+ if (progress) next[sid] = progress
+ else delete next[sid]
+ return { modelLoadProgress: next }
+ }),
+
+ addPendingAsk: (sid, requestId, request) =>
+ set((s) => ({
+ pendingAsks: {
+ ...s.pendingAsks,
+ [sid]: [...(s.pendingAsks[sid] ?? []), { requestId, request }],
+ },
+ })),
+
+ removePendingAsk: (sid, requestId) =>
+ set((s) => ({
+ pendingAsks: {
+ ...s.pendingAsks,
+ [sid]: (s.pendingAsks[sid] ?? []).filter((a) => a.requestId !== requestId),
+ },
+ })),
+
+ finalizeRun: (sid) => {
+ // Run-level failure surfaces via `useMessageErrors` (Generation-failed
+ // banner), not as a synthetic tool-error turn — that used to render a
+ // misleading error-styled tool card even though no tool call failed.
+ const turns: CodeTurn[] = (get().liveTurns[sid] ?? []).map((tn) =>
+ tn.role === 'tool' && tn.status === 'running'
+ ? { ...tn, status: 'done' as const, isError: true, result: tn.result || '(interrupted)' }
+ : tn
+ )
+ const subs = (get().subagents[sid] ?? []).map((r) =>
+ r.status !== 'done' ? { ...r, status: 'done' as const, endedAt: Date.now() } : r
+ )
+ set((s) => ({
+ liveTurns: { ...s.liveTurns, [sid]: turns },
+ subagents: { ...s.subagents, [sid]: subs },
+ }))
+ return { turns, subagents: subs }
+ },
+
+ clearCodeRun: (sid) =>
+ set((s) => ({
+ liveTurns: omitKey(s.liveTurns, sid),
+ subagents: omitKey(s.subagents, sid),
+ runId: omitKey(s.runId, sid),
+ pendingAsks: omitKey(s.pendingAsks, sid),
+ usage: omitKey(s.usage, sid),
+ llamacppRuns: omitKey(s.llamacppRuns, sid),
+ pendingLlamacppError: omitKey(s.pendingLlamacppError, sid),
+ loadingModels: omitKey(s.loadingModels, sid),
+ modelLoadProgress: omitKey(s.modelLoadProgress, sid),
+ })),
+}))
+
+// Per-session selectors, mirroring useAppState's useIsThreadActive — a
+// component reading only one session's slice re-renders on that session's
+// changes, not on every other session's.
+export const useIsSessionActive = (sid: string | undefined) =>
+ useCodeRun((s) => (sid ? s.runId[sid] != null : false))
+
diff --git a/web-app/src/hooks/useCodeSessions.ts b/web-app/src/hooks/useCodeSessions.ts
index 1d667d2d3..11aa6ed29 100644
--- a/web-app/src/hooks/useCodeSessions.ts
+++ b/web-app/src/hooks/useCodeSessions.ts
@@ -1,25 +1,37 @@
+import type { UIMessage } from 'ai'
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
import { backendStorage } from '@/lib/backendStorage'
+import { codeTurnsToUIMessages } from '@/lib/codeTurns'
+import type {
+ CodeTurn,
+ SubagentRun,
+ Usage,
+ CodeGoal,
+ TodoList,
+} from '@/types/codeSession'
-// A single visible transcript entry. `tool` rows are display-only and carry the
-// structured call/result so the UI can render a tool card. The extra fields are
-// optional for backward-compat with sessions persisted before they existed.
-export type CodeTurn = {
- role: 'user' | 'assistant' | 'tool'
- content: string
- // Tool-row only: merged from the `tool_call` + matching `tool_result` events.
- callId?: string
- name?: string
- args?: unknown
- result?: string
- isError?: boolean
- diff?: string
- status?: 'running' | 'done'
-}
+// The transcript/todo/subagent shapes live in a store-free module so panels and
+// pure helpers can import them without pulling in zustand. Re-exported here
+// because this store is still their most natural import site.
+export type {
+ CodeTurn,
+ Usage,
+ SubagentRun,
+ TodoStatus,
+ TodoItem,
+ TodoPhase,
+ TodoList,
+ CodeGoal,
+} from '@/types/codeSession'
-// OpenAI-style history replayed to the agent on the next turn (no tool rows).
+/**
+ * @deprecated Superseded by `CodeSession.messages`. This shape cannot model
+ * tool calls, so replaying it drops every tool turn — survivable while Rust
+ * owned the loop and kept its own history, but not now the client is the
+ * history. Retained only so sessions persisted by an earlier build still load.
+ */
export type CodeMessage = {
role: 'user' | 'assistant'
content: string
@@ -28,9 +40,24 @@ export type CodeMessage = {
export type CodeSession = {
id: string
title: string
+ /** An attached project folder, mounted read-only. Writes always land in the
+ * session's own sandbox, never here. */
folder: string | null
turns: CodeTurn[]
- history: CodeMessage[]
+ /** The authoritative conversation, sent to the model each turn. */
+ messages: UIMessage[]
+ /** @deprecated Read once to migrate into `messages`, then left alone. */
+ history?: CodeMessage[]
+ /** Finished subagent runs across this session, merged by runId. */
+ subagents?: SubagentRun[]
+ /** Usage from the most recent completed run. */
+ lastUsage?: Usage
+ /** `/goal` state: checked after each turn, cleared when met. */
+ goal?: CodeGoal
+ /** Canonical session todo list, updated by the `todo_write` tool. */
+ todos?: TodoList
+ /** Plan mode: the agent reads and proposes, without writing. Absent means off. */
+ planMode?: boolean
updated: number
}
@@ -40,9 +67,28 @@ type CodeSessionsState = {
createSession: () => string
selectSession: (id: string) => void
deleteSession: (id: string) => void
- setFolder: (id: string, folder: string) => void
+ setFolder: (id: string, folder: string | null) => void
+ setPlanMode: (id: string, planMode: boolean) => void
setTitle: (id: string, title: string) => void
- commitTurns: (id: string, turns: CodeTurn[], history: CodeMessage[]) => void
+ setMessages: (id: string, messages: UIMessage[]) => void
+ setGoal: (id: string, goal: CodeGoal | null) => void
+ setTodos: (id: string, todos: TodoList) => void
+ /**
+ * @deprecated Bridge for the pre-AI-SDK code route, which has no
+ * `UIMessage[]` to commit. Removed together with that route.
+ */
+ commitLegacyTurns: (
+ id: string,
+ turns: CodeTurn[],
+ history: CodeMessage[]
+ ) => void
+ commitTurns: (
+ id: string,
+ turns: CodeTurn[],
+ messages: UIMessage[],
+ subagents: SubagentRun[],
+ usage?: Usage
+ ) => void
clearSession: (id: string) => void
}
@@ -61,7 +107,7 @@ export const useCodeSessions = create<CodeSessionsState>()(
title: 'New session',
folder: null,
turns: [],
- history: [],
+ messages: [],
updated: now(),
}
set((s) => ({ sessions: [session, ...s.sessions], currentId: id }))
@@ -85,29 +131,81 @@ export const useCodeSessions = create<CodeSessionsState>()(
),
})),
+ setMessages: (id, messages) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id ? { ...x, messages, updated: now() } : x
+ ),
+ })),
+
+ setGoal: (id, goal) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id ? { ...x, goal: goal ?? undefined } : x
+ ),
+ })),
+
+ setTodos: (id, todos) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) => (x.id === id ? { ...x, todos } : x)),
+ })),
+
+ setPlanMode: (id, planMode) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) =>
+ x.id === id ? { ...x, planMode, updated: now() } : x
+ ),
+ })),
+
setTitle: (id, title) =>
set((s) => ({
sessions: s.sessions.map((x) => (x.id === id ? { ...x, title } : x)),
})),
- commitTurns: (id, turns, history) =>
+ commitLegacyTurns: (id, turns, history) =>
set((s) => ({
sessions: s.sessions.map((x) =>
x.id === id
- ? {
- ...x,
- turns: [...x.turns, ...turns],
- history,
- updated: now(),
- }
+ ? { ...x, turns: [...x.turns, ...turns], history, updated: now() }
: x
),
})),
+ commitTurns: (id, turns, messages, subagents, usage) =>
+ set((s) => ({
+ sessions: s.sessions.map((x) => {
+ if (x.id !== id) return x
+ // Accumulate across this session's runs, keyed by runId — a later
+ // run that dispatches no subagents of its own must not erase what
+ // an earlier run in the same session already finished.
+ const incoming = new Set(subagents.map((r) => r.runId))
+ return {
+ ...x,
+ turns: [...x.turns, ...turns],
+ messages,
+ subagents: [
+ ...(x.subagents ?? []).filter((r) => !incoming.has(r.runId)),
+ ...subagents,
+ ],
+ lastUsage: usage ?? x.lastUsage,
+ updated: now(),
+ }
+ }),
+ })),
+
clearSession: (id) =>
set((s) => ({
sessions: s.sessions.map((x) =>
- x.id === id ? { ...x, turns: [], history: [], updated: now() } : x
+ x.id === id
+ ? {
+ ...x,
+ turns: [],
+ messages: [],
+ subagents: [],
+ lastUsage: undefined,
+ updated: now(),
+ }
+ : x
),
})),
}),
@@ -119,6 +217,26 @@ export const useCodeSessions = create<CodeSessionsState>()(
// hydrateBackendStores() once the ServiceHub is ready.
storage: createJSONStorage(() => backendStorage),
skipHydration: true,
+ version: 1,
+ // v0 persisted an OpenAI-shaped `history` that could not represent tool
+ // calls, so replaying it dropped every tool turn. Rebuild the message
+ // list from `turns`, which did record them, and leave `history` in place
+ // untouched rather than mutating a blob a rollback would still read.
+ migrate: (persisted, version) => {
+ const state = persisted as { sessions?: CodeSession[] } | undefined
+ if (version >= 1 || !state?.sessions) return persisted
+ return {
+ ...state,
+ sessions: state.sessions.map((session) =>
+ session.messages
+ ? session
+ : {
+ ...session,
+ messages: codeTurnsToUIMessages(session.turns ?? [], session.id),
+ }
+ ),
+ }
+ },
}
)
)
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index ac976f118..71a5ea987 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -2,7 +2,9 @@
"htmlArtifact": {
"code": "Code",
"preview": "Preview",
- "previewStreaming": "Available when generation finishes"
+ "previewStreaming": "Available when generation finishes",
+ "unresolvedAssets_one": "1 asset reference can't load in the preview. Relative paths have no base URL to resolve against.",
+ "unresolvedAssets_other": "{{count}} asset references can't load in the preview. Relative paths have no base URL to resolve against."
},
"assistants": "Assistants",
"hardware": "Hardware",
@@ -598,5 +600,70 @@
"seconds": "{{count}}s",
"minutes": "{{count}}m",
"hours": "{{count}}h"
- }
+ },
+ "collapse": "Collapse",
+ "expand": "Expand",
+ "todoPanelTitle": "Progress",
+ "todoPanelEmpty": "No todo list yet.",
+ "artifactOpenPreview": "Open preview",
+ "artifactOpenExternal": "Open",
+ "artifactMoreActions": "More actions",
+ "artifactShowInFolder": "Show in Folder",
+ "skillsUsedLabel": "Skills used",
+ "skillsUsed": "Skills used: {{skills}}",
+ "artifactsAll": "All",
+ "artifactsEmpty": "Nothing produced yet. Artifacts from Cowork runs show up here.",
+ "artifactsNoMatch": "No artifacts match.",
+ "artifactsSearch": "Search artifacts",
+ "artifactsShowMore": "Show {{count}} more",
+ "workspace": {
+ "readsFrom": "Reads from",
+ "writesTo": "Writes to",
+ "readOnly": "read-only",
+ "sandbox": "Sandbox",
+ "sandboxForSession": "Sandbox for this session",
+ "footnote": "Anything the agent creates stays in the sandbox. Your folder is never modified.",
+ "footnoteEmpty": "Attach a folder to let the agent read your project. It still won't change anything in it.",
+ "attach": "Attach a folder",
+ "change": "Change folder",
+ "detach": "Detach folder",
+ "open": "Open",
+ "reveal": "Reveal",
+ "missing": "This folder isn't there anymore. Attach a different one.",
+ "a11yWithFolder": "Workspace. Reads from {{folder}}, read-only. Writes to this session’s sandbox.",
+ "a11ySandboxOnly": "Workspace. Writes to this session’s sandbox. No folder attached."
+ },
+ "sandbox": {
+ "noTerminal": "No terminal",
+ "a11y": "Running commands is turned off. Details.",
+ "title": "Running commands is turned off",
+ "body": "Jan lets the agent run shell commands only when your system can confine them. No sandbox is available here, so the agent can read, write and edit files in its sandbox — but not run anything.",
+ "fixLinux": "Linux uses bubblewrap. Install it, then restart Jan.",
+ "fixMac": "macOS uses the built-in sandbox at /usr/bin/sandbox-exec. Restart Jan once it is available.",
+ "fixWindows": "Windows uses AppContainer. Restart Jan to try again.",
+ "recheck": "Check again"
+ },
+ "planMode": {
+ "label": "Plan",
+ "tooltipOff": "Plan first — the agent reads and proposes, without writing.",
+ "tooltipOn": "Planning. Turn this off to let the agent write files.",
+ "onAnnounce": "Plan mode on",
+ "placeholder": "Ask for a plan. The agent won't change any files."
+ },
+ "budget": {
+ "steps": "step {{step}}/{{max}}",
+ "stoppedSteps": "Stopped at {{max}} steps. The agent hasn’t finished.",
+ "keepGoing": "Keep going",
+ "stoppedTokens": "Stopped — this session hit its token budget.",
+ "compact": "Compact",
+ "newSession": "New session"
+ },
+ "askContinue": "Continue",
+ "askNext": "Next question",
+ "askPrev": "Previous question",
+ "askRecommended": "Recommended",
+ "askSelectedCount": "{{count}} selected",
+ "askSomethingElse": "Something else",
+ "askSomethingElsePlaceholder": "Type your own answer",
+ "submit": "Submit"
}
diff --git a/web-app/src/routeTree.gen.ts b/web-app/src/routeTree.gen.ts
index 2dcbb9231..e1c41c801 100644
--- a/web-app/src/routeTree.gen.ts
+++ b/web-app/src/routeTree.gen.ts
@@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root'
import { Route as SystemMonitorRouteImport } from './routes/system-monitor'
import { Route as LogsRouteImport } from './routes/logs'
import { Route as CodeRouteImport } from './routes/code'
+import { Route as ArtifactsRouteImport } from './routes/artifacts'
import { Route as IndexRouteImport } from './routes/index'
import { Route as HubIndexRouteImport } from './routes/hub/index'
import { Route as ThreadsThreadIdRouteImport } from './routes/threads/$threadId'
@@ -50,6 +51,11 @@ const CodeRoute = CodeRouteImport.update({
path: '/code',
getParentRoute: () => rootRouteImport,
} as any)
+const ArtifactsRoute = ArtifactsRouteImport.update({
+ id: '/artifacts',
+ path: '/artifacts',
+ getParentRoute: () => rootRouteImport,
+} as any)
const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
@@ -164,6 +170,7 @@ const SettingsProvidersProviderNameRoute =
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
+ '/artifacts': typeof ArtifactsRoute
'/code': typeof CodeRoute
'/logs': typeof LogsRoute
'/system-monitor': typeof SystemMonitorRoute
@@ -191,6 +198,7 @@ export interface FileRoutesByFullPath {
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
+ '/artifacts': typeof ArtifactsRoute
'/code': typeof CodeRoute
'/logs': typeof LogsRoute
'/system-monitor': typeof SystemMonitorRoute
@@ -219,6 +227,7 @@ export interface FileRoutesByTo {
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
+ '/artifacts': typeof ArtifactsRoute
'/code': typeof CodeRoute
'/logs': typeof LogsRoute
'/system-monitor': typeof SystemMonitorRoute
@@ -248,6 +257,7 @@ export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths:
| '/'
+ | '/artifacts'
| '/code'
| '/logs'
| '/system-monitor'
@@ -275,6 +285,7 @@ export interface FileRouteTypes {
fileRoutesByTo: FileRoutesByTo
to:
| '/'
+ | '/artifacts'
| '/code'
| '/logs'
| '/system-monitor'
@@ -302,6 +313,7 @@ export interface FileRouteTypes {
id:
| '__root__'
| '/'
+ | '/artifacts'
| '/code'
| '/logs'
| '/system-monitor'
@@ -330,6 +342,7 @@ export interface FileRouteTypes {
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
+ ArtifactsRoute: typeof ArtifactsRoute
CodeRoute: typeof CodeRoute
LogsRoute: typeof LogsRoute
SystemMonitorRoute: typeof SystemMonitorRoute
@@ -379,6 +392,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof CodeRouteImport
parentRoute: typeof rootRouteImport
}
+ '/artifacts': {
+ id: '/artifacts'
+ path: '/artifacts'
+ fullPath: '/artifacts'
+ preLoaderRoute: typeof ArtifactsRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/': {
id: '/'
path: '/'
@@ -538,6 +558,7 @@ declare module '@tanstack/react-router' {
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
+ ArtifactsRoute: ArtifactsRoute,
CodeRoute: CodeRoute,
LogsRoute: LogsRoute,
SystemMonitorRoute: SystemMonitorRoute,
diff --git a/web-app/src/routes/artifacts.tsx b/web-app/src/routes/artifacts.tsx
new file mode 100644
index 000000000..798e53596
--- /dev/null
+++ b/web-app/src/routes/artifacts.tsx
@@ -0,0 +1,223 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { useEffect, useMemo, useState } from 'react'
+import { IconSearch } from '@tabler/icons-react'
+import { ChevronsUpDown, FolderOpen, SquareArrowOutUpRight } from 'lucide-react'
+import HeaderPage from '@/containers/HeaderPage'
+import { Button } from '@/components/ui/button'
+import { Card } from '@/components/ui/card'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
+import { route } from '@/constants/routes'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { useCodeSessions } from '@/hooks/useCodeSessions'
+import { useCodeRun } from '@/hooks/useCodeRun'
+import { useServiceHub } from '@/hooks/useServiceHub'
+import {
+ ARTIFACT_GROUP_NAMES,
+ ARTIFACT_ICON,
+ artifactsFromTurns,
+ type CodeArtifact,
+} from '@/lib/codeArtifacts'
+import { previewKindFor, resolveInRoot } from '@/lib/codePreview'
+
+export const Route = createFileRoute(route.artifacts as any)({
+ component: ArtifactsPage,
+})
+
+const PAGE = 24
+
+type Row = CodeArtifact & { sessionId: string; root: string | null }
+
+function ArtifactsPage() {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+ const serviceHub = useServiceHub()
+ const sessions = useCodeSessions((s) => s.sessions)
+ const [query, setQuery] = useState('')
+ const [group, setGroup] = useState<CodeArtifact['group'] | null>(null)
+ // ponytail: a render cap with "show more" rather than paging or a virtual
+ // list. Search and the kind filter already narrow the set, and DOM size was
+ // the only real cost. Swap for virtualization if this hits thousands.
+ const [limit, setLimit] = useState(PAGE)
+
+ // ponytail: derived from the sessions already on disk rather than a durable
+ // artifact store (#299). No registration path, no migration — the trade-off
+ // is that an artifact disappears if its session is deleted. See #310 for why
+ // that store needs splitting before it can carry artifact records.
+ const rows = useMemo<Row[]>(
+ () =>
+ sessions.flatMap((session) =>
+ artifactsFromTurns(session.turns, session.folder).map((artifact) => ({
+ ...artifact,
+ sessionId: session.id,
+ root: session.folder ?? null,
+ }))
+ ),
+ [sessions]
+ )
+
+ const shown = useMemo(() => {
+ const q = query.trim().toLowerCase()
+ return rows.filter(
+ (r) =>
+ (!group || r.group === group) &&
+ (!q || r.title.toLowerCase().includes(q) || r.path.toLowerCase().includes(q))
+ )
+ }, [rows, query, group])
+
+ // Narrowing the set should start from the top again.
+ useEffect(() => setLimit(PAGE), [query, group])
+
+ const open = (row: Row) => {
+ useCodeSessions.getState().selectSession(row.sessionId)
+ useCodeRun.getState().requestPreview(row.sessionId, row.path)
+ navigate({ to: route.code })
+ }
+
+ return (
+ <div className="flex h-svh w-full flex-col">
+ {/* Search in the header, dropdown filter on the right — the hub page's
+ layout, so this reads as part of Jan rather than its own thing. */}
+ <HeaderPage>
+ <div className="relative z-20 flex h-10 w-full items-center justify-between py-3 pr-3">
+ <div className="flex w-full items-center gap-2">
+ <IconSearch size={14} className="shrink-0 text-muted-foreground" />
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t('common:artifactsSearch')}
+ className="w-full focus:outline-none"
+ />
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm" className="shrink-0">
+ {group ?? t('common:artifactsAll')}
+ <ChevronsUpDown className="ml-2 size-4 shrink-0 text-muted-foreground" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="bottom" align="end">
+ <DropdownMenuItem onClick={() => setGroup(null)}>
+ {t('common:artifactsAll')}
+ </DropdownMenuItem>
+ {ARTIFACT_GROUP_NAMES.map((g) => (
+ <DropdownMenuItem key={g} onClick={() => setGroup(g)}>
+ {g}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </HeaderPage>
+
+ <div className="h-[calc(100%-60px)] w-full overflow-y-auto p-4">
+ <div className="mx-auto w-full md:w-4/5 xl:w-4/6">
+ {shown.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ {/* Distinct: nothing made yet vs nothing matching the filter. */}
+ {rows.length === 0 ? t('common:artifactsEmpty') : t('common:artifactsNoMatch')}
+ </p>
+ ) : (
+ <div className="grid auto-rows-min gap-3 sm:grid-cols-2 lg:grid-cols-3">
+ {shown.slice(0, limit).map((row) => {
+ const Icon = ARTIFACT_ICON[row.group]
+ const kind = previewKindFor(row.path)
+ const abs = row.root ? resolveInRoot(row.root, row.path) : null
+ // A real thumbnail only where the browser renders the file on
+ // its own; HTML would need executing the page.
+ const thumb =
+ abs && (kind === 'image' || kind === 'svg')
+ ? serviceHub.core().convertFileSrc(abs)
+ : null
+ return (
+ <Card
+ key={`${row.sessionId}:${row.path}`}
+ className="flex items-center gap-3 p-3 transition-colors hover:border-accent"
+ >
+ <button
+ type="button"
+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 text-left"
+ onClick={() => open(row)}
+ title={t('common:artifactOpenPreview')}
+ >
+ {thumb ? (
+ <img
+ src={thumb}
+ alt=""
+ className="size-10 shrink-0 rounded-md border object-contain"
+ />
+ ) : (
+ <div className="flex size-10 shrink-0 items-center justify-center rounded-md border">
+ <Icon size={18} className="text-muted-foreground" />
+ </div>
+ )}
+ {/* min-w-0 on a block box: `truncate` is inert otherwise. */}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm font-medium">{row.title}</span>
+ <span className="block truncate text-xs text-muted-foreground">
+ {row.group} · {row.label}
+ </span>
+ <span className="block truncate text-xs text-muted-foreground/70">
+ {row.path}
+ </span>
+ </span>
+ </button>
+ {abs && (
+ <div className="flex shrink-0 items-center rounded-md border">
+ <button
+ type="button"
+ onClick={() => void serviceHub.opener().openPath(abs)}
+ className="flex items-center gap-1.5 rounded-l-md px-2.5 py-1.5 text-xs hover:bg-accent"
+ title={t('common:artifactOpenExternal')}
+ >
+ <SquareArrowOutUpRight size={13} className="text-muted-foreground" />
+ </button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={t('common:artifactMoreActions')}
+ className="rounded-r-md border-l px-1.5 py-1.5 hover:bg-accent"
+ >
+ <ChevronsUpDown size={13} className="text-muted-foreground" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => void serviceHub.opener().openPath(abs)}
+ >
+ <SquareArrowOutUpRight size={14} />
+ {t('common:artifactOpenExternal')}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => void serviceHub.opener().revealItemInDir(abs)}
+ >
+ <FolderOpen size={14} />
+ {t('common:artifactShowInFolder')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
+ </Card>
+ )
+ })}
+ </div>
+ )}
+ {shown.length > limit && (
+ <div className="mt-3 flex justify-center">
+ <Button variant="outline" size="sm" onClick={() => setLimit((n) => n + PAGE)}>
+ {t('common:artifactsShowMore', { count: shown.length - limit })}
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/web-app/src/routes/code.tsx b/web-app/src/routes/code.tsx
index 339c33c04..9c8fcd2bf 100644
--- a/web-app/src/routes/code.tsx
+++ b/web-app/src/routes/code.tsx
@@ -4,29 +4,20 @@ import ChatInput from '@/containers/ChatInput'
import HeaderPage from '@/containers/HeaderPage'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { route } from '@/constants/routes'
-import { Button } from '@/components/ui/button'
import { useServiceHub } from '@/hooks/useServiceHub'
-import { GitBranch, Laptop, Folder } from 'lucide-react'
-import { useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
-import { invoke, Channel } from '@tauri-apps/api/core'
+import { invoke } from '@tauri-apps/api/core'
import { getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'
-import { cn, getProviderTitle, getModelDisplayName } from '@/lib/utils'
-import { predefinedProviders } from '@/constants/providers'
-import { providerHasRemoteApiKeys } from '@/lib/provider-api-keys'
+import { sessionWorkspacePath } from '@janhq/tauri-plugin-agent-tools-api'
+import { cn } from '@/lib/utils'
import {
useCodeSessions,
ensureCurrentSession,
- type CodeTurn,
- type CodeMessage,
} from '@/hooks/useCodeSessions'
+import type { AskAnswer, CodeTurn } from '@/types/codeSession'
import DropdownModelProvider from '@/containers/DropdownModelProvider'
import { useModelProvider } from '@/hooks/useModelProvider'
-import { usePrompt } from '@/hooks/usePrompt'
-import CodePermissionDialog, {
- type PendingPermission,
- type PermissionDecision,
-} from '@/containers/dialogs/CodePermissionDialog'
import { MessageItem } from '@/containers/MessageItem'
import SkillSelector from '@/containers/SkillSelector'
import { codeTurnsToUIMessages } from '@/lib/codeTurns'
@@ -39,149 +30,58 @@ import {
ConversationContent,
ConversationScrollButton,
} from '@/components/ai-elements/conversation'
+import { CoworkWorkspacePill } from '@/containers/CoworkWorkspacePill'
+import { CoworkPlanToggle } from '@/containers/CoworkPlanToggle'
+import { CoworkSandboxChip } from '@/containers/CoworkSandboxChip'
+import { CoworkBudgetNotice } from '@/containers/CoworkBudgetNotice'
+import { CodeAskCard } from '@/containers/CodeAskCard'
+import { CoworkChatTransport } from '@/lib/coworkTransport'
+import { dispatchCoworkTool } from '@/lib/coworkDispatch'
+import { applyTodoOp, renderTodoResult } from '@/lib/coworkTodo'
+import { parseAskRequest, renderAskResult } from '@/lib/coworkAsk'
+import { getSandboxStatus } from '@/lib/agentTools'
+import { MAX_AGENT_STEPS } from '@/lib/coworkBudget'
+import {
+ abortRun,
+ answerAsk,
+ runTurn,
+ type RunOutcome,
+ type StreamSink,
+ type ToolOutcome,
+} from '@/lib/coworkRunner'
+import { useCodeRun } from '@/hooks/useCodeRun'
export const Route = createFileRoute(route.code as any)({
component: CodePage,
})
-// StreamEvent shapes emitted by the Rust agent loop (events.rs, tag = "type").
-type StreamEvent =
- | { type: 'token'; text: string }
- | { type: 'step'; index: number; max: number }
- | { type: 'tool_call'; id: string; name: string; args: unknown }
- | { type: 'tool_result'; id: string; content: string; is_error: boolean; diff?: string }
- | { type: 'done'; stop_reason: string; usage: unknown }
- | { type: 'error'; code: string; message: string }
- | {
- type: 'permission_request'
- request_id: string
- tool_name: string
- capability: string
- path?: string
- command?: string
- diff?: string
- prompt_kind: string
- offers_always: boolean
- }
-
-// Per-run token ceiling. `max_turns: 0` lets a multi-step task run to completion;
-// this budget is the real bound that stops a runaway loop (see SessionBudget in
-// session.rs). Only the *marginal* token increase between requests counts — every
-// turn replays the full conversation, so summing absolute totals would grow
-// quadratically with context length and cut off a legitimate long task. A real
-// runaway (hundreds of turns) still accumulates unbounded marginal spend and trips.
-const MAX_SESSION_TOKENS = 200_000
-
-// Cap the history replayed to the agent so a long session never sends more than
-// the model can take (rough ~4 chars/token estimate → well under the ceiling).
-// Keeps the most recent messages; older ones roll off. Display keeps everything.
-const MAX_HISTORY_CHARS = 400_000
-
-function capHistory(messages: CodeMessage[]): CodeMessage[] {
- let budget = MAX_HISTORY_CHARS
- const kept: CodeMessage[] = []
- for (let i = messages.length - 1; i >= 0; i--) {
- budget -= messages[i].content.length
- if (budget < 0 && kept.length > 0) break
- kept.unshift(messages[i])
- }
- return kept
-}
-
-// Strict chat templates (llama.cpp Jinja) require strictly alternating
-// user/assistant roles and reject empty content. Drop empties and merge
-// consecutive same-role messages so a turn that produced no assistant text
-// (tool-only / cancelled / errored) can't leave two user messages adjacent.
-const normalizeAlternating = (messages: CodeMessage[]): CodeMessage[] => {
- const out: CodeMessage[] = []
- for (const m of messages) {
- if (!m.content.trim()) continue
- // The template also requires the conversation to START with user; drop any
- // leading assistant message (e.g. after aggressive trimming).
- if (out.length === 0 && m.role !== 'user') continue
- const last = out[out.length - 1]
- if (last && last.role === m.role) {
- last.content = `${last.content}\n\n${m.content}`
- } else {
- out.push({ role: m.role, content: m.content })
- }
- }
- return out
-}
-
-// Slash commands available from the input. Client-side actions — they never hit
-// the agent. `descKey` is an i18n key resolved at render time. mode 'run'
-// executes immediately; 'args' fills the input so the user can pick an argument
-// (e.g. /models → model picker).
-const SLASH_COMMANDS = [
- { name: '/help', descKey: 'common:cmdHelp', mode: 'run' },
- { name: '/clear', descKey: 'common:cmdClear', mode: 'run' },
- { name: '/models', descKey: 'common:cmdModels', mode: 'args' },
-] as const
-
-// A row in the slash menu — commands and model options share one shape so the
-// keyboard navigation works uniformly across both.
-type MenuItem = {
- key: string
- label: string
- description: string
- onSelect: () => void
-}
-
function CodePage() {
const { t } = useTranslation()
const serviceHub = useServiceHub()
+ const { selectedModel, selectedProvider } = useModelProvider()
const sessions = useCodeSessions((s) => s.sessions)
const currentId = useCodeSessions((s) => s.currentId)
- const current = sessions.find((s) => s.id === currentId)
- const selectedModel = useModelProvider((s) => s.selectedModel)
- const selectedProvider = useModelProvider((s) => s.selectedProvider)
- const providers = useModelProvider((s) => s.providers)
-
- const folder = current?.folder ?? null
- const folderName = folder ? folder.split(/[/\\]/).pop() : undefined
- const [gitBranch, setGitBranch] = useState<string | null>(null)
-
- // Fetch git branch when the folder changes.
- useEffect(() => {
- if (!folder) {
- setGitBranch(null)
- return
- }
- setGitBranch(null)
- invoke<string | null>('agent_git_branch', { project: folder })
- .then(setGitBranch)
- .catch(() => setGitBranch(null))
- }, [folder])
+ const session = useMemo(
+ () => sessions.find((s) => s.id === currentId) ?? null,
+ [sessions, currentId]
+ )
+ const folder = session?.folder ?? null
+ const planMode = session?.planMode ?? false
- // In-flight transcript for the active run; committed to the store on `done`.
- const [liveTurns, setLiveTurns] = useState<CodeTurn[]>([])
const [running, setRunning] = useState(false)
- // Mirrors `running` for reads from closures that outlive a render (the slash
- // menu's onSelect is memoized without a `running` dep, so it would otherwise
- // see a stale value).
- const runningRef = useRef(false)
+ const [liveTurns, setLiveTurns] = useState<CodeTurn[]>([])
const liveTurnsRef = useRef<CodeTurn[]>([])
- const runIdRef = useRef<string | null>(null)
-
- // Local (llamacpp) models can take a while to load before the first token.
- // The router emits `llamacpp-model-load-progress`, which LlamacppOomListener
- // pipes into the global useAppState load state; we just flip `loadingModel`
- // (the flag PromptProgress keys off) on for the code run so the shared
- // progress card shows here too. Cleared once generation starts or the run ends.
- const modelLoadingRef = useRef(false)
- const finishModelLoad = () => {
- if (!modelLoadingRef.current) return
- modelLoadingRef.current = false
- useAppState.getState().updateLoadingModel(false)
- useAppState.getState().updateModelLoadProgress(undefined)
- }
- // Clear the shared load flag if the user navigates away mid-load.
- useEffect(() => finishModelLoad, [])
+ const [stoppedBy, setStoppedBy] = useState<RunOutcome['stoppedBy'] | null>(
+ null
+ )
+ const [gitBranch, setGitBranch] = useState<string | null>(null)
+ const [workspacePath, setWorkspacePath] = useState<string | null>(null)
+ const [ask, setAsk] = useState<{
+ requestId: string
+ request: ReturnType<typeof parseAskRequest>
+ } | null>(null)
- // Same auto-scroll wiring the chat route uses, so the streaming reasoning
- // block scrolls and shows the scroll-to-bottom button identically here.
const {
containerRef: reasoningContainerRef,
isAtBottom: isReasoningAtBottom,
@@ -189,407 +89,272 @@ function CodePage() {
forceScrollToBottom: forceScrollReasoningToBottom,
} = useAutoScroll()
- // Queue of gated tool calls awaiting the user's approval. The agent loop
- // awaits each one, so in practice there is at most one live at a time, but we
- // queue defensively. The head is shown in the approval dialog.
- const [pendingPerms, setPendingPerms] = useState<PendingPermission[]>([])
-
- const respondPermission = (requestId: string, decision: PermissionDecision) => {
- invoke('agent_permission_respond', { requestId, decision }).catch(() => {})
- setPendingPerms((prev) => prev.filter((p) => p.requestId !== requestId))
- }
-
- const displayedTurns: CodeTurn[] = useMemo(
- () => [...(current?.turns ?? []), ...liveTurns],
- [current?.turns, liveTurns]
- )
- // Committed turns are stable during a run; only the live tail changes per
- // token. Memoize them separately so streaming rebuilds just the small tail,
- // not the whole transcript. Distinct id prefixes keep React keys unique.
- const committedMessages = useMemo(
- () => codeTurnsToUIMessages(current?.turns ?? [], 'c'),
- [current?.turns]
- )
- // Sessions persist their diffs, but the runtime diff store is transient, so
- // reopening a session would otherwise render its write/edit cards with no
- // diff at all.
+ // The session's sandbox, resolved once so the workspace pill can name the
+ // directory writes actually land in.
useEffect(() => {
- const { recordDiff } = useToolCallRuntime.getState()
- for (const turn of current?.turns ?? []) {
- if (turn.callId && turn.diff) recordDiff(turn.callId, turn.diff)
- }
- }, [current?.turns])
- const liveMessages = useMemo(
- () => codeTurnsToUIMessages(liveTurns, 'l'),
- [liveTurns]
- )
- const uiMessages = useMemo(
- () => [...committedMessages, ...liveMessages],
- [committedMessages, liveMessages]
- )
-
- // Slash commands: the input text lives in the shared usePrompt store, so we can
- // drive the menu (and keyboard nav) without touching ChatInput.
- const prompt = usePrompt((s) => s.prompt)
- const [menuIndex, setMenuIndex] = useState(0)
-
- // Switchable models for /models — mirrors DropdownModelProvider's filtering:
- // active providers only, no embedding models, and skip remote providers that
- // have no API key configured (they can't actually be used).
- const allModels = useMemo(() => {
- const items: { providerName: string; id: string; label: string }[] = []
- providers.forEach((p) => {
- if (!p.active) return
- const isPredefined = predefinedProviders.some((e) =>
- e.provider.includes(p.provider)
- )
- if (
- p.provider !== 'llamacpp' &&
- !providerHasRemoteApiKeys(p) &&
- (isPredefined || p.models.length === 0)
- )
- return
- p.models.forEach((m) => {
- if (m.embedding) return
- items.push({
- providerName: p.provider,
- id: m.id,
- label: getModelDisplayName(m),
- })
- })
- })
- return items
- }, [providers])
-
- const runCommand = (raw: string) => {
- const parts = raw.trim().split(/\s+/)
- const name = parts[0]
- const arg = parts.slice(1).join(' ')
- switch (name) {
- case '/help':
- toast(t('common:commands'), {
- description: SLASH_COMMANDS.map(
- (c) => `${c.name} — ${t(c.descKey)}`
- ).join('\n'),
- })
- break
- case '/clear':
- // Clearing mid-run would wipe the session the in-flight run is about to
- // commit its transcript into, leaving it inconsistent.
- if (runningRef.current) {
- toast.error(t('common:cmdBusy'))
- break
- }
- if (currentId) useCodeSessions.getState().clearSession(currentId)
- break
- case '/models': {
- const q = arg.toLowerCase()
- const found = allModels.find(
- (m) => m.id.toLowerCase() === q || m.label.toLowerCase() === q
- )
- if (found) switchModel(found.providerName, found.id)
- else toast(t('common:cmdModelsHint'))
- break
+ let alive = true
+ if (!session?.id) return
+ void (async () => {
+ try {
+ const dataFolder = await serviceHub.app().getJanDataFolder()
+ if (!dataFolder) return
+ const path = await sessionWorkspacePath(dataFolder, session.id)
+ if (alive) setWorkspacePath(path)
+ } catch {
+ // A missing path only costs the pill a subtitle.
}
- default:
- toast.error(t('common:cmdUnknown', { name }))
+ })()
+ return () => {
+ alive = false
}
- }
+ }, [session?.id, serviceHub])
- const switchModel = (providerName: string, modelId: string) => {
- useModelProvider.getState().selectModelProvider(providerName, modelId)
- usePrompt.getState().setPrompt('')
- toast.success(t('common:cmdModelSwitched', { name: modelId }))
- }
-
- // Build the current menu: model picker when the text is `/models[ filter]`,
- // otherwise the command list filtered by the typed `/token`.
- const menuItems: MenuItem[] = useMemo(() => {
- const inModelMode = prompt === '/models' || prompt.startsWith('/models ')
- if (inModelMode) {
- const filter = prompt.slice('/models'.length).trim().toLowerCase()
- return allModels
- .filter((m) => `${m.id} ${m.label}`.toLowerCase().includes(filter))
- .slice(0, 50)
- .map((m) => ({
- key: `${m.providerName}/${m.id}`,
- label: m.label,
- description: getProviderTitle(m.providerName),
- onSelect: () => switchModel(m.providerName, m.id),
- }))
- }
- if (prompt.startsWith('/') && !prompt.includes(' ')) {
- const q = prompt.slice(1)
- return SLASH_COMMANDS.filter((c) => c.name.slice(1).startsWith(q)).map(
- (c) => ({
- key: c.name,
- label: c.name,
- description: t(c.descKey),
- onSelect: () =>
- c.mode === 'args'
- ? usePrompt.getState().setPrompt(`${c.name} `)
- : (usePrompt.getState().setPrompt(''), runCommand(c.name)),
- })
- )
+ useEffect(() => {
+ if (!folder) {
+ setGitBranch(null)
+ return
}
- return []
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [prompt, allModels, t])
+ invoke<string | null>('agent_git_branch', { project: folder })
+ .then(setGitBranch)
+ .catch(() => setGitBranch(null))
+ }, [folder])
- // Reset the highlighted row whenever the menu contents change.
- useEffect(() => setMenuIndex(0), [prompt])
+ const attachFolder = useCallback(async () => {
+ const picked = await serviceHub.dialog().open({ directory: true })
+ if (typeof picked !== 'string') return
+ const sid = ensureCurrentSession()
+ useCodeSessions.getState().setFolder(sid, picked)
+ }, [serviceHub])
- // Capture-phase keydown so ↑/↓/Enter/Esc drive the menu BEFORE ChatInput's
- // textarea sees them (no ChatInput changes needed).
- const onMenuKeyDown = (e: React.KeyboardEvent) => {
- if (menuItems.length === 0) return
- if (e.key === 'ArrowDown') {
- e.preventDefault()
- e.stopPropagation()
- setMenuIndex((i) => Math.min(i + 1, menuItems.length - 1))
- } else if (e.key === 'ArrowUp') {
- e.preventDefault()
- e.stopPropagation()
- setMenuIndex((i) => Math.max(i - 1, 0))
- } else if (e.key === 'Enter') {
- e.preventDefault()
- e.stopPropagation()
- menuItems[Math.min(menuIndex, menuItems.length - 1)]?.onSelect()
- } else if (e.key === 'Escape') {
- e.preventDefault()
- e.stopPropagation()
- usePrompt.getState().setPrompt('')
- }
- }
+ const detachFolder = useCallback(() => {
+ if (session?.id) useCodeSessions.getState().setFolder(session.id, null)
+ }, [session?.id])
- const pushLive = (turn: CodeTurn) => {
- liveTurnsRef.current = [...liveTurnsRef.current, turn]
- setLiveTurns(liveTurnsRef.current)
- }
-
- const appendToken = (text: string) => {
- const arr = liveTurnsRef.current
- const last = arr[arr.length - 1]
- if (last && last.role === 'assistant') {
- liveTurnsRef.current = [
- ...arr.slice(0, -1),
- { ...last, content: last.content + text },
- ]
- } else {
- liveTurnsRef.current = [...arr, { role: 'assistant', content: text }]
- }
- setLiveTurns(liveTurnsRef.current)
- }
+ const displayedTurns = useMemo(
+ () => (running ? liveTurns : (session?.turns ?? [])),
+ [running, liveTurns, session?.turns]
+ )
+ const uiMessages = useMemo(
+ () => codeTurnsToUIMessages(displayedTurns, session?.id ?? 'code'),
+ [displayedTurns, session?.id]
+ )
- // Merge a `tool_result` into the tool turn its `tool_call` created.
- const updateToolTurn = (callId: string, patch: Partial<CodeTurn>) => {
- const arr = liveTurnsRef.current
- const idx = arr.findIndex((tn) => tn.role === 'tool' && tn.callId === callId)
- if (idx === -1) return
- liveTurnsRef.current = [
- ...arr.slice(0, idx),
- { ...arr[idx], ...patch },
- ...arr.slice(idx + 1),
- ]
+ const pushLive = useCallback((turns: CodeTurn[]) => {
+ liveTurnsRef.current = [...liveTurnsRef.current, ...turns]
setLiveTurns(liveTurnsRef.current)
- }
-
- const handleSelectFolder = async () => {
- const selected = await serviceHub.dialog().open({
- multiple: false,
- directory: true,
- defaultPath: folder ?? undefined,
- })
- if (typeof selected === 'string') {
- const sid = ensureCurrentSession()
- useCodeSessions.getState().setFolder(sid, selected)
- }
- }
+ }, [])
const handleSubmit = async (text: string) => {
- // Slash commands are client-side actions; they never reach the agent.
- if (text.trim().startsWith('/')) {
- runCommand(text)
- return
- }
if (running) return
-
const sid = ensureCurrentSession()
const store = useCodeSessions.getState()
- const session = store.sessions.find((s) => s.id === sid)
- if (!session?.folder) {
- toast.error(t('common:selectFolder'))
- return
- }
+ const current = store.sessions.find((s) => s.id === sid)
if (!selectedModel?.id) {
toast.error(t('common:selectModel'))
return
}
- if (session.title === 'New session') {
- store.setTitle(sid, text.slice(0, 40))
- }
+ if (current?.title === 'New session') store.setTitle(sid, text.slice(0, 40))
- // Mirror the CLI agent: replay the full history each turn (capped only by a
- // coarse sliding window against runaway growth). normalizeAlternating is the
- // one guard the CLI lacks — it keeps roles strictly alternating so a turn
- // that produced no assistant text can't leave two user messages adjacent.
- // Real out-of-context handling belongs in the shared Rust loop, not here.
- const outgoing: CodeMessage[] = normalizeAlternating([
- ...capHistory(session.history),
- { role: 'user', content: text },
- ])
+ setStoppedBy(null)
liveTurnsRef.current = [{ role: 'user', content: text }]
setLiveTurns(liveTurnsRef.current)
- runningRef.current = true
setRunning(true)
- // Local models load before the first token — but only on a cold start.
- // Probe the engine (as the chat transport does) so the load card shows only
- // when the model isn't already loaded, not on every warm run.
+ // Local models load before the first token, but only on a cold start. Probe
+ // the engine so the load card shows on a real load, not on every warm run.
if (selectedProvider === 'llamacpp') {
try {
const loaded = await getLoadedModels()
if (!loaded.includes(selectedModel.id)) {
- modelLoadingRef.current = true
useAppState.getState().updateModelLoadProgress(undefined)
useAppState.getState().updateLoadingModel(true)
}
} catch {
- // Probe failed; skip the load card rather than flash it every run.
+ // Probe failed; skip the card rather than flash it every run.
}
}
- const runId = crypto.randomUUID()
- runIdRef.current = runId
-
- // Captured across the stream + catch so a failed run leaves a visible marker
- // in the transcript (not just a transient toast).
- let runError: string | null = null
-
- const onEvent = new Channel<StreamEvent>()
- onEvent.onmessage = (ev) => {
- switch (ev.type) {
- case 'token':
- // First actual output means the model finished loading and is now
- // generating; drop the load card. (`step` fires before invoke/load,
- // so clearing on it would hide the card during the real load.)
- finishModelLoad()
- appendToken(ev.text)
- break
- case 'tool_call':
- // A tool call is model output too — loading is done.
- finishModelLoad()
- pushLive({
- role: 'tool',
- content: '',
- callId: ev.id,
- name: ev.name,
- args: ev.args,
- status: 'running',
- })
- break
- case 'tool_result':
- updateToolTurn(ev.id, {
- result: ev.content,
- isError: ev.is_error,
- diff: ev.diff,
- status: 'done',
- })
- // Kept out of the turn's output text so the model never sees it and
- // the widget's output parsing stays intact.
- if (ev.diff) {
- useToolCallRuntime.getState().recordDiff(ev.id, ev.diff)
- }
- break
- case 'permission_request':
- setPendingPerms((prev) => [
- ...prev,
- {
- requestId: ev.request_id,
- toolName: ev.tool_name,
- capability: ev.capability,
- path: ev.path,
- command: ev.command,
- diff: ev.diff,
- promptKind: ev.prompt_kind,
- offersAlways: ev.offers_always,
- },
- ])
- break
- case 'error':
- if (ev.code !== 'cancelled') {
- runError = ev.message
- toast.error(ev.message)
- }
- break
- case 'done':
- break
- }
+ // Warm the sandbox probe: the transport's prompt and tool set read it
+ // synchronously via sandboxEnforces().
+ await getSandboxStatus()
+ const transport = new CoworkChatTransport(sid, {
+ planMode: current?.planMode ?? false,
+ subagentNames: [],
+ // Subagents need `agent_subagent_list`, which is not wired yet.
+ allowSubagents: false,
+ workspacePath,
+ readOnlyFolder: current?.folder ?? null,
+ })
+ await transport.refreshTools()
+
+ const controller = new AbortController()
+ abortRef.current = controller
+
+ const sink: StreamSink = {
+ onText: (delta) => {
+ const last = liveTurnsRef.current[liveTurnsRef.current.length - 1]
+ if (last && last.role === 'assistant') {
+ last.content += delta
+ setLiveTurns([...liveTurnsRef.current])
+ } else {
+ pushLive([{ role: 'assistant', content: delta }])
+ }
+ },
+ onToolStart: (callId, name) =>
+ pushLive([
+ { role: 'tool', content: '', callId, name, status: 'running' },
+ ]),
+ onToolArgsDelta: () => {},
+ onToolCall: (call) => {
+ const row = liveTurnsRef.current.find(
+ (turn) => turn.callId === call.toolCallId
+ )
+ if (row) {
+ row.args = call.input
+ setLiveTurns([...liveTurnsRef.current])
+ }
+ },
}
+ const baseMessages = current?.messages ?? []
+ const messages = [
+ ...baseMessages,
+ {
+ id: `${sid}-user-${baseMessages.length}`,
+ role: 'user',
+ parts: [{ type: 'text', text }],
+ } as any,
+ ]
+
+ let outcome: RunOutcome | null = null
try {
- await invoke('agent_run', {
- runId,
- onEvent,
- body: {
- project: session.folder,
- messages: outgoing,
- max_turns: 0,
- max_session_tokens: MAX_SESSION_TOKENS,
- model: selectedModel.id,
+ outcome = await runTurn({
+ messages,
+ signal: controller.signal,
+ sessionTokens: session?.lastUsage?.total_tokens ?? 0,
+ deps: {
+ sendStep: (msgs, signal) =>
+ transport.sendMessages({
+ chatId: sid,
+ messages: msgs,
+ abortSignal: signal,
+ trigger: 'submit-message',
+ messageId: undefined,
+ } as any),
+ dispatch: (call) =>
+ dispatchCoworkTool(call, {
+ sessionId: sid,
+ readOnlyFolder: current?.folder ?? null,
+ planMode: current?.planMode ?? false,
+ onTodo: async (input) => {
+ const result = applyTodoOp(
+ useCodeSessions.getState().sessions.find((s) => s.id === sid)
+ ?.todos,
+ input
+ )
+ if (result.error) {
+ return { output: `ERROR: ${result.error}`, isError: true }
+ }
+ useCodeSessions.getState().setTodos(sid, result.list)
+ return { output: renderTodoResult(result.list) }
+ },
+ onAsk: (callId, input) =>
+ new Promise<ToolOutcome>((resolve) => {
+ const parsed = parseAskRequest(input)
+ if (typeof parsed === 'string') {
+ resolve({ output: `ERROR: ${parsed}`, isError: true })
+ return
+ }
+ setAsk({ requestId: callId, request: parsed })
+ askResolvers.current.set(callId, (answers) => {
+ setAsk(null)
+ resolve(renderAskResult(answers))
+ })
+ }),
+ onTask: async () => ({
+ output:
+ 'Subagents are not available in this build. Do the work yourself.',
+ isError: true,
+ }),
+ }),
+ sink,
+ onStep: ({ result, turns, outcomes }) => {
+ // Replace the optimistic running rows with the settled ones so the
+ // transcript shows results, not spinners.
+ liveTurnsRef.current = liveTurnsRef.current.filter(
+ (turn) =>
+ !(turn.role === 'tool' && outcomes.has(turn.callId ?? '')) &&
+ !(turn.role === 'assistant' && turn.content === result.text)
+ )
+ pushLive(turns)
+ for (const [callId, outcome] of outcomes) {
+ if (outcome.diff) {
+ useToolCallRuntime.getState().recordDiff(callId, outcome.diff)
+ }
+ }
+ },
+ nextMessageId: (() => {
+ let n = baseMessages.length
+ return () => `${sid}-asst-${n++}`
+ })(),
},
})
} catch (e) {
- runError = String(e)
- toast.error(String(e))
+ pushLive([
+ {
+ role: 'tool',
+ content: '',
+ name: 'error',
+ result: e instanceof Error ? e.message : String(e),
+ isError: true,
+ status: 'done',
+ },
+ ])
} finally {
- // Drop the load card if the run ended before any stream event (error,
- // cancel, or an unloaded model that never produced output).
- finishModelLoad()
- // Any tool call still 'running' when the run ends was interrupted (cancel
- // or error mid-tool); finalize it so it doesn't render as a forever spinner.
- liveTurnsRef.current = liveTurnsRef.current.map((tn) =>
- tn.role === 'tool' && tn.status === 'running'
- ? { ...tn, status: 'done', isError: true, result: tn.result || '(interrupted)' }
- : tn
- )
- // Surface a failed run in the transcript so it is not silently empty.
- if (runError) {
- liveTurnsRef.current = [
- ...liveTurnsRef.current,
- {
- role: 'tool',
- content: '',
- name: 'error',
- result: runError,
- isError: true,
- status: 'done',
- },
- ]
- }
- // Commit the whole in-flight transcript into the session.
- const assistantText = liveTurnsRef.current
- .filter((tn) => tn.role === 'assistant')
- .map((tn) => tn.content)
- .join('\n')
- const history: CodeMessage[] = assistantText
- ? [...outgoing, { role: 'assistant', content: assistantText }]
- : outgoing
- useCodeSessions.getState().commitTurns(sid, liveTurnsRef.current, history)
+ useAppState.getState().updateLoadingModel(false)
+ useCodeSessions
+ .getState()
+ .commitTurns(
+ sid,
+ liveTurnsRef.current,
+ outcome?.messages ?? messages,
+ [],
+ outcome?.usage ?? undefined
+ )
liveTurnsRef.current = []
setLiveTurns([])
- runningRef.current = false
setRunning(false)
- runIdRef.current = null
- // The loop has dropped any outstanding permission receivers; drop the UI.
- setPendingPerms([])
+ abortRef.current = null
+ askResolvers.current.clear()
+ setAsk(null)
+ setStoppedBy(outcome?.stoppedBy ?? null)
}
}
- const handleStop = () => {
- if (runIdRef.current)
- invoke('agent_cancel', { runId: runIdRef.current }).catch(() => {})
- }
+ const abortRef = useRef<AbortController | null>(null)
+ const askResolvers = useRef(
+ new Map<string, (answers: AskAnswer[] | null) => void>()
+ )
+
+ const handleStop = useCallback(() => {
+ abortRef.current?.abort('cancelled')
+ if (session?.id) abortRun(session.id)
+ for (const resolve of askResolvers.current.values()) resolve(null)
+ askResolvers.current.clear()
+ }, [session?.id])
+
+ const respondAsk = useCallback(
+ (requestId: string, answers: AskAnswer[] | null) => {
+ const resolve = askResolvers.current.get(requestId)
+ askResolvers.current.delete(requestId)
+ if (resolve) resolve(answers)
+ else if (session?.id) answerAsk(session.id, requestId, answers)
+ },
+ [session?.id]
+ )
+
+ // A run outlives this component, so unmounting must not stop it.
+ useEffect(() => () => useCodeRun.getState().clearPendingPreview(), [])
return (
<div className="flex flex-col h-[calc(100dvh-(env(safe-area-inset-bottom)+env(safe-area-inset-top)))]">
@@ -600,8 +365,6 @@ function CodePage() {
</HeaderPage>
<div className="flex flex-1 flex-col h-full overflow-hidden">
- {/* Scroll area fills the remaining space; absolute inset-0 keeps message
- volume from ever pushing the fixed input off-screen. */}
<div className="flex-1 relative">
{displayedTurns.length === 0 ? (
<div className="absolute inset-0 flex flex-col items-center justify-center px-3">
@@ -611,7 +374,9 @@ function CodePage() {
</div>
) : (
<Conversation className="absolute inset-0 text-start">
- <ConversationContent className={cn('mx-auto w-full md:w-4/5 xl:w-4/6')}>
+ <ConversationContent
+ className={cn('mx-auto w-full md:w-4/5 xl:w-4/6')}
+ >
{uiMessages.map((message, i) => (
<MessageItem
key={message.id}
@@ -625,95 +390,71 @@ function CodePage() {
onReasoningScrollToBottom={forceScrollReasoningToBottom}
/>
))}
- {/* Shared load card; renders only while a local model is loading
- (hideIdle suppresses the generic "Working…" fallback). */}
- {running && <PromptProgress hideIdle />}
+ {running && <PromptProgress hideIdle stateKey={session?.id} />}
+ {stoppedBy === 'steps' && (
+ <CoworkBudgetNotice
+ kind="steps"
+ max={MAX_AGENT_STEPS}
+ onContinue={() => void handleSubmit('Continue.')}
+ />
+ )}
+ {stoppedBy === 'tokens' && (
+ <CoworkBudgetNotice
+ kind="tokens"
+ onCompact={() => toast.info(t('common:budget.compact'))}
+ onNewSession={() =>
+ useCodeSessions.getState().createSession()
+ }
+ />
+ )}
</ConversationContent>
<ConversationScrollButton />
</Conversation>
)}
</div>
- {/* Fixed input dock at the bottom. */}
<div className="pb-4 shrink-0">
<div className="mx-auto w-full md:w-4/5 xl:w-4/6">
<div className="flex items-center gap-2 px-1 pb-2">
- <Button variant="outline" size="sm" className="h-7 gap-1.5 rounded-full">
- <Laptop size={14} className="text-muted-foreground" />
- <span>{t('common:local')}</span>
- </Button>
- <div className="flex items-center gap-1 min-w-0 max-w-[460px]">
- <Button
- variant="outline"
- size="sm"
- className="h-7 gap-1.5 rounded-full shrink-0"
- onClick={handleSelectFolder}
- title={folder ?? t('common:selectFolder')}
- >
- <Folder size={14} className="text-muted-foreground shrink-0" />
- <span className="truncate max-w-[140px]">
- {folderName ?? t('common:selectFolder')}
- </span>
- </Button>
- {folder && (
- <span className="text-xs text-muted-foreground truncate" title={folder}>
- {folder}
- </span>
- )}
- {gitBranch && (
- <span className="inline-flex items-center gap-1 rounded-full bg-muted px-1.5 py-0.5 text-xs font-mono text-muted-foreground shrink-0">
- <GitBranch size={10} />
- {gitBranch}
- </span>
- )}
- </div>
+ <CoworkPlanToggle
+ planMode={planMode}
+ onChange={(next) => {
+ if (session?.id)
+ useCodeSessions.getState().setPlanMode(session.id, next)
+ }}
+ />
+ <CoworkWorkspacePill
+ folder={folder}
+ sandboxPath={workspacePath}
+ gitBranch={gitBranch}
+ onAttach={() => void attachFolder()}
+ onDetach={detachFolder}
+ />
+ <CoworkSandboxChip />
<div className="ml-auto">
<SkillSelector folder={folder} />
</div>
</div>
- <div className="relative" onKeyDownCapture={onMenuKeyDown}>
- {menuItems.length > 0 && (
- <div className="absolute left-0 right-0 bottom-full mb-2 z-10 max-h-64 overflow-y-auto rounded-md border bg-popover shadow-md">
- {menuItems.map((item, i) => (
- <button
- key={item.key}
- type="button"
- ref={
- i === menuIndex
- ? (el) => el?.scrollIntoView({ block: 'nearest' })
- : undefined
- }
- onClick={item.onSelect}
- onMouseEnter={() => setMenuIndex(i)}
- className={cn(
- 'flex w-full items-center gap-3 px-3 py-2 text-left text-sm',
- i === menuIndex ? 'bg-accent' : 'hover:bg-accent'
- )}
- >
- <span className="font-mono font-medium">{item.label}</span>
- <span className="truncate text-xs text-muted-foreground">
- {item.description}
- </span>
- </button>
- ))}
- </div>
- )}
- <ChatInput
- showSpeedToken={false}
- initialMessage={true}
- onSubmit={handleSubmit}
- onStop={handleStop}
- chatStatus={running ? 'streaming' : 'ready'}
- />
- </div>
+ {ask && typeof ask.request !== 'string' && (
+ <div className="px-1 pb-2">
+ <CodeAskCard
+ requestId={ask.requestId}
+ request={ask.request}
+ onRespond={respondAsk}
+ />
+ </div>
+ )}
+ <ChatInput
+ showSpeedToken={false}
+ initialMessage={true}
+ scopeKey={session?.id}
+ onSubmit={handleSubmit}
+ onStop={handleStop}
+ chatStatus={running ? 'streaming' : 'ready'}
+ />
</div>
</div>
</div>
-
- <CodePermissionDialog
- request={pendingPerms[0] ?? null}
- onRespond={respondPermission}
- />
</div>
)
}