Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cowork): rename the surface, and make its artifacts reachable
Akarshan Biswas3ec132c95ad4
diff --git a/web-app/src/components/PromptProgress.tsx b/web-app/src/components/PromptProgress.tsxindex dd82e6bc9..bebdd0bf4 100644--- a/web-app/src/components/PromptProgress.tsx+++ b/web-app/src/components/PromptProgress.tsx@@ -1,8 +1,9 @@import { useAppState } from '@/hooks/useAppState'-import { useCodeRun } from '@/hooks/useCodeRun'+import { useCoworkRun } from '@/hooks/useCoworkRun'import { Loader } from 'lucide-react'import { useParams } from '@tanstack/react-router'import { Progress } from '@/components/ui/progress'+import { cn } from '@/lib/utils'export function PromptProgress({hideIdle = false,@@ -13,7 +14,7 @@ export function PromptProgress({* Identifies a caller outside the `/threads/:threadId` route — Cowork, keyed* by its own session id — overriding the auto-detected route param, and* switching the loading/progress read from useAppState's thread-keyed- * Records to useCodeRun's session-keyed mirror of the same shape. Prompt+ * Records to useCoworkRun's session-keyed mirror of the same shape. Prompt* progress has no Cowork equivalent, so it keeps the global fallback;* harmless, since Cowork never writes there.*/@@ -28,7 +29,7 @@ export function PromptProgress({const chatLoadingModel = useAppState((state) =>(threadId ? state.loadingModels[threadId] : undefined) ?? state.loadingModel)- const coworkLoadingModel = useCodeRun((state) =>+ const coworkLoadingModel = useCoworkRun((state) =>stateKey ? state.loadingModels[stateKey] : undefined)const loadingModel = stateKey ? coworkLoadingModel : chatLoadingModel@@ -36,7 +37,7 @@ export function PromptProgress({(threadId ? state.modelLoadProgressByThread[threadId] : undefined) ??state.modelLoadProgress)- const coworkLoadProgress = useCodeRun((state) =>+ const coworkLoadProgress = useCoworkRun((state) =>stateKey ? state.modelLoadProgress[stateKey] : undefined)const loadProgress = stateKey ? coworkLoadProgress : chatLoadProgress@@ -81,8 +82,18 @@ export function PromptProgress({const detail =showReading && !loadingModel ? buildDetail(promptProgress) : undefined+ // The floor keeps the box from resizing as the percentage and ETA change; a+ // bare "Working…" has nothing to stabilise, so it shrink-wraps instead of+ // sitting in a mostly-empty rectangle.+ const sized = loadingModel || showReading+return (- <div className="inline-flex flex-col gap-2 rounded-lg border border-border/40 bg-muted/30 px-3 py-2 min-w-56">+ <div+ className={cn(+ 'inline-flex flex-col gap-2 rounded-lg border border-border/40 bg-muted/30 px-3 py-2',+ sized && 'min-w-56'+ )}+ ><div className="flex items-center gap-2 text-sm"><Loader className="animate-spin w-3.5 h-3.5 text-primary shrink-0" /><span className="font-medium text-foreground">{label}</span>diff --git a/web-app/src/components/TokenCounter.tsx b/web-app/src/components/TokenCounter.tsxindex 782243dd2..12a96afcf 100644--- a/web-app/src/components/TokenCounter.tsx+++ b/web-app/src/components/TokenCounter.tsx@@ -7,7 +7,7 @@ import {TooltipProvider,TooltipTrigger,} from '@/components/ui/tooltip'-import { useTokensCount } from '@/hooks/useTokensCount'+import { useTokensCount, type TokenUsageSource } from '@/hooks/useTokensCount'import { ThreadMessage } from '@janhq/core'import {IconBrain,@@ -27,6 +27,8 @@ interface TokenCounterProps {className?: stringcompact?: booleanadditionalTokens?: number+ /** Usage reported directly, for a surface that keeps no thread messages. */+ source?: TokenUsageSource}const WARN_PCT = 85@@ -38,9 +40,10 @@ export const TokenCounter = memo(function TokenCounter({messages = [],className,additionalTokens = 0,+ source,}: TokenCounterProps) {const { t } = useTranslation()- const { calculateTokens, ...tokenData } = useTokensCount(messages)+ const { calculateTokens, ...tokenData } = useTokensCount(messages, source)const [isAnimating, setIsAnimating] = useState(false)const [prevTokenCount, setPrevTokenCount] = useState(0)diff --git a/web-app/src/components/left-sidebar/NavCode.tsx b/web-app/src/components/left-sidebar/NavCowork.tsxsimilarity index 90%rename from web-app/src/components/left-sidebar/NavCode.tsxrename to web-app/src/components/left-sidebar/NavCowork.tsxindex e44a7f5ed..b3fe1cea3 100644--- a/web-app/src/components/left-sidebar/NavCode.tsx+++ b/web-app/src/components/left-sidebar/NavCowork.tsx@@ -37,12 +37,12 @@ import {MessageCircleIcon,type MessageCircleIconHandle,} from '@/components/animated-icon/message-circle'-import { useCodeSessions, type CodeSession } from '@/hooks/useCodeSessions'-import { useIsSessionActive } from '@/hooks/useCodeRun'+import { useCoworkSessions, type CoworkSession } from '@/hooks/useCoworkSessions'+import { useIsSessionActive } from '@/hooks/useCoworkRun'import { memo, useCallback, useRef, useState } from 'react'import SkillsManagerDialog from '@/containers/dialogs/SkillsManagerDialog'-type CodeNavItem = {+type CoworkNavItem = {title: stringicon: LucideIcononClick: () => void@@ -60,7 +60,7 @@ const SessionItem = memo(function SessionItem({onSelect,onRequestDelete,}: {- session: CodeSession+ session: CoworkSessionisCurrent: booleanisMobile: booleanonSelect: (id: string) => void@@ -110,12 +110,12 @@ const SessionItem = memo(function SessionItem({)})-export function NavCode() {+export function NavCowork() {const { t } = useTranslation()const navigate = useNavigate()const { isMobile } = useSidebar()- const sessions = useCodeSessions((s) => s.sessions)- const currentId = useCodeSessions((s) => s.currentId)+ const sessions = useCoworkSessions((s) => s.sessions)+ const currentId = useCoworkSessions((s) => s.currentId)const [skillsOpen, setSkillsOpen] = useState(false)// Session pending deletion; drives the confirm dialog (null = closed).const [pendingDelete, setPendingDelete] = useState<{@@ -123,21 +123,21 @@ export function NavCode() {title: string} | null>(null)- const goCode = useCallback(() => navigate({ to: route.code }), [navigate])+ const goCowork = useCallback(() => navigate({ to: route.cowork }), [navigate])const newSessionIconRef = useRef<MessageCircleIconHandle>(null)const newSession = () => {- useCodeSessions.getState().createSession()- goCode()+ useCoworkSessions.getState().createSession()+ goCowork()}const selectSession = useCallback((id: string) => {- useCodeSessions.getState().selectSession(id)- goCode()+ useCoworkSessions.getState().selectSession(id)+ goCowork()},- [goCode]+ [goCowork])- const items: CodeNavItem[] = [+ const items: CoworkNavItem[] = [{title: t('common:artifacts'),icon: Box,@@ -151,7 +151,7 @@ export function NavCode() {]const confirmDelete = () => {- if (pendingDelete) useCodeSessions.getState().deleteSession(pendingDelete.id)+ if (pendingDelete) useCoworkSessions.getState().deleteSession(pendingDelete.id)setPendingDelete(null)}diff --git a/web-app/src/components/left-sidebar/NavTabs.tsx b/web-app/src/components/left-sidebar/NavTabs.tsxindex bc203ad9a..cd2c54168 100644--- a/web-app/src/components/left-sidebar/NavTabs.tsx+++ b/web-app/src/components/left-sidebar/NavTabs.tsx@@ -15,8 +15,8 @@ export function NavTabs() {const { t } = useTranslation()const { pathname } = useLocation()- const isCode = isCoworkRoute(pathname)- // Home owns the chat surfaces (new chat, threads, projects); Code owns /code.+ const isCowork = isCoworkRoute(pathname)+ // Home owns the chat surfaces (new chat, threads, projects); Cowork owns /cowork.const isHome =pathname === route.home ||pathname.startsWith('/threads') ||@@ -24,7 +24,7 @@ export function NavTabs() {const tabs: TabItem[] = [{ label: t('common:home'), to: route.home, icon: HomeIcon, isActive: isHome },- { label: t('common:code'), to: route.code, icon: Handshake, isActive: isCode },+ { label: t('common:cowork'), to: route.cowork, icon: Handshake, isActive: isCowork },]return (diff --git a/web-app/src/components/left-sidebar/index.tsx b/web-app/src/components/left-sidebar/index.tsxindex 3c899cb5a..2455399bb 100644--- a/web-app/src/components/left-sidebar/index.tsx+++ b/web-app/src/components/left-sidebar/index.tsx@@ -1,6 +1,6 @@import { DownloadManagement } from '@/containers/DownloadManegement'import { NavChats } from './NavChats'-import { NavCode } from './NavCode'+import { NavCowork } from './NavCowork'import { NavMain } from './NavMain'import { NavProjects } from './NavProjects'import { NavTabs } from './NavTabs'@@ -21,7 +21,7 @@ import { isCoworkRoute } from '@/constants/routes'export function LeftSidebar() {const { open: isLeftPanelOpen } = useLeftPanel()const { pathname } = useLocation()- const isCode = isCoworkRoute(pathname)+ const isCowork = isCoworkRoute(pathname)// Right-align the header when native controls own the top-left (macOS, or a Linux// DE placing buttons left); "Jan" moves into the right cluster except on macOS.const leftButtons = useTitlebarLayout((s) => s.layout.left.length)@@ -42,10 +42,10 @@ export function LeftSidebar() {</div></div><NavTabs />- {isCode ? <NavCode /> : <NavMain />}+ {isCowork ? <NavCowork /> : <NavMain />}</SidebarHeader><SidebarContent className="mask-b-from-95% mask-t-from-98%">- {!isCode && (+ {!isCowork && (<><NavProjects /><NavChats />diff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.tsindex 59a557a1a..51d7c66d8 100644--- a/web-app/src/constants/localStorage.ts+++ b/web-app/src/constants/localStorage.ts@@ -32,7 +32,8 @@ export const localStorageKey = {latestJanModel: 'latest-jan-model',defaultEmbeddingModel: 'default-embedding-model',pausedDownloads: 'paused-downloads',- codeSessions: 'code-sessions',+ // Value predates the Cowork rename; changing it would orphan saved sessions.+ coworkSessions: 'code-sessions',}export const CACHE_EXPIRY_MS = 1000 * 60 * 60 * 24diff --git a/web-app/src/constants/routes.ts b/web-app/src/constants/routes.tsindex 6fb5ecefd..61fcf97c8 100644--- a/web-app/src/constants/routes.ts+++ b/web-app/src/constants/routes.ts@@ -1,7 +1,7 @@export const route = {// home as new chat or threadhome: '/',- code: '/code',+ cowork: '/cowork',artifacts: '/artifacts',appLogs: '/logs',project: '/project',@@ -39,4 +39,4 @@ export const route = {* instead of falling back to Home. A new Cowork route only has to be added here.*/export const isCoworkRoute = (pathname: string): boolean =>- pathname === route.code || pathname === route.artifacts+ pathname === route.cowork || pathname === route.artifactsdiff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex f50c32945..a46c7f92e 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -3,6 +3,8 @@ import { cn, formatBytes } from '@/lib/utils'import { usePrompt } from '@/hooks/usePrompt'import { useThreads } from '@/hooks/useThreads'import { useCallback, useEffect, useMemo, useRef, useState, memo } from 'react'+import type { ReactNode } from 'react'+import { Separator } from '@/components/ui/separator'import { Button } from '@/components/ui/button'import {Tooltip,@@ -32,7 +34,6 @@ import {IconPaperclip,IconLoader2,IconWorldSearch,- IconFolderCode,IconBrandChrome,} from '@tabler/icons-react'import { generateId } from 'ai'@@ -71,6 +72,7 @@ import DropdownToolsAvailable from '@/containers/DropdownToolsAvailable'import { useServiceHub } from '@/hooks/useServiceHub'import { useTools } from '@/hooks/useTools'import { TokenCounter } from '@/components/TokenCounter'+import type { TokenUsageSource } from '@/hooks/useTokensCount'import { useMessages } from '@/hooks/useMessages'import { useShallow } from 'zustand/react/shallow'import { McpExtensionToolLoader } from './McpExtensionToolLoader'@@ -110,7 +112,6 @@ import {type FilePickerEntry as FileEntry,} from '@/lib/path-references'import { FilePickerPopover } from '@/components/FilePickerPopover'-import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'type ChatInputProps = {className?: string@@ -130,6 +131,28 @@ type ChatInputProps = {// Callers outside the general chat (e.g. Cowork, keyed by session id) pass// their own id so each gets an independent queue and attachment draft.scopeKey?: string+ /**+ * Whether the surface's tool set is configured from this composer.+ *+ * False for a surface that builds its own set (Cowork, via+ * `buildCoworkTools`). Its toggles here would be inert on this surface while+ * still writing the global chat stores, so a user turning "agent tools" off+ * in Cowork would silently disable them in Chat.+ */+ ownsToolSet?: boolean+ /**+ * Surface-specific controls docked in the composer's control row (Cowork's+ * plan toggle and folder chip). They sit outside the streaming dim, because+ * both configure the *next* message rather than the run in flight.+ */+ surfaceControls?: ReactNode+ /**+ * Usage for a surface that keeps no thread messages (Cowork). Rendering the+ * counter here rather than in the caller is what keeps its placement, the+ * `tokenCounterCompact` setting and the spacing to the send button identical+ * across surfaces.+ */+ tokenSource?: TokenUsageSource}// Video containers llama-server can decode via ffmpeg/ffprobe into frames.@@ -159,6 +182,9 @@ const ChatInput = memo(function ChatInput({onStop,chatStatus,scopeKey,+ ownsToolSet = true,+ surfaceControls,+ tokenSource,}: ChatInputProps) {const textareaRef = useRef<HTMLTextAreaElement>(null)const [isFocused, setIsFocused] = useState(false)@@ -201,13 +227,11 @@ const ChatInput = memo(function ChatInput({)// When projectId is present, treat as normal chat (disable agent mode UI)const effectiveAgentMode = isAgentMode && !projectId+ // Gate for the controls that shape which tools the model is offered.+ const showToolControls = ownsToolSet && !effectiveAgentModeconst toggleAgentMode = useAgentMode((state) => state.toggleAgentMode)const webSearchEnabled = useWebSearchConfig((s) => s.webSearchEnabled)const setWebSearchEnabled = useWebSearchConfig((s) => s.setWebSearchEnabled)- const agentToolsEnabled = useAgentToolsConfig((s) => s.agentToolsEnabled)- const setAgentToolsEnabled = useAgentToolsConfig(- (s) => s.setAgentToolsEnabled- )const [filePickerOpen, setFilePickerOpen] = useState(false)const [filePickerQuery, setFilePickerQuery] = useState('')@@ -397,6 +421,7 @@ const ChatInput = memo(function ChatInput({isInitialMessage: !!initialMessage,hasMessages: (threadMessages?.length ?? 0) > 0,hasPromptText: prompt.trim().length > 0,+ hasReportedUsage: (tokenSource?.usage?.totalTokens ?? 0) > 0,})const [selectedAssistantId, setSelectedAssistantId] = useState<string | undefined@@ -2185,7 +2210,7 @@ const ChatInput = memo(function ChatInput({<div className="px-1 flex items-center gap-1 flex-1 min-w-0"><divclassName={cn(- 'px-1 flex items-center w-full gap-1',+ 'px-1 flex items-center gap-1',isStreaming && 'opacity-50 pointer-events-none')}>@@ -2290,7 +2315,7 @@ const ChatInput = memo(function ChatInput({updateCurrentThreadAssistant,}}/>- {!effectiveAgentMode && hasJanBrowserMCPConfig && modelSupportsBrowser && (+ {showToolControls && hasJanBrowserMCPConfig && modelSupportsBrowser && (<Tooltip><TooltipTrigger asChild><Button@@ -2332,7 +2357,7 @@ const ChatInput = memo(function ChatInput({</Tooltip>)}- {!effectiveAgentMode && selectedModel?.capabilities?.includes('embeddings') && (+ {showToolControls && selectedModel?.capabilities?.includes('embeddings') && (<Tooltip><TooltipTrigger asChild><Button@@ -2351,7 +2376,7 @@ const ChatInput = memo(function ChatInput({</Tooltip>)}- {!effectiveAgentMode && selectedModel?.capabilities?.includes('tools') &&+ {showToolControls && selectedModel?.capabilities?.includes('tools') &&hasActiveMCPServers &&(MCPToolComponent ? (// Use custom MCP component@@ -2473,34 +2498,6 @@ const ChatInput = memo(function ChatInput({</Tooltip>)}- {!effectiveAgentMode && selectedModel?.capabilities?.includes('tools') && (- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="ghost"- size="icon-xs"- className={cn(agentToolsEnabled && 'text-primary')}- onClick={() => setAgentToolsEnabled(!agentToolsEnabled)}- >- <IconFolderCode- size={18}- className={cn(- 'text-muted-foreground',- agentToolsEnabled && 'text-primary'- )}- />- </Button>- </TooltipTrigger>- <TooltipContent>- <p>- {agentToolsEnabled- ? t('common:agent_tools') + t('common:activeSuffix')- : t('common:agent_tools')}- </p>- </TooltipContent>- </Tooltip>- )}-{!effectiveAgentMode &&(selectedProvider === 'llamacpp' ||selectedProvider === 'google' ||@@ -2816,12 +2813,25 @@ const ChatInput = memo(function ChatInput({)})()}</div>+ {surfaceControls && (+ <div className="flex min-w-0 flex-1 items-center gap-1">+ <Separator+ orientation="vertical"+ className="mx-1 h-4 shrink-0"+ />+ {surfaceControls}+ </div>+ )}</div><div className="flex items-center gap-2">{tokenCounterVisible && tokenCounterCompact && (<div className="flex-1 flex justify-center">- <TokenCounter messages={threadMessages || []} compact={true} />+ <TokenCounter+ messages={threadMessages || []}+ source={tokenSource}+ compact={true}+ /></div>)}@@ -2893,7 +2903,7 @@ const ChatInput = memo(function ChatInput({{tokenCounterVisible && !tokenCounterCompact && (<div className="flex-1 w-full flex justify-start px-2">- <TokenCounter messages={threadMessages || []} />+ <TokenCounter messages={threadMessages || []} source={tokenSource} /></div>)}diff --git a/web-app/src/containers/CodeArtifactCard.tsx b/web-app/src/containers/CoworkArtifactCard.tsxsimilarity index 94%rename from web-app/src/containers/CodeArtifactCard.tsxrename to web-app/src/containers/CoworkArtifactCard.tsxindex 58f583a5e..8d635d8be 100644--- a/web-app/src/containers/CodeArtifactCard.tsx+++ b/web-app/src/containers/CoworkArtifactCard.tsx@@ -8,8 +8,8 @@ import {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'+import { resolveInRoot } from '@/lib/coworkPreview'+import { ARTIFACT_ICON, type CoworkArtifact } from '@/lib/coworkArtifacts'/*** Inline card for something the agent produced (jan-internal #242).@@ -20,12 +20,12 @@ import { ARTIFACT_ICON, type CodeArtifact } from '@/lib/codeArtifacts'** Card body opens the in-app preview; the split button hands the file to the OS.*/-export function CodeArtifactCard({+export function CoworkArtifactCard({artifact,root,onPreview,}: {- artifact: CodeArtifact+ artifact: CoworkArtifactroot: string | nullonPreview: (path: string) => void}) {diff --git a/web-app/src/containers/CodeAskCard.tsx b/web-app/src/containers/CoworkAskCard.tsxsimilarity index 98%rename from web-app/src/containers/CodeAskCard.tsxrename to web-app/src/containers/CoworkAskCard.tsxindex b7ae80c3a..2cd82bf22 100644Binary files a/web-app/src/containers/CodeAskCard.tsx and b/web-app/src/containers/CoworkAskCard.tsx differdiff --git a/web-app/src/containers/CoworkChangesChip.tsx b/web-app/src/containers/CoworkChangesChip.tsxnew file mode 100644index 000000000..1691a4638--- /dev/null+++ b/web-app/src/containers/CoworkChangesChip.tsx@@ -0,0 +1,58 @@+import { FileDiff } 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'+import type { CoworkFileDiff } from '@/lib/coworkDiffs'++/**+ * Opens the diff rail, and stays out of the way until the agent has written+ * something — the same rule the plan, folder and skills controls follow.+ */+export function CoworkChangesChip({+ files,+ open,+ onToggle,+}: {+ files: CoworkFileDiff[]+ open: boolean+ onToggle: () => void+}) {+ const { t } = useTranslation()+ if (files.length === 0) return null++ const additions = files.reduce((sum, file) => sum + file.additions, 0)+ const deletions = files.reduce((sum, file) => sum + file.deletions, 0)++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ aria-pressed={open}+ aria-label={t('common:changes.a11y', {+ files: files.length,+ additions,+ deletions,+ })}+ onClick={onToggle}+ className={cn('shrink-0', open && 'text-primary')}+ >+ <FileDiff className="size-3.5 shrink-0" />+ <span className="font-mono tabular-nums text-muted-foreground">+ +{additions}+ </span>+ <span className="font-mono tabular-nums text-muted-foreground">+ -{deletions}+ </span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>{t('common:changes.title')}</TooltipContent>+ </Tooltip>+ )+}diff --git a/web-app/src/containers/CodeDiffPanel.tsx b/web-app/src/containers/CoworkDiffPanel.tsxsimilarity index 68%rename from web-app/src/containers/CodeDiffPanel.tsxrename to web-app/src/containers/CoworkDiffPanel.tsxindex f7a30c9f6..8994b19a6 100644--- a/web-app/src/containers/CodeDiffPanel.tsx+++ b/web-app/src/containers/CoworkDiffPanel.tsx@@ -1,21 +1,26 @@import { useState } from 'react'-import { ChevronDown, GitBranch } from 'lucide-react'+import { ChevronDown } from 'lucide-react'import { cn } from '@/lib/utils'+import { useTranslation } from '@/i18n/react-i18next-compat'import { DiffView } from '@/components/DiffView'-import { CodeSidePanel } from '@/containers/CodeSidePanel'-import type { CodeFileDiff } from '@/lib/codeDiffs'+import { CoworkSidePanel } from '@/containers/CoworkSidePanel'+import type { CoworkFileDiff } from '@/lib/coworkDiffs'-export function CodeDiffPanel({+/**+ * Every write and edit this session landed, grouped by file.+ *+ * No folder or branch header: an attached folder is mounted read-only, so+ * nothing here is ever a change to the user's project. Naming their repo and+ * branch beside "Agent changes" claimed the opposite.+ */+export function CoworkDiffPanel({files,- folderName,- gitBranch,onClose,}: {- files: CodeFileDiff[]- folderName?: string- gitBranch: string | null+ files: CoworkFileDiff[]onClose: () => void}): React.ReactElement {+ const { t } = useTranslation()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)@@ -33,8 +38,8 @@ export function CodeDiffPanel({}return (- <CodeSidePanel- title="Agent changes"+ <CoworkSidePanel+ title={t('common:changes.title')}summary={<span className="shrink-0 text-xs font-mono text-main-view-fg/60">+{additions} -{deletions}@@ -43,26 +48,9 @@ export function CodeDiffPanel({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.+ {t('common:changes.empty')}</p>) : (<div className="divide-y">@@ -96,8 +84,12 @@ export function CodeDiffPanel({{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 ? (+ <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>@@ -116,6 +108,6 @@ export function CodeDiffPanel({</div>)}</div>- </CodeSidePanel>+ </CoworkSidePanel>)}diff --git a/web-app/src/containers/CoworkEmptyState.tsx b/web-app/src/containers/CoworkEmptyState.tsxnew file mode 100644index 000000000..f4e4f0737--- /dev/null+++ b/web-app/src/containers/CoworkEmptyState.tsx@@ -0,0 +1,70 @@+import { Handshake } from 'lucide-react'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { basenameOf } from '@/lib/coworkPreview'++type Props = {+ /** Attached project folder, or null when nothing is attached. */+ folder: string | null+ /** Loads an example into the composer. Never sends it: an example is a+ * starting point the user is expected to edit. */+ onPick: (text: string) => void+}++const EXAMPLE_KEYS = ['first', 'second', 'third'] as const++/**+ * The first thing a new session shows.+ *+ * Anchored to the composer rather than centred in the viewport: the block sits+ * directly above the input, sharing its width and left edge, so the eye travels+ * from the invitation into the box. Centring it left a heading marooned in the+ * middle of an empty pane, and made the jump to the first message jarring.+ *+ * The examples name the attached folder when there is one. That is the whole+ * point of them -- a fixed list of suggestions is wallpaper, but "Find every+ * TODO in jan-app" is a task you might actually run next.+ */+export function CoworkEmptyState({ folder, onPick }: Props) {+ const { t } = useTranslation()+ const name = folder ? basenameOf(folder) : null+ const scope = name ? 'folder' : 'sandbox'++ return (+ <div className="absolute inset-0 flex flex-col justify-end px-3 pb-2">+ <div className="mx-auto w-full md:w-4/5 xl:w-4/6">+ <div className="animate-in fade-in-0 duration-500 motion-reduce:animate-none">+ <Handshake size={20} className="text-primary" aria-hidden />+ <h1 className="mt-3 font-studio text-2xl font-medium tracking-tight">+ {t('common:coworkEmpty.title')}+ </h1>+ <p className="mt-1.5 max-w-lg text-sm text-muted-foreground">+ {name+ ? t('common:coworkEmpty.subtitleFolder', { folder: name })+ : t('common:coworkEmpty.subtitleSandbox')}+ </p>++ <p className="mt-6 text-xs font-medium uppercase tracking-wider text-muted-foreground/60">+ {t('common:coworkEmpty.try')}+ </p>+ <div className="mt-1 flex flex-col items-start">+ {EXAMPLE_KEYS.map((key) => {+ const text = t(`common:coworkEmpty.${scope}.${key}`, {+ folder: name,+ })+ return (+ <button+ key={key}+ type="button"+ onClick={() => onPick(text)}+ className="max-w-full rounded-lg px-2 py-1.5 text-left text-sm text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {text}+ </button>+ )+ })}+ </div>+ </div>+ </div>+ </div>+ )+}diff --git a/web-app/src/containers/CoworkPlanToggle.tsx b/web-app/src/containers/CoworkPlanToggle.tsxindex 6a8580925..34f4ee330 100644--- a/web-app/src/containers/CoworkPlanToggle.tsx+++ b/web-app/src/containers/CoworkPlanToggle.tsx@@ -14,13 +14,13 @@ type Props = {}/**- * 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.+ * A pressed-state button, not a Switch: a Switch reads as a settings control,+ * 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.+ * Icon-only until it is on, then it grows a label. The composer's control row+ * is a row of quiet ghost icons; an outlined pill sitting among them read as+ * bolted on, and a mode that is off has nothing to say. `text-primary` for the+ * on state is the row's own convention, borrowed from the web-search toggle.*/export function CoworkPlanToggle({ planMode, onChange }: Props) {const { t } = useTranslation()@@ -30,28 +30,24 @@ export function CoworkPlanToggle({ planMode, onChange }: Props) {<Tooltip><TooltipTrigger asChild><Button- variant={planMode ? 'secondary' : 'outline'}- size="sm"+ variant="ghost"+ size={planMode ? 'xs' : 'icon-xs'}aria-pressed={planMode}+ aria-label={t('common:planMode.label')}onClick={() => onChange(!planMode)}className={cn(- 'h-7 gap-1.5 rounded-full shrink-0',- planMode && 'border-primary/40'+ 'shrink-0',+ planMode ? 'text-primary' : 'text-muted-foreground')}><Diamond- size={13}aria-hiddenclassName={cn('shrink-0',- planMode- ? 'fill-current text-primary'- : 'text-muted-foreground'+ planMode ? 'size-3.5 fill-current' : 'size-[18px]')}/>- <span className={planMode ? undefined : 'text-muted-foreground'}>- {t('common:planMode.label')}- </span>+ {planMode && <span>{t('common:planMode.label')}</span>}</Button></TooltipTrigger><TooltipContent>diff --git a/web-app/src/containers/CoworkPreviewPanel.tsx b/web-app/src/containers/CoworkPreviewPanel.tsxnew file mode 100644index 000000000..49b01ae3e--- /dev/null+++ b/web-app/src/containers/CoworkPreviewPanel.tsx@@ -0,0 +1,264 @@+import { useCallback, useEffect, useMemo, useState } from 'react'+import { FolderOpen, Globe, RotateCw, SquareArrowOutUpRight } from 'lucide-react'+import { Button } from '@/components/ui/button'+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/components/ui/tooltip'+import { RenderMarkdown } from '@/containers/RenderMarkdown'+import { CoworkSidePanel } from '@/containers/CoworkSidePanel'+import { getServiceHub, useServiceHub } from '@/hooks/useServiceHub'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { buildSrcDoc } from '@/lib/htmlSandbox'+import { cn } from '@/lib/utils'+import {+ MAX_PREVIEW_BYTES,+ basenameOf,+ isAssetKind,+ previewKindFor,+ resolveInRoot,+ unresolvedRefs,+ type PreviewState,+} from '@/lib/coworkPreview'++/** Held as a key, not a translated string: the loader must not depend on `t`,+ * whose identity changes on every render. */+const TOO_LARGE = 'common:preview.tooLarge'++type Props = {+ /** The session sandbox. Every previewed path must resolve inside it. */+ root: string | null+ path: string+ onClose: () => void+}++/**+ * Renders one artifact beside the transcript.+ *+ * Files are read straight off disk through the asset protocol rather than the+ * agent's `read` tool: that tool caps its output and appends a truncation+ * footer, which is right for a model and wrong for a preview, and it hands back+ * a description of an image rather than its bytes.+ */+export function CoworkPreviewPanel({ root, path, onClose }: Props) {+ const { t } = useTranslation()+ const serviceHub = useServiceHub()+ const [state, setState] = useState<PreviewState>({ status: 'idle' })+ // Bumped by Reload. Content is never swapped underneath the user: they may be+ // mid-interaction in a document or a running page.+ const [nonce, setNonce] = useState(0)+ const [allowNetwork, setAllowNetwork] = useState(false)++ const abs = useMemo(+ () => (root ? resolveInRoot(root, path) : null),+ [root, path]+ )+ const kind = useMemo(() => previewKindFor(path), [path])++ useEffect(() => {+ let alive = true+ if (!abs) {+ setState({ status: 'failed', path, reason: 'common:preview.outside' })+ return+ }+ if (kind === 'file') {+ setState({ status: 'unsupported', path })+ return+ }+ setState({ status: 'loading', path })++ void (async () => {+ const url = getServiceHub().core().convertFileSrc(abs)+ if (isAssetKind(kind)) {+ // The element streams the file itself, so there is nothing to fetch and+ // a large video costs nothing to "open".+ if (alive) setState({ status: 'ready', path, kind, assetUrl: url })+ return+ }+ try {+ const res = await fetch(url)+ if (!res.ok) throw new Error(String(res.status))+ const size = Number(res.headers.get('content-length') ?? 0)+ if (size > MAX_PREVIEW_BYTES) throw new Error(TOO_LARGE)+ const content = await res.text()+ if (content.length > MAX_PREVIEW_BYTES) throw new Error(TOO_LARGE)+ if (!alive) return+ setState({+ status: 'ready',+ path,+ kind,+ content,+ unresolvedRefs: kind === 'html' ? unresolvedRefs(content) : undefined,+ })+ } catch (e) {+ if (!alive) return+ setState({+ status: 'failed',+ path,+ reason: e instanceof Error ? e.message : String(e),+ })+ }+ })()++ return () => {+ alive = false+ }+ }, [abs, path, kind, nonce])++ const reload = useCallback(() => setNonce((n) => n + 1), [])++ const iconButton = (+ label: string,+ Icon: typeof RotateCw,+ onClick: () => void,+ active?: boolean+ ) => (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={onClick}+ aria-label={label}+ aria-pressed={active}+ className={cn(+ 'shrink-0',+ active ? 'text-primary' : 'text-muted-foreground'+ )}+ >+ <Icon className="size-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ )++ return (+ <CoworkSidePanel+ title={basenameOf(path)}+ onClose={onClose}+ summary={+ <div className="flex shrink-0 items-center gap-0.5">+ {state.status === 'ready' && state.kind === 'html' &&+ iconButton(+ t('common:preview.allowNetwork'),+ Globe,+ () => setAllowNetwork((v) => !v),+ allowNetwork+ )}+ {iconButton(t('common:preview.reload'), RotateCw, reload)}+ {abs && (+ <>+ {iconButton(+ t('common:artifactOpenExternal'),+ SquareArrowOutUpRight,+ () => void serviceHub.opener().openPath(abs)+ )}+ {iconButton(+ t('common:artifactShowInFolder'),+ FolderOpen,+ () => void serviceHub.opener().revealItemInDir(abs)+ )}+ </>+ )}+ </div>+ }+ >+ <PreviewBody state={state} allowNetwork={allowNetwork} />+ </CoworkSidePanel>+ )+}++function Notice({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground">+ {children}+ </div>+ )+}++function PreviewBody({+ state,+ allowNetwork,+}: {+ state: PreviewState+ allowNetwork: boolean+}) {+ const { t } = useTranslation()++ if (state.status === 'idle' || state.status === 'loading') {+ return <Notice>{t('common:preview.loading')}</Notice>+ }+ if (state.status === 'unsupported') {+ return <Notice>{t('common:preview.unsupported')}</Notice>+ }+ if (state.status === 'failed') {+ // Our own reasons are keys; anything from `fetch` is already a message.+ return (+ <Notice>+ {state.reason.startsWith('common:') ? t(state.reason) : state.reason}+ </Notice>+ )+ }++ switch (state.kind) {+ case 'html':+ case 'svg': {+ // SVG is static markup, so it runs no scripts; HTML gets them, because an+ // artifact that draws a chart is inert without them.+ const scripts = state.kind === 'html'+ return (+ <div className="flex h-full flex-col">+ {(state.unresolvedRefs ?? 0) > 0 && (+ <p className="border-b bg-muted/40 px-3 py-2 text-xs text-muted-foreground">+ {t('common:preview.unresolvedRefs', {+ count: state.unresolvedRefs,+ })}+ </p>+ )}+ <iframe+ title={state.path}+ srcDoc={buildSrcDoc(state.content ?? '', allowNetwork, scripts)}+ sandbox={scripts ? 'allow-scripts' : ''}+ className="min-h-0 w-full flex-1 border-0 bg-white"+ />+ </div>+ )+ }+ case 'markdown':+ return (+ <div className="h-full overflow-auto px-4 py-3">+ <RenderMarkdown content={state.content ?? ''} />+ </div>+ )+ case 'text':+ return (+ <pre className="h-full overflow-auto p-3 font-mono text-xs leading-relaxed">+ {state.content}+ </pre>+ )+ case 'image':+ return (+ <div className="flex h-full items-center justify-center overflow-auto p-3">+ <img+ src={state.assetUrl}+ alt={basenameOf(state.path)}+ className="max-h-full max-w-full object-contain"+ />+ </div>+ )+ case 'video':+ return (+ <div className="flex h-full items-center justify-center p-3">+ <video src={state.assetUrl} controls className="max-h-full w-full" />+ </div>+ )+ case 'audio':+ return (+ <div className="flex h-full items-center justify-center p-3">+ <audio src={state.assetUrl} controls className="w-full" />+ </div>+ )+ }+}diff --git a/web-app/src/containers/CodeSidePanel.tsx b/web-app/src/containers/CoworkSidePanel.tsxsimilarity index 96%rename from web-app/src/containers/CodeSidePanel.tsxrename to web-app/src/containers/CoworkSidePanel.tsxindex 717f1cd6e..1b15613b0 100644--- a/web-app/src/containers/CodeSidePanel.tsx+++ b/web-app/src/containers/CoworkSidePanel.tsx@@ -3,7 +3,7 @@ import { Maximize2, Minimize2, X } from 'lucide-react'import { cn } from '@/lib/utils'import { useTranslation } from '@/i18n/react-i18next-compat'-type CodeSidePanelProps = {+type CoworkSidePanelProps = {title: ReactNodeleading?: ReactNodesummary?: ReactNode@@ -15,13 +15,13 @@ const PANEL_MIN_W = 240const PANEL_MAX_W = 640const PANEL_DEFAULT_W = 320-export function CodeSidePanel({+export function CoworkSidePanel({title,leading,summary,children,onClose,-}: CodeSidePanelProps): React.ReactElement {+}: CoworkSidePanelProps): React.ReactElement {const { t } = useTranslation()const [expanded, setExpanded] = useState(false)const [width, setWidth] = useState(PANEL_DEFAULT_W)diff --git a/web-app/src/containers/CodeTodoPanel.tsx b/web-app/src/containers/CoworkTodoPanel.tsxsimilarity index 96%rename from web-app/src/containers/CodeTodoPanel.tsxrename to web-app/src/containers/CoworkTodoPanel.tsxindex 4a4639eb5..3785dd7a6 100644--- a/web-app/src/containers/CodeTodoPanel.tsx+++ b/web-app/src/containers/CoworkTodoPanel.tsx@@ -2,8 +2,8 @@ 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 type { TodoList, TodoStatus } from '@/types/coworkSession'+import { CoworkSidePanel } from '@/containers/CoworkSidePanel'import { cleanTaskLabel } from '@/lib/todoLabels'/** Status dot: filled when resolved, hollow while still open. */@@ -38,7 +38,7 @@ function StatusDot({ status }: { status: TodoStatus }) {* (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({+export function CoworkTodoPanel({todos,onClose,}: {@@ -63,7 +63,7 @@ export function CodeTodoPanel({})return (- <CodeSidePanel+ <CoworkSidePaneltitle={t('common:todoPanelTitle')}summary={tasks.length > 0 ? (@@ -150,6 +150,6 @@ export function CodeTodoPanel({)}</div></div>- </CodeSidePanel>+ </CoworkSidePanel>)}diff --git a/web-app/src/containers/CoworkWorkspacePill.tsx b/web-app/src/containers/CoworkWorkspacePill.tsxindex 9f2a592f2..ef7d088b7 100644--- a/web-app/src/containers/CoworkWorkspacePill.tsx+++ b/web-app/src/containers/CoworkWorkspacePill.tsx@@ -1,4 +1,4 @@-import { Folder, GitBranch, HardDrive, Lock } from 'lucide-react'+import { Folder, FolderPlus, GitBranch, Lock } from 'lucide-react'import { Button } from '@/components/ui/button'import {Popover,@@ -8,30 +8,31 @@ import {import { Separator } from '@/components/ui/separator'import { useTranslation } from '@/i18n/react-i18next-compat'import { useServiceHub } from '@/hooks/useServiceHub'-import { basenameOf } from '@/lib/codePreview'+import { basenameOf } from '@/lib/coworkPreview'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 | nullgitBranch?: string | nullonAttach: () => voidonDetach: () => void}/**- * Names both halves of the session's filesystem: the read-only folder it reads- * from, and the sandbox it writes to.+ * Attach, inspect and detach the read-only project folder.*- * 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.+ * The sandbox it writes into is deliberately unnamed: it is an implementation+ * detail the user never picks or opens, and surfacing it invited the reading+ * that the folder and the sandbox are two halves of one choice. What has to+ * stay visible is the read-only contract on the folder.+ *+ * The trigger is icon-only until a folder is attached, matching the composer+ * row's other controls: with nothing attached there is no name to print, and a+ * pill reading "Attach a folder" outweighed every icon beside it.*/export function CoworkWorkspacePill({folder,- sandboxPath,gitBranch,onAttach,onDetach,@@ -44,29 +45,26 @@ export function CoworkWorkspacePill({<Popover><PopoverTrigger asChild><Button- variant="outline"- size="sm"- className="h-7 gap-1.5 rounded-full shrink-0"+ variant="ghost"+ size={folderName ? 'xs' : 'icon-xs'}+ className="shrink-0 text-muted-foreground"aria-label={folderName? t('common:workspace.a11yWithFolder', { folder: folderName })- : t('common:workspace.a11ySandboxOnly')+ : t('common:workspace.a11yNoFolder')}>{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">- →+ <Folder className="size-3.5 shrink-0" />+ <span className="max-w-[120px] truncate text-foreground">+ {folderName}</span>+ <Lock className="size-3 shrink-0 text-muted-foreground/70" /></>- ) : null}- <HardDrive size={14} className="text-muted-foreground shrink-0" />- <span>{t('common:workspace.sandbox')}</span>+ ) : (+ <FolderPlus className="size-[18px] shrink-0" />+ )}</Button></PopoverTrigger>@@ -109,9 +107,7 @@ export function CoworkWorkspacePill({variant="ghost"size="sm"className="h-7"- onClick={() =>- void serviceHub.opener().revealItemInDir(folder)- }+ onClick={() => void serviceHub.opener().revealItemInDir(folder)}>{t('common:workspace.reveal')}</Button>@@ -120,36 +116,6 @@ export function CoworkWorkspacePill({</>) : 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')diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex 1217bc86b..408593459 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -10,7 +10,7 @@ import {usedSkillNames,type ActivityLabel,} from '@/lib/agentActivity'-import type { SubagentRun } from '@/types/codeSession'+import type { SubagentRun } from '@/types/coworkSession'import { Loader } from 'lucide-react'/** How close to the cap the step counter becomes visible. */diff --git a/web-app/src/containers/SkillSelector.tsx b/web-app/src/containers/SkillSelector.tsxindex d44a4214f..98e939c12 100644--- a/web-app/src/containers/SkillSelector.tsx+++ b/web-app/src/containers/SkillSelector.tsx@@ -8,6 +8,7 @@ import { Button } from '@/components/ui/button'import { Switch } from '@/components/ui/switch'import { useTranslation } from '@/i18n/react-i18next-compat'import { useSkills, effectiveEnabled, storedEnabled } from '@/hooks/useSkills'+import { cn } from '@/lib/utils'/*** Top-of-input control showing which skills will be advertised to the agent this@@ -34,15 +35,23 @@ export default function SkillSelector({ folder }: { folder: string | null }) {<Popover><PopoverTrigger asChild><Button- variant="outline"- size="sm"- className="h-7 gap-1.5 rounded-full"+ variant="ghost"+ size={effective.size > 0 ? 'xs' : 'icon-xs'}+ className="shrink-0 text-muted-foreground"title={t('common:skillsInContext')}+ aria-label={t('common:skillsInContext')}>- <Sparkles size={14} className="text-muted-foreground" />- <span>- {t('common:skills')} {effective.size}/{allNames.length}- </span>+ <Sparkles+ className={cn(+ 'shrink-0',+ effective.size > 0 ? 'size-3.5' : 'size-[18px]'+ )}+ />+ {effective.size > 0 && (+ <span className="tabular-nums text-foreground">+ {effective.size}/{allNames.length}+ </span>+ )}</Button></PopoverTrigger><PopoverContent align="end" className="w-72 p-1">diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsxindex 6b639ddb3..01f27734d 100644--- a/web-app/src/containers/__tests__/ChatInput.test.tsx+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx@@ -644,4 +644,49 @@ describe('ChatInput', () => {expect(transferAttachmentsMock).not.toHaveBeenCalled()})+ describe('tool controls', () => {+ const icons = (cls: string) =>+ document.querySelectorAll(`.tabler-icon-${cls}`).length++ // Web access is a global capability both surfaces honour -- Cowork reads+ // the same store when it builds its tool set -- so the toggle travels.+ it('offers the web-search toggle on every surface', () => {+ renderInput()+ expect(icons('world-search')).toBe(1)+ renderInput({ ownsToolSet: false })+ expect(icons('world-search')).toBeGreaterThan(0)+ })++ // Its only switch is Settings > Agent Tools now. In the composer it read as+ // a per-message choice while actually flipping a global.+ it('no longer offers the agent-tools toggle', () => {+ renderInput()+ expect(icons('folder-code')).toBe(0)+ })++ it('withholds MCP controls from a surface that owns its tool set', () => {+ renderInput({ ownsToolSet: false })+ // The composer still works: the textarea and attachments stay.+ expect(getTextarea()).toBeInTheDocument()+ })+ })++ describe('surfaceControls', () => {+ it('docks a surface\'s own controls in the control row', () => {+ renderInput({ surfaceControls: <button>plan</button> })+ expect(screen.getByText('plan')).toBeInTheDocument()+ })++ // They configure the next message, not the run in flight, so streaming+ // must not disable them the way it dims the tool icons.+ it('keeps them live while streaming', () => {+ renderInput({+ surfaceControls: <button>plan</button>,+ chatStatus: 'streaming',+ })+ const dimmed = document.querySelector('.pointer-events-none')+ expect(dimmed).toBeTruthy()+ expect(dimmed!.contains(screen.getByText('plan'))).toBe(false)+ })+ })})diff --git a/web-app/src/containers/__tests__/CodeAskCard.test.tsx b/web-app/src/containers/__tests__/CoworkAskCard.test.tsxsimilarity index 79%rename from web-app/src/containers/__tests__/CodeAskCard.test.tsxrename to web-app/src/containers/__tests__/CoworkAskCard.test.tsxindex 3c18a771c..e0bafd6d3 100644--- a/web-app/src/containers/__tests__/CodeAskCard.test.tsx+++ b/web-app/src/containers/__tests__/CoworkAskCard.test.tsx@@ -1,8 +1,8 @@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'+import { CoworkAskCard } from '@/containers/CoworkAskCard'+import type { AskRequestPayload } from '@/hooks/useCoworkRun'vi.mock('@/i18n/react-i18next-compat', () => ({useTranslation: () => ({@@ -46,23 +46,23 @@ beforeEach(() => {const submitButton = () => screen.getByLabelText('common:submit')-describe('CodeAskCard', () => {+describe('CoworkAskCard', () => {it('renders nothing when there is no pending request', () => {const { container } = render(- <CodeAskCard requestId={null} request={null} onRespond={onRespond} />+ <CoworkAskCard requestId={null} request={null} onRespond={onRespond} />)expect(container).toBeEmptyDOMElement()})it('submits the selected option label', () => {- render(<CodeAskCard requestId="ask-1" request={single} onRespond={onRespond} />)+ render(<CoworkAskCard 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} />)+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)fireEvent.click(screen.getByText('Small'))fireEvent.click(screen.getByText('Large'))fireEvent.click(submitButton())@@ -70,7 +70,7 @@ describe('CodeAskCard', () => {})it('multi-select accumulates', () => {- render(<CodeAskCard requestId="ask-1" request={multi} onRespond={onRespond} />)+ render(<CoworkAskCard requestId="ask-1" request={multi} onRespond={onRespond} />)fireEvent.click(screen.getByText('Team'))fireEvent.click(screen.getByText('Public'))fireEvent.click(submitButton())@@ -80,7 +80,7 @@ describe('CodeAskCard', () => {})it('free text and options are mutually exclusive, per the QuestionResult contract', () => {- render(<CodeAskCard requestId="ask-1" request={single} onRespond={onRespond} />)+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)fireEvent.click(screen.getByText('Small'))fireEvent.click(screen.getByText('common:askSomethingElse'))fireEvent.change(screen.getByPlaceholderText('common:askSomethingElsePlaceholder'), {@@ -94,7 +94,7 @@ describe('CodeAskCard', () => {})it('cannot submit on empty free text', () => {- render(<CodeAskCard requestId="ask-1" request={single} onRespond={onRespond} />)+ render(<CoworkAskCard requestId="ask-1" request={single} onRespond={onRespond} />)fireEvent.click(screen.getByText('common:askSomethingElse'))expect(submitButton()).toBeDisabled()fireEvent.change(screen.getByPlaceholderText('common:askSomethingElsePlaceholder'), {@@ -104,7 +104,7 @@ describe('CodeAskCard', () => {})it('requires every question answered before submitting, since the core rejects partial responses', () => {- render(<CodeAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)+ render(<CoworkAskCard 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'))@@ -120,24 +120,24 @@ describe('CodeAskCard', () => {})it('Skip declines the whole request (the core has no per-question skip)', () => {- render(<CodeAskCard requestId="ask-1" request={twoQuestions} onRespond={onRespond} />)+ render(<CoworkAskCard 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} />)+ render(<CoworkAskCard 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} />+ <CoworkAskCard 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} />)+ rerender(<CoworkAskCard requestId="ask-2" request={single} onRespond={onRespond} />)expect(submitButton()).toBeDisabled()})})diff --git a/web-app/src/containers/__tests__/CoworkChangesChip.test.tsx b/web-app/src/containers/__tests__/CoworkChangesChip.test.tsxnew file mode 100644index 000000000..a8bc3b077--- /dev/null+++ b/web-app/src/containers/__tests__/CoworkChangesChip.test.tsx@@ -0,0 +1,58 @@+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 { CoworkChangesChip } from '../CoworkChangesChip'+import type { CoworkFileDiff } from '@/lib/coworkDiffs'++const file = (+ path: string,+ additions: number,+ deletions: number+): CoworkFileDiff => ({ path, additions, deletions, operations: [] })++describe('CoworkChangesChip', () => {+ // Same rule as the plan and folder controls: nothing written yet is nothing+ // to say, so the dock row stays quiet.+ it('renders nothing before the agent has written anything', () => {+ const { container } = render(+ <CoworkChangesChip files={[]} open={false} onToggle={vi.fn()} />+ )+ expect(container).toBeEmptyDOMElement()+ })++ it('totals the counts across every changed file', () => {+ render(+ <CoworkChangesChip+ files={[file('a.ts', 3, 1), file('b.ts', 4, 6)]}+ open={false}+ onToggle={vi.fn()}+ />+ )+ expect(screen.getByText('+7')).toBeInTheDocument()+ expect(screen.getByText('-7')).toBeInTheDocument()+ })++ it('reports its state and toggles the rail', async () => {+ const onToggle = vi.fn()+ render(+ <CoworkChangesChip+ files={[file('a.ts', 1, 0)]}+ open={true}+ onToggle={onToggle}+ />+ )+ const button = screen.getByRole('button')+ expect(button).toHaveAttribute('aria-pressed', 'true')++ await userEvent.click(button)+ expect(onToggle).toHaveBeenCalledOnce()+ })+})diff --git a/web-app/src/containers/__tests__/CoworkDiffPanel.test.tsx b/web-app/src/containers/__tests__/CoworkDiffPanel.test.tsxnew file mode 100644index 000000000..a71beeffd--- /dev/null+++ b/web-app/src/containers/__tests__/CoworkDiffPanel.test.tsx@@ -0,0 +1,59 @@+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 }),+}))++vi.mock('@/components/DiffView', () => ({+ DiffView: ({ diff }: { diff: string }) => <pre data-testid="diff">{diff}</pre>,+}))++import { CoworkDiffPanel } from '../CoworkDiffPanel'+import type { CoworkFileDiff } from '@/lib/coworkDiffs'++const files: CoworkFileDiff[] = [+ {+ path: 'report.md',+ additions: 5,+ deletions: 2,+ operations: [{ diff: '+ new line', source: 'main' }],+ },+ {+ path: 'chart.py',+ additions: 1,+ deletions: 0,+ operations: [+ { diff: '+ import numpy', source: 'subagent', sourceName: 'researcher' },+ ],+ },+]++describe('CoworkDiffPanel', () => {+ it('summarises the totals across files', () => {+ render(<CoworkDiffPanel files={files} onClose={vi.fn()} />)+ expect(screen.getByText('+6 -2')).toBeInTheDocument()+ })++ // Collapsed by default: a run touching a dozen files should open as a list,+ // not a wall of hunks.+ it('reveals a file’s hunks only once it is expanded', async () => {+ render(<CoworkDiffPanel files={files} onClose={vi.fn()} />)+ expect(screen.queryByTestId('diff')).toBeNull()++ await userEvent.click(screen.getByText('report.md'))+ expect(screen.getByTestId('diff')).toHaveTextContent('+ new line')+ })++ it('attributes a subagent’s edit to it', async () => {+ render(<CoworkDiffPanel files={files} onClose={vi.fn()} />)+ await userEvent.click(screen.getByText('chart.py'))+ expect(screen.getByText('researcher')).toBeInTheDocument()+ })++ it('says what will appear here when nothing has changed', () => {+ render(<CoworkDiffPanel files={[]} onClose={vi.fn()} />)+ expect(screen.getByText('common:changes.empty')).toBeInTheDocument()+ })+})diff --git a/web-app/src/containers/__tests__/CoworkEmptyState.test.tsx b/web-app/src/containers/__tests__/CoworkEmptyState.test.tsxnew file mode 100644index 000000000..c21719c68--- /dev/null+++ b/web-app/src/containers/__tests__/CoworkEmptyState.test.tsx@@ -0,0 +1,52 @@+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?.folder ? `${k}[${opts.folder}]` : k,+ }),+}))++import { CoworkEmptyState } from '../CoworkEmptyState'++describe('CoworkEmptyState', () => {+ it('offers workspace examples when no folder is attached', () => {+ render(<CoworkEmptyState folder={null} onPick={vi.fn()} />)++ expect(+ screen.getByText('common:coworkEmpty.subtitleSandbox')+ ).toBeInTheDocument()+ expect(+ screen.getByText('common:coworkEmpty.sandbox.first')+ ).toBeInTheDocument()+ expect(screen.queryByText(/coworkEmpty\.folder\./)).toBeNull()+ })++ // The reason the examples exist: a fixed list is wallpaper, one naming the+ // folder you just attached is a task you might actually run.+ it('names the attached folder in every example', () => {+ render(+ <CoworkEmptyState folder="/home/u/Projects/jan-app" onPick={vi.fn()} />+ )++ expect(+ screen.getByText('common:coworkEmpty.subtitleFolder[jan-app]')+ ).toBeInTheDocument()+ for (const key of ['first', 'second', 'third']) {+ expect(+ screen.getByText(`common:coworkEmpty.folder.${key}[jan-app]`)+ ).toBeInTheDocument()+ }+ })++ // Loaded, not sent: an example is a starting point the user edits.+ it('loads a picked example rather than submitting it', async () => {+ const onPick = vi.fn()+ render(<CoworkEmptyState folder={null} onPick={onPick} />)++ await userEvent.click(screen.getByText('common:coworkEmpty.sandbox.second'))+ expect(onPick).toHaveBeenCalledWith('common:coworkEmpty.sandbox.second')+ })+})diff --git a/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx b/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsxnew file mode 100644index 000000000..77645638f--- /dev/null+++ b/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx@@ -0,0 +1,140 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, waitFor } from '@testing-library/react'++vi.mock('@/i18n/react-i18next-compat', () => ({+ useTranslation: () => ({+ t: (k: string, opts?: Record<string, unknown>) =>+ opts?.count !== undefined ? `${k}#${opts.count}` : k,+ }),+}))++const convertFileSrc = vi.fn((p: string) => `asset://${p}`)+const openPath = vi.fn()+const revealItemInDir = vi.fn()+const hub = {+ core: () => ({ convertFileSrc }),+ opener: () => ({ openPath, revealItemInDir }),+}+vi.mock('@/hooks/useServiceHub', () => ({+ useServiceHub: () => hub,+ getServiceHub: () => hub,+}))++vi.mock('@/containers/RenderMarkdown', () => ({+ RenderMarkdown: ({ content }: { content: string }) => (+ <div data-testid="markdown">{content}</div>+ ),+}))++import { CoworkPreviewPanel } from '../CoworkPreviewPanel'+import { MAX_PREVIEW_BYTES } from '@/lib/coworkPreview'++const ROOT = '/data/agent-workspace/sessions/s1'++const respondWith = (body: string) => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({+ ok: true,+ headers: { get: () => String(body.length) },+ text: async () => body,+ }))+ )+}++const view = (path: string) =>+ render(<CoworkPreviewPanel root={ROOT} path={path} onClose={vi.fn()} />)++describe('CoworkPreviewPanel', () => {+ beforeEach(() => {+ convertFileSrc.mockClear()+ vi.unstubAllGlobals()+ })++ // The one security-relevant behaviour: the panel is handed paths the model+ // chose, and must never read one that leaves the sandbox.+ it('refuses a path that escapes the workspace instead of reading it', async () => {+ const fetchSpy = vi.fn()+ vi.stubGlobal('fetch', fetchSpy)+ view('../../../etc/passwd')++ await screen.findByText('common:preview.outside')+ expect(fetchSpy).not.toHaveBeenCalled()+ expect(convertFileSrc).not.toHaveBeenCalled()+ })++ it('streams an image from disk rather than fetching it', async () => {+ const fetchSpy = vi.fn()+ vi.stubGlobal('fetch', fetchSpy)+ view('chart.png')++ const img = await screen.findByRole('img')+ expect(img).toHaveAttribute('src', `asset://${ROOT}/chart.png`)+ expect(fetchSpy).not.toHaveBeenCalled()+ })++ // Scripts on (a chart artifact is inert without them), network off until+ // asked for -- so model markup cannot phone out on open.+ it('sandboxes html with scripts allowed and network withheld', async () => {+ respondWith('<h1>Report</h1><script>draw()</script>')+ view('report.html')++ const frame = (await screen.findByTitle('report.html')) as HTMLIFrameElement+ expect(frame.getAttribute('sandbox')).toBe('allow-scripts')+ expect(frame.srcdoc).toContain("script-src 'unsafe-inline'")+ expect(frame.srcdoc).not.toContain('https:')+ expect(frame.srcdoc).toContain('<h1>Report</h1>')+ })++ it('runs no scripts for an svg', async () => {+ respondWith('<svg><rect /></svg>')+ view('logo.svg')++ const frame = (await screen.findByTitle('logo.svg')) as HTMLIFrameElement+ expect(frame.getAttribute('sandbox')).toBe('')+ expect(frame.srcdoc).toContain("default-src 'none'")+ })++ // A page whose relative assets cannot resolve renders visibly broken; saying+ // so beats presenting it as correct.+ it('counts links the sandbox cannot resolve', async () => {+ respondWith('<img src="a.png"><img src="https://x.dev/b.png">')+ view('page.html')++ await screen.findByText('common:preview.unresolvedRefs#1')+ })++ it('renders markdown through the shared renderer', async () => {+ respondWith('# Title')+ view('notes.md')++ expect(await screen.findByTestId('markdown')).toHaveTextContent('# Title')+ })++ it('offers another app instead of previewing an unsupported file', async () => {+ view('archive.zip')+ await screen.findByText('common:preview.unsupported')+ })++ it('stops before loading a file too big to preview', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({+ ok: true,+ headers: { get: () => String(MAX_PREVIEW_BYTES + 1) },+ text: async () => 'x',+ }))+ )+ view('huge.html')+ await screen.findByText('common:preview.tooLarge')+ })++ it('reports a read failure rather than rendering an empty page', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({ ok: false, status: 404, headers: { get: () => '0' } }))+ )+ view('gone.html')+ await waitFor(() => expect(screen.getByText('404')).toBeInTheDocument())+ })+})diff --git a/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsx b/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsxindex 280ab104c..85c84b127 100644--- a/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsx+++ b/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsx@@ -17,40 +17,33 @@ vi.mock('@/hooks/useServiceHub', () => ({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 () => {+ it('invites attaching a folder when none is attached', async () => {render(- <CoworkWorkspacePill- folder={null}- sandboxPath={SANDBOX}- onAttach={vi.fn()}- onDetach={vi.fn()}- />+ <CoworkWorkspacePill folder={null} onAttach={vi.fn()} onDetach={vi.fn()} />)- await userEvent.click(screen.getByRole('button'))+ await userEvent.click(screen.getByRole('button', { name: /a11yNoFolder/ }))- 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()+ expect(+ screen.getAllByText('common:workspace.attach').length+ ).toBeGreaterThan(0)})// 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 () => {+ // name the direction and mark the folder read-only. A regression here would+ // have the UI implying the agent edits the user's project.+ it('names the read direction and marks the folder read-only', async () => {render(<CoworkWorkspacePillfolder="/home/u/Projects/jan-app"- sandboxPath={SANDBOX}gitBranch="dev"onAttach={vi.fn()}onDetach={vi.fn()}@@ -59,7 +52,6 @@ describe('CoworkWorkspacePill', () => {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)@@ -71,7 +63,6 @@ describe('CoworkWorkspacePill', () => {render(<CoworkWorkspacePillfolder="/home/u/Projects/jan-app"- sandboxPath={SANDBOX}onAttach={vi.fn()}onDetach={vi.fn()}/>@@ -90,7 +81,6 @@ describe('CoworkWorkspacePill', () => {render(<CoworkWorkspacePillfolder="/home/u/Projects/jan-app"- sandboxPath={SANDBOX}onAttach={vi.fn()}onDetach={onDetach}/>diff --git a/web-app/src/containers/dialogs/SkillsManagerDialog.tsx b/web-app/src/containers/dialogs/SkillsManagerDialog.tsxindex 85de2b76c..46a945853 100644--- a/web-app/src/containers/dialogs/SkillsManagerDialog.tsx+++ b/web-app/src/containers/dialogs/SkillsManagerDialog.tsx@@ -12,7 +12,7 @@ import { Input } from '@/components/ui/input'import { Textarea } from '@/components/ui/textarea'import { cn } from '@/lib/utils'import { useTranslation } from '@/i18n/react-i18next-compat'-import { useCodeSessions } from '@/hooks/useCodeSessions'+import { useCoworkSessions } from '@/hooks/useCoworkSessions'import { useSkills, type HubSkill } from '@/hooks/useSkills'export default function SkillsManagerDialog({@@ -23,8 +23,8 @@ export default function SkillsManagerDialog({onOpenChange: (open: boolean) => void}) {const { t } = useTranslation()- const sessions = useCodeSessions((s) => s.sessions)- const currentId = useCodeSessions((s) => s.currentId)+ const sessions = useCoworkSessions((s) => s.sessions)+ const currentId = useCoworkSessions((s) => s.currentId)const folder = sessions.find((s) => s.id === currentId)?.folder ?? nullconst { skills, remove, write, read, hubList, hubImport } = useSkills(folder)diff --git a/web-app/src/hooks/__tests__/useCodeRun.test.ts b/web-app/src/hooks/__tests__/useCodeRun.test.tsdeleted file mode 100644index 4b574488b..000000000--- a/web-app/src/hooks/__tests__/useCodeRun.test.ts+++ /dev/null@@ -1,117 +0,0 @@-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__/useCoworkRun.test.ts b/web-app/src/hooks/__tests__/useCoworkRun.test.tsnew file mode 100644index 000000000..bb53442c4--- /dev/null+++ b/web-app/src/hooks/__tests__/useCoworkRun.test.ts@@ -0,0 +1,141 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useCoworkRun } from '../useCoworkRun'++// 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('useCoworkRun - llamacpp attribution', () => {+ beforeEach(() => {+ useCoworkRun.setState({+ llamacppRuns: {},+ pendingLlamacppError: {},+ runId: {},+ loadingModels: {},+ modelLoadProgress: {},+ })+ })++ it('tracks and clears which session is running which model', () => {+ useCoworkRun.getState().setLlamacppRun('session-a', 'model-1')+ expect(useCoworkRun.getState().llamacppRuns).toEqual({ 'session-a': 'model-1' })++ useCoworkRun.getState().clearLlamacppRun('session-a')+ expect(useCoworkRun.getState().llamacppRuns).toEqual({})+ })++ it('clearLlamacppRun on an untracked session is a no-op, not a crash', () => {+ expect(() => useCoworkRun.getState().clearLlamacppRun('nobody')).not.toThrow()+ expect(useCoworkRun.getState().llamacppRuns).toEqual({})+ })++ it('takePendingLlamacppError reads and clears in one step', () => {+ useCoworkRun.getState().setPendingLlamacppError('session-a', 'oom')++ expect(useCoworkRun.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(useCoworkRun.getState().takePendingLlamacppError('session-a')).toBeUndefined()+ expect(useCoworkRun.getState().pendingLlamacppError).toEqual({})+ })++ it('takePendingLlamacppError on a session with nothing pending returns undefined', () => {+ expect(useCoworkRun.getState().takePendingLlamacppError('idle-session')).toBeUndefined()+ })++ it('does not cross-attribute between two sessions running different models', () => {+ useCoworkRun.getState().setLlamacppRun('session-a', 'model-1')+ useCoworkRun.getState().setLlamacppRun('session-b', 'model-2')+ useCoworkRun.getState().setPendingLlamacppError('session-a', 'oom')++ expect(useCoworkRun.getState().llamacppRuns).toEqual({+ 'session-a': 'model-1',+ 'session-b': 'model-2',+ })+ expect(useCoworkRun.getState().takePendingLlamacppError('session-b')).toBeUndefined()+ expect(useCoworkRun.getState().takePendingLlamacppError('session-a')).toBe('oom')+ })++ it('clearCodeRun sweeps up llamacppRuns and pendingLlamacppError for that session too', () => {+ useCoworkRun.getState().setLlamacppRun('session-a', 'model-1')+ useCoworkRun.getState().setPendingLlamacppError('session-a', 'oom')++ useCoworkRun.getState().clearCodeRun('session-a')++ expect(useCoworkRun.getState().llamacppRuns).toEqual({})+ expect(useCoworkRun.getState().pendingLlamacppError).toEqual({})+ })+})++describe('useCoworkRun - per-session loading state', () => {+ beforeEach(() => {+ useCoworkRun.setState({ loadingModels: {}, modelLoadProgress: {} })+ })++ it('sets and unsets the loading flag per session', () => {+ useCoworkRun.getState().setSessionLoadingModel('session-a', true)+ expect(useCoworkRun.getState().loadingModels).toEqual({ 'session-a': true })++ useCoworkRun.getState().setSessionLoadingModel('session-a', false)+ // Absent, not `false` — mirrors useAppState's own loadingModels+ // convention (key presence, not a boolean value, is the signal).+ expect(useCoworkRun.getState().loadingModels).toEqual({})+ })++ it('sets and clears load progress per session', () => {+ useCoworkRun+ .getState()+ .setSessionModelLoadProgress('session-a', { modelId: 'model-1', value: 0.4 })+ expect(useCoworkRun.getState().modelLoadProgress['session-a']).toEqual({+ modelId: 'model-1',+ value: 0.4,+ })++ useCoworkRun.getState().setSessionModelLoadProgress('session-a', undefined)+ expect(useCoworkRun.getState().modelLoadProgress).toEqual({})+ })++ it('keeps two sessions\' loading state independent', () => {+ useCoworkRun.getState().setSessionLoadingModel('session-a', true)+ useCoworkRun.getState().setSessionLoadingModel('session-b', true)++ useCoworkRun.getState().setSessionLoadingModel('session-a', false)++ expect(useCoworkRun.getState().loadingModels).toEqual({ 'session-b': true })+ })++ it('clearCodeRun sweeps up per-session loading state too', () => {+ useCoworkRun.getState().setSessionLoadingModel('session-a', true)+ useCoworkRun+ .getState()+ .setSessionModelLoadProgress('session-a', { modelId: 'model-1', value: 0.4 })++ useCoworkRun.getState().clearCodeRun('session-a')++ expect(useCoworkRun.getState().loadingModels).toEqual({})+ expect(useCoworkRun.getState().modelLoadProgress).toEqual({})+ })+})++describe('useCoworkRun - subagent lanes', () => {+ it('empties only the given session at the start of a run', () => {+ useCoworkRun.getState().startSubagent('s1', 'r1', 'researcher')+ useCoworkRun.getState().startSubagent('s2', 'r2', 'reviewer')+ useCoworkRun.getState().resetSubagents('s1')+ expect(useCoworkRun.getState().subagents.s1).toEqual([])+ // A background session's children must survive another session's new run.+ expect(useCoworkRun.getState().subagents.s2).toHaveLength(1)+ })++ it('keeps concurrent children in separate lanes', () => {+ useCoworkRun.getState().resetSubagents('s3')+ useCoworkRun.getState().startSubagent('s3', 'a', 'one')+ useCoworkRun.getState().startSubagent('s3', 'b', 'two')+ useCoworkRun.getState().routeIntoSubagent('s3', 'a', {+ type: 'token',+ text: 'from a',+ })+ const runs = useCoworkRun.getState().subagents.s3+ expect(runs.find((r) => r.runId === 'a')?.turns[0].content).toBe('from a')+ expect(runs.find((r) => r.runId === 'b')?.turns).toEqual([])+ })+})diff --git a/web-app/src/hooks/__tests__/useCodeSessions.test.ts b/web-app/src/hooks/__tests__/useCoworkSessions.test.tssimilarity index 59%rename from web-app/src/hooks/__tests__/useCodeSessions.test.tsrename to web-app/src/hooks/__tests__/useCoworkSessions.test.tsindex 9bd821530..8806decdf 100644--- a/web-app/src/hooks/__tests__/useCodeSessions.test.ts+++ b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts@@ -8,10 +8,10 @@ vi.mock('@/lib/backendStorage', () => ({},}))-import { useCodeSessions } from '../useCodeSessions'-import type { CodeTurn, SubagentRun } from '@/types/codeSession'+import { useCoworkSessions } from '../useCoworkSessions'+import type { CoworkTurn, SubagentRun } from '@/types/coworkSession'-const reset = () => useCodeSessions.setState({ sessions: [], currentId: null })+const reset = () => useCoworkSessions.setState({ sessions: [], currentId: null })const sub = (runId: string, name: string): SubagentRun => ({runId,@@ -21,23 +21,23 @@ const sub = (runId: string, name: string): SubagentRun => ({turns: [],})-describe('useCodeSessions', () => {+describe('useCoworkSessions', () => {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)!+ const id = useCoworkSessions.getState().createSession()+ const s = useCoworkSessions.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 id = useCoworkSessions.getState().createSession()+ const turn: CoworkTurn = { 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)!+ useCoworkSessions.getState().commitTurns(id, [turn], msgs, [])+ useCoworkSessions.getState().commitTurns(id, [turn], msgs, [])+ const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!expect(s.turns).toHaveLength(2)expect(s.messages).toHaveLength(1)})@@ -45,29 +45,29 @@ describe('useCodeSessions', () => {// 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)!+ const id = useCoworkSessions.getState().createSession()+ useCoworkSessions.getState().commitTurns(id, [], [], [sub('r1', 'alpha')])+ useCoworkSessions.getState().commitTurns(id, [], [], [])+ let s = useCoworkSessions.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)!+ useCoworkSessions.getState().commitTurns(id, [], [], [sub('r1', 'renamed')])+ s = useCoworkSessions.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)!+ const id = useCoworkSessions.getState().createSession()+ useCoworkSessions.getState().commitTurns(id, [], [], [], { total_tokens: 42 })+ useCoworkSessions.getState().commitTurns(id, [], [], [])+ const s = useCoworkSessions.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+ const id = useCoworkSessions.getState().createSession()+ useCoworkSessions.getState().commitTurns(id,@@ -76,8 +76,8 @@ describe('useCodeSessions', () => {[sub('r1', 'alpha')],{ total_tokens: 1 })- useCodeSessions.getState().clearSession(id)- const s = useCodeSessions.getState().sessions.find((x) => x.id === id)!+ useCoworkSessions.getState().clearSession(id)+ const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!expect(s.turns).toEqual([])expect(s.messages).toEqual([])expect(s.subagents).toEqual([])@@ -85,24 +85,24 @@ describe('useCodeSessions', () => {})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)!+ const id = useCoworkSessions.getState().createSession()+ useCoworkSessions.getState().setPlanMode(id, true)+ useCoworkSessions.getState().setFolder(id, '/tmp/project')+ let s = useCoworkSessions.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)!+ useCoworkSessions.getState().setFolder(id, null)+ s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!expect(s.folder).toBeNull()})})-describe('useCodeSessions persist migration', () => {+describe('useCoworkSessions 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 migrate = useCoworkSessions.persist.getOptions().migrate!const out = migrate({sessions: [@@ -136,7 +136,7 @@ describe('useCodeSessions persist migration', () => {})it('leaves an already-migrated session alone', () => {- const migrate = useCodeSessions.persist.getOptions().migrate!+ const migrate = useCoworkSessions.persist.getOptions().migrate!const existing = [{ id: 's1', turns: [], messages: [{ id: 'keep' }] }]const out = migrate({ sessions: existing }, 1) as {sessions: Array<{ messages: Array<{ id: string }> }>diff --git a/web-app/src/hooks/__tests__/useTokensCount.test.ts b/web-app/src/hooks/__tests__/useTokensCount.test.tsindex ef5399332..2bd9cbe54 100644--- a/web-app/src/hooks/__tests__/useTokensCount.test.ts+++ b/web-app/src/hooks/__tests__/useTokensCount.test.ts@@ -192,6 +192,47 @@ describe('useTokensCount', () => {expect(result.current.percentage).toBeUndefined()})+ // Cowork keeps its own turns, not ThreadMessages, so it reports usage+ // directly rather than synthesising messages to carry it.+ describe('direct usage source', () => {+ it('counts tokens for a remote provider with no messages at all', () => {+ modelProviderState.selectedProvider = 'anthropic'+ const { result } = renderHook(() =>+ useTokensCount([], {+ threadId: 'session-1',+ usage: { inputTokens: 900, outputTokens: 100, totalTokens: 1000 },+ })+ )+ expect(result.current.tokenCount).toBe(1000)+ expect(result.current.inputTokens).toBe(900)+ })++ it('measures a local run against the context window', async () => {+ modelProviderState.selectedProvider = 'llamacpp'+ const { result } = renderHook(() =>+ useTokensCount([], {+ threadId: 'session-1',+ usage: { inputTokens: 400, outputTokens: 100, totalTokens: 500 },+ })+ )+ await waitFor(() => expect(result.current.modelProps).toBeDefined())+ expect(result.current.tokenCount).toBe(500)+ expect(result.current.maxTokens).toBe(1000)+ expect(result.current.percentage).toBe(50)+ })++ // Otherwise a surface passing both would read a stale number off the+ // messages while its own is fresher.+ it('wins over usage found on the messages', () => {+ modelProviderState.selectedProvider = 'anthropic'+ const messages = [makeMessage({ metadata: { usage: { totalTokens: 7 } } })]+ const { result } = renderHook(() =>+ useTokensCount(messages, { usage: { totalTokens: 4242 } })+ )+ expect(result.current.tokenCount).toBe(4242)+ })+ })+it('context overflow still works when there are no live stats at all', async () => {const messages = [makeMessage({diff --git a/web-app/src/hooks/useCodeRun.ts b/web-app/src/hooks/useCoworkRun.tssimilarity index 93%rename from web-app/src/hooks/useCodeRun.tsrename to web-app/src/hooks/useCoworkRun.tsindex 65e441b81..b1e2e6576 100644--- a/web-app/src/hooks/useCodeRun.ts+++ b/web-app/src/hooks/useCoworkRun.ts@@ -1,11 +1,11 @@import { create } from 'zustand'import type {- CodeTurn,+ CoworkTurn,SubagentRun,Usage,TodoList,AskRequestPayload,-} from '@/types/codeSession'+} from '@/types/coworkSession'import type { ModelLoadProgress } from '@/hooks/useAppState'// The ask shapes live in the store-free types module; re-exported here because@@ -15,7 +15,7 @@ export type {AskQuestion,AskRequestPayload,AskAnswer,-} from '@/types/codeSession'+} from '@/types/coworkSession'// StreamEvent shapes emitted by the Rust agent loop (events.rs, tag = "type").// Owned here because this store is what consumes/dispatches them.@@ -39,7 +39,7 @@ export type 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[] {+function appendAssistantToken(turns: CoworkTurn[], text: string): CoworkTurn[] {const last = turns[turns.length - 1]if (last && last.role === 'assistant')return [...turns.slice(0, -1), { ...last, content: last.content + text }]@@ -47,12 +47,12 @@ function appendAssistantToken(turns: CodeTurn[], text: string): CodeTurn[] {}// 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.+// pushToolTurn call site (cowork.tsx) and a subagent's wrapped tool_call.export function makeToolCallTurn(ev: {id: stringname: stringargs: unknown-}): CodeTurn {+}): CoworkTurn {return {role: 'tool',content: '',@@ -67,10 +67,10 @@ export function makeToolCallTurn(ev: {// 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[],+ turns: CoworkTurn[],callId: string,- patch: Partial<CodeTurn>-): CodeTurn[] {+ patch: Partial<CoworkTurn>+): CoworkTurn[] {const idx = turns.findIndex((tn) => tn.role === 'tool' && tn.callId === callId)if (idx === -1) return turnsreturn [...turns.slice(0, idx), { ...turns[idx], ...patch }, ...turns.slice(idx + 1)]@@ -78,7 +78,7 @@ function mergeToolResult(// 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[] {+function applyInnerToTurns(turns: CoworkTurn[], inner: StreamEvent): CoworkTurn[] {switch (inner.type) {case 'token':return appendAssistantToken(turns, inner.text)@@ -116,7 +116,7 @@ function omitKey<T>(map: Record<string, T>, key: string): Record<string, T> {return next}-// Transient (non-persisted) run state for the Code UI, keyed by session id —+// Transient (non-persisted) run state for the Cowork 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.@@ -124,8 +124,8 @@ function omitKey<T>(map: Record<string, T>, key: string): Record<string, T> {// 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[]>+type CoworkRunState = {+ liveTurns: Record<string, CoworkTurn[]>subagents: Record<string, SubagentRun[]>runId: Record<string, string>// In-flight `ask` tool questions per session. A subagent's wrapped ask is@@ -162,13 +162,16 @@ type CodeRunState = {beginRun: (sid: string, runId: string, userText: string, images?: string[]) => voidappendToken: (sid: string, text: string) => void- pushToolTurn: (sid: string, turn: CodeTurn) => void- updateToolTurn: (sid: string, callId: string, patch: Partial<CodeTurn>) => void+ pushToolTurn: (sid: string, turn: CoworkTurn) => void+ updateToolTurn: (sid: string, callId: string, patch: Partial<CoworkTurn>) => 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+ /** Empty a session's subagent lanes at the start of a run, so the panel shows+ * this run's children rather than every child the session ever had. */+ resetSubagents: (sid: string) => voidstartSubagent: (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@@ -195,11 +198,11 @@ type CodeRunState = {// 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[] }+ finalizeRun: (sid: string) => { turns: CoworkTurn[]; subagents: SubagentRun[] }clearCodeRun: (sid: string) => void}-export const useCodeRun = create<CodeRunState>()((set, get) => ({+export const useCoworkRun = create<CoworkRunState>()((set, get) => ({liveTurns: {},subagents: {},runId: {},@@ -271,6 +274,9 @@ export const useCodeRun = create<CodeRunState>()((set, get) => ({}}),+ resetSubagents: (sid) =>+ set((s) => ({ subagents: { ...s.subagents, [sid]: [] } })),+startSubagent: (sid, runId, name) =>set((s) => {const runs = s.subagents[sid] ?? []@@ -412,7 +418,7 @@ export const useCodeRun = create<CodeRunState>()((set, get) => ({// 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) =>+ const turns: CoworkTurn[] = (get().liveTurns[sid] ?? []).map((tn) =>tn.role === 'tool' && tn.status === 'running'? { ...tn, status: 'done' as const, isError: true, result: tn.result || '(interrupted)' }: tn@@ -445,5 +451,5 @@ export const useCodeRun = create<CodeRunState>()((set, get) => ({// 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))+ useCoworkRun((s) => (sid ? s.runId[sid] != null : false))diff --git a/web-app/src/hooks/useCodeSessions.ts b/web-app/src/hooks/useCoworkSessions.tssimilarity index 87%rename from web-app/src/hooks/useCodeSessions.tsrename to web-app/src/hooks/useCoworkSessions.tsindex 11aa6ed29..339ca90bc 100644--- a/web-app/src/hooks/useCodeSessions.ts+++ b/web-app/src/hooks/useCoworkSessions.ts@@ -3,57 +3,57 @@ 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 { coworkTurnsToUIMessages } from '@/lib/coworkTurns'import type {- CodeTurn,+ CoworkTurn,SubagentRun,Usage,- CodeGoal,+ CoworkGoal,TodoList,-} from '@/types/codeSession'+} from '@/types/coworkSession'// 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,+ CoworkTurn,Usage,SubagentRun,TodoStatus,TodoItem,TodoPhase,TodoList,- CodeGoal,-} from '@/types/codeSession'+ CoworkGoal,+} from '@/types/coworkSession'/**- * @deprecated Superseded by `CodeSession.messages`. This shape cannot model+ * @deprecated Superseded by `CoworkSession.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 = {+export type CoworkMessage = {role: 'user' | 'assistant'content: string}-export type CodeSession = {+export type CoworkSession = {id: stringtitle: string/** An attached project folder, mounted read-only. Writes always land in the* session's own sandbox, never here. */folder: string | null- turns: CodeTurn[]+ turns: CoworkTurn[]/** The authoritative conversation, sent to the model each turn. */messages: UIMessage[]/** @deprecated Read once to migrate into `messages`, then left alone. */- history?: CodeMessage[]+ history?: CoworkMessage[]/** 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+ goal?: CoworkGoal/** Canonical session todo list, updated by the `todo_write` tool. */todos?: TodoList/** Plan mode: the agent reads and proposes, without writing. Absent means off. */@@ -61,8 +61,8 @@ export type CodeSession = {updated: number}-type CodeSessionsState = {- sessions: CodeSession[]+type CoworkSessionsState = {+ sessions: CoworkSession[]currentId: string | nullcreateSession: () => stringselectSession: (id: string) => void@@ -71,20 +71,20 @@ type CodeSessionsState = {setPlanMode: (id: string, planMode: boolean) => voidsetTitle: (id: string, title: string) => voidsetMessages: (id: string, messages: UIMessage[]) => void- setGoal: (id: string, goal: CodeGoal | null) => void+ setGoal: (id: string, goal: CoworkGoal | null) => voidsetTodos: (id: string, todos: TodoList) => void/**- * @deprecated Bridge for the pre-AI-SDK code route, which has no+ * @deprecated Bridge for the pre-AI-SDK Cowork route, which has no* `UIMessage[]` to commit. Removed together with that route.*/commitLegacyTurns: (id: string,- turns: CodeTurn[],- history: CodeMessage[]+ turns: CoworkTurn[],+ history: CoworkMessage[]) => voidcommitTurns: (id: string,- turns: CodeTurn[],+ turns: CoworkTurn[],messages: UIMessage[],subagents: SubagentRun[],usage?: Usage@@ -94,7 +94,7 @@ type CodeSessionsState = {const now = () => Date.now()-export const useCodeSessions = create<CodeSessionsState>()(+export const useCoworkSessions = create<CoworkSessionsState>()(persist((set) => ({sessions: [],@@ -102,7 +102,7 @@ export const useCodeSessions = create<CodeSessionsState>()(createSession: () => {const id = crypto.randomUUID()- const session: CodeSession = {+ const session: CoworkSession = {id,title: 'New session',folder: null,@@ -210,7 +210,7 @@ export const useCodeSessions = create<CodeSessionsState>()(})),}),{- name: localStorageKey.codeSessions,+ name: localStorageKey.coworkSessions,// Persist through the Rust settings store (see backendStorage) so sessions// live in <jan_data>/settings.json instead of webview localStorage.// Async storage requires skipHydration + explicit rehydrate in@@ -223,7 +223,7 @@ export const useCodeSessions = create<CodeSessionsState>()(// 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+ const state = persisted as { sessions?: CoworkSession[] } | undefinedif (version >= 1 || !state?.sessions) return persistedreturn {...state,@@ -232,7 +232,7 @@ export const useCodeSessions = create<CodeSessionsState>()(? session: {...session,- messages: codeTurnsToUIMessages(session.turns ?? [], session.id),+ messages: coworkTurnsToUIMessages(session.turns ?? [], session.id),}),}@@ -243,7 +243,7 @@ export const useCodeSessions = create<CodeSessionsState>()(/** Return the current session, creating one if none is selected. */export function ensureCurrentSession(): string {- const { currentId, sessions, createSession } = useCodeSessions.getState()+ const { currentId, sessions, createSession } = useCoworkSessions.getState()if (currentId && sessions.some((s) => s.id === currentId)) return currentIdreturn createSession()}diff --git a/web-app/src/hooks/useTokensCount.ts b/web-app/src/hooks/useTokensCount.tsindex 9bfe7a2bb..f121546be 100644--- a/web-app/src/hooks/useTokensCount.ts+++ b/web-app/src/hooks/useTokensCount.ts@@ -27,12 +27,24 @@ export interface TokenCountData {isOverflow?: boolean}-interface UsageMeta {+export interface UsageMeta {inputTokens?: numberoutputTokens?: numbertotalTokens?: number}+/**+ * Usage for a surface that keeps no `ThreadMessage`s.+ *+ * Cowork stores its transcript as its own turns, so there is nothing to scan+ * for `metadata.usage`. It reports the same two facts directly rather than+ * synthesising thread messages to carry them.+ */+export interface TokenUsageSource {+ threadId?: string+ usage?: UsageMeta+}+// The token-usage popup normally reflects the last *successful* turn. When a// request overflows, that turn is never recorded, so the popup would keep// showing a comfortable percentage next to an "out of context" error. Parse@@ -66,7 +78,10 @@ const readSettingNumber = (v: unknown): number | undefined => {return undefined}-export const useTokensCount = (messages: ThreadMessage[] = []) => {+export const useTokensCount = (+ messages: ThreadMessage[] = [],+ source?: TokenUsageSource+) => {const { selectedModel, selectedProvider, getProviderByName } =useModelProvider()const [modelProps, setModelProps] = useState<ModelProps | undefined>(@@ -79,7 +94,7 @@ export const useTokensCount = (messages: ThreadMessage[] = []) => {selectedProvider === 'llamacpp' || selectedProvider === 'mlx'const modelId = isLocalProvider ? selectedModel?.id : undefined- const threadId = messages[0]?.thread_id+ const threadId = source?.threadId ?? messages[0]?.thread_id// Populated per-chunk while a llama.cpp turn is streaming (timings_per_token);// cleared on stream start/finish/error, so its presence means "live now".const liveStats = useAppState((s) =>@@ -132,7 +147,7 @@ export const useTokensCount = (messages: ThreadMessage[] = []) => {fitEnabled: false,}}- const usage = getLatestServerUsage(messages)+ const usage = source?.usage ?? getLatestServerUsage(messages)return {tokenCount: usage.totalTokens ?? 0,inputTokens: usage.inputTokens,@@ -158,7 +173,7 @@ export const useTokensCount = (messages: ThreadMessage[] = []) => {outputTokens: liveStats.completionTokens,totalTokens: liveStats.promptTokens + liveStats.completionTokens,}- : getLatestServerUsage(messages)+ : (source?.usage ?? getLatestServerUsage(messages))const tokenCount = overflow?.requestTokens ?? usage.totalTokens ?? 0const maxTokens = overflow?.contextTokens ?? modelProps?.nCtxconst percentage = maxTokens ? (tokenCount / maxTokens) * 100 : undefined@@ -196,6 +211,7 @@ export const useTokensCount = (messages: ThreadMessage[] = []) => {}}, [messages,+ source,modelId,selectedProvider,isLocalProvider,diff --git a/web-app/src/i18n/__tests__/keys.test.ts b/web-app/src/i18n/__tests__/keys.test.tsindex fe923e516..e6fa488cf 100644--- a/web-app/src/i18n/__tests__/keys.test.ts+++ b/web-app/src/i18n/__tests__/keys.test.ts@@ -35,19 +35,33 @@ const sourceFiles = (dir: string): string[] =>return /\.tsx?$/.test(e.name) && !/\.test\.tsx?$/.test(e.name) ? [full] : []})-const resolves = (+const lookup = (bundle: Record<string, unknown>,ns: string,key: string-): boolean => {+): unknown => {let cur: unknown = bundle[ns]for (const part of key.split('.')) {- if (typeof cur !== 'object' || cur === null || !(part in cur)) return false+ if (typeof cur !== 'object' || cur === null || !(part in cur)) return undefinedcur = (cur as Record<string, unknown>)[part]}- return typeof cur === 'string'+ return cur}+/**+ * A count-aware key is stored as `_one`/`_other` so i18next can pick the form,+ * never under its own name. Without this the only way to satisfy the scan is to+ * drop the namespace prefix and fall out of it entirely.+ */+const resolves = (+ bundle: Record<string, unknown>,+ ns: string,+ key: string+): boolean =>+ typeof lookup(bundle, ns, key) === 'string' ||+ (typeof lookup(bundle, ns, `${key}_one`) === 'string' &&+ typeof lookup(bundle, ns, `${key}_other`) === 'string')+// Only literal keys; dynamically-built ones can't be checked statically.const KEY_CALL = /t\(\s*['"]([a-zA-Z0-9_-]+):([a-zA-Z0-9_.]+)['"]/gdiff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.tsindex 9ebbb1656..d8f7996c3 100644--- a/web-app/src/lib/__tests__/agentTools.test.ts+++ b/web-app/src/lib/__tests__/agentTools.test.ts@@ -134,7 +134,8 @@ describe('agentTools', () => {undefined,undefined,false,- undefined+ undefined,+ 'thread')useAgentToolsConfig.getState().setBashNetworkEnabled(true)@@ -147,7 +148,8 @@ describe('agentTools', () => {undefined,undefined,true,- undefined+ undefined,+ 'thread')useAgentToolsConfig.getState().setBashNetworkEnabled(false)})@@ -180,7 +182,8 @@ describe('agentTools', () => {undefined,undefined,false,- undefined+ undefined,+ 'thread')})@@ -202,7 +205,8 @@ describe('agentTools', () => {undefined,undefined,false,- '/home/u/repo'+ '/home/u/repo',+ 'thread')})@@ -257,7 +261,8 @@ describe('agentTools', () => {undefined,undefined,false,- undefined+ undefined,+ 'thread')})diff --git a/web-app/src/lib/__tests__/codeArtifacts.test.ts b/web-app/src/lib/__tests__/coworkArtifacts.test.tssimilarity index 97%rename from web-app/src/lib/__tests__/codeArtifacts.test.tsrename to web-app/src/lib/__tests__/coworkArtifacts.test.tsindex 7b7ed4e0d..6a956bd2e 100644--- a/web-app/src/lib/__tests__/codeArtifacts.test.ts+++ b/web-app/src/lib/__tests__/coworkArtifacts.test.ts@@ -5,8 +5,8 @@ import {isArtifactPath,artifactsFromParts,artifactsFromTurns,-} from '@/lib/codeArtifacts'-import type { CodeTurn } from '@/hooks/useCodeSessions'+} from '@/lib/coworkArtifacts'+import type { CoworkTurn } from '@/hooks/useCoworkSessions'const write = (path: string, state = 'output-available', output = `Created ${path} (10 bytes)`) => ({type: 'tool-write',@@ -117,7 +117,7 @@ describe('artifactsFromParts', () => {})describe('artifactsFromTurns', () => {- const toolTurn = (name: string, path: string, extra: Partial<CodeTurn> = {}) =>+ const toolTurn = (name: string, path: string, extra: Partial<CoworkTurn> = {}) =>({role: 'tool',content: '',@@ -126,7 +126,7 @@ describe('artifactsFromTurns', () => {status: 'done',result: `Created ${path} (10 bytes)`,...extra,- }) as CodeTurn+ }) as CoworkTurnit('reads write/edit artifacts straight off session turns', () => {const turns = [@@ -134,7 +134,7 @@ describe('artifactsFromTurns', () => {toolTurn('write', 'index.html'),toolTurn('write', 'package.json'),toolTurn('read', 'index.html'),- ] as CodeTurn[]+ ] as CoworkTurn[]expect(artifactsFromTurns(turns).map((a) => a.path)).toEqual(['index.html'])})@@ -194,7 +194,7 @@ describe('artifactsFromTurns', () => {isError: false,result:'[download] Destination: /Users/thinhlpg/Desktop/Rick Astley - Never Gonna Give You Up.mp4\n[download] 100% of 11MiB',- } as CodeTurn,+ } as CoworkTurn,]const artifacts = artifactsFromTurns(turns, '/Users/thinhlpg/Desktop')expect(artifacts).toHaveLength(1)@@ -212,7 +212,7 @@ describe('artifactsFromTurns', () => {status: 'done',isError: false,result: '-rw-r--r--@ 1 u staff 144K Aug 6 11:50 cat_video.mp4',- } as CodeTurn,+ } as CoworkTurn,]const artifacts = artifactsFromTurns(turns, '/p')expect(artifacts).toHaveLength(1)@@ -229,7 +229,7 @@ describe('artifactsFromTurns', () => {status: 'done',isError: false,result: '-rw-r--r--@ 1 u staff 144K Aug 6 11:50 /p/cat_video.mp4',- } as CodeTurn,+ } as CoworkTurn,]const artifacts = artifactsFromTurns(turns, '/p')expect(artifacts).toHaveLength(1)@@ -246,7 +246,7 @@ describe('artifactsFromTurns', () => {status: 'done',isError: false,result: '/opt/homebrew/bin/yt-dlp\n/opt/homebrew/bin/ffmpeg',- } as CodeTurn,+ } as CoworkTurn,]expect(artifactsFromTurns(turns, '/p')).toEqual([])})@@ -261,7 +261,7 @@ describe('artifactsFromTurns', () => {status: 'done',isError: true,result: "can't open file 'make.py': No such file",- } as CodeTurn,+ } as CoworkTurn,]expect(artifactsFromTurns(turns, '/p')).toEqual([])})diff --git a/web-app/src/lib/__tests__/coworkBudget.test.ts b/web-app/src/lib/__tests__/coworkBudget.test.tsindex 2f68e0147..5d6a3f21b 100644--- a/web-app/src/lib/__tests__/coworkBudget.test.ts+++ b/web-app/src/lib/__tests__/coworkBudget.test.ts@@ -1,6 +1,8 @@import { describe, it, expect } from 'vitest'import {budgetExceeded,+ newSpend,+ recordSpend,MAX_AGENT_STEPS,MAX_SUBAGENT_STEPS,MAX_SESSION_TOKENS,@@ -51,3 +53,64 @@ describe('budgetExceeded', () => {expect(MAX_SUBAGENT_STEPS).toBeLessThan(MAX_AGENT_STEPS)})})++describe('recordSpend', () => {+ // The bug this exists to prevent: every step of an agent turn replays the+ // whole conversation, so summing each step's total_tokens charges the same+ // context once per step and trips a 200k cap ten steps into a 100-step run.+ it('charges prompt growth once, not the replayed prompt every step', () => {+ let s = newSpend()+ s = recordSpend(s, {+ prompt_tokens: 10_000,+ completion_tokens: 200,+ total_tokens: 10_200,+ })+ expect(s.spent).toBe(10_200)+ // Step two replays the same 10k prompt plus the previous output.+ s = recordSpend(s, {+ prompt_tokens: 10_400,+ completion_tokens: 300,+ total_tokens: 10_700,+ })+ // 300 new output + 400 of prompt growth, not another 10,700.+ expect(s.spent).toBe(10_900)+ })++ it('never charges negative growth when the prompt shrinks after a compaction', () => {+ let s = newSpend()+ s = recordSpend(s, {+ prompt_tokens: 10_000,+ completion_tokens: 100,+ total_tokens: 10_100,+ })+ s = recordSpend(s, {+ prompt_tokens: 4_000,+ completion_tokens: 50,+ total_tokens: 4_050,+ })+ expect(s.spent).toBe(10_150)+ })++ it('falls back to the total delta when the provider omits the breakdown', () => {+ let s = newSpend()+ s = recordSpend(s, { total_tokens: 500 })+ s = recordSpend(s, { total_tokens: 900 })+ expect(s.spent).toBe(900)+ })++ it('falls back to completion tokens when there is no total', () => {+ let s = newSpend()+ s = recordSpend(s, { completion_tokens: 40 })+ s = recordSpend(s, { completion_tokens: 60 })+ expect(s.spent).toBe(100)+ })++ it('leaves the spend untouched when a step reports no usage', () => {+ const s = recordSpend(newSpend(77), null)+ expect(s.spent).toBe(77)+ })++ it('carries a starting spend', () => {+ expect(newSpend(1_000).spent).toBe(1_000)+ })+})diff --git a/web-app/src/lib/__tests__/codeDiffs.test.ts b/web-app/src/lib/__tests__/coworkDiffs.test.tssimilarity index 95%rename from web-app/src/lib/__tests__/codeDiffs.test.tsrename to web-app/src/lib/__tests__/coworkDiffs.test.tsindex 1ea87cefe..9113852ee 100644--- a/web-app/src/lib/__tests__/codeDiffs.test.ts+++ b/web-app/src/lib/__tests__/coworkDiffs.test.ts@@ -1,12 +1,12 @@import { describe, expect, it } from 'vitest'-import { collectCodeFileDiffs } from '@/lib/codeDiffs'-import type { CodeTurn, SubagentRun } from '@/hooks/useCodeSessions'+import { collectCodeFileDiffs } from '@/lib/coworkDiffs'+import type { CoworkTurn, SubagentRun } from '@/hooks/useCoworkSessions'const edit = (path: unknown,diff: string,- extra: Partial<CodeTurn> = {}-): CodeTurn => ({+ extra: Partial<CoworkTurn> = {}+): CoworkTurn => ({role: 'tool',content: '',name: 'edit',diff --git a/web-app/src/lib/__tests__/coworkDispatch.test.ts b/web-app/src/lib/__tests__/coworkDispatch.test.tsindex c3ee4d7d7..ffeb294de 100644--- a/web-app/src/lib/__tests__/coworkDispatch.test.ts+++ b/web-app/src/lib/__tests__/coworkDispatch.test.ts@@ -3,6 +3,12 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'const { executeAgentTool } = vi.hoisted(() => ({ executeAgentTool: vi.fn() }))vi.mock('@/lib/agentTools', () => ({ executeAgentTool }))+const { executeWebTool } = vi.hoisted(() => ({ executeWebTool: vi.fn() }))+vi.mock('@/lib/webSearchTool', () => ({+ WEB_TOOL_NAMES: new Set(['web_search', 'web_fetch']),+ executeWebTool,+}))+import { dispatchCoworkTool } from '../coworkDispatch'import type { PendingToolCall } from '../coworkRunner'@@ -16,6 +22,7 @@ const ctx = (over = {}) => ({sessionId: 's1',readOnlyFolder: null,planMode: false,+ webSearch: false,onTodo: vi.fn(async () => ({ output: 'todo ok' })),onAsk: vi.fn(async () => ({ output: 'ask ok' })),onTask: vi.fn(async () => ({ output: 'task ok' })),@@ -28,6 +35,9 @@ describe('dispatchCoworkTool', () => {executeAgentTool.mockResolvedValue({ content: 'ok' })})+ // The trailing 'session' is load-bearing: under the default 'thread' scope a+ // session's files land where the thread sweep's keep-list can never mention+ // them, and the sweep deletes the only copy of the agent's work.it('routes built-ins to the Rust plugin with the session as workspace key', async () => {const c = ctx()await dispatchCoworkTool(call('read', { path: 'a' }), c)@@ -35,7 +45,8 @@ describe('dispatchCoworkTool', () => {'read',{ path: 'a' },'s1',- null+ null,+ 'session')})@@ -65,7 +76,13 @@ describe('dispatchCoworkTool', () => {it('passes the attached folder through', async () => {await dispatchCoworkTool(call('grep'), ctx({ readOnlyFolder: '/repo' }))- expect(executeAgentTool).toHaveBeenCalledWith('grep', {}, 's1', '/repo')+ expect(executeAgentTool).toHaveBeenCalledWith(+ 'grep',+ {},+ 's1',+ '/repo',+ 'session'+ )})it('carries the display diff without putting it in the output', async () => {@@ -92,3 +109,38 @@ describe('dispatchCoworkTool', () => {expect(out).toEqual({ output: 'ipc died', isError: true })})})++describe('web tools', () => {+ beforeEach(() => executeWebTool.mockReset())++ it('routes a web call to the websearch plugin', async () => {+ executeWebTool.mockResolvedValue({ content: { kind: 'web', results: [] } })+ const out = await dispatchCoworkTool(+ call('web_search', { query: 'jan' }),+ ctx({ webSearch: true })+ )+ expect(executeWebTool).toHaveBeenCalledWith('web_search', { query: 'jan' })+ // Serialized, not passed through: the model gets a string, and the citation+ // parser re-parses it for the source chips.+ expect(JSON.parse(out.output)).toMatchObject({ kind: 'web' })+ expect(out.isError).toBeFalsy()+ })++ // Withholding is not authoritative -- a model can call a tool that was never+ // advertised -- so an off switch in Settings is enforced here too.+ it('refuses without reaching the network when web search is off', async () => {+ const out = await dispatchCoworkTool(call('web_search'), ctx())+ expect(executeWebTool).not.toHaveBeenCalled()+ expect(out.isError).toBe(true)+ expect(out.output).toContain('Settings')+ })++ it('reports a plugin failure as a tool error', async () => {+ executeWebTool.mockResolvedValue({ error: 'no API key' })+ const out = await dispatchCoworkTool(+ call('web_fetch', { url: 'https://x.dev' }),+ ctx({ webSearch: true })+ )+ expect(out).toMatchObject({ output: 'no API key', isError: true })+ })+})diff --git a/web-app/src/lib/__tests__/codePreview.test.ts b/web-app/src/lib/__tests__/coworkPreview.test.tssimilarity index 99%rename from web-app/src/lib/__tests__/codePreview.test.tsrename to web-app/src/lib/__tests__/coworkPreview.test.tsindex 2696f90cc..8d4faa578 100644--- a/web-app/src/lib/__tests__/codePreview.test.ts+++ b/web-app/src/lib/__tests__/coworkPreview.test.ts@@ -6,7 +6,7 @@ import {isAssetKind,unresolvedRefs,resolveInRoot,-} from '@/lib/codePreview'+} from '@/lib/coworkPreview'describe('previewKindFor', () => {it('maps the renderable types', () => {diff --git a/web-app/src/lib/__tests__/coworkPrompt.test.ts b/web-app/src/lib/__tests__/coworkPrompt.test.tsindex 678d37acd..135df99f3 100644--- a/web-app/src/lib/__tests__/coworkPrompt.test.ts+++ b/web-app/src/lib/__tests__/coworkPrompt.test.ts@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest'import {buildCoworkSystemPrompt,+ buildSubagentSystemPrompt,PLAN_REVIEW_QUESTION_ID,} from '../coworkPrompt'@@ -8,6 +9,7 @@ const opts = (over = {}) => ({workspacePath: '/data/agent-workspace/sessions/s1',readOnlyFolder: null,planMode: false,+ webSearch: false,bashAvailable: true,subagentNames: [],...over,@@ -59,3 +61,57 @@ describe('buildCoworkSystemPrompt', () => {expect(buildCoworkSystemPrompt(opts())).not.toContain('# Subagents')})})++describe('buildSubagentSystemPrompt', () => {+ const opts = {+ workspacePath: '/ws/s1',+ readOnlyFolder: '/home/me/repo',+ bashAvailable: true,+ }++ it('keeps the definition prompt and adds the workspace facts', () => {+ const out = buildSubagentSystemPrompt('You review Rust.', opts)+ expect(out).toContain('You review Rust.')+ // The Rust `system_prompt_override` replaces the whole prompt, which works+ // for the CLI (cwd is the project) but leaves a desktop child unable to+ // guess its sandbox path.+ expect(out).toContain('/ws/s1')+ expect(out).toContain('READ-ONLY')+ })++ it('states the three things a child cannot do', () => {+ const out = buildSubagentSystemPrompt('p', opts)+ expect(out).toContain('cannot see the conversation')+ expect(out).toContain('cannot ask the user')+ expect(out).toContain('cannot dispatch')+ })++ it('never leaks plan mode or a subagent roster into a child', () => {+ const out = buildSubagentSystemPrompt('p', opts)+ expect(out).not.toContain('PLAN MODE')+ expect(out).not.toContain('# Subagents')+ })++ // A child whose allowlist dropped the web tools must not be told it has them.+ it('describes web access only when the child kept the tools', () => {+ expect(buildSubagentSystemPrompt('p', { ...opts, webSearch: true })).toContain(+ '# Web'+ )+ expect(buildSubagentSystemPrompt('p', opts)).not.toContain('# Web')+ })+})++describe('web block', () => {+ it('is absent when web search is off', () => {+ expect(buildCoworkSystemPrompt(opts())).not.toContain('# Web')+ })++ // The marker has to match chat's, or the renderer shows raw text instead of+ // source chips.+ it('names both tools and the citation marker when on', () => {+ const p = buildCoworkSystemPrompt(opts({ webSearch: true }))+ expect(p).toContain('web_search')+ expect(p).toContain('web_fetch')+ expect(p).toContain('[[cite:URL]]')+ })+})diff --git a/web-app/src/lib/__tests__/coworkRunner.test.ts b/web-app/src/lib/__tests__/coworkRunner.test.tsindex fb3797a7a..7a124ea97 100644--- a/web-app/src/lib/__tests__/coworkRunner.test.ts+++ b/web-app/src/lib/__tests__/coworkRunner.test.ts@@ -146,17 +146,33 @@ describe('runTurn', () => {expect(d.sendStep).not.toHaveBeenCalled()})- it('accumulates usage across steps into the session total', async () => {+ // Each step's reported total includes the whole replayed prompt, so the spend+ // is the growth between steps, not the sum of the totals (which would be 300+ // here and would trip the cap on a run nowhere near it).+ it('charges only the growth in usage across steps', async () => {const d = deps([[...toolStep('read'), ...textStep('', 100)],- textStep('done', 50),+ textStep('done', 200),])const out = await runTurn({messages: [user('hi')],deps: d,signal: new AbortController().signal,})- expect(out.sessionTokens).toBe(150)+ expect(out.sessionTokens).toBe(200)+ })++ it('does not charge a step whose reported total shrank', async () => {+ const d = deps([+ [...toolStep('read'), ...textStep('', 100)],+ textStep('done', 60),+ ])+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.sessionTokens).toBe(100)})it('marks outstanding calls interrupted when aborted mid-dispatch', async () => {diff --git a/web-app/src/lib/__tests__/coworkSubagent.test.ts b/web-app/src/lib/__tests__/coworkSubagent.test.tsnew file mode 100644index 000000000..bb97b3eeb--- /dev/null+++ b/web-app/src/lib/__tests__/coworkSubagent.test.ts@@ -0,0 +1,464 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import type { Tool } from 'ai'++const { streamText, convertToModelMessages } = vi.hoisted(() => ({+ streamText: vi.fn(),+ convertToModelMessages: vi.fn(async (m: unknown) => m),+}))+vi.mock('ai', async (orig) => ({+ ...(await orig<typeof import('ai')>()),+ streamText,+ convertToModelMessages,+}))++import {+ intersectAllowedTools,+ parseSubagentRequest,+ parentToolNames,+ resolveSubagent,+ runSubagent,+ subagentTools,+ MAX_PARALLEL_SUBAGENTS,+ __testing,+} from '../coworkSubagent'+import type { StreamEvent } from '@/hooks/useCoworkRun'+import { MAX_SUBAGENT_STEPS } from '../coworkBudget'++const tools = (...names: string[]): Record<string, Tool> =>+ Object.fromEntries(names.map((n) => [n, {} as Tool]))++const definition = (over = {}) => ({+ name: 'researcher',+ description: 'reads things',+ system_prompt: 'You research.',+ allowed_tools: null as string[] | null,+ model: null as string | null,+ ...over,+})++describe('parseSubagentRequest', () => {+ it('requires a name and a description', () => {+ expect(parseSubagentRequest({})).toContain('subagent_name')+ // The child cannot see the parent's conversation, so an empty brief is a+ // guaranteed-useless run rather than a recoverable one.+ expect(parseSubagentRequest({ subagent_name: 'x' })).toContain(+ 'description'+ )+ })++ it('keeps an inline prompt and allowlist', () => {+ const req = parseSubagentRequest({+ subagent_name: 'oneoff',+ description: 'do it',+ system_prompt: 'You are terse.',+ allowed_tools: ['read', 42, 'grep'],+ })+ expect(req).toEqual({+ subagent_name: 'oneoff',+ description: 'do it',+ system_prompt: 'You are terse.',+ allowed_tools: ['read', 'grep'],+ })+ })++ it('drops a blank inline prompt rather than running an empty role', () => {+ const req = parseSubagentRequest({+ subagent_name: 'x',+ description: 'd',+ system_prompt: ' ',+ })+ expect(req).not.toHaveProperty('system_prompt')+ })+})++describe('intersectAllowedTools', () => {+ const parent = ['read', 'grep', 'write', 'skill_list', 'skill_read']++ it('inherits the parent set when neither side narrows', () => {+ expect(intersectAllowedTools(null, null, parent)).toEqual({ tools: null })+ })++ it('narrows to the definition, dropping what the parent lacks', () => {+ // The definition's author cannot know the parent's mode, so a tool the+ // parent lacks is dropped rather than raised as an error.+ const out = intersectAllowedTools(['read', 'bash'], null, parent)+ expect(out).toEqual({ tools: ['read', 'skill_list', 'skill_read'] })+ })++ it('refuses a request outside the definition', () => {+ expect(+ intersectAllowedTools(['read'], ['write'], parent)+ ).toEqual({+ error: expect.stringContaining("outside the subagent definition's"),+ })+ })++ it('refuses a request the parent cannot call', () => {+ // This is what makes plan mode and a withheld `bash` propagate: the parent's+ // advertised set is the ceiling.+ expect(intersectAllowedTools(null, ['bash'], parent)).toEqual({+ error: expect.stringContaining('not available to this run'),+ })+ })++ it('never widens past the parent', () => {+ const out = intersectAllowedTools(null, ['read'], parent)+ expect(out).toEqual({ tools: ['read', 'skill_list', 'skill_read'] })+ })++ it('always grants the read-side skill tools', () => {+ // Ported from `SUBAGENT_SKILL_TOOLS`: a Claude-style `tools:` list never+ // names them, so a narrowed set must not strip them.+ const out = intersectAllowedTools(['read'], null, parent)+ expect(out).toEqual({ tools: ['read', ...__testing.SUBAGENT_SKILL_TOOLS] })+ })++ it('does not grant skill tools the parent itself lacks', () => {+ expect(intersectAllowedTools(['read'], null, ['read'])).toEqual({+ tools: ['read'],+ })+ })+})++describe('resolveSubagent', () => {+ const parent = ['read', 'grep', 'skill_list', 'skill_read']++ it('uses a saved definition', () => {+ const out = resolveSubagent(+ { subagent_name: 'researcher', description: 'go' },+ [definition({ allowed_tools: ['read'], model: 'm-1' })],+ parent+ )+ expect(out).toEqual({+ name: 'researcher',+ systemPrompt: 'You research.',+ allowedTools: ['read', 'skill_list', 'skill_read'],+ model: 'm-1',+ })+ })++ it('runs a one-off from an inline prompt', () => {+ const out = resolveSubagent(+ {+ subagent_name: 'oneoff',+ description: 'go',+ system_prompt: 'You are terse.',+ allowed_tools: ['read'],+ },+ [],+ parent+ )+ expect(out).toEqual({+ name: 'oneoff',+ systemPrompt: 'You are terse.',+ allowedTools: ['read', 'skill_list', 'skill_read'],+ model: null,+ })+ })++ it('errors on an unknown name with no inline prompt', () => {+ const out = resolveSubagent(+ { subagent_name: 'ghost', description: 'go' },+ [],+ parent+ )+ expect(out).toEqual({+ error: expect.stringContaining("unknown subagent 'ghost'"),+ })+ })++ it('lets a call site narrow a saved definition', () => {+ const out = resolveSubagent(+ {+ subagent_name: 'researcher',+ description: 'go',+ allowed_tools: ['read'],+ },+ [definition({ allowed_tools: ['read', 'grep'] })],+ parent+ )+ expect(out).toMatchObject({+ allowedTools: ['read', 'skill_list', 'skill_read'],+ })+ })+})++describe('subagentTools', () => {+ it('withholds the parent-only tools whatever the allowlist says', () => {+ // `task` is the depth cap; `ask` and `todo` belong to the parent's+ // conversation, which no child is attached to.+ const out = subagentTools(+ tools('read', 'task', 'ask', 'todo'),+ ['read', 'task', 'ask', 'todo']+ )+ expect(Object.keys(out)).toEqual(['read'])+ })++ it('narrows to the allowlist', () => {+ const out = subagentTools(tools('read', 'grep', 'write'), ['read'])+ expect(Object.keys(out)).toEqual(['read'])+ })++ it('inherits everything offerable when the allowlist is null', () => {+ const out = subagentTools(tools('read', 'grep', 'task'), null)+ expect(Object.keys(out)).toEqual(['read', 'grep'])+ })+})++describe('parentToolNames', () => {+ it('excludes what a child can never be granted', () => {+ expect(parentToolNames(tools('read', 'task', 'ask', 'todo'))).toEqual([+ 'read',+ ])+ })+})++describe('Semaphore', () => {+ it('runs up to the cap at once and queues the rest in order', async () => {+ const s = new __testing.Semaphore(2)+ const a = await s.acquire()+ await s.acquire()+ expect(s.waiting).toBe(0)+ expect(s.available).toBe(0)++ const order: number[] = []+ const third = s.acquire().then((r) => {+ order.push(3)+ return r+ })+ const fourth = s.acquire().then((r) => {+ order.push(4)+ return r+ })+ expect(s.waiting).toBe(2)++ a()+ ;(await third)()+ ;(await fourth)()+ // FIFO, so the queue position reported to the UI is the one it gets.+ expect(order).toEqual([3, 4])+ })+})++// A `finish` chunk carrying usage, matching what `toUIMessageStream` emits.+const chunkStream = (chunks: unknown[]) =>+ new ReadableStream({+ start(c) {+ for (const chunk of chunks) c.enqueue(chunk)+ c.close()+ },+ })++const textStep = (text: string, usage = 12) => [+ { type: 'text-delta', delta: text },+ { type: 'finish', messageMetadata: { usage: { totalTokens: usage } } },+]++const toolStep = (id: string, name: string, input: unknown) => [+ { type: 'tool-input-start', toolCallId: id, toolName: name },+ { type: 'tool-input-available', toolCallId: id, toolName: name, input },+ { type: 'finish', messageMetadata: { usage: { totalTokens: 5 } } },+]++function mockSteps(steps: unknown[][]) {+ let i = 0+ streamText.mockImplementation(() => ({+ toUIMessageStream: () => chunkStream(steps[i++] ?? []),+ }))+}++const baseOpts = (over = {}) => ({+ resolved: {+ name: 'researcher',+ systemPrompt: 'You research.',+ allowedTools: null,+ model: null,+ },+ description: 'find the config',+ model: 'model-instance' as never,+ parentTools: tools('read', 'task', 'ask'),+ system: {+ workspacePath: '/ws/s1',+ readOnlyFolder: null,+ bashAvailable: false,+ },+ dispatch: vi.fn(async () => ({ output: 'ok' })),+ signal: new AbortController().signal,+ events: {+ onQueued: vi.fn(),+ onStart: vi.fn(),+ onInner: vi.fn(),+ onEnd: vi.fn(),+ },+ ...over,+})++describe('runSubagent', () => {+ beforeEach(() => {+ streamText.mockReset()+ convertToModelMessages.mockClear()+ })++ it('returns the final text as the task output', async () => {+ mockSteps([textStep('the config is at /etc/x')])+ const opts = baseOpts()+ const out = await runSubagent(opts)+ expect(out.output).toBe('the config is at /etc/x')+ expect(out.isError).toBeFalsy()+ expect(opts.events.onStart).toHaveBeenCalled()+ expect(opts.events.onEnd).toHaveBeenCalledWith(+ expect.objectContaining({ total_tokens: 12 })+ )+ })++ it('reuses the parent model instance rather than creating one', async () => {+ mockSteps([textStep('done')])+ await runSubagent(baseOpts())+ expect(streamText).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'model-instance' })+ )+ })++ it('never advertises the parent-only tools to the child', async () => {+ mockSteps([textStep('done')])+ await runSubagent(baseOpts())+ const passed = streamText.mock.calls[0][0].tools as Record<string, Tool>+ expect(Object.keys(passed)).toEqual(['read'])+ })++ it('starts from a fresh history: only the description', async () => {+ mockSteps([textStep('done')])+ await runSubagent(baseOpts())+ const sent = streamText.mock.calls[0][0].messages as Array<{+ role: string+ parts: Array<{ text: string }>+ }>+ expect(sent).toHaveLength(1)+ expect(sent[0].role).toBe('user')+ expect(sent[0].parts[0].text).toBe('find the config')+ })++ it('puts the sandbox path in the child system prompt', async () => {+ mockSteps([textStep('done')])+ await runSubagent(baseOpts())+ const system = streamText.mock.calls[0][0].system as string+ // A child cannot guess the sandbox path, and the Rust override would have+ // replaced the workspace block wholesale.+ expect(system).toContain('You research.')+ expect(system).toContain('/ws/s1')+ expect(system).toContain('cannot dispatch')+ })++ it('reports the child transcript as inner stream events', async () => {+ mockSteps([toolStep('c1', 'read', { path: 'a' }), textStep('found it')])+ const opts = baseOpts()+ await runSubagent(opts)+ const kinds = (opts.events.onInner.mock.calls as [StreamEvent][]).map(+ ([e]) => e.type+ )+ // `applyInnerToTurns` consumes exactly these, unchanged from the Rust shape.+ expect(kinds).toContain('tool_call_started')+ expect(kinds).toContain('tool_call')+ expect(kinds).toContain('tool_result')+ expect(kinds).toContain('token')+ })++ it('dispatches the child tool calls', async () => {+ mockSteps([toolStep('c1', 'read', { path: 'a' }), textStep('done')])+ const opts = baseOpts()+ await runSubagent(opts)+ expect(opts.dispatch).toHaveBeenCalledWith(+ expect.objectContaining({ toolName: 'read' }),+ expect.anything()+ )+ })++ it('reports a step cap as an error, keeping the partial output', async () => {+ mockSteps(+ Array.from({ length: 4 }, (_, i) =>+ toolStep(`c${i}`, 'read', { path: 'a' })+ )+ )+ const out = await runSubagent(baseOpts({ maxSteps: 2 }))+ // The parent can finish the errand itself, but not if it believes the child+ // answered in full.+ expect(out.isError).toBe(true)+ expect(out.output).toContain('2-step budget')+ })++ it('defaults to the subagent step cap, not the parent one', async () => {+ mockSteps(+ Array.from({ length: MAX_SUBAGENT_STEPS + 1 }, (_, i) =>+ toolStep(`c${i}`, 'read', { path: 'a' })+ )+ )+ const out = await runSubagent(baseOpts())+ expect(out.output).toContain(`${MAX_SUBAGENT_STEPS}-step budget`)+ })++ it('returns cleanly when already aborted', async () => {+ mockSteps([textStep('never')])+ const controller = new AbortController()+ controller.abort()+ const opts = baseOpts({ signal: controller.signal })+ const out = await runSubagent(opts)+ expect(out.isError).toBe(true)+ expect(streamText).not.toHaveBeenCalled()+ // Still closed out, so a caller that opened a lane on `onQueued` does not+ // leave a spinner running.+ expect(opts.events.onEnd).toHaveBeenCalled()+ })++ it('surfaces a stream error as the task result', async () => {+ streamText.mockImplementation(() => ({+ toUIMessageStream: () =>+ chunkStream([{ type: 'error', errorText: 'context overflow' }]),+ }))+ const out = await runSubagent(baseOpts())+ expect(out).toMatchObject({ output: 'context overflow', isError: true })+ })++ it('says so when the child produced no answer', async () => {+ mockSteps([[{ type: 'finish', messageMetadata: {} }]])+ const out = await runSubagent(baseOpts())+ expect(out.output).toContain('no answer')+ })++ it('caps concurrency at three', () => {+ expect(MAX_PARALLEL_SUBAGENTS).toBe(3)+ })++ it('queues the fourth child and reports its position', async () => {+ let releaseAll = () => {}+ const held = new Promise<void>((r) => {+ releaseAll = r+ })+ streamText.mockImplementation(() => ({+ toUIMessageStream: () =>+ new ReadableStream({+ async start(c) {+ await held+ c.enqueue({ type: 'text-delta', delta: 'done' })+ c.close()+ },+ }),+ }))++ const runs = Array.from({ length: 4 }, () => baseOpts())+ const all = Promise.all(runs.map((o) => runSubagent(o)))+ // Let the three admitted children reach streamText.+ for (let i = 0; i < 20; i += 1) await Promise.resolve()++ expect(streamText).toHaveBeenCalledTimes(MAX_PARALLEL_SUBAGENTS)+ const queued = runs.filter((o) => o.events.onQueued.mock.calls.length > 0)+ expect(queued).toHaveLength(1)+ expect(queued[0].events.onQueued).toHaveBeenCalledWith(1)+ expect(queued[0].events.onStart).not.toHaveBeenCalled()++ releaseAll()+ await all+ // The queued child runs once a permit frees, rather than being dropped.+ expect(streamText).toHaveBeenCalledTimes(4)+ expect(queued[0].events.onStart).toHaveBeenCalled()+ })+})diff --git a/web-app/src/lib/__tests__/coworkSubagentRegistry.test.ts b/web-app/src/lib/__tests__/coworkSubagentRegistry.test.tsnew file mode 100644index 000000000..ed5b15cb8--- /dev/null+++ b/web-app/src/lib/__tests__/coworkSubagentRegistry.test.ts@@ -0,0 +1,63 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }))+vi.mock('@tauri-apps/api/core', () => ({ invoke }))++import {+ listSubagents,+ refreshSubagents,+ __testing,+} from '../coworkSubagentRegistry'++const def = (name: string) => ({+ name,+ description: `d-${name}`,+ system_prompt: `p-${name}`,+ allowed_tools: null,+ model: null,+})++describe('coworkSubagentRegistry', () => {+ beforeEach(() => {+ invoke.mockReset()+ __testing.reset()+ })++ // No `project` argument: a default Cowork session has no project root, which+ // is why the desktop reads a single directory instead of the CLI's merge.+ it('lists definitions with no project argument', async () => {+ invoke.mockResolvedValue([def('researcher')])+ await expect(listSubagents()).resolves.toEqual([def('researcher')])+ expect(invoke).toHaveBeenCalledWith('agent_subagent_list')+ expect(invoke.mock.calls[0]).toHaveLength(1)+ })++ it('caches so a run does not re-read the directory per step', async () => {+ invoke.mockResolvedValue([def('a')])+ await listSubagents()+ await listSubagents()+ expect(invoke).toHaveBeenCalledTimes(1)+ })++ it('re-reads after a refresh', async () => {+ invoke.mockResolvedValue([def('a')])+ await listSubagents()+ refreshSubagents()+ invoke.mockResolvedValue([def('a'), def('b')])+ await expect(listSubagents()).resolves.toHaveLength(2)+ })++ // A missing directory or an older binary without the command must cost the+ // run its saved names, not the run: a one-off subagent still works.+ it('degrades to an empty list when the command fails', async () => {+ invoke.mockRejectedValue(new Error('command not found'))+ await expect(listSubagents()).resolves.toEqual([])+ })++ it('does not retry a failed load on every step', async () => {+ invoke.mockRejectedValue(new Error('nope'))+ await listSubagents()+ await listSubagents()+ expect(invoke).toHaveBeenCalledTimes(1)+ })+})diff --git a/web-app/src/lib/__tests__/coworkTodo.test.ts b/web-app/src/lib/__tests__/coworkTodo.test.tsindex 3a1b1403e..91f5d9f50 100644--- a/web-app/src/lib/__tests__/coworkTodo.test.ts+++ b/web-app/src/lib/__tests__/coworkTodo.test.ts@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest'import { applyTodoOp, renderTodoResult, todoProgress } from '../coworkTodo'-import type { TodoList } from '@/types/codeSession'+import type { TodoList } from '@/types/coworkSession'// Ported from `core/agent/todo.rs`'s own tests: the two implementations drive// the same schema and the same panel, so they have to agree.diff --git a/web-app/src/lib/__tests__/coworkTools.test.ts b/web-app/src/lib/__tests__/coworkTools.test.tsindex 63327e32c..955224d22 100644--- a/web-app/src/lib/__tests__/coworkTools.test.ts+++ b/web-app/src/lib/__tests__/coworkTools.test.ts@@ -24,6 +24,7 @@ const ALL = ['read', 'ls', 'grep', 'write', 'edit', 'bash', 'memory_write']const opts = (over: Partial<Parameters<typeof buildCoworkTools>[0]> = {}) => ({planMode: false,+ webSearch: false,subagentNames: ['researcher'],allowSubagents: true,...over,@@ -104,6 +105,41 @@ describe('coworkToolSignature', () => {})})+describe('web tools', () => {+ beforeEach(() => {+ getAgentToolSchemas.mockReset()+ getAgentToolSchemas.mockResolvedValue(ALL.map(schema))+ })++ it('are withheld when web search is off', async () => {+ const tools = await buildCoworkTools(opts({ webSearch: false }))+ expect(tools.web_search).toBeUndefined()+ expect(tools.web_fetch).toBeUndefined()+ })++ it('are advertised when it is on', async () => {+ const tools = await buildCoworkTools(opts({ webSearch: true }))+ expect(tools.web_search).toBeDefined()+ expect(tools.web_fetch).toBeDefined()+ })++ // Research is most of what planning is, so unlike write/edit/bash these are+ // reads that plan mode keeps.+ it('survive plan mode', async () => {+ const tools = await buildCoworkTools(opts({ webSearch: true, planMode: true }))+ expect(tools.web_search).toBeDefined()+ expect(tools.bash).toBeUndefined()+ })++ // Advertising them changes the tool JSON, so a run that froze without them+ // must not silently pick them up.+ it('change the freeze signature', () => {+ expect(coworkToolSignature(opts({ webSearch: true }), true)).not.toBe(+ coworkToolSignature(opts({ webSearch: false }), true)+ )+ })+})+describe('allowedToolNames', () => {it('refuses the same set plan mode withholds', () => {const out = allowedToolNames([...ALL, TASK_TOOL_NAME], opts({ planMode: true }))diff --git a/web-app/src/lib/__tests__/coworkTransport.test.ts b/web-app/src/lib/__tests__/coworkTransport.test.tsindex 217735af9..4e1ffa813 100644--- a/web-app/src/lib/__tests__/coworkTransport.test.ts+++ b/web-app/src/lib/__tests__/coworkTransport.test.ts@@ -15,6 +15,7 @@ import { CHAT_SLOT_ID, COWORK_SLOT_ID } from '@/constants/models'const config = (over = {}) => ({planMode: false,+ webSearch: false,subagentNames: ['researcher'],allowSubagents: true,workspacePath: '/ws/s1',@@ -99,3 +100,24 @@ describe('CoworkChatTransport', () => {).not.toThrow()})})++describe('CoworkChatTransport.advertisedTools', () => {+ beforeEach(() => {+ buildCoworkTools.mockReset()+ buildCoworkTools.mockResolvedValue({ read: {}, task: {} })+ sandboxEnforces.mockReturnValue(true)+ })++ // A subagent's allowlist intersects with this, so plan mode and a withheld+ // `bash` reach children without a second policy check.+ it('reports the set frozen for the run', async () => {+ const t = new CoworkChatTransport('s1', config())+ await t.refreshTools()+ expect(Object.keys(t.advertisedTools)).toEqual(['read', 'task'])+ })++ it('is empty before a run advertises anything', () => {+ const t = new CoworkChatTransport('s1', config())+ expect(t.advertisedTools).toEqual({})+ })+})diff --git a/web-app/src/lib/__tests__/codeTurns.test.ts b/web-app/src/lib/__tests__/coworkTurns.test.tssimilarity index 85%rename from web-app/src/lib/__tests__/codeTurns.test.tsrename to web-app/src/lib/__tests__/coworkTurns.test.tsindex 402ed3859..ed301547c 100644--- a/web-app/src/lib/__tests__/codeTurns.test.ts+++ b/web-app/src/lib/__tests__/coworkTurns.test.ts@@ -1,17 +1,17 @@import { describe, it, expect } from 'vitest'-import { codeTurnsToUIMessages } from '@/lib/codeTurns'-import type { CodeTurn } from '@/hooks/useCodeSessions'+import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'+import type { CoworkTurn } from '@/hooks/useCoworkSessions'/* eslint-disable @typescript-eslint/no-explicit-any */const partsOf = (messages: any[], index = 0) => messages[index]?.parts ?? []-const toolPart = (turns: CodeTurn[]) =>- partsOf(codeTurnsToUIMessages(turns)).find((p: any) =>+const toolPart = (turns: CoworkTurn[]) =>+ partsOf(coworkTurnsToUIMessages(turns)).find((p: any) =>p.type?.startsWith('tool-'))-describe('codeTurnsToUIMessages', () => {+describe('coworkTurnsToUIMessages', () => {it('starts a new user message and flushes the assistant before it', () => {- const messages = codeTurnsToUIMessages([+ const messages = coworkTurnsToUIMessages([{ role: 'user', content: 'first' },{ role: 'assistant', content: 'answer' },{ role: 'user', content: 'second' },@@ -96,9 +96,9 @@ describe('codeTurnsToUIMessages', () => {})it('keeps ids unique across prefixes so committed and live turns can merge', () => {- const turns: CodeTurn[] = [{ role: 'user', content: 'hi' }]- const committed = codeTurnsToUIMessages(turns, 'c')- const live = codeTurnsToUIMessages(turns, 'l')+ const turns: CoworkTurn[] = [{ role: 'user', content: 'hi' }]+ const committed = coworkTurnsToUIMessages(turns, 'c')+ const live = coworkTurnsToUIMessages(turns, 'l')expect(committed[0].id).not.toBe(live[0].id)})})diff --git a/web-app/src/lib/__tests__/tokenCounterVisibility.test.ts b/web-app/src/lib/__tests__/tokenCounterVisibility.test.tsindex 545753fa2..44c1e4e00 100644--- a/web-app/src/lib/__tests__/tokenCounterVisibility.test.ts+++ b/web-app/src/lib/__tests__/tokenCounterVisibility.test.ts@@ -104,4 +104,44 @@ describe('shouldShowTokenCounter', () => {})).toBe(false)})++ // Cowork keeps no thread messages and mounts a permanently "initial" input,+ // so every one of the thread-shaped conditions is false for it.+ describe('reported usage', () => {+ const cowork = {+ ...base,+ isInitialMessage: true,+ hasMessages: false,+ hasPromptText: false,+ }++ it('shows once a surface reports usage of its own', () => {+ expect(+ shouldShowTokenCounter({ ...cowork, hasReportedUsage: true })+ ).toBe(true)+ })++ it('stays hidden before that surface has counted anything', () => {+ expect(+ shouldShowTokenCounter({ ...cowork, hasReportedUsage: false })+ ).toBe(false)+ })++ it('does not override the model and agent-mode conditions', () => {+ expect(+ shouldShowTokenCounter({+ ...cowork,+ hasReportedUsage: true,+ hasSelectedModel: false,+ })+ ).toBe(false)+ expect(+ shouldShowTokenCounter({+ ...cowork,+ hasReportedUsage: true,+ isAgentMode: true,+ })+ ).toBe(false)+ })+ })})diff --git a/web-app/src/lib/agentActivity.test.ts b/web-app/src/lib/agentActivity.test.tsindex d777446ae..5c4b82898 100644--- a/web-app/src/lib/agentActivity.test.ts+++ b/web-app/src/lib/agentActivity.test.ts@@ -5,8 +5,10 @@ import {usedSkillNames,activeToolPart,subagentActivityLabel,+ awaitsModel,} from './agentActivity'-import type { SubagentRun } from '@/hooks/useCodeSessions'+import type { SubagentRun } from '@/hooks/useCoworkSessions'+import type { CoworkTurn } from '@/types/coworkSession'describe('toolActivityText', () => {it('formats write with basename only', () => {@@ -197,3 +199,36 @@ describe('subagentActivityLabel', () => {})})})++describe('awaitsModel', () => {+ const tool = (status: CoworkTurn['status']): CoworkTurn => ({+ role: 'tool',+ content: '',+ callId: 'c1',+ name: 'bash',+ status,+ })++ it('is false when nothing is running', () => {+ expect(awaitsModel(false, [])).toBe(false)+ expect(awaitsModel(false, [{ role: 'user', content: 'hi' }])).toBe(false)+ })++ it('is true before the first token', () => {+ expect(awaitsModel(true, [{ role: 'user', content: 'hi' }])).toBe(true)+ expect(awaitsModel(true, [])).toBe(true)+ })++ // The gap between a finished tool and the next token has nothing else on+ // screen reporting progress.+ it('is true again after a tool settles', () => {+ expect(awaitsModel(true, [tool('done')])).toBe(true)+ })++ it('is false while a tool is running or text is streaming', () => {+ expect(awaitsModel(true, [tool('running')])).toBe(false)+ expect(awaitsModel(true, [{ role: 'assistant', content: 'thinking' }])).toBe(+ false+ )+ })+})diff --git a/web-app/src/lib/agentActivity.ts b/web-app/src/lib/agentActivity.tsindex b7a45493b..2d23979da 100644--- a/web-app/src/lib/agentActivity.ts+++ b/web-app/src/lib/agentActivity.ts@@ -1,4 +1,4 @@-import type { CodeTurn, SubagentRun } from '@/types/codeSession'+import type { CoworkTurn, SubagentRun } from '@/types/coworkSession'export type ActivityLabel = { text: string; startedAt: number } | null@@ -115,7 +115,7 @@ export function usedSkillNames(parts: ToolPartLike[]): string[] {return [...names]}-function lastRunningToolTurn(turns: CodeTurn[]): CodeTurn | undefined {+function lastRunningToolTurn(turns: CoworkTurn[]): CoworkTurn | undefined {for (let i = turns.length - 1; i >= 0; i--) {const turn = turns[i]if (turn.role === 'tool' && turn.status === 'running') return turn@@ -140,3 +140,18 @@ export function subagentActivityLabel(subagents: SubagentRun[]): ActivityLabel {const startedAt = Math.min(...running.map((s) => s.startedAt))return { text: `${running.length} subagents working`, startedAt }}++/**+ * Whether a running agent is waiting on the model with nothing to show for it.+ *+ * True in the two gaps an agent loop leaves: before the first token, and again+ * after each tool result. Streaming text and a running tool already report+ * themselves, so a generic "Working…" beside them is noise.+ */+export function awaitsModel(running: boolean, turns: CoworkTurn[]): boolean {+ if (!running) return false+ const last = turns.at(-1)+ if (!last) return true+ if (last.role === 'user') return true+ return last.role === 'tool' && last.status === 'done'+}diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex 9a8997972..7b001e55a 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -6,6 +6,7 @@ import {threadWorkspaceSweep,type SandboxStatus,type ToolSchema,+ type WorkspaceScope,} from '@janhq/tauri-plugin-agent-tools-api'import { getServiceHub } from '@/hooks/useServiceHub'import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'@@ -141,7 +142,14 @@ export async function executeAgentTool(* that overlaps the workspace or the Jan data folder, rather than silently* dropping it, so an unusable attachment surfaces as a tool error.*/- readOnlyProject?: string | null+ readOnlyProject?: string | null,+ /**+ * Which sandbox namespace `threadId` names. Load-bearing: a Cowork session id+ * is not a chat thread id, so running one under `'thread'` would put its files+ * where the thread sweep's keep-list can never mention them — and the sweep+ * would delete the only copy of the agent's work.+ */+ scope: WorkspaceScope = 'thread'): Promise<AgentToolResult> {try {const dataFolder = await getServiceHub().app().getJanDataFolder()@@ -158,7 +166,8 @@ export async function executeAgentTool(undefined,undefined,useAgentToolsConfig.getState().bashNetworkEnabled,- readOnlyProject ?? undefined+ readOnlyProject ?? undefined,+ scope)if (result.isError) return { error: result.content }return { content: result.content, diff: result.diff ?? undefined }diff --git a/web-app/src/lib/codeArtifacts.ts b/web-app/src/lib/coworkArtifacts.tssimilarity index 94%rename from web-app/src/lib/codeArtifacts.tsrename to web-app/src/lib/coworkArtifacts.tsindex b60caa195..f4bd2601a 100644--- a/web-app/src/lib/codeArtifacts.ts+++ b/web-app/src/lib/coworkArtifacts.ts@@ -1,6 +1,6 @@import { AudioLines, Code2, FileText, ImageIcon, Video } from 'lucide-react'-import { basenameOf, extensionOf, resolveInRoot } from '@/lib/codePreview'-import type { CodeTurn } from '@/types/codeSession'+import { basenameOf, extensionOf, resolveInRoot } from '@/lib/coworkPreview'+import type { CoworkTurn } from '@/types/coworkSession'/*** Artifacts a run produced, derived from its `write`/`edit` tool calls@@ -20,7 +20,7 @@ import type { CodeTurn } from '@/types/codeSession'* Modifications remain visible in the diff panel (#285), which is the right* surface for "what did the agent change".*/-export type CodeArtifact = {+export type CoworkArtifact = {/** Project-relative path, as the tool reported it. */path: string/** Display name — the basename without its extension. */@@ -32,7 +32,7 @@ export type CodeArtifact = {}/** Extension → grouping. Anything absent is not an artifact. */-const ARTIFACT_GROUPS: Record<string, CodeArtifact['group']> = {+const ARTIFACT_GROUPS: Record<string, CoworkArtifact['group']> = {html: 'Code',htm: 'Code',svg: 'Code',@@ -66,7 +66,7 @@ export function isArtifactPath(path: string): boolean {return extensionOf(path) in ARTIFACT_GROUPS}-export function artifactFor(path: string): CodeArtifact | null {+export function artifactFor(path: string): CoworkArtifact | null {const ext = extensionOf(path)const group = ARTIFACT_GROUPS[ext]if (!group) return null@@ -158,12 +158,12 @@ export function bashArtifactPaths(command: unknown,output: unknown,root: string | null | undefined-): CodeArtifact[] {+): CoworkArtifact[] {const cmd = typeof command === 'string' ? command : ''const out = typeof output === 'string' ? output : ''if (!out) return []const seen = new Set<string>()- const found: CodeArtifact[] = []+ const found: CoworkArtifact[] = []const consider = (raw: string) => {const token = raw.trim()if (!token || seen.has(token) || !isArtifactPath(token)) return@@ -197,9 +197,9 @@ export function bashArtifactPaths(* Deduplicated by path, keeping first-seen order: a run that writes then edits* the same file produced one artifact, not two.*/-export function artifactsFromParts(parts: PartLike[] | undefined): CodeArtifact[] {+export function artifactsFromParts(parts: PartLike[] | undefined): CoworkArtifact[] {if (!parts?.length) return []- const out: CodeArtifact[] = []+ const out: CoworkArtifact[] = []const seen = new Set<string>()for (const part of parts) {// `edit` targets a file that already existed, so it never creates one.@@ -220,7 +220,7 @@ export function artifactsFromParts(parts: PartLike[] | undefined): CodeArtifact[/*** Artifacts a whole session produced, read straight off its turns.*- * Deliberately not `codeTurnsToUIMessages` + {@link artifactsFromParts}: that+ * Deliberately not `coworkTurnsToUIMessages` + {@link artifactsFromParts}: that* builds the full message tree (markdown parts, reasoning splitting, tool* grouping) for every session just to recover a handful of paths. The library* lists every session at once, so that cost is paid per render.@@ -229,11 +229,11 @@ export function artifactsFromParts(parts: PartLike[] | undefined): CodeArtifact[* one artifact, not one per rewrite.*/export function artifactsFromTurns(- turns: CodeTurn[] | undefined,+ turns: CoworkTurn[] | undefined,root?: string | null-): CodeArtifact[] {+): CoworkArtifact[] {if (!turns?.length) return []- const byPath = new Map<string, CodeArtifact>()+ const byPath = new Map<string, CoworkArtifact>()for (const turn of turns) {if (turn.role !== 'tool') continue// Only a completed, non-error call produced a file.diff --git a/web-app/src/lib/coworkAsk.ts b/web-app/src/lib/coworkAsk.tsindex bb313192e..71ac31cd1 100644--- a/web-app/src/lib/coworkAsk.ts+++ b/web-app/src/lib/coworkAsk.ts@@ -2,7 +2,7 @@ import type {AskAnswer,AskQuestion,AskRequestPayload,-} from '@/types/codeSession'+} from '@/types/coworkSession'import type { ToolOutcome } from '@/lib/coworkRunner'/**diff --git a/web-app/src/lib/coworkBudget.ts b/web-app/src/lib/coworkBudget.tsindex 1f5ecafff..988649c4f 100644--- a/web-app/src/lib/coworkBudget.ts+++ b/web-app/src/lib/coworkBudget.ts@@ -13,7 +13,13 @@ export const MAX_AGENT_STEPS = 100/** Tighter for a nested run, which should be a focused errand. */export const MAX_SUBAGENT_STEPS = 30-/** Cumulative tokens for a session, matching what the Rust loop enforced. */+/**+ * Token spend for one user request, matching what the Rust loop enforced.+ *+ * Per request, not per session, because that is where `SessionBudget` actually+ * lives in Rust: it is constructed inside `run_orchestration_streamed`, so each+ * request gets its own allowance.+ */export const MAX_SESSION_TOKENS = 200_000export type BudgetState = {@@ -21,6 +27,67 @@ export type BudgetState = {sessionTokens: number}+/**+ * Running spend, and what is needed to charge only the *new* tokens.+ *+ * `lastTotal`/`lastPrompt` exist because every step of an agent turn replays the+ * whole conversation, so each step's `total_tokens` includes the prompt again.+ * Summing those totals charges the same context 20+ times over and trips the cap+ * a few steps into a run that is nowhere near it.+ */+export type SpendState = {+ spent: number+ lastTotal: number+ lastPrompt?: number+}++export const newSpend = (spent = 0): SpendState => ({ spent, lastTotal: 0 })++/**+ * Fold one step's usage into the running spend.+ *+ * Charges new completion tokens plus positive prompt *growth*, not replayed+ * prompt history; the first step of a request uses its reported total as the+ * baseline. Falls back through progressively weaker signals because providers+ * omit different usage fields. Ported from `core/agent/session.rs::record`.+ */+export function recordSpend(+ state: SpendState,+ usage: {+ prompt_tokens?: number+ completion_tokens?: number+ total_tokens?: number+ } | null+): SpendState {+ if (!usage) return state+ const { prompt_tokens: prompt, completion_tokens: completion } = usage+ const total = usage.total_tokens+ const gap = (a: number, b: number) => Math.max(0, a - b)++ let delta: number+ let lastTotal = state.lastTotal+ if (total != null) {+ if (prompt != null && state.lastPrompt != null && completion != null) {+ delta = completion + gap(prompt, state.lastPrompt)+ } else if (prompt != null && state.lastPrompt == null) {+ delta = total+ } else if (state.lastPrompt != null && completion != null) {+ delta = Math.max(completion, gap(total, state.lastTotal))+ } else {+ delta = gap(total, state.lastTotal)+ }+ lastTotal = total+ } else {+ delta = completion ?? 0+ }++ return {+ spent: state.spent + delta,+ lastTotal,+ lastPrompt: prompt ?? state.lastPrompt,+ }+}+export type BudgetStop = 'steps' | 'tokens' | null/** Which cap, if any, this run has reached. */diff --git a/web-app/src/lib/codeDiffs.ts b/web-app/src/lib/coworkDiffs.tssimilarity index 78%rename from web-app/src/lib/codeDiffs.tsrename to web-app/src/lib/coworkDiffs.tsindex 1ee4c98a5..24da55afb 100644--- a/web-app/src/lib/codeDiffs.ts+++ b/web-app/src/lib/coworkDiffs.ts@@ -1,21 +1,21 @@-import type { CodeTurn, SubagentRun } from '@/types/codeSession'+import type { CoworkTurn, SubagentRun } from '@/types/coworkSession'-export type CodeDiffOperation = {+export type CoworkDiffOperation = {diff: stringsource: 'main' | 'subagent'sourceName?: string}-export type CodeFileDiff = {+export type CoworkFileDiff = {path: stringadditions: numberdeletions: number- operations: CodeDiffOperation[]+ operations: CoworkDiffOperation[]}function addOperation(- files: Map<string, CodeFileDiff>,- turn: CodeTurn,+ files: Map<string, CoworkFileDiff>,+ turn: CoworkTurn,source: 'main' | 'subagent',sourceName?: string) {@@ -36,7 +36,7 @@ function addOperation(const lines = turn.diff.split('\n')const additions = lines.filter((line) => line.startsWith('+ ')).lengthconst deletions = lines.filter((line) => line.startsWith('- ')).length- const operation: CodeDiffOperation = sourceName+ const operation: CoworkDiffOperation = sourceName? { diff: turn.diff, source, sourceName }: { diff: turn.diff, source }const current = files.get(path)@@ -52,10 +52,10 @@ function addOperation(}export function collectCodeFileDiffs(- turns: CodeTurn[],+ turns: CoworkTurn[],subagents: SubagentRun[]-): CodeFileDiff[] {- const files = new Map<string, CodeFileDiff>()+): CoworkFileDiff[] {+ const files = new Map<string, CoworkFileDiff>()for (const turn of turns) {addOperation(files, turn, 'main')diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.tsindex 67dce8a51..8230849eb 100644--- a/web-app/src/lib/coworkDispatch.ts+++ b/web-app/src/lib/coworkDispatch.ts@@ -6,11 +6,15 @@ import {TODO_TOOL_NAME,} from '@/lib/coworkTools'import type { PendingToolCall, ToolOutcome } from '@/lib/coworkRunner'+import { WEB_TOOL_NAMES, executeWebTool } from '@/lib/webSearchTool'export type DispatchContext = {sessionId: stringreadOnlyFolder: string | nullplanMode: boolean+ /** Mirrors the advertised set. Refused when off, so a call to a tool that was+ * never advertised cannot reach the network the user switched off. */+ webSearch: boolean/** Applies one `todo` operation and persists the result. */onTodo: (input: unknown) => Promise<ToolOutcome>/** Suspends until the user answers, or the run is aborted. */@@ -60,11 +64,34 @@ export async function dispatchCoworkTool(return await ctx.onTask(call.toolCallId, call.input)}+ if (WEB_TOOL_NAMES.has(toolName)) {+ if (!ctx.webSearch) {+ return {+ output:+ `The \`${toolName}\` tool is off: web access is disabled in ` ++ 'Settings. Work from what you can read locally.',+ isError: true,+ }+ }+ const web = await executeWebTool(toolName, call.input ?? {})+ if (web.error) return { output: web.error, isError: true }+ return {+ output:+ typeof web.content === 'string'+ ? web.content+ : JSON.stringify(web.content ?? ''),+ }+ }++ // `'session'`, not the default `'thread'`: a Cowork session id lives in its+ // own namespace, and the thread sweep would otherwise delete this sandbox+ // because no chat thread claims it.const result = await executeAgentTool(toolName,call.input,ctx.sessionId,- ctx.readOnlyFolder+ ctx.readOnlyFolder,+ 'session')if (result.error) return { output: result.error, isError: true }return {diff --git a/web-app/src/lib/codePreview.ts b/web-app/src/lib/coworkPreview.tssimilarity index 100%rename from web-app/src/lib/codePreview.tsrename to web-app/src/lib/coworkPreview.tsdiff --git a/web-app/src/lib/coworkPrompt.ts b/web-app/src/lib/coworkPrompt.tsindex 49c3a3e8a..5c655c24b 100644--- a/web-app/src/lib/coworkPrompt.ts+++ b/web-app/src/lib/coworkPrompt.ts@@ -50,8 +50,21 @@ export type CoworkPromptOptions = {/** False when no OS sandbox enforces, in which case `bash` is not offered. */bashAvailable: booleansubagentNames: string[]+ /** Whether `web_search`/`web_fetch` are advertised this run. */+ webSearch: boolean}+/** Marker text matches chat's, so the same renderer turns it into source chips. */+const WEB_BLOCK = [+ '# Web',+ '',+ 'You can search with `web_search` and read pages with `web_fetch`. Use them',+ 'whenever the task needs current or external information. When a statement',+ 'rests on a source, cite it inline right after that statement as',+ '[[cite:URL]], using the full URL from a `web_search` result. Do not add a',+ 'separate sources section.',+].join('\n')+function workspaceBlock(opts: CoworkPromptOptions): string {const lines = ['# Workspace', '']if (opts.workspacePath) {@@ -86,6 +99,7 @@ function workspaceBlock(opts: CoworkPromptOptions): string {export function buildCoworkSystemPrompt(opts: CoworkPromptOptions): string {const blocks = [IDENTITY, GUIDELINES, workspaceBlock(opts)]+ if (opts.webSearch) blocks.push(WEB_BLOCK)if (opts.subagentNames.length > 0 && !opts.planMode) {blocks.push([@@ -101,3 +115,31 @@ export function buildCoworkSystemPrompt(opts: CoworkPromptOptions): string {if (opts.planMode) blocks.push(PLAN_ADDENDUM)return blocks.join('\n\n')}++/**+ * A child's system prompt: its own role, then the workspace facts.+ *+ * The Rust loop replaces the whole system prompt with the definition's+ * (`system_prompt_override`), which works there because the CLI's project root+ * is the shell's working directory. Here it is a sandbox path the child has no+ * way to guess, and an attached folder is read-only — so the workspace block+ * travels with the definition rather than replacing it.+ */+export function buildSubagentSystemPrompt(+ definitionPrompt: string,+ opts: Omit<CoworkPromptOptions, 'planMode' | 'subagentNames'>+): string {+ return [+ definitionPrompt.trim(),+ workspaceBlock({ ...opts, planMode: false, subagentNames: [] }),+ ...(opts.webSearch ? [WEB_BLOCK] : []),+ [+ '# Scope',+ '',+ 'You are a subagent running one errand. You cannot see the conversation',+ 'that dispatched you, cannot ask the user questions, and cannot dispatch',+ 'subagents of your own. Your final message is the whole answer returned to',+ 'the agent that called you, so make it self-contained.',+ ].join('\n'),+ ].join('\n\n')+}diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.tsindex 566707b53..2116fb3ec 100644--- a/web-app/src/lib/coworkRunner.ts+++ b/web-app/src/lib/coworkRunner.ts@@ -1,9 +1,11 @@/* eslint-disable @typescript-eslint/no-explicit-any */import type { UIMessage, UIMessageChunk } from 'ai'-import type { AskAnswer, CodeTurn, Usage } from '@/types/codeSession'+import type { AskAnswer, CoworkTurn, Usage } from '@/types/coworkSession'import {MAX_AGENT_STEPS,budgetExceeded,+ newSpend,+ recordSpend,type BudgetStop,} from '@/lib/coworkBudget'@@ -224,8 +226,8 @@ export function assistantMessageFor(export function turnsFor(step: StepResult,outcomes: Map<string, ToolOutcome>-): CodeTurn[] {- const turns: CodeTurn[] = []+): CoworkTurn[] {+ const turns: CoworkTurn[] = []if (step.text) turns.push({ role: 'assistant', content: step.text })for (const call of step.toolCalls) {const outcome = outcomes.get(call.toolCallId)@@ -260,7 +262,7 @@ export type RunDeps = {onStep: (info: {step: numberresult: StepResult- turns: CodeTurn[]+ turns: CoworkTurn[]outcomes: Map<string, ToolOutcome>}) => void/** Monotonic ids for the assistant messages this run appends. */@@ -295,7 +297,9 @@ export async function runTurn(opts: {const maxSteps = opts.maxSteps ?? MAX_AGENT_STEPSconst messages = [...opts.messages]let step = 0- let sessionTokens = opts.sessionTokens ?? 0+ // Not a running sum of each step's `total_tokens`: every step replays the whole+ // conversation, so summing totals charges the same context once per step.+ let spend = newSpend(opts.sessionTokens ?? 0)let usage: Usage | null = nullfor (;;) {@@ -304,17 +308,20 @@ export async function runTurn(opts: {messages,steps: step,usage,- sessionTokens,+ sessionTokens: spend.spent,stoppedBy: 'aborted',}}- const overBudget = budgetExceeded({ step, sessionTokens }, maxSteps)+ const overBudget = budgetExceeded(+ { step, sessionTokens: spend.spent },+ maxSteps+ )if (overBudget) {return {messages,steps: step,usage,- sessionTokens,+ sessionTokens: spend.spent,stoppedBy: overBudget,}}@@ -327,7 +334,7 @@ export async function runTurn(opts: {step += 1if (result.usage) {usage = result.usage- sessionTokens += result.usage.total_tokens ?? 0+ spend = recordSpend(spend, result.usage)}if (result.errorText) {@@ -342,7 +349,7 @@ export async function runTurn(opts: {messages,steps: step,usage,- sessionTokens,+ sessionTokens: spend.spent,stoppedBy: 'error',errorText: result.errorText,}@@ -370,13 +377,19 @@ export async function runTurn(opts: {messages,steps: step,usage,- sessionTokens,+ sessionTokens: spend.spent,stoppedBy: 'aborted',}}// No tool calls means the model answered rather than asked for more work.if (result.toolCalls.length === 0) {- return { messages, steps: step, usage, sessionTokens, stoppedBy: 'done' }+ return {+ messages,+ steps: step,+ usage,+ sessionTokens: spend.spent,+ stoppedBy: 'done',+ }}}}diff --git a/web-app/src/lib/coworkSubagent.ts b/web-app/src/lib/coworkSubagent.tsnew file mode 100644index 000000000..55e400315--- /dev/null+++ b/web-app/src/lib/coworkSubagent.ts@@ -0,0 +1,480 @@+/* eslint-disable @typescript-eslint/no-explicit-any */+import {+ convertToModelMessages,+ streamText,+ type LanguageModel,+ type Tool,+ type UIMessage,+ type UIMessageChunk,+} from 'ai'+import type { Usage } from '@/types/coworkSession'+import type { SubagentDefinition } from '@/lib/coworkSubagentRegistry'+import {+ ASK_TOOL_NAME,+ TASK_TOOL_NAME,+ TODO_TOOL_NAME,+} from '@/lib/coworkTools'+import { MAX_SUBAGENT_STEPS } from '@/lib/coworkBudget'+import {+ runTurn,+ type PendingToolCall,+ type StreamSink,+ type ToolOutcome,+} from '@/lib/coworkRunner'+import { buildSubagentSystemPrompt } from '@/lib/coworkPrompt'+import type { StreamEvent } from '@/hooks/useCoworkRun'++/**+ * Nested subagent runs.+ *+ * Deliberately not routed through `CoworkChatTransport`: the transport writes+ * app-global singletons (`setCurrentStreamThreadId`, `updateLoadingModel`,+ * `updateLiveTokenStats`) that a nested run would clobber for its parent, so the+ * header would report the child's progress as the session's. This calls+ * `streamText` directly and reuses only the parent's already-created model+ * instance, so a child costs no second llama-server load.+ *+ * The cost of that reuse: llama.cpp slot params are baked in at model creation,+ * so a child prefills on the parent's slot and evicts its KV prefix, which the+ * parent then re-prefills on its next step. Fixing it means a dedicated+ * subagent slot, which is part of the still-open slot-reservation decision.+ *+ * The Rust pair `dispatch_subagent`/`await_subagent` collapses to one blocking+ * `task` call here. The SDK already emits several tool calls per step and the+ * runner dispatches them in order, so a run id to await later buys nothing.+ */++/** Concurrent children, mirroring `DEFAULT_MAX_PARALLEL_SUBAGENTS`. */+export const MAX_PARALLEL_SUBAGENTS = 3++/**+ * Always granted to a child, whatever the allowlist says.+ *+ * A skill is a procedure the child may need to follow, and a Claude-style+ * `tools:` list never names these — so a narrowed toolset must not strip them.+ * Read-side only: authoring stays with the top-level agent.+ * Ported from `subagent.rs::SUBAGENT_SKILL_TOOLS`.+ */+const SUBAGENT_SKILL_TOOLS = ['skill_list', 'skill_read']++/**+ * Never offered to a child, whatever the allowlist says.+ *+ * `task` is the depth cap: a subagent cannot spawn subagents. `ask` and `todo`+ * belong to the parent's conversation — no card is rendered for a child, and the+ * todo list is the session's, not the errand's. Matches the Rust child args,+ * which null out `ask_requests` and `todo_registry`.+ */+const WITHHELD_FROM_SUBAGENTS = new Set([+ TASK_TOOL_NAME,+ ASK_TOOL_NAME,+ TODO_TOOL_NAME,+])++export type SubagentRequest = {+ subagent_name: string+ description: string+ system_prompt?: string+ allowed_tools?: string[]+}++export type ResolvedSubagent = {+ name: string+ systemPrompt: string+ /** `null` inherits the parent's toolset minus what is withheld. */+ allowedTools: string[] | null+ model: string | null+}++/** Reject a malformed `task` call rather than running an errand with no brief. */+export function parseSubagentRequest(input: unknown): SubagentRequest | string {+ const raw = (input ?? {}) as Partial<SubagentRequest>+ if (typeof raw.subagent_name !== 'string' || !raw.subagent_name.trim()) {+ return '`task` requires a non-empty `subagent_name`'+ }+ if (typeof raw.description !== 'string' || !raw.description.trim()) {+ return '`task` requires a `description`: the subagent cannot see this conversation, so state everything it needs'+ }+ const req: SubagentRequest = {+ subagent_name: raw.subagent_name,+ description: raw.description,+ }+ if (typeof raw.system_prompt === 'string' && raw.system_prompt.trim()) {+ req.system_prompt = raw.system_prompt+ }+ if (Array.isArray(raw.allowed_tools)) {+ req.allowed_tools = raw.allowed_tools.filter(+ (t): t is string => typeof t === 'string'+ )+ }+ return req+}++/**+ * The child's effective allowlist: the definition's list, narrowed by the+ * call-site list, narrowed by what the parent itself can call.+ *+ * Never widens. Fails closed on a tool the definition or the parent does not+ * permit, rather than dropping it silently — a child that quietly lost the one+ * tool it needed looks like a model failure. A definition-listed tool the parent+ * lacks *is* dropped: the definition's author cannot know the parent's mode.+ * Ported from `subagent.rs::intersect_allowed_tools`.+ */+export function intersectAllowedTools(+ definition: string[] | null | undefined,+ request: string[] | null | undefined,+ parentTools: string[]+): { tools: string[] | null } | { error: string } {+ const parent = new Set(parentTools)+ const withSkills = (tools: string[]) => {+ const out = [...tools]+ for (const skill of SUBAGENT_SKILL_TOOLS) {+ if (!out.includes(skill) && parent.has(skill)) out.push(skill)+ }+ return out+ }++ if (request && request.length > 0) {+ const effective: string[] = []+ for (const tool of request) {+ if (definition && !definition.includes(tool)) {+ return {+ error: `tool '${tool}' is outside the subagent definition's allowed_tools`,+ }+ }+ if (!parent.has(tool)) {+ return { error: `tool '${tool}' is not available to this run` }+ }+ effective.push(tool)+ }+ return { tools: withSkills(effective) }+ }+ if (definition) {+ return { tools: withSkills(definition.filter((t) => parent.has(t))) }+ }+ return { tools: null }+}++/**+ * Resolve a request against the saved definitions.+ *+ * An unknown name is only an error when no inline `system_prompt` was supplied:+ * a one-off subagent is first-class, which is what keeps `task` useful before+ * anything is saved. Ported from `subagent.rs::resolve_dispatch`.+ */+export function resolveSubagent(+ req: SubagentRequest,+ definitions: SubagentDefinition[],+ parentTools: string[]+): ResolvedSubagent | { error: string } {+ const saved = definitions.find((d) => d.name === req.subagent_name)+ const narrowed = intersectAllowedTools(+ saved ? saved.allowed_tools : (req.allowed_tools ?? null),+ // An inline allowlist *is* the one-off's definition, so it is not also+ // applied as a call-site narrowing (that would compare it to itself).+ saved ? (req.allowed_tools ?? null) : null,+ parentTools+ )+ if ('error' in narrowed) return narrowed+ if (saved) {+ return {+ name: saved.name,+ systemPrompt: saved.system_prompt,+ allowedTools: narrowed.tools,+ model: saved.model,+ }+ }+ if (!req.system_prompt) {+ return {+ error:+ `unknown subagent '${req.subagent_name}': no saved definition. For a ` ++ 'one-off, retry with a `system_prompt` describing its role.',+ }+ }+ return {+ name: req.subagent_name,+ systemPrompt: req.system_prompt,+ allowedTools: narrowed.tools,+ model: null,+ }+}++/** The child's advertised tools: the parent's set, minus what a child never+ * gets, then narrowed to its allowlist. */+export function subagentTools(+ parentTools: Record<string, Tool>,+ allowedTools: string[] | null+): Record<string, Tool> {+ const out: Record<string, Tool> = {}+ for (const [name, tool] of Object.entries(parentTools)) {+ if (WITHHELD_FROM_SUBAGENTS.has(name)) continue+ if (allowedTools && !allowedTools.includes(name)) continue+ out[name] = tool+ }+ return out+}++/** Tool names a child may call, for narrowing a nested request. */+export function parentToolNames(tools: Record<string, Tool>): string[] {+ return Object.keys(tools).filter((n) => !WITHHELD_FROM_SUBAGENTS.has(n))+}++/**+ * A fair FIFO gate over concurrent children.+ *+ * Resolves in call order rather than whatever order the microtask queue+ * happens to run, so the queue position reported to the UI is the position the+ * child actually gets.+ */+class Semaphore {+ private free: number+ private waiters: Array<() => void> = []++ constructor(private readonly cap: number) {+ this.free = Math.max(1, cap)+ }++ /** Number of callers currently waiting, for the queued badge. */+ get waiting(): number {+ return this.waiters.length+ }++ /** Free permits; zero means the next `acquire` will queue. */+ get available(): number {+ return this.free+ }++ async acquire(): Promise<() => void> {+ if (this.free > 0) {+ this.free -= 1+ return () => this.release()+ }+ await new Promise<void>((resolve) => this.waiters.push(resolve))+ return () => this.release()+ }++ private release(): void {+ const next = this.waiters.shift()+ if (next) {+ next()+ return+ }+ this.free = Math.min(this.cap, this.free + 1)+ }+}++const gate = new Semaphore(MAX_PARALLEL_SUBAGENTS)++export type SubagentEvents = {+ /** Waiting for a concurrency slot; `waiting` is 1-based FIFO position. */+ onQueued: (waiting: number) => void+ onStart: () => void+ /** One event in the child's own transcript lane. */+ onInner: (event: StreamEvent) => void+ onEnd: (usage: Usage | null) => void+}++export type RunSubagentOptions = {+ resolved: ResolvedSubagent+ description: string+ /** The parent's model instance. Reused so no second load happens. */+ model: LanguageModel+ parentTools: Record<string, Tool>+ system: {+ workspacePath: string | null+ readOnlyFolder: string | null+ bashAvailable: boolean+ }+ /** Runs one of the child's tool calls. Same sandbox as the parent. */+ dispatch: (call: PendingToolCall, signal: AbortSignal) => Promise<ToolOutcome>+ signal: AbortSignal+ events: SubagentEvents+ /** Session tokens already spent, so a child cannot outrun the session cap. */+ sessionTokens?: number+ maxSteps?: number+}++export type SubagentResult = {+ /** The child's final answer, which becomes the `task` tool's output. */+ output: string+ usage: Usage | null+ isError?: boolean+ sessionTokens: number+}++/** One model turn for a child, as a UI message stream the runner can consume. */+function childStep(opts: {+ model: LanguageModel+ system: string+ tools: Record<string, Tool>+ messages: UIMessage[]+ signal: AbortSignal+}): Promise<ReadableStream<UIMessageChunk>> {+ return (async () => {+ const modelMessages = await convertToModelMessages(opts.messages, {+ ignoreIncompleteToolCalls: true,+ })+ const result = streamText({+ model: opts.model,+ system: opts.system,+ messages: modelMessages,+ abortSignal: opts.signal,+ tools: Object.keys(opts.tools).length > 0 ? opts.tools : undefined,+ toolChoice: Object.keys(opts.tools).length > 0 ? 'auto' : undefined,+ })+ return result.toUIMessageStream({+ messageMetadata: ({ part }) => {+ if (part.type !== 'finish') return undefined+ const usage = (part as any).totalUsage+ return {+ usage: {+ inputTokens: usage?.inputTokens,+ outputTokens: usage?.outputTokens,+ totalTokens: usage?.totalTokens,+ },+ }+ },+ onError: (error) =>+ error instanceof Error ? error.message : String(error),+ })+ })()+}++/**+ * Run one subagent to completion and return its final answer.+ *+ * Blocking by design: the parent's `task` call resolves with the result, so the+ * model needs no run-id bookkeeping. Never throws — a failed child comes back as+ * an error string the parent can read and work around.+ */+export async function runSubagent(+ opts: RunSubagentOptions+): Promise<SubagentResult> {+ const { events, resolved } = opts+ let sessionTokens = opts.sessionTokens ?? 0++ // Report the position before queueing, so the badge shows where this child+ // actually sits rather than "queued" with no sense of how far back.+ if (gate.available === 0) events.onQueued(gate.waiting + 1)+ const release = await gate.acquire()+ try {+ if (opts.signal.aborted) {+ events.onEnd(null)+ return { output: '(cancelled)', usage: null, isError: true, sessionTokens }+ }+ events.onStart()++ const tools = subagentTools(opts.parentTools, resolved.allowedTools)+ const system = buildSubagentSystemPrompt(resolved.systemPrompt, {+ workspacePath: opts.system.workspacePath,+ readOnlyFolder: opts.system.readOnlyFolder,+ bashAvailable: opts.system.bashAvailable && 'bash' in tools,+ // Derived, not passed: the intersection above may have dropped them.+ webSearch: 'web_search' in tools,+ })++ // A fresh history: the child does not see the parent's conversation, so the+ // description is the whole brief.+ const messages: UIMessage[] = [+ {+ id: 'sub-user-0',+ role: 'user',+ parts: [{ type: 'text', text: opts.description }],+ } as UIMessage,+ ]++ let finalText = ''+ const sink: StreamSink = {+ onText: (delta) => events.onInner({ type: 'token', text: delta }),+ onToolStart: (id, name) =>+ events.onInner({ type: 'tool_call_started', id, name }),+ onToolArgsDelta: (id, delta) =>+ events.onInner({ type: 'tool_call_args_delta', id, delta }),+ onToolCall: (call) =>+ events.onInner({+ type: 'tool_call',+ id: call.toolCallId,+ name: call.toolName,+ args: call.input,+ }),+ }++ let n = 0+ const outcome = await runTurn({+ messages,+ signal: opts.signal,+ maxSteps: opts.maxSteps ?? MAX_SUBAGENT_STEPS,+ sessionTokens,+ deps: {+ sendStep: (msgs, signal) =>+ childStep({+ model: opts.model,+ system,+ tools,+ messages: msgs,+ signal,+ }),+ dispatch: opts.dispatch,+ sink,+ onStep: ({ result, outcomes }) => {+ if (result.text.trim()) finalText = result.text+ for (const [id, o] of outcomes) {+ events.onInner({+ type: 'tool_result',+ id,+ content: o.output,+ is_error: o.isError ?? false,+ diff: o.diff,+ })+ }+ },+ nextMessageId: () => `sub-asst-${n++}`,+ },+ })+ sessionTokens = outcome.sessionTokens+ events.onEnd(outcome.usage)++ if (outcome.stoppedBy === 'error') {+ return {+ output: outcome.errorText ?? 'the subagent failed',+ usage: outcome.usage,+ isError: true,+ sessionTokens,+ }+ }+ if (outcome.stoppedBy === 'aborted') {+ return {+ output: '(the subagent was cancelled)',+ usage: outcome.usage,+ isError: true,+ sessionTokens,+ }+ }+ if (outcome.stoppedBy === 'steps' || outcome.stoppedBy === 'tokens') {+ // Report the cap plainly with whatever it did produce: the parent can+ // usually finish the errand itself, but not if it thinks the child+ // answered in full.+ const cap =+ outcome.stoppedBy === 'steps'+ ? `its ${opts.maxSteps ?? MAX_SUBAGENT_STEPS}-step budget`+ : 'the session token budget'+ return {+ output:+ `The subagent '${resolved.name}' stopped at ${cap} without finishing.` ++ (finalText ? `\n\nIts last output was:\n${finalText}` : ''),+ usage: outcome.usage,+ isError: true,+ sessionTokens,+ }+ }+ return {+ output: finalText || '(the subagent returned no answer)',+ usage: outcome.usage,+ sessionTokens,+ }+ } finally {+ release()+ }+}++export const __testing = { Semaphore, SUBAGENT_SKILL_TOOLS }diff --git a/web-app/src/lib/coworkSubagentRegistry.ts b/web-app/src/lib/coworkSubagentRegistry.tsnew file mode 100644index 000000000..88f9ebc8e--- /dev/null+++ b/web-app/src/lib/coworkSubagentRegistry.ts@@ -0,0 +1,52 @@+import { invoke } from '@tauri-apps/api/core'++/**+ * The saved subagent definitions available to a Cowork run.+ *+ * Desktop keeps a single directory (`<janDataFolder>/agent-workspace/subagents`)+ * rather than the CLI's plugin/user/project merge: a default session has no+ * project root, and an attached folder is mounted read-only, so scanning it+ * would let a cloned repo inject a system prompt and a tool allowlist into the+ * agent. See `core/agent/subagent.rs::desktop_subagents_dir`.+ *+ * Field names stay snake_case because the same JSON shape is what the `task`+ * tool receives from the model.+ */+export type SubagentDefinition = {+ name: string+ description: string+ system_prompt: string+ /** Narrows the child's toolset. `null` inherits the parent's. */+ allowed_tools: string[] | null+ model: string | null+}++let cache: SubagentDefinition[] | null = null++/**+ * Saved definitions, cached for the app's lifetime.+ *+ * Never throws: an unreadable directory or a missing command costs the run its+ * saved names, not the run itself — a one-off subagent with an inline+ * `system_prompt` still works, which is how the `task` tool stays usable.+ */+export async function listSubagents(): Promise<SubagentDefinition[]> {+ if (cache) return cache+ try {+ cache = await invoke<SubagentDefinition[]>('agent_subagent_list')+ } catch {+ cache = []+ }+ return cache+}++/** Drop the cache so a newly written definition shows up without a restart. */+export function refreshSubagents(): void {+ cache = null+}++export const __testing = {+ reset: () => {+ cache = null+ },+}diff --git a/web-app/src/lib/coworkTodo.ts b/web-app/src/lib/coworkTodo.tsindex 6db6ebdec..41ca88ae9 100644--- a/web-app/src/lib/coworkTodo.ts+++ b/web-app/src/lib/coworkTodo.ts@@ -1,4 +1,4 @@-import type { TodoItem, TodoList, TodoPhase } from '@/types/codeSession'+import type { TodoItem, TodoList, TodoPhase } from '@/types/coworkSession'/*** The `todo` tool's reducer, ported from `core/agent/todo.rs`.diff --git a/web-app/src/lib/coworkTools.ts b/web-app/src/lib/coworkTools.tsindex d4d1cacf1..fd32ab85a 100644--- a/web-app/src/lib/coworkTools.ts+++ b/web-app/src/lib/coworkTools.ts@@ -8,6 +8,12 @@*/import { jsonSchema, type Tool } from 'ai'import { getAgentToolSchemas } from '@/lib/agentTools'+import {+ WEB_FETCH_DESCRIPTION,+ WEB_FETCH_INPUT_SCHEMA,+ WEB_SEARCH_DESCRIPTION,+ WEB_SEARCH_INPUT_SCHEMA,+} from '@/lib/webSearchTool'/** Tools that can mutate something. Withheld, and refused, in plan mode. */export const PLAN_DENIED_TOOLS = new Set([@@ -138,6 +144,12 @@ export type CoworkToolOptions = {subagentNames: string[]/** Depth 1+ cannot spawn further subagents; mirrors the Rust loop's cap. */allowSubagents: boolean+ /**+ * Follows the global web-search setting, the same one chat reads. Cowork has+ * no toggle of its own: the surface configures nothing about its tool set, so+ * this is a Settings-level capability rather than a per-session choice.+ */+ webSearch: boolean}/**@@ -155,6 +167,7 @@ export function coworkToolSignature(opts.planMode ? 'plan' : 'normal',sandboxEnforces ? 'jail' : 'nojail',opts.allowSubagents ? opts.subagentNames.join(',') : 'nosub',+ opts.webSearch ? 'web' : 'noweb',].join('|')}@@ -187,6 +200,18 @@ export async function buildCoworkTools(} as Tool}+ // Reads, so plan mode keeps them: research is most of what planning is.+ if (opts.webSearch) {+ tools['web_search'] = {+ description: WEB_SEARCH_DESCRIPTION,+ inputSchema: jsonSchema(WEB_SEARCH_INPUT_SCHEMA as Record<string, unknown>),+ } as Tool+ tools['web_fetch'] = {+ description: WEB_FETCH_DESCRIPTION,+ inputSchema: jsonSchema(WEB_FETCH_INPUT_SCHEMA as Record<string, unknown>),+ } as Tool+ }+tools[TODO_TOOL_NAME] = todoTooltools[ASK_TOOL_NAME] = askToolif (opts.allowSubagents && !opts.planMode) {diff --git a/web-app/src/lib/coworkTransport.ts b/web-app/src/lib/coworkTransport.tsindex c0a201dfd..97f8d2583 100644--- a/web-app/src/lib/coworkTransport.ts+++ b/web-app/src/lib/coworkTransport.ts@@ -52,6 +52,16 @@ export class CoworkChatTransport extends CustomChatTransport {this.frozenTools = null}+ /**+ * The set actually advertised this run, for narrowing a subagent's tools.+ *+ * A child's allowlist intersects with this rather than with the full built-in+ * list, so plan mode and a withheld `bash` propagate to children for free.+ */+ get advertisedTools(): Record<string, Tool> {+ return this.frozenTools ?? this.tools+ }+/** Cowork gets its own llama.cpp slot: sharing chat's would evict the viewed* thread's prefix on every one of this turn's many prefills, and vice versa. */protected override slotParams(threadId?: string): Record<string, unknown> {@@ -71,6 +81,7 @@ export class CoworkChatTransport extends CustomChatTransport {planMode: this.config.planMode,bashAvailable: sandboxEnforces(),subagentNames: this.config.allowSubagents ? this.config.subagentNames : [],+ webSearch: this.config.webSearch,})const files = this.buildFilesSystemInstruction(messages)return files.trim().length > 0 ? `${base}\n\n${files}` : basediff --git a/web-app/src/lib/codeTurns.ts b/web-app/src/lib/coworkTurns.tssimilarity index 93%rename from web-app/src/lib/codeTurns.tsrename to web-app/src/lib/coworkTurns.tsindex 0feb66c62..805df15d5 100644--- a/web-app/src/lib/codeTurns.ts+++ b/web-app/src/lib/coworkTurns.ts@@ -1,10 +1,10 @@/* eslint-disable @typescript-eslint/no-explicit-any */import type { UIMessage } from 'ai'-import type { CodeTurn } from '@/types/codeSession'+import type { CoworkTurn } from '@/types/coworkSession'import { reasoningPartsFromText } from '@/lib/messages'/**- * Adapts the code screen's flat `CodeTurn[]` transcript into the AI SDK+ * Adapts the code screen's flat `CoworkTurn[]` transcript into the AI SDK* `UIMessage[]` shape that `MessageItem` (the shared chat renderer) consumes.** Grouping: each `user` turn starts a user message; every following@@ -17,8 +17,8 @@ import { reasoningPartsFromText } from '@/lib/messages'* real coloured diff by `AgentToolWidget`, keyed on `toolCallId`. Folding it into* the output text would also corrupt the output the widget parses.*/-export function codeTurnsToUIMessages(- turns: CodeTurn[],+export function coworkTurnsToUIMessages(+ turns: CoworkTurn[],idPrefix = 'code'): UIMessage[] {const messages: UIMessage[] = []diff --git a/web-app/src/lib/hydrateStores.ts b/web-app/src/lib/hydrateStores.tsindex 5dfe41bf2..e470a8b48 100644--- a/web-app/src/lib/hydrateStores.ts+++ b/web-app/src/lib/hydrateStores.ts@@ -20,7 +20,7 @@ import { useJanModelPromptDismissed } from '@/hooks/useJanModelPrompt'import { useDefaultEmbeddingModel } from '@/hooks/useDefaultEmbeddingModel'import { useAgentMode } from '@/hooks/useAgentMode'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'-import { useCodeSessions } from '@/hooks/useCodeSessions'+import { useCoworkSessions } from '@/hooks/useCoworkSessions'import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'/**@@ -53,7 +53,7 @@ const secondaryStores = [useDefaultEmbeddingModel,useAgentMode,useWebSearchConfig,- useCodeSessions,+ useCoworkSessions,useAgentToolsConfig,] as constdiff --git a/web-app/src/lib/tokenCounterVisibility.ts b/web-app/src/lib/tokenCounterVisibility.tsindex 7ce6e9663..983df735a 100644--- a/web-app/src/lib/tokenCounterVisibility.ts+++ b/web-app/src/lib/tokenCounterVisibility.ts@@ -4,6 +4,12 @@ export interface TokenCounterVisibilityInput {isInitialMessage: booleanhasMessages: booleanhasPromptText: boolean+ /**+ * The caller reported usage directly (Cowork, which keeps no thread+ * messages). The remaining conditions all ask "is there a turn worth+ * counting yet"; reported usage answers that outright.+ */+ hasReportedUsage?: boolean}/**@@ -18,8 +24,8 @@ export const shouldShowTokenCounter = ({isInitialMessage,hasMessages,hasPromptText,+ hasReportedUsage = false,}: TokenCounterVisibilityInput): boolean =>hasSelectedModel &&!isAgentMode &&- !isInitialMessage &&- (hasMessages || hasPromptText)+ (hasReportedUsage || (!isInitialMessage && (hasMessages || hasPromptText)))diff --git a/web-app/src/locales/__tests__/localeKeys.test.ts b/web-app/src/locales/__tests__/localeKeys.test.tsindex 4e0963cca..bcc96c9a4 100644--- a/web-app/src/locales/__tests__/localeKeys.test.ts+++ b/web-app/src/locales/__tests__/localeKeys.test.ts@@ -41,6 +41,15 @@ const DYNAMIC_KEYS: Record<string, string[]> = {'checkSearchProbeFailed','checkSearchUnavailable',],+ common: [+ // CoworkEmptyState picks its example set by whether a folder is attached.+ 'coworkEmpty.sandbox.first',+ 'coworkEmpty.sandbox.second',+ 'coworkEmpty.sandbox.third',+ 'coworkEmpty.folder.first',+ 'coworkEmpty.folder.second',+ 'coworkEmpty.folder.third',+ ],'model-errors': ['engine.unknown','engine.MODEL_LOAD_FAILED',@@ -72,14 +81,25 @@ function loadNamespace(namespace: string): Record<string, unknown> {return JSON.parse(readFileSync(join(LOCALE_DIR, `${namespace}.json`), 'utf8'))}+function lookup(bundle: Record<string, unknown>, key: string): unknown {+ return key.split('.').reduce<unknown>((node, part) => {+ if (node && typeof node === 'object' && part in node) {+ return (node as Record<string, unknown>)[part]+ }+ return undefined+ }, bundle)+}++/**+ * A count-aware key lives in the bundle as `_one`/`_other`, never under its own+ * name, so i18next can pick the form. Without this, the only way to satisfy the+ * scan is to drop the `common:` prefix and fall out of it entirely.+ */function resolveKey(bundle: Record<string, unknown>, key: string): boolean {return (- key.split('.').reduce<unknown>((node, part) => {- if (node && typeof node === 'object' && part in node) {- return (node as Record<string, unknown>)[part]- }- return undefined- }, bundle) !== undefined+ lookup(bundle, key) !== undefined ||+ (lookup(bundle, `${key}_one`) !== undefined &&+ lookup(bundle, `${key}_other`) !== undefined))}diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 71a5ea987..eba8c7a36 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -36,7 +36,7 @@"privacy": "Privacy","keyboardShortcuts": "Shortcuts","home": "Home",- "code": "Code",+ "cowork": "Cowork","newSession": "New session","artifacts": "Artifacts","customize": "Customize",@@ -126,7 +126,21 @@"deny": "Deny","start": "Start","stop": "Stop",- "preview": "Preview",+ "preview": {+ "loading": "Opening…",+ "unsupported": "Jan can't show this kind of file. Open it to see it in another app.",+ "outside": "This file is no longer in the session workspace.",+ "tooLarge": "Too big to preview. Open it to see it in another app.",+ "reload": "Reload",+ "allowNetwork": "Allow network",+ "unresolvedRefs_one": "1 file this page links to can't load in the preview. Open it to see it in a browser.",+ "unresolvedRefs_other": "{{count}} files this page links to can't load in the preview. Open it to see it in a browser."+ },+ "changes": {+ "title": "Agent changes",+ "empty": "Files the agent writes or edits will show up here.",+ "a11y": "Agent changes: {{files}} files, {{additions}} added, {{deletions}} removed"+ },"compactWidth": "Compact Width","fullWidth": "Full Width","dark": "Dark",@@ -618,11 +632,8 @@"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.",+ "footnote": "The agent only reads this folder. Nothing inside it is ever 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",@@ -630,8 +641,24 @@"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."+ "a11yWithFolder": "Project folder {{folder}}, attached read-only. Change or detach it.",+ "a11yNoFolder": "No project folder attached. Attach one."+ },+ "coworkEmpty": {+ "title": "What are we working on?",+ "subtitleSandbox": "Give Jan a task. It reads and writes files, runs commands, and works through the steps on its own.",+ "subtitleFolder": "Give Jan a task. It reads {{folder}} without changing anything in it, and works on its own from there.",+ "try": "Try",+ "sandbox": {+ "first": "Write a Python script that renames files by the date they were taken",+ "second": "Build a single-page dashboard from a CSV I'll paste in",+ "third": "Draft a README for a project I describe to you"+ },+ "folder": {+ "first": "Explain how {{folder}} is put together",+ "second": "Find every TODO in {{folder}} and group them by area",+ "third": "Write tests for the part of {{folder}} I point you at"+ }},"sandbox": {"noTerminal": "No terminal",@@ -658,6 +685,7 @@"compact": "Compact","newSession": "New session"},+ "modelNoTools": "{{model}} can’t call tools, so it can’t act as an agent. Pick a tool-calling model.","askContinue": "Continue","askNext": "Next question","askPrev": "Previous question",diff --git a/web-app/src/routeTree.gen.ts b/web-app/src/routeTree.gen.tsindex e1c41c801..6c52f6e05 100644--- a/web-app/src/routeTree.gen.ts+++ b/web-app/src/routeTree.gen.ts@@ -11,7 +11,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 CoworkRouteImport } from './routes/cowork'import { Route as ArtifactsRouteImport } from './routes/artifacts'import { Route as IndexRouteImport } from './routes/index'import { Route as HubIndexRouteImport } from './routes/hub/index'@@ -46,9 +46,9 @@ const LogsRoute = LogsRouteImport.update({path: '/logs',getParentRoute: () => rootRouteImport,} as any)-const CodeRoute = CodeRouteImport.update({- id: '/code',- path: '/code',+const CoworkRoute = CoworkRouteImport.update({+ id: '/cowork',+ path: '/cowork',getParentRoute: () => rootRouteImport,} as any)const ArtifactsRoute = ArtifactsRouteImport.update({@@ -171,7 +171,7 @@ const SettingsProvidersProviderNameRoute =export interface FileRoutesByFullPath {'/': typeof IndexRoute'/artifacts': typeof ArtifactsRoute- '/code': typeof CodeRoute+ '/cowork': typeof CoworkRoute'/logs': typeof LogsRoute'/system-monitor': typeof SystemMonitorRoute'/hub/$modelId': typeof HubModelIdRoute@@ -199,7 +199,7 @@ export interface FileRoutesByFullPath {export interface FileRoutesByTo {'/': typeof IndexRoute'/artifacts': typeof ArtifactsRoute- '/code': typeof CodeRoute+ '/cowork': typeof CoworkRoute'/logs': typeof LogsRoute'/system-monitor': typeof SystemMonitorRoute'/hub/$modelId': typeof HubModelIdRoute@@ -228,7 +228,7 @@ export interface FileRoutesById {__root__: typeof rootRouteImport'/': typeof IndexRoute'/artifacts': typeof ArtifactsRoute- '/code': typeof CodeRoute+ '/cowork': typeof CoworkRoute'/logs': typeof LogsRoute'/system-monitor': typeof SystemMonitorRoute'/hub/$modelId': typeof HubModelIdRoute@@ -258,7 +258,7 @@ export interface FileRouteTypes {fullPaths:| '/'| '/artifacts'- | '/code'+ | '/cowork'| '/logs'| '/system-monitor'| '/hub/$modelId'@@ -286,7 +286,7 @@ export interface FileRouteTypes {to:| '/'| '/artifacts'- | '/code'+ | '/cowork'| '/logs'| '/system-monitor'| '/hub/$modelId'@@ -314,7 +314,7 @@ export interface FileRouteTypes {| '__root__'| '/'| '/artifacts'- | '/code'+ | '/cowork'| '/logs'| '/system-monitor'| '/hub/$modelId'@@ -343,7 +343,7 @@ export interface FileRouteTypes {export interface RootRouteChildren {IndexRoute: typeof IndexRouteArtifactsRoute: typeof ArtifactsRoute- CodeRoute: typeof CodeRoute+ CoworkRoute: typeof CoworkRouteLogsRoute: typeof LogsRouteSystemMonitorRoute: typeof SystemMonitorRouteHubModelIdRoute: typeof HubModelIdRoute@@ -385,11 +385,11 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof LogsRouteImportparentRoute: typeof rootRouteImport}- '/code': {- id: '/code'- path: '/code'- fullPath: '/code'- preLoaderRoute: typeof CodeRouteImport+ '/cowork': {+ id: '/cowork'+ path: '/cowork'+ fullPath: '/cowork'+ preLoaderRoute: typeof CoworkRouteImportparentRoute: typeof rootRouteImport}'/artifacts': {@@ -559,7 +559,7 @@ declare module '@tanstack/react-router' {const rootRouteChildren: RootRouteChildren = {IndexRoute: IndexRoute,ArtifactsRoute: ArtifactsRoute,- CodeRoute: CodeRoute,+ CoworkRoute: CoworkRoute,LogsRoute: LogsRoute,SystemMonitorRoute: SystemMonitorRoute,HubModelIdRoute: HubModelIdRoute,diff --git a/web-app/src/routes/artifacts.tsx b/web-app/src/routes/artifacts.tsxindex 798e53596..f01b778a7 100644--- a/web-app/src/routes/artifacts.tsx+++ b/web-app/src/routes/artifacts.tsx@@ -14,16 +14,17 @@ import {} 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 { useCoworkSessions } from '@/hooks/useCoworkSessions'+import { useCoworkRun } from '@/hooks/useCoworkRun'+import { getServiceHub, useServiceHub } from '@/hooks/useServiceHub'+import { sessionWorkspacePath } from '@janhq/tauri-plugin-agent-tools-api'import {ARTIFACT_GROUP_NAMES,ARTIFACT_ICON,artifactsFromTurns,- type CodeArtifact,-} from '@/lib/codeArtifacts'-import { previewKindFor, resolveInRoot } from '@/lib/codePreview'+ type CoworkArtifact,+} from '@/lib/coworkArtifacts'+import { previewKindFor, resolveInRoot } from '@/lib/coworkPreview'export const Route = createFileRoute(route.artifacts as any)({component: ArtifactsPage,@@ -31,15 +32,57 @@ export const Route = createFileRoute(route.artifacts as any)({const PAGE = 24-type Row = CodeArtifact & { sessionId: string; root: string | null }+type Row = CoworkArtifact & { sessionId: string; root: string | null }++/**+ * Each session's sandbox, keyed by id.+ *+ * Artifacts only ever live there: an attached folder is mounted read-only, so+ * every write the agent lands is inside the sandbox. Resolving against+ * `session.folder` pointed at a path that does not exist -- and at nothing at+ * all for a session with no folder attached, which hid Open and the thumbnails+ * entirely.+ */+function useSessionWorkspaces(sessionIds: string[]): Record<string, string> {+ const [paths, setPaths] = useState<Record<string, string>>({})+ const key = sessionIds.join(',')++ useEffect(() => {+ let alive = true+ void (async () => {+ const dataFolder = await getServiceHub().app().getJanDataFolder()+ if (!dataFolder) return+ const found = await Promise.all(+ key+ .split(',')+ .filter(Boolean)+ .map(async (id) => {+ try {+ return [id, await sessionWorkspacePath(dataFolder, id)] as const+ } catch {+ return [id, ''] as const+ }+ })+ )+ if (alive) {+ setPaths(Object.fromEntries(found.filter(([, path]) => path)))+ }+ })()+ return () => {+ alive = false+ }+ }, [key])++ return paths+}function ArtifactsPage() {const { t } = useTranslation()const navigate = useNavigate()const serviceHub = useServiceHub()- const sessions = useCodeSessions((s) => s.sessions)+ const sessions = useCoworkSessions((s) => s.sessions)const [query, setQuery] = useState('')- const [group, setGroup] = useState<CodeArtifact['group'] | null>(null)+ const [group, setGroup] = useState<CoworkArtifact['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.@@ -49,16 +92,21 @@ function ArtifactsPage() {// 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 workspaces = useSessionWorkspaces(+ useMemo(() => sessions.map((s) => s.id), [sessions])+ )+const rows = useMemo<Row[]>(() =>- sessions.flatMap((session) =>- artifactsFromTurns(session.turns, session.folder).map((artifact) => ({+ sessions.flatMap((session) => {+ const root = workspaces[session.id] ?? null+ return artifactsFromTurns(session.turns, root).map((artifact) => ({...artifact,sessionId: session.id,- root: session.folder ?? null,+ root,}))- ),- [sessions]+ }),+ [sessions, workspaces])const shown = useMemo(() => {@@ -66,7 +114,9 @@ function ArtifactsPage() {return rows.filter((r) =>(!group || r.group === group) &&- (!q || r.title.toLowerCase().includes(q) || r.path.toLowerCase().includes(q))+ (!q ||+ r.title.toLowerCase().includes(q) ||+ r.path.toLowerCase().includes(q)))}, [rows, query, group])@@ -74,9 +124,9 @@ function ArtifactsPage() {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 })+ useCoworkSessions.getState().selectSession(row.sessionId)+ useCoworkRun.getState().requestPreview(row.sessionId, row.path)+ navigate({ to: route.cowork })}return (@@ -120,7 +170,9 @@ function ArtifactsPage() {{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')}+ {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">@@ -158,7 +210,9 @@ function ArtifactsPage() {)}{/* 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-sm font-medium">+ {row.title}+ </span><span className="block truncate text-xs text-muted-foreground">{row.group} · {row.label}</span>@@ -175,7 +229,10 @@ function ArtifactsPage() {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" />+ <SquareArrowOutUpRight+ size={13}+ className="text-muted-foreground"+ /></button><DropdownMenu><DropdownMenuTrigger asChild>@@ -184,18 +241,25 @@ function ArtifactsPage() {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" />+ <ChevronsUpDown+ size={13}+ className="text-muted-foreground"+ /></button></DropdownMenuTrigger><DropdownMenuContent align="end"><DropdownMenuItem- onClick={() => void serviceHub.opener().openPath(abs)}+ onClick={() =>+ void serviceHub.opener().openPath(abs)+ }><SquareArrowOutUpRight size={14} />{t('common:artifactOpenExternal')}</DropdownMenuItem><DropdownMenuItem- onClick={() => void serviceHub.opener().revealItemInDir(abs)}+ onClick={() =>+ void serviceHub.opener().revealItemInDir(abs)+ }><FolderOpen size={14} />{t('common:artifactShowInFolder')}@@ -211,7 +275,11 @@ function ArtifactsPage() {)}{shown.length > limit && (<div className="mt-3 flex justify-center">- <Button variant="outline" size="sm" onClick={() => setLimit((n) => n + PAGE)}>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setLimit((n) => n + PAGE)}+ >{t('common:artifactsShowMore', { count: shown.length - limit })}</Button></div>diff --git a/web-app/src/routes/code.tsx b/web-app/src/routes/code.tsxdeleted file mode 100644index 9c8fcd2bf..000000000--- a/web-app/src/routes/code.tsx+++ /dev/null@@ -1,460 +0,0 @@-/* eslint-disable @typescript-eslint/no-explicit-any */-import { createFileRoute } from '@tanstack/react-router'-import ChatInput from '@/containers/ChatInput'-import HeaderPage from '@/containers/HeaderPage'-import { useTranslation } from '@/i18n/react-i18next-compat'-import { route } from '@/constants/routes'-import { useServiceHub } from '@/hooks/useServiceHub'-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { toast } from 'sonner'-import { invoke } from '@tauri-apps/api/core'-import { getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'-import { sessionWorkspacePath } from '@janhq/tauri-plugin-agent-tools-api'-import { cn } from '@/lib/utils'-import {- useCodeSessions,- ensureCurrentSession,-} from '@/hooks/useCodeSessions'-import type { AskAnswer, CodeTurn } from '@/types/codeSession'-import DropdownModelProvider from '@/containers/DropdownModelProvider'-import { useModelProvider } from '@/hooks/useModelProvider'-import { MessageItem } from '@/containers/MessageItem'-import SkillSelector from '@/containers/SkillSelector'-import { codeTurnsToUIMessages } from '@/lib/codeTurns'-import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'-import { PromptProgress } from '@/components/PromptProgress'-import { useAppState } from '@/hooks/useAppState'-import { useAutoScroll } from '@/hooks/useAutoScroll'-import {- Conversation,- 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,-})--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 session = useMemo(- () => sessions.find((s) => s.id === currentId) ?? null,- [sessions, currentId]- )- const folder = session?.folder ?? null- const planMode = session?.planMode ?? false-- const [running, setRunning] = useState(false)- const [liveTurns, setLiveTurns] = useState<CodeTurn[]>([])- const liveTurnsRef = useRef<CodeTurn[]>([])- 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)-- const {- containerRef: reasoningContainerRef,- isAtBottom: isReasoningAtBottom,- handleScroll: handleReasoningScroll,- forceScrollToBottom: forceScrollReasoningToBottom,- } = useAutoScroll()-- // The session's sandbox, resolved once so the workspace pill can name the- // directory writes actually land in.- useEffect(() => {- 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.- }- })()- return () => {- alive = false- }- }, [session?.id, serviceHub])-- useEffect(() => {- if (!folder) {- setGitBranch(null)- return- }- invoke<string | null>('agent_git_branch', { project: folder })- .then(setGitBranch)- .catch(() => setGitBranch(null))- }, [folder])-- 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])-- const detachFolder = useCallback(() => {- if (session?.id) useCodeSessions.getState().setFolder(session.id, null)- }, [session?.id])-- const displayedTurns = useMemo(- () => (running ? liveTurns : (session?.turns ?? [])),- [running, liveTurns, session?.turns]- )- const uiMessages = useMemo(- () => codeTurnsToUIMessages(displayedTurns, session?.id ?? 'code'),- [displayedTurns, session?.id]- )-- const pushLive = useCallback((turns: CodeTurn[]) => {- liveTurnsRef.current = [...liveTurnsRef.current, ...turns]- setLiveTurns(liveTurnsRef.current)- }, [])-- const handleSubmit = async (text: string) => {- if (running) return- const sid = ensureCurrentSession()- const store = useCodeSessions.getState()- const current = store.sessions.find((s) => s.id === sid)- if (!selectedModel?.id) {- toast.error(t('common:selectModel'))- return- }- if (current?.title === 'New session') store.setTitle(sid, text.slice(0, 40))-- setStoppedBy(null)- liveTurnsRef.current = [{ role: 'user', content: text }]- setLiveTurns(liveTurnsRef.current)- setRunning(true)-- // 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)) {- useAppState.getState().updateModelLoadProgress(undefined)- useAppState.getState().updateLoadingModel(true)- }- } catch {- // Probe failed; skip the card rather than flash it every run.- }- }-- // 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 {- 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) {- pushLive([- {- role: 'tool',- content: '',- name: 'error',- result: e instanceof Error ? e.message : String(e),- isError: true,- status: 'done',- },- ])- } finally {- useAppState.getState().updateLoadingModel(false)- useCodeSessions- .getState()- .commitTurns(- sid,- liveTurnsRef.current,- outcome?.messages ?? messages,- [],- outcome?.usage ?? undefined- )- liveTurnsRef.current = []- setLiveTurns([])- setRunning(false)- abortRef.current = null- askResolvers.current.clear()- setAsk(null)- setStoppedBy(outcome?.stoppedBy ?? null)- }- }-- 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)))]">- <HeaderPage>- <div className="flex items-center justify-between w-full pr-2">- <DropdownModelProvider useLastUsedModel />- </div>- </HeaderPage>-- <div className="flex flex-1 flex-col h-full overflow-hidden">- <div className="flex-1 relative">- {displayedTurns.length === 0 ? (- <div className="absolute inset-0 flex flex-col items-center justify-center px-3">- <h1 className="text-2xl font-studio font-medium">- {t('common:newSession')}- </h1>- </div>- ) : (- <Conversation className="absolute inset-0 text-start">- <ConversationContent- className={cn('mx-auto w-full md:w-4/5 xl:w-4/6')}- >- {uiMessages.map((message, i) => (- <MessageItem- key={message.id}- message={message}- isFirstMessage={i === 0}- isLastMessage={i === uiMessages.length - 1}- status={running ? 'streaming' : 'ready'}- reasoningContainerRef={reasoningContainerRef}- isReasoningAtBottom={isReasoningAtBottom}- onReasoningScroll={handleReasoningScroll}- onReasoningScrollToBottom={forceScrollReasoningToBottom}- />- ))}- {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>-- <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">- <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>- {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>- </div>- )-}diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxnew file mode 100644index 000000000..c03a956ee--- /dev/null+++ b/web-app/src/routes/cowork.tsx@@ -0,0 +1,703 @@+/* eslint-disable @typescript-eslint/no-explicit-any */+import { createFileRoute } from '@tanstack/react-router'+import ChatInput from '@/containers/ChatInput'+import HeaderPage from '@/containers/HeaderPage'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { route } from '@/constants/routes'+import { useServiceHub } from '@/hooks/useServiceHub'+import {+ Fragment,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react'+import { toast } from 'sonner'+import { invoke } from '@tauri-apps/api/core'+import { getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'+import { sessionWorkspacePath } from '@janhq/tauri-plugin-agent-tools-api'+import { cn } from '@/lib/utils'+import {+ useCoworkSessions,+ ensureCurrentSession,+} from '@/hooks/useCoworkSessions'+import type { AskAnswer, CoworkTurn, Usage } from '@/types/coworkSession'+import DropdownModelProvider from '@/containers/DropdownModelProvider'+import { useModelProvider } from '@/hooks/useModelProvider'+import { MessageItem } from '@/containers/MessageItem'+import SkillSelector from '@/containers/SkillSelector'+import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'+import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'+import { PromptProgress } from '@/components/PromptProgress'+import { useAppState } from '@/hooks/useAppState'+import { useAutoScroll } from '@/hooks/useAutoScroll'+import {+ Conversation,+ ConversationContent,+ ConversationScrollButton,+} from '@/components/ai-elements/conversation'+import { CoworkWorkspacePill } from '@/containers/CoworkWorkspacePill'+import { CoworkPlanToggle } from '@/containers/CoworkPlanToggle'+import { CoworkEmptyState } from '@/containers/CoworkEmptyState'+import { usePrompt } from '@/hooks/usePrompt'+import { awaitsModel } from '@/lib/agentActivity'+import { artifactsFromParts } from '@/lib/coworkArtifacts'+import { CoworkArtifactCard } from '@/containers/CoworkArtifactCard'+import { CoworkPreviewPanel } from '@/containers/CoworkPreviewPanel'+import { CoworkDiffPanel } from '@/containers/CoworkDiffPanel'+import { CoworkChangesChip } from '@/containers/CoworkChangesChip'+import { collectCodeFileDiffs } from '@/lib/coworkDiffs'+import { CoworkSandboxChip } from '@/containers/CoworkSandboxChip'+import { CoworkBudgetNotice } from '@/containers/CoworkBudgetNotice'+import { CoworkAskCard } from '@/containers/CoworkAskCard'+import { CoworkChatTransport } from '@/lib/coworkTransport'+import { dispatchCoworkTool } from '@/lib/coworkDispatch'+import { applyTodoOp, renderTodoResult } from '@/lib/coworkTodo'+import { parseAskRequest, renderAskResult } from '@/lib/coworkAsk'+import { getSandboxStatus, sandboxEnforces } from '@/lib/agentTools'+import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'+import { MAX_AGENT_STEPS } from '@/lib/coworkBudget'+import {+ abortRun,+ answerAsk,+ runTurn,+ type RunOutcome,+ type StreamSink,+ type ToolOutcome,+} from '@/lib/coworkRunner'+import { useCoworkRun } from '@/hooks/useCoworkRun'+import {+ listSubagents,+ type SubagentDefinition,+} from '@/lib/coworkSubagentRegistry'+import {+ parseSubagentRequest,+ resolveSubagent,+ parentToolNames,+ runSubagent,+} from '@/lib/coworkSubagent'++export const Route = createFileRoute(route.cowork as any)({+ component: CoworkPage,+})++function CoworkPage() {+ const { t } = useTranslation()+ const serviceHub = useServiceHub()+ const { selectedModel, selectedProvider } = useModelProvider()++ const sessions = useCoworkSessions((s) => s.sessions)+ const currentId = useCoworkSessions((s) => s.currentId)+ const session = useMemo(+ () => sessions.find((s) => s.id === currentId) ?? null,+ [sessions, currentId]+ )+ const folder = session?.folder ?? null+ const planMode = session?.planMode ?? false++ const [running, setRunning] = useState(false)+ const [liveTurns, setLiveTurns] = useState<CoworkTurn[]>([])+ const liveTurnsRef = useRef<CoworkTurn[]>([])+ const [stoppedBy, setStoppedBy] = useState<RunOutcome['stoppedBy'] | null>(+ null+ )+ const [gitBranch, setGitBranch] = useState<string | null>(null)+ const [subagentDefs, setSubagentDefs] = useState<SubagentDefinition[]>([])+ const [workspacePath, setWorkspacePath] = useState<string | null>(null)+ // The step just finished, so the counter tracks a run instead of jumping once+ // at the end. Falls back to the committed usage between runs.+ const [liveUsage, setLiveUsage] = useState<Usage | null>(null)+ // The rail holds one panel at a time: preview and diff both want the width,+ // so showing them together starves the transcript (C7).+ const [rail, setRail] = useState<+ { kind: 'preview'; path: string } | { kind: 'diff' } | null+ >(null)+ const showPreview = useCallback(+ (path: string) => setRail({ kind: 'preview', path }),+ []+ )+ const [ask, setAsk] = useState<{+ requestId: string+ request: ReturnType<typeof parseAskRequest>+ } | null>(null)++ const {+ containerRef: reasoningContainerRef,+ isAtBottom: isReasoningAtBottom,+ handleScroll: handleReasoningScroll,+ forceScrollToBottom: forceScrollReasoningToBottom,+ } = useAutoScroll()++ // The session's sandbox, resolved once so the workspace pill can name the+ // directory writes actually land in.+ useEffect(() => {+ 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.+ }+ })()+ return () => {+ alive = false+ }+ }, [session?.id, serviceHub])++ // Saved definitions name the `task` tool's options. Loaded once: the list is+ // only advertised, so a definition added mid-session applies at the next run.+ useEffect(() => {+ let alive = true+ void listSubagents().then((defs) => {+ if (alive) setSubagentDefs(defs)+ })+ return () => {+ alive = false+ }+ }, [])++ useEffect(() => {+ if (!folder) {+ setGitBranch(null)+ return+ }+ invoke<string | null>('agent_git_branch', { project: folder })+ .then(setGitBranch)+ .catch(() => setGitBranch(null))+ }, [folder])++ const attachFolder = useCallback(async () => {+ const picked = await serviceHub.dialog().open({ directory: true })+ if (typeof picked !== 'string') return+ const sid = ensureCurrentSession()+ useCoworkSessions.getState().setFolder(sid, picked)+ }, [serviceHub])++ const detachFolder = useCallback(() => {+ if (session?.id) useCoworkSessions.getState().setFolder(session.id, null)+ }, [session?.id])++ const displayedTurns = useMemo(+ () => (running ? liveTurns : (session?.turns ?? [])),+ [running, liveTurns, session?.turns]+ )+ const uiMessages = useMemo(+ () => coworkTurnsToUIMessages(displayedTurns, session?.id ?? 'cowork'),+ [displayedTurns, session?.id]+ )++ const usage = liveUsage ?? session?.lastUsage ?? null+ const tokenSource = useMemo(+ () => ({+ threadId: session?.id,+ usage: usage+ ? {+ inputTokens: usage.prompt_tokens,+ outputTokens: usage.completion_tokens,+ totalTokens: usage.total_tokens,+ }+ : undefined,+ }),+ [session?.id, usage]+ )++ // Live runs write into the run store; a committed session carries its own.+ const liveSubagents = useCoworkRun((s) =>+ session?.id ? s.subagents[session.id] : undefined+ )+ const fileDiffs = useMemo(+ () =>+ collectCodeFileDiffs(+ displayedTurns,+ liveSubagents ?? session?.subagents ?? []+ ),+ [displayedTurns, liveSubagents, session?.subagents]+ )++ const awaitingModel = useMemo(+ () => awaitsModel(running, displayedTurns),+ [running, displayedTurns]+ )++ const pushLive = useCallback((turns: CoworkTurn[]) => {+ liveTurnsRef.current = [...liveTurnsRef.current, ...turns]+ setLiveTurns(liveTurnsRef.current)+ }, [])++ const handleSubmit = async (text: string) => {+ if (running) return+ const sid = ensureCurrentSession()+ const store = useCoworkSessions.getState()+ const current = store.sessions.find((s) => s.id === sid)+ if (!selectedModel?.id) {+ toast.error(t('common:selectModel'))+ return+ }+ // Without tool calling the transport drops the tool set silently, and the+ // agent then narrates work it never did. Refusing up front is honest; a+ // toolless "agent" run is worse than no run.+ if (!selectedModel.capabilities?.includes('tools')) {+ toast.error(t('common:modelNoTools', { model: selectedModel.id }))+ return+ }+ if (current?.title === 'New session') store.setTitle(sid, text.slice(0, 40))++ setStoppedBy(null)+ setLiveUsage(null)+ liveTurnsRef.current = [{ role: 'user', content: text }]+ setLiveTurns(liveTurnsRef.current)+ useCoworkRun.getState().resetSubagents(sid)+ setRunning(true)++ // 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)) {+ useAppState.getState().updateModelLoadProgress(undefined)+ useAppState.getState().updateLoadingModel(true)+ }+ } catch {+ // Probe failed; skip the card rather than flash it every run.+ }+ }++ // Warm the sandbox probe: the transport's prompt and tool set read it+ // synchronously via sandboxEnforces().+ await getSandboxStatus()+ // Read once per run, not subscribed: the advertised set is frozen for the+ // run anyway, so a mid-run flip in Settings would only desync the prompt.+ const webSearch = useWebSearchConfig.getState().webSearchEnabled+ const transport = new CoworkChatTransport(sid, {+ planMode: current?.planMode ?? false,+ subagentNames: subagentDefs.map((d) => d.name),+ // Always on at depth 0, even with nothing saved: a one-off subagent with+ // an inline `system_prompt` is first-class, as it is in Rust.+ allowSubagents: true,+ webSearch,+ 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 {+ outcome = await runTurn({+ messages,+ signal: controller.signal,+ // Starts at zero each request, matching Rust: `SessionBudget` is built+ // inside `run_orchestration_streamed`, so the allowance is per request.+ // The previous turn's `total_tokens` is a context size, not a spend, and+ // seeding with it would pre-charge the whole replayed prompt.+ sessionTokens: 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,+ webSearch,+ onTodo: async (input) => {+ const result = applyTodoOp(+ useCoworkSessions+ .getState()+ .sessions.find((s) => s.id === sid)?.todos,+ input+ )+ if (result.error) {+ return { output: `ERROR: ${result.error}`, isError: true }+ }+ useCoworkSessions.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 (callId, input) => {+ const req = parseSubagentRequest(input)+ if (typeof req === 'string') {+ return { output: `ERROR: ${req}`, isError: true }+ }+ const resolved = resolveSubagent(+ req,+ subagentDefs,+ parentToolNames(transport.advertisedTools)+ )+ if ('error' in resolved) {+ return { output: `ERROR: ${resolved.error}`, isError: true }+ }+ if (!transport.model) {+ return {+ output:+ 'ERROR: no model is loaded for this run, so no subagent can start',+ isError: true,+ }+ }+ const child = await runSubagent({+ resolved,+ description: req.description,+ // The parent's instance: a second one would mean a second+ // llama-server load for the same model.+ model: transport.model,+ parentTools: transport.advertisedTools,+ system: {+ workspacePath,+ readOnlyFolder: current?.folder ?? null,+ bashAvailable: sandboxEnforces(),+ },+ signal: controller.signal,+ sessionTokens: 0,+ // A child never gets `todo`/`ask`/`task`, so these refuse+ // rather than execute: a model can still emit a call to a+ // tool that was never advertised.+ dispatch: (call) =>+ dispatchCoworkTool(call, {+ sessionId: sid,+ readOnlyFolder: current?.folder ?? null,+ planMode: current?.planMode ?? false,+ webSearch,+ onTodo: async () => ({+ output:+ 'The todo list belongs to the agent that dispatched you.',+ isError: true,+ }),+ onAsk: async () => ({+ output:+ 'You cannot ask the user questions. Decide, and say what you assumed.',+ isError: true,+ }),+ onTask: async () => ({+ output: 'A subagent cannot dispatch subagents.',+ isError: true,+ }),+ }),+ events: {+ onQueued: (waiting) =>+ useCoworkRun+ .getState()+ .queueSubagent(sid, callId, resolved.name, waiting),+ onStart: () =>+ useCoworkRun+ .getState()+ .startSubagent(sid, callId, resolved.name),+ onInner: (event) =>+ useCoworkRun+ .getState()+ .routeIntoSubagent(sid, callId, event),+ onEnd: (usage) =>+ useCoworkRun.getState().endSubagent(sid, callId, usage),+ },+ })+ useCoworkRun+ .getState()+ .attachSubagentOutput(sid, callId, child.output)+ return { output: child.output, isError: child.isError }+ },+ }),+ sink,+ onStep: ({ result, turns, outcomes }) => {+ if (result.usage) setLiveUsage(result.usage)+ // 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) {+ pushLive([+ {+ role: 'tool',+ content: '',+ name: 'error',+ result: e instanceof Error ? e.message : String(e),+ isError: true,+ status: 'done',+ },+ ])+ } finally {+ useAppState.getState().updateLoadingModel(false)+ useCoworkSessions+ .getState()+ .commitTurns(+ sid,+ liveTurnsRef.current,+ outcome?.messages ?? messages,+ useCoworkRun.getState().subagents[sid] ?? [],+ outcome?.usage ?? undefined+ )+ liveTurnsRef.current = []+ setLiveTurns([])+ setRunning(false)+ abortRef.current = null+ askResolvers.current.clear()+ setAsk(null)+ setStoppedBy(outcome?.stoppedBy ?? null)+ }+ }++ 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(() => () => useCoworkRun.getState().clearPendingPreview(), [])++ // The artifacts library selects a session, parks the path here and navigates.+ // Consumed once, so returning to Cowork later does not reopen it.+ const pendingPreview = useCoworkRun((s) => s.pendingPreview)+ useEffect(() => {+ if (!pendingPreview || !session?.id) return+ if (pendingPreview.sessionId !== session.id) return+ setRail({ kind: 'preview', path: pendingPreview.path })+ useCoworkRun.getState().clearPendingPreview()+ }, [pendingPreview, session?.id])++ // Nothing to show once the session changes: both panels describe the session+ // they were opened from.+ useEffect(() => setRail(null), [session?.id])++ return (+ <div className="flex flex-col h-[calc(100dvh-(env(safe-area-inset-bottom)+env(safe-area-inset-top)))]">+ <HeaderPage>+ <div className="flex items-center justify-between w-full pr-2">+ <DropdownModelProvider useLastUsedModel />+ </div>+ </HeaderPage>++ <div className="flex flex-1 h-full overflow-hidden">+ <div className="flex min-w-0 flex-1 flex-col h-full overflow-hidden">+ <div className="flex-1 relative">+ {displayedTurns.length === 0 ? (+ <CoworkEmptyState+ folder={folder}+ onPick={(text) => usePrompt.getState().setPrompt(text)}+ />+ ) : (+ <Conversation className="absolute inset-0 text-start">+ <ConversationContent+ className={cn('mx-auto w-full md:w-4/5 xl:w-4/6')}+ >+ {uiMessages.map((message, i) => (+ <Fragment key={message.id}>+ <MessageItem+ message={message}+ isFirstMessage={i === 0}+ isLastMessage={i === uiMessages.length - 1}+ status={running ? 'streaming' : 'ready'}+ reasoningContainerRef={reasoningContainerRef}+ isReasoningAtBottom={isReasoningAtBottom}+ onReasoningScroll={handleReasoningScroll}+ onReasoningScrollToBottom={forceScrollReasoningToBottom}+ />+ {/* Derived from the message's own write parts, so nothing+ shared with the chat surface needs to know artifacts+ exist. */}+ {artifactsFromParts(message.parts).map((artifact) => (+ <CoworkArtifactCard+ key={artifact.path}+ artifact={artifact}+ root={workspacePath}+ onPreview={showPreview}+ />+ ))}+ </Fragment>+ ))}+ {running && (+ // Row wrapper as in the chat route: the transcript is a+ // column flex, which stretches the indicator's own+ // `inline-flex` box across the whole column.+ <div className="flex flex-row items-center gap-2">+ <PromptProgress+ hideIdle={!awaitingModel}+ stateKey={session?.id}+ />+ </div>+ )}+ {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={() =>+ useCoworkSessions.getState().createSession()+ }+ />+ )}+ </ConversationContent>+ <ConversationScrollButton />+ </Conversation>+ )}+ </div>++ <div className="pb-4 shrink-0">+ <div className="mx-auto w-full md:w-4/5 xl:w-4/6">+ {ask && typeof ask.request !== 'string' && (+ <div className="px-1 pb-2">+ <CoworkAskCard+ requestId={ask.requestId}+ request={ask.request}+ onRespond={respondAsk}+ />+ </div>+ )}+ <ChatInput+ showSpeedToken={false}+ initialMessage={true}+ scopeKey={session?.id}+ ownsToolSet={false}+ onSubmit={handleSubmit}+ onStop={handleStop}+ chatStatus={running ? 'streaming' : 'ready'}+ tokenSource={tokenSource}+ surfaceControls={+ <>+ <CoworkPlanToggle+ planMode={planMode}+ onChange={(next) => {+ if (session?.id)+ useCoworkSessions+ .getState()+ .setPlanMode(session.id, next)+ }}+ />+ <CoworkWorkspacePill+ folder={folder}+ gitBranch={gitBranch}+ onAttach={() => void attachFolder()}+ onDetach={detachFolder}+ />+ <CoworkSandboxChip />+ <CoworkChangesChip+ files={fileDiffs}+ open={rail?.kind === 'diff'}+ onToggle={() =>+ setRail((r) =>+ r?.kind === 'diff' ? null : { kind: 'diff' }+ )+ }+ />+ <div className="ml-auto flex items-center">+ <SkillSelector folder={folder} />+ </div>+ </>+ }+ />+ </div>+ </div>+ </div>++ {rail?.kind === 'preview' && (+ <CoworkPreviewPanel+ root={workspacePath}+ path={rail.path}+ onClose={() => setRail(null)}+ />+ )}+ {rail?.kind === 'diff' && (+ <CoworkDiffPanel files={fileDiffs} onClose={() => setRail(null)} />+ )}+ </div>+ </div>+ )+}diff --git a/web-app/src/types/codeSession.ts b/web-app/src/types/coworkSession.tssimilarity index 97%rename from web-app/src/types/codeSession.tsrename to web-app/src/types/coworkSession.tsindex 1108ae1d1..0e0b6ca23 100644--- a/web-app/src/types/codeSession.ts+++ b/web-app/src/types/coworkSession.ts@@ -9,7 +9,7 @@/** A single visible transcript entry. `tool` rows are display-only and carry the* structured call/result so the UI can render a tool card. */-export type CodeTurn = {+export type CoworkTurn = {role: 'user' | 'assistant' | 'tool'content: string/** User-row only: data URLs of images attached via paste/file picker. */@@ -47,7 +47,7 @@ export type SubagentRun = {/** 1-based FIFO queue position while `queued`; cleared on start. */waiting?: number/** The subagent's own trace. The final answer is in `finalOutput`, not here. */- turns: CodeTurn[]+ turns: CoworkTurn[]finalOutput?: stringusage?: Usage}@@ -71,7 +71,7 @@ export type TodoList = {/** `/goal` state: set by `/goal <condition>`, checked after each turn completes,* cleared by `/goal clear` or once the evaluator reports it met. */-export type CodeGoal = {+export type CoworkGoal = {condition: stringturns: numberstatus: 'active' | 'achieved'