Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cowork): monitor bridge, native reasoning, artifact cards, env-aware prompt
Akarshan Biswas31473d1b2a21
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex fcee4abef..4a3c0bcbc 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -70,7 +70,7 @@},{"identifier": "opener:allow-open-path",- "description": "Open a Cowork artifact in the OS default application. Scoped to any path because a Cowork project folder is user-chosen and can live anywhere; the same breadth the assetProtocol scope already has.",+ "description": "Open a Cowork artifact in the OS default application. Scoped to any path because a Cowork project folder is user-chosen and can live anywhere; the same breadth the assetProtocol scope already has. Depends on plugins.opener.requireLiteralLeadingDot=false in tauri.conf.json: the Unix default makes `**` refuse dot-led components, and every Cowork workspace sits under ~/.local/share on Linux, so without it this scope matches nothing there.","windows": ["*"],"allow": [{diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex a4324cbf5..e6140645c 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -42,6 +42,9 @@}},"plugins": {+ "opener": {+ "requireLiteralLeadingDot": false+ },"os": {"version": "latest","resolve": truediff --git a/web-app/src/containers/CoworkArtifactCard.tsx b/web-app/src/containers/CoworkArtifactCard.tsxindex 8d635d8be..e3c41be61 100644--- a/web-app/src/containers/CoworkArtifactCard.tsx+++ b/web-app/src/containers/CoworkArtifactCard.tsx@@ -1,18 +1,31 @@-import { ChevronDown, FolderOpen, SquareArrowOutUpRight } from 'lucide-react'+import { ChevronDown, Eye, FolderOpen, SquareArrowOutUpRight } from 'lucide-react'import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuSeparator,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu'import { Card } from '@/components/ui/card'import { useServiceHub } from '@/hooks/useServiceHub'import { useTranslation } from '@/i18n/react-i18next-compat'-import { resolveInRoot } from '@/lib/coworkPreview'+import { previewKindFor, resolveInRoot } from '@/lib/coworkPreview'import { ARTIFACT_ICON, type CoworkArtifact } from '@/lib/coworkArtifacts'+import { cn } from '@/lib/utils'++/** One accent per artifact family, so a transcript full of cards scans by+ * colour before it scans by title. Alpha backgrounds keep both themes. */+const GROUP_TINT: Record<CoworkArtifact['group'], string> = {+ Code: 'bg-violet-500/10 text-violet-600 dark:text-violet-400',+ Image: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',+ Document: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',+ Video: 'bg-rose-500/10 text-rose-600 dark:text-rose-400',+ Audio: 'bg-sky-500/10 text-sky-600 dark:text-sky-400',+}/**- * Inline card for something the agent produced (jan-internal #242).+ * Card for something the agent produced (jan-internal #242), shared by the+ * Cowork transcript and the artifacts library.** Rendered by the Cowork transcript itself rather than by `MessageItem`, which* is shared with the chat surface — the association is derived from a message's@@ -24,61 +37,122 @@ export function CoworkArtifactCard({artifact,root,onPreview,+ showPath = false,+ className,}: {artifact: CoworkArtifactroot: string | nullonPreview: (path: string) => void+ /** The library sets this: many sessions' files need the disambiguating path. */+ showPath?: boolean+ className?: string}) {const { t } = useTranslation()const serviceHub = useServiceHub()const Icon = ARTIFACT_ICON[artifact.group]const abs = root ? resolveInRoot(root, artifact.path) : null+ const kind = previewKindFor(artifact.path)+ // A real thumbnail only where the browser renders the file on its own; HTML+ // would need executing the page.+ const thumb =+ abs && (kind === 'image' || kind === 'svg')+ ? serviceHub.core().convertFileSrc(abs)+ : nullreturn (- <Card className="my-3 flex items-center gap-3 p-3">+ <Card+ className={cn(+ 'group/artifact flex items-center gap-3 p-2.5 transition-all hover:border-accent hover:shadow-sm',+ className+ )}+ ><buttontype="button"onClick={() => onPreview(artifact.path)}title={t('common:artifactOpenPreview')}- className="flex min-w-0 flex-1 items-center gap-3 text-left"+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 text-left">- <span className="flex size-10 shrink-0 items-center justify-center rounded-md border">- <Icon size={18} className="text-muted-foreground" />- </span>- <span className="min-w-0">- <span className="block truncate text-sm font-medium">{artifact.title}</span>- <span className="block truncate text-xs text-muted-foreground">- {artifact.group} · {artifact.label}+ {thumb ? (+ <img+ src={thumb}+ alt=""+ className="size-11 shrink-0 rounded-lg border object-cover"+ />+ ) : (+ <span+ className={cn(+ 'flex size-11 shrink-0 items-center justify-center rounded-lg',+ GROUP_TINT[artifact.group]+ )}+ >+ <Icon size={20} /></span>+ )}+ {/* 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">+ {artifact.title}+ </span>+ <span className="mt-0.5 flex items-center gap-1.5 text-xs text-muted-foreground">+ <span className="rounded border px-1 text-[10px] font-semibold tracking-wide">+ {artifact.label}+ </span>+ <span className="truncate">+ {t(`common:artifactGroup${artifact.group}`)}+ </span>+ </span>+ {showPath && (+ <span className="mt-0.5 block truncate text-xs text-muted-foreground/70">+ {artifact.path}+ </span>+ )}</span>+ {/* Hover affordance: the whole body is a preview button, but nothing+ said so before the pointer found the tooltip. */}+ <Eye+ size={14}+ className="shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/artifact:opacity-100"+ /></button>{abs && (- <div className="flex shrink-0 items-center rounded-md border">+ <div className="flex shrink-0 items-center overflow-hidden rounded-md border"><buttontype="button"onClick={() => void serviceHub.opener().openPath(abs)}- className="flex items-center gap-1.5 rounded-l-md px-2.5 py-1.5 text-xs hover:bg-accent"+ title={t('common:artifactOpenExternal')}+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium hover:bg-accent"><SquareArrowOutUpRight size={13} className="text-muted-foreground" />- {t('common:artifactOpenExternal')}+ <span className="hidden sm:inline">+ {t('common:artifactOpenExternal')}+ </span></button><DropdownMenu><DropdownMenuTrigger asChild><buttontype="button"aria-label={t('common:artifactMoreActions')}- className="rounded-r-md border-l px-1.5 py-1.5 hover:bg-accent"+ className="border-l px-1.5 py-1.5 hover:bg-accent"><ChevronDown size={13} className="text-muted-foreground" /></button></DropdownMenuTrigger><DropdownMenuContent align="end">- <DropdownMenuItem onClick={() => void serviceHub.opener().openPath(abs)}>+ <DropdownMenuItem onClick={() => onPreview(artifact.path)}>+ <Eye size={14} />+ {t('common:artifactOpenPreview')}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() => void serviceHub.opener().openPath(abs)}+ ><SquareArrowOutUpRight size={14} />{t('common:artifactOpenExternal')}</DropdownMenuItem>- <DropdownMenuItem onClick={() => void serviceHub.opener().revealItemInDir(abs)}>+ <DropdownMenuItem+ onClick={() => void serviceHub.opener().revealItemInDir(abs)}+ ><FolderOpen size={14} />{t('common:artifactShowInFolder')}</DropdownMenuItem>diff --git a/web-app/src/hooks/useCoworkRun.ts b/web-app/src/hooks/useCoworkRun.tsindex 9026eb513..99c94c50d 100644--- a/web-app/src/hooks/useCoworkRun.ts+++ b/web-app/src/hooks/useCoworkRun.ts@@ -21,6 +21,7 @@ export type {// Owned here because this store is what consumes/dispatches them.export type StreamEvent =| { type: 'token'; text: string }+ | { type: 'reasoning'; text: string }| { type: 'step'; index: number; max: number }| { type: 'tool_call_started'; id: string; name: string }| { type: 'tool_call_args_delta'; id: string; delta: string }@@ -82,6 +83,18 @@ function applyInnerToTurns(turns: CoworkTurn[], inner: StreamEvent): CoworkTurn[switch (inner.type) {case 'token':return appendAssistantToken(turns, inner.text)+ // Native reasoning, merged like a token but into the row's own `reasoning`+ // slot: it must not join `content`, which is what the lane treats as the+ // child's answer text.+ case 'reasoning': {+ const last = turns[turns.length - 1]+ if (last && last.role === 'assistant')+ return [+ ...turns.slice(0, -1),+ { ...last, reasoning: (last.reasoning ?? '') + inner.text },+ ]+ return [...turns, { role: 'assistant', content: '', reasoning: inner.text }]+ }case 'tool_call_started': {if (turns.some((tn) => tn.role === 'tool' && tn.callId === inner.id)) return turnsreturn [diff --git a/web-app/src/lib/__tests__/coworkMonitor.test.ts b/web-app/src/lib/__tests__/coworkMonitor.test.tsnew file mode 100644index 000000000..67cddd172--- /dev/null+++ b/web-app/src/lib/__tests__/coworkMonitor.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it } from 'vitest'+import type { MonitorUpdate } from '@/lib/agentTools'+import {+ MONITOR_TOOL_NAME,+ MonitorLane,+ monitorTool,+ parseMonitorId,+ type MonitorInbox,+} from '@/lib/coworkMonitor'+import type { SubagentNotice } from '@/lib/coworkSubagent'++function fakeInbox() {+ const calls: string[] = []+ const notices: SubagentNotice[] = []+ const inbox: MonitorInbox = {+ begin: () => calls.push('begin'),+ finish: (n) => {+ calls.push('finish')+ notices.push(n)+ },+ note: (n) => {+ calls.push('note')+ notices.push(n)+ },+ abandon: () => calls.push('abandon'),+ }+ return { inbox, calls, notices }+}++const startResult = (id: string) =>+ `Monitor started (monitor_id=${id}) watching build.log with 2 conditions.`++const update = (over: Partial<MonitorUpdate>): MonitorUpdate => ({+ monitorId: 'mon-1',+ headline: 'Monitor mon-1: condition "x" matched',+ text: 'Monitor mon-1 condition x matched on build.log:\nhit',+ done: false,+ ...over,+})++describe('parseMonitorId', () => {+ it('extracts the id a start result names', () => {+ expect(parseMonitorId(startResult('mon-3'))).toBe('mon-3')+ })++ it('is null for an error result', () => {+ expect(parseMonitorId('ERROR: at most 8 monitors may be active')).toBeNull()+ })+})++describe('MonitorLane', () => {+ it('claims a slot on start and releases it on the terminal update', () => {+ const { inbox, calls, notices } = fakeInbox()+ const lane = new MonitorLane(inbox)+ lane.started(startResult('mon-1'))+ lane.update(update({ done: false }))+ lane.update(update({ done: true }))+ expect(calls).toEqual(['begin', 'note', 'finish'])+ expect(notices[1].text).toContain('hit')+ })++ it('does not claim a slot for a failed start', () => {+ const { inbox, calls } = fakeInbox()+ new MonitorLane(inbox).started('ERROR: outside the project')+ expect(calls).toEqual([])+ })++ it('an explicit stop releases the slot without a ping', () => {+ const { inbox, calls } = fakeInbox()+ const lane = new MonitorLane(inbox)+ lane.started(startResult('mon-1'))+ lane.stopped('mon-1', 'Monitor mon-1 stopped. Conditions met: none; unmet: x.')+ expect(calls).toEqual(['begin', 'abandon'])+ })++ it('a stop that failed releases nothing', () => {+ const { inbox, calls } = fakeInbox()+ const lane = new MonitorLane(inbox)+ lane.started(startResult('mon-1'))+ lane.stopped('mon-1', "ERROR: unknown or already-stopped monitor 'mon-1'")+ expect(calls).toEqual(['begin'])+ })++ it('a terminal update racing an earlier stop cannot release the slot twice', () => {+ const { inbox, calls } = fakeInbox()+ const lane = new MonitorLane(inbox)+ lane.started(startResult('mon-1'))+ lane.stopped('mon-1', 'Monitor mon-1 stopped. Conditions met: none; unmet: x.')+ lane.update(update({ done: true }))+ // The late update is still shown as a note, but the shared running count+ // (which also guards live subagents) comes down exactly once.+ expect(calls).toEqual(['begin', 'abandon', 'note'])+ })+})++describe('monitorTool', () => {+ it('keeps the contract the Rust schema advertises', () => {+ expect(MONITOR_TOOL_NAME).toBe('monitor')+ const description = monitorTool().description ?? ''+ expect(description).toContain('<SYSTEM> note per match')+ expect(description).toContain('exit 0 means the condition matched')+ })+})diff --git a/web-app/src/lib/__tests__/coworkPrompt.test.ts b/web-app/src/lib/__tests__/coworkPrompt.test.tsindex 9dccaf932..269cf3870 100644--- a/web-app/src/lib/__tests__/coworkPrompt.test.ts+++ b/web-app/src/lib/__tests__/coworkPrompt.test.ts@@ -71,6 +71,50 @@ describe('buildCoworkSystemPrompt', () => {)})+ it('states the environment when gathered and omits the block otherwise', () => {+ const p = buildCoworkSystemPrompt(+ opts({+ environment: {+ os: 'linux',+ arch: 'x86_64',+ appVersion: '0.7.0',+ locale: 'en-US',+ date: 'Tue Sep 02 2026',+ },+ })+ )+ expect(p).toContain('# Environment')+ expect(p).toContain('- OS: linux (x86_64)')+ expect(p).toContain('- App: Jan v0.7.0 (desktop)')+ expect(p).toContain("- Today's date: Tue Sep 02 2026")+ expect(p).toContain('- User locale: en-US')+ expect(buildCoworkSystemPrompt(opts())).not.toContain('# Environment')+ })++ // Web builds gather no OS or version; the block must not print empty lines.+ it('drops environment lines it has no value for', () => {+ const p = buildCoworkSystemPrompt(+ opts({+ environment: {+ os: null,+ arch: null,+ appVersion: null,+ locale: null,+ date: 'Tue Sep 02 2026',+ },+ })+ )+ expect(p).toContain("- Today's date: Tue Sep 02 2026")+ expect(p).not.toContain('- OS:')+ expect(p).not.toContain('- App:')+ expect(p).not.toContain('- User locale:')+ })++ it('encourages delegating long jobs to a subagent', () => {+ const p = buildCoworkSystemPrompt(opts({ subagentNames: ['researcher'] }))+ expect(p).toMatch(/prefer a subagent for long or repetitive jobs/i)+ })+it('describes subagents only when some are available and not planning', () => {expect(buildCoworkSystemPrompt(opts({ subagentNames: ['researcher'] }))@@ -116,6 +160,23 @@ describe('buildSubagentSystemPrompt', () => {expect(out).not.toContain('# Available Memories')})+ // A child runs shell commands on the same machine, so it gets the same facts.+ it('carries the environment through to a child when gathered', () => {+ const out = buildSubagentSystemPrompt('p', {+ ...opts,+ environment: {+ os: 'macos',+ arch: 'aarch64',+ appVersion: '0.7.0',+ locale: 'en-US',+ date: 'Tue Sep 02 2026',+ },+ })+ expect(out).toContain('# Environment')+ expect(out).toContain('- OS: macos (aarch64)')+ expect(buildSubagentSystemPrompt('p', opts)).not.toContain('# Environment')+ })+// 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(diff --git a/web-app/src/lib/__tests__/coworkRunner.test.ts b/web-app/src/lib/__tests__/coworkRunner.test.tsindex 4ee4f4dce..18f36b6b8 100644--- a/web-app/src/lib/__tests__/coworkRunner.test.ts+++ b/web-app/src/lib/__tests__/coworkRunner.test.ts@@ -53,6 +53,7 @@ const toolStep = (name: string, id = 'c1'): UIMessageChunk[] => [const noopSink = () => ({onText: vi.fn(),+ onReasoning: vi.fn(),onToolStart: vi.fn(),onToolArgsDelta: vi.fn(),onToolCall: vi.fn(),@@ -81,6 +82,25 @@ const user = (text: string): UIMessage =>({ id: 'u1', role: 'user', parts: [{ type: 'text', text }] }) as UIMessagedescribe('consumeStep', () => {+ /// Native reasoning arrives as its own chunk type and must neither be+ /// dropped (nothing on screen while the model thinks) nor folded into+ /// `text` (which goes back upstream as wire content).+ it('streams reasoning-delta beside the text, never inside it', async () => {+ const sink = noopSink()+ const r = await consumeStep(+ streamOf([+ { type: 'reasoning-delta', id: 'r', delta: 'weigh ' } as UIMessageChunk,+ { type: 'reasoning-delta', id: 'r', delta: 'options' } as UIMessageChunk,+ ...textStep('answer'),+ ]),+ sink+ )+ expect(r.reasoning).toBe('weigh options')+ expect(r.text).toBe('answer')+ expect(sink.onReasoning).toHaveBeenCalledWith('weigh ')+ expect(sink.onText).toHaveBeenCalledWith('answer')+ })+it('folds text, tool calls and usage out of the chunk stream', async () => {const sink = noopSink()const r = await consumeStep(@@ -325,12 +345,45 @@ describe('runTurn', () => {})})+describe('reasoning placement', () => {+ const step: StepResult = {+ text: 'answer',+ reasoning: 'weigh options',+ toolCalls: [],+ usage: null,+ aborted: false,+ }++ it('leads the assistant message as a reasoning part, ahead of the text', () => {+ const msg = assistantMessageFor('m0', step, new Map()) as {+ parts: Array<{ type: string; text?: string }>+ }+ expect(msg.parts[0]).toEqual({ type: 'reasoning', text: 'weigh options' })+ expect(msg.parts[1]).toEqual({ type: 'text', text: 'answer' })+ })++ it('rides the committed turn beside the content, and a reasoning-only step still gets a row', () => {+ expect(turnsFor(step, new Map())[0]).toMatchObject({+ role: 'assistant',+ content: 'answer',+ reasoning: 'weigh options',+ })+ const thoughtOnly = { ...step, text: '' }+ expect(turnsFor(thoughtOnly, new Map())[0]).toMatchObject({+ role: 'assistant',+ content: '',+ reasoning: 'weigh options',+ })+ })+})+describe('diff sidecar', () => {// A diff is a rendering aid. Sending it to the model doubles the cost of// every edit and corrupts the output the tool widget parses.it('never reaches the model-facing message', () => {const step: StepResult = {text: '',+ reasoning: '',toolCalls: [{ toolCallId: 'c1', toolName: 'edit', input: {} } as PendingToolCall,],diff --git a/web-app/src/lib/__tests__/coworkTurns.test.ts b/web-app/src/lib/__tests__/coworkTurns.test.tsindex 768d14466..a415bad86 100644--- a/web-app/src/lib/__tests__/coworkTurns.test.ts+++ b/web-app/src/lib/__tests__/coworkTurns.test.ts@@ -10,6 +10,26 @@ const toolPart = (turns: CoworkTurn[]) =>)describe('coworkTurnsToUIMessages', () => {+ it('renders native reasoning as a reasoning part ahead of the answer', () => {+ const messages = coworkTurnsToUIMessages([+ { role: 'user', content: 'q' },+ { role: 'assistant', content: 'answer', reasoning: 'weigh options' },+ ])+ const parts = partsOf(messages, 1)+ expect(parts[0]).toEqual({ type: 'reasoning', text: 'weigh options' })+ expect(parts[1]).toEqual({ type: 'text', text: 'answer' })+ })++ it('a reasoning-only turn still renders (thought, then straight to a tool)', () => {+ const messages = coworkTurnsToUIMessages([+ { role: 'user', content: 'q' },+ { role: 'assistant', content: '', reasoning: 'thinking' },+ ])+ expect(partsOf(messages, 1)).toEqual([+ { type: 'reasoning', text: 'thinking' },+ ])+ })+it('starts a new user message and flushes the assistant before it', () => {const messages = coworkTurnsToUIMessages([{ role: 'user', content: 'first' },diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex f713e53ba..f8bc9f9a5 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -8,7 +8,12 @@ import {memoryRead,subagentResultReserve,subagentResultFill,+ startMonitor,+ stopMonitor,+ listMonitors,+ stopSessionMonitors,type MemoryCatalogEntry,+ type MonitorUpdate,type SandboxStatus,type ToolSchema,type WorkspaceScope,@@ -278,6 +283,70 @@ export async function executeAgentTool(}}+export type { MonitorUpdate }++/**+ * Start a file monitor for a Cowork session. `onUpdate` receives every match+ * (and the terminal all-met/timeout update) as it happens; the returned string+ * is the model-facing `monitor` tool result. An error comes back as an+ * `ERROR:`-prefixed output rather than a throw, matching the tool contract.+ */+export async function startAgentMonitor(+ sessionId: string,+ args: unknown,+ onUpdate: (update: MonitorUpdate) => void,+ readOnlyProject?: string | null,+ allowNetwork = false+): Promise<{ output: string; isError?: boolean }> {+ try {+ const dataFolder = await getServiceHub().app().getJanDataFolder()+ if (!dataFolder) return { output: 'ERROR: Jan data folder is unavailable', isError: true }+ const input =+ args && typeof args === 'object' ? (args as Record<string, unknown>) : {}+ const output = await startMonitor(dataFolder, sessionId, input, onUpdate, {+ allowNetwork,+ readOnlyProject: readOnlyProject ?? undefined,+ scope: 'session',+ })+ return { output }+ } catch (e) {+ return { output: `ERROR: ${messageOf(e)}`, isError: true }+ }+}++/** Stop one monitor. The result string is model-facing either way. */+export async function stopAgentMonitor(+ sessionId: string,+ monitorId: string+): Promise<string> {+ try {+ return await stopMonitor(sessionId, monitorId)+ } catch (e) {+ return `ERROR: ${messageOf(e)}`+ }+}++/** One line per active monitor, for `monitor {op:"list"}`. */+export async function listAgentMonitors(sessionId: string): Promise<string> {+ try {+ return await listMonitors(sessionId)+ } catch (e) {+ return `ERROR: ${messageOf(e)}`+ }+}++/**+ * Abort every monitor a session still has. Best-effort teardown at run end: a+ * failure leaves watchers whose updates go nowhere, not user-visible damage.+ */+export async function stopAgentSessionMonitors(sessionId: string): Promise<void> {+ try {+ await stopSessionMonitors(sessionId)+ } catch (e) {+ console.warn('[agentTools] Failed to stop session monitors:', messageOf(e))+ }+}+/** A file claimed for a subagent's answer: the name to fill it by, and the* model-visible path (`/tmp/subagents/<id>.md`, where the scratch is mounted* over `/tmp`) the parent agent can `read`. */diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.tsindex faf48c4d8..949e230eb 100644--- a/web-app/src/lib/coworkDispatch.ts+++ b/web-app/src/lib/coworkDispatch.ts@@ -1,4 +1,9 @@-import { executeAgentTool } from '@/lib/agentTools'+import {+ executeAgentTool,+ listAgentMonitors,+ startAgentMonitor,+ stopAgentMonitor,+} from '@/lib/agentTools'import { useCoworkConfig } from '@/hooks/useCoworkConfig'import {ASK_TOOL_NAME,@@ -6,6 +11,7 @@ import {TASK_TOOL_NAME,TODO_TOOL_NAME,} from '@/lib/coworkTools'+import { MONITOR_TOOL_NAME, type MonitorLane } from '@/lib/coworkMonitor'import type { PendingToolCall, ToolOutcome } from '@/lib/coworkRunner'import { WEB_TOOL_NAMES, executeWebTool } from '@/lib/webSearchTool'@@ -22,6 +28,9 @@ export type DispatchContext = {onAsk: (toolCallId: string, input: unknown) => Promise<ToolOutcome>/** Runs a nested subagent to completion. */onTask: (toolCallId: string, input: unknown) => Promise<ToolOutcome>+ /** The run's monitor bookkeeping; `null` for a subagent's dispatch, which+ * refuses the tool (a child has no inbox for a watcher to ping). */+ monitors: MonitorLane | null}/**@@ -42,6 +51,47 @@ function planRefusal(toolName: string): ToolOutcome {}}+/**+ * One `monitor` op. The watcher runs in Rust; this routes the call and keeps+ * the run's `MonitorLane` in step so the inbox parks the run while a watcher is+ * owed work and never double-releases a slot.+ */+async function runMonitorOp(+ input: unknown,+ ctx: DispatchContext+): Promise<ToolOutcome> {+ const monitors = ctx.monitors+ if (!monitors) {+ return {+ output: 'The monitor belongs to the agent that dispatched you.',+ isError: true,+ }+ }+ const args = (input ?? {}) as { op?: unknown; monitor_id?: unknown }+ const op = typeof args.op === 'string' ? args.op : ''+ if (op === 'start') {+ const started = await startAgentMonitor(+ ctx.sessionId,+ input,+ (update) => monitors.update(update),+ ctx.readOnlyFolder,+ useCoworkConfig.getState().networkEnabled+ )+ if (!started.isError) monitors.started(started.output)+ return { output: started.output, isError: started.isError }+ }+ if (op === 'stop') {+ const monitorId = typeof args.monitor_id === 'string' ? args.monitor_id : ''+ const result = await stopAgentMonitor(ctx.sessionId, monitorId)+ monitors.stopped(monitorId, result)+ return { output: result, isError: result.startsWith('ERROR') }+ }+ if (op === 'list') {+ return { output: await listAgentMonitors(ctx.sessionId) }+ }+ return { output: `ERROR: unknown monitor op '${op}'`, isError: true }+}+/*** Route one tool call. Always resolves: a rejection here would abort the run,* where the model can usually recover from being told what went wrong.@@ -64,6 +114,9 @@ export async function dispatchCoworkTool(if (toolName === TASK_TOOL_NAME) {return await ctx.onTask(call.toolCallId, call.input)}+ if (toolName === MONITOR_TOOL_NAME) {+ return await runMonitorOp(call.input, ctx)+ }if (WEB_TOOL_NAMES.has(toolName)) {if (!ctx.webSearch) {diff --git a/web-app/src/lib/coworkEnv.ts b/web-app/src/lib/coworkEnv.tsnew file mode 100644index 000000000..72ffcaff5--- /dev/null+++ b/web-app/src/lib/coworkEnv.ts@@ -0,0 +1,38 @@+import { isPlatformTauri } from '@/lib/platform'+import type { CoworkEnvironment } from '@/lib/coworkPrompt'++/**+ * Facts about the machine the agent is running on, for the system prompt's+ * `# Environment` block. The OS/app half never changes for a process, so it is+ * gathered once; the date is stamped fresh on every call because a session can+ * outlive midnight.+ */+let staticEnv: Omit<CoworkEnvironment, 'date'> | null = null++async function gatherStatic(): Promise<Omit<CoworkEnvironment, 'date'>> {+ let os: string | null = null+ let arch: string | null = null+ let appVersion: string | null = null+ if (isPlatformTauri()) {+ try {+ const osApi = await import('@tauri-apps/plugin-os')+ os = osApi.platform()+ arch = osApi.arch()+ const { getVersion } = await import('@tauri-apps/api/app')+ appVersion = await getVersion()+ } catch {+ // Web build or a missing plugin: the block simply omits these lines.+ }+ }+ return {+ os,+ arch,+ appVersion,+ locale: typeof navigator !== 'undefined' ? navigator.language : null,+ }+}++export async function getCoworkEnvironment(): Promise<CoworkEnvironment> {+ if (!staticEnv) staticEnv = await gatherStatic()+ return { ...staticEnv, date: new Date().toDateString() }+}diff --git a/web-app/src/lib/coworkMonitor.ts b/web-app/src/lib/coworkMonitor.tsnew file mode 100644index 000000000..058148403--- /dev/null+++ b/web-app/src/lib/coworkMonitor.ts@@ -0,0 +1,131 @@+import { jsonSchema, type Tool } from 'ai'+import type { MonitorUpdate } from '@/lib/agentTools'+import type { SubagentNotice } from '@/lib/coworkSubagent'++/**+ * The `monitor` tool on the Cowork surface.+ *+ * The watcher itself runs in Rust (`tools/monitor.rs`, reached through the+ * plugin's guest-js): it tails the file, evaluates the condition scripts under+ * the same OS sandbox `bash` gets, and streams every match back as a+ * `MonitorUpdate`. What lives here is the client half: the transcribed schema+ * (like `task`/`todo`), and the bookkeeping that turns updates into inbox pings+ * so a match reaches the model as the same `<SYSTEM>` note a finished subagent+ * sends -- and keeps the run alive while a watcher is still owed work.+ */++export const MONITOR_TOOL_NAME = 'monitor'++/** Wording ported from `monitor_tool_schema` in Rust; the two surfaces must+ * advertise the same contract. */+export function monitorTool(): Tool {+ return {+ description:+ 'Watch a file a long-running job streams output into (e.g. a backgrounded bash job redirecting to a log) and evaluate condition scripts against it. Each condition is a shell script run from the project root whenever the file changes; exit 0 means the condition matched and its stdout is the matched content. You get a <SYSTEM> note per match, so start the monitor and keep working. The monitor stops when every condition has matched, on stop, or at its timeout. A met condition is never re-checked.',+ inputSchema: jsonSchema({+ type: 'object',+ properties: {+ op: { type: 'string', enum: ['start', 'stop', 'list'] },+ file: {+ type: 'string',+ description:+ 'For start: the file to watch, relative to the project root (or under /tmp). It may not exist yet.',+ },+ conditions: {+ type: 'array',+ description:+ "For start: the conditions to watch for. Scripts should be cheap checks (e.g. grep -m1 'BUILD FAILED' build.log), not jobs.",+ items: {+ type: 'object',+ properties: {+ name: {+ type: 'string',+ description:+ 'Short unique label, quoted back to you when it matches.',+ },+ script: {+ type: 'string',+ description:+ 'Shell script; exit 0 = matched, stdout = the matched content.',+ },+ },+ required: ['name', 'script'],+ },+ },+ timeout: {+ type: 'integer',+ description:+ 'For start: seconds before the monitor gives up and reports its unmet conditions (default 1800, max 7200).',+ },+ monitor_id: {+ type: 'string',+ description: 'For stop: the id returned by start.',+ },+ },+ required: ['op'],+ }),+ } as Tool+}++/** The id a successful start result names (`monitor_id=mon-N`), or null. */+export function parseMonitorId(startResult: string): string | null {+ const match = startResult.match(/monitor_id=([A-Za-z0-9_-]+)/)+ return match ? match[1] : null+}++/**+ * What the run's inbox needs to hear about monitors. Structurally what+ * `SubagentInbox` provides, so the two kinds of background work share one+ * inbox and one park/resume path.+ */+export type MonitorInbox = {+ begin: () => void+ finish: (notice: SubagentNotice) => void+ note: (notice: SubagentNotice) => void+ abandon: () => void+}++/**+ * One run's view of its monitors, bridging Rust updates to the inbox.+ *+ * The open-set exists because the inbox's running count is shared with the+ * subagents: `finish`/`abandon` must fire exactly once per started monitor, and+ * a stop racing the monitor's own terminal update would otherwise decrement+ * twice -- reading `pending()` false while a subagent is still running.+ */+export class MonitorLane {+ private open = new Set<string>()++ constructor(private readonly inbox: MonitorInbox) {}++ /** Record a successful start (its result names the id) and claim a running+ * slot, so the run parks on the watcher instead of ending under it. */+ started(startResult: string): void {+ const id = parseMonitorId(startResult)+ if (!id) return+ this.open.add(id)+ this.inbox.begin()+ }++ /** Route one Rust update: a terminal one closes the slot, any other is a+ * ping the model reacts to while the watcher keeps going. */+ update(update: MonitorUpdate): void {+ const notice: SubagentNotice = {+ headline: update.headline,+ text: update.text,+ }+ if (update.done && this.open.delete(update.monitorId)) {+ this.inbox.finish(notice)+ return+ }+ this.inbox.note(notice)+ }++ /** Account for an explicit `stop`: the slot is released with no ping, since+ * the model's own tool result already reports the outcome. */+ stopped(monitorId: string, stopResult: string): void {+ if (!stopResult.startsWith('ERROR') && this.open.delete(monitorId)) {+ this.inbox.abandon()+ }+ }+}diff --git a/web-app/src/lib/coworkPrompt.ts b/web-app/src/lib/coworkPrompt.tsindex 3d5a8372b..b9888bb75 100644--- a/web-app/src/lib/coworkPrompt.ts+++ b/web-app/src/lib/coworkPrompt.ts@@ -41,6 +41,18 @@ export const EXECUTE_PLAN_LABEL = 'Execute plan'export const KEEP_PLANNING_LABEL = 'Keep planning'export const EXIT_PLAN_LABEL = 'Exit plan mode'+/** Machine facts for the `# Environment` block. Gathered by `coworkEnv.ts`;+ * a plain value here so the builder stays pure and testable. */+export type CoworkEnvironment = {+ os: string | null+ arch: string | null+ appVersion: string | null+ locale: string | null+ /** Human-readable, stamped at gather time -- a model's sense of "today" is+ * its training cutoff unless told otherwise. */+ date: string+}+export type CoworkPromptOptions = {/** The sandbox directory: the only writable location. */workspacePath: string | null@@ -52,6 +64,8 @@ export type CoworkPromptOptions = {subagentNames: string[]/** Whether `web_search`/`web_fetch` are advertised this run. */webSearch: boolean+ /** Optional so the prompt still builds where nothing was gathered. */+ environment?: CoworkEnvironment | null/*** Progressive-disclosure recall: one line per note, dereferenced on demand* with `memory_read`. Snapshotted at the run boundary alongside the frozen@@ -89,6 +103,20 @@ const WEB_BLOCK = ['separate sources section.',].join('\n')+function environmentBlock(env: CoworkEnvironment): string {+ const lines = ['# Environment', '']+ if (env.os) lines.push(`- OS: ${env.os}${env.arch ? ` (${env.arch})` : ''}`)+ if (env.appVersion) lines.push(`- App: Jan v${env.appVersion} (desktop)`)+ lines.push(`- Today's date: ${env.date}`)+ if (env.locale) lines.push(`- User locale: ${env.locale}`)+ lines.push(+ '',+ 'Trust these over your own assumptions for anything platform- or',+ 'time-sensitive.'+ )+ return lines.join('\n')+}+function workspaceBlock(opts: CoworkPromptOptions): string {const lines = ['# Workspace', '']if (opts.workspacePath) {@@ -122,7 +150,9 @@ function workspaceBlock(opts: CoworkPromptOptions): string {}export function buildCoworkSystemPrompt(opts: CoworkPromptOptions): string {- const blocks = [IDENTITY, GUIDELINES, workspaceBlock(opts)]+ const blocks = [IDENTITY, GUIDELINES]+ if (opts.environment) blocks.push(environmentBlock(opts.environment))+ blocks.push(workspaceBlock(opts))if (opts.memoryCatalog.length > 0) blocks.push(memoryBlock(opts.memoryCatalog))if (opts.webSearch) blocks.push(WEB_BLOCK)if (opts.subagentNames.length > 0 && !opts.planMode) {@@ -133,6 +163,10 @@ export function buildCoworkSystemPrompt(opts: CoworkPromptOptions): string {'The `task` tool runs a nested agent that does not see this conversation.','State everything it needs in `description`. Use one for work that is','self-contained and would otherwise flood your own context.',+ 'Strongly prefer a subagent for long or repetitive jobs -- a broad',+ 'research sweep, working through many files, generating and then',+ 'verifying a large output. Delegating keeps your own context focused on',+ 'the plan, and a backgrounded subagent works while you continue.',`Available: ${opts.subagentNames.join(', ')}.`,].join('\n'))@@ -158,6 +192,7 @@ export function buildSubagentSystemPrompt(): string {return [definitionPrompt.trim(),+ ...(opts.environment ? [environmentBlock(opts.environment)] : []),workspaceBlock({ ...opts, planMode: false, subagentNames: [], memoryCatalog: [] }),...(opts.webSearch ? [WEB_BLOCK] : []),[diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.tsindex eefb2abac..c4f521e62 100644--- a/web-app/src/lib/coworkRunner.ts+++ b/web-app/src/lib/coworkRunner.ts@@ -41,6 +41,11 @@ export type ToolOutcome = {/** One model turn's worth of stream, folded into a shape the loop can act on. */export type StepResult = {text: string+ /** Natively streamed reasoning (`reasoning-delta` chunks), accumulated apart+ * from `text`: the answer text becomes wire-history `content`, and reasoning+ * must never travel there inline. Inline `<think>` reasoning is different --+ * it IS the content the model sent -- and stays in `text`. */+ reasoning: stringtoolCalls: PendingToolCall[]usage: Usage | nullerrorText?: string@@ -181,6 +186,10 @@ const usageOf = (meta: unknown): Usage | null => {export type StreamSink = {onText: (delta: string) => void+ /** A natively streamed reasoning fragment. Dropping these is not an option:+ * unlike inline `<think>` they never reach `onText`, so a sink without this+ * would show nothing at all while the model thinks. */+ onReasoning: (delta: string) => voidonToolStart: (toolCallId: string, toolName: string) => voidonToolArgsDelta: (toolCallId: string, delta: string) => voidonToolCall: (call: PendingToolCall) => void@@ -198,6 +207,7 @@ export async function consumeStep(const reader = stream.getReader()const result: StepResult = {text: '',+ reasoning: '',toolCalls: [],usage: null,aborted: false,@@ -212,6 +222,10 @@ export async function consumeStep(result.text += chunk.deltasink.onText(chunk.delta)break+ case 'reasoning-delta':+ result.reasoning += chunk.delta+ sink.onReasoning(chunk.delta)+ breakcase 'tool-input-start':sink.onToolStart(chunk.toolCallId, chunk.toolName)break@@ -254,6 +268,9 @@ export function assistantMessageFor(outcomes: Map<string, ToolOutcome>): UIMessage {const parts: any[] = []+ // Before the text part, matching emission order -- and as a `reasoning` part,+ // the same shape chat threads persist, so the transport treats it the same.+ if (step.reasoning) parts.push({ type: 'reasoning', text: step.reasoning })if (step.text) parts.push({ type: 'text', text: step.text })for (const call of step.toolCalls) {const outcome = outcomes.get(call.toolCallId)@@ -282,7 +299,15 @@ export function turnsFor(outcomes: Map<string, ToolOutcome>): CoworkTurn[] {const turns: CoworkTurn[] = []- if (step.text) turns.push({ role: 'assistant', content: step.text })+ // A reasoning-only step (thought, then straight to a tool call) still gets a+ // row: its reasoning would otherwise vanish from the committed transcript.+ if (step.text || step.reasoning) {+ turns.push({+ role: 'assistant',+ content: step.text,+ ...(step.reasoning ? { reasoning: step.reasoning } : {}),+ })+ }for (const call of step.toolCalls) {const outcome = outcomes.get(call.toolCallId)turns.push({@@ -406,6 +431,12 @@ export async function runTurn(opts: {received = truedeps.sink.onText(d)},+ // Reasoning bytes on screen count as received too: replaying the+ // request after them would duplicate the thinking block.+ onReasoning: (d) => {+ received = true+ deps.sink.onReasoning(d)+ },onToolStart: (id, name) => {received = truedeps.sink.onToolStart(id, name)diff --git a/web-app/src/lib/coworkSubagent.ts b/web-app/src/lib/coworkSubagent.tsindex 330388ef8..1aa0c90e5 100644--- a/web-app/src/lib/coworkSubagent.ts+++ b/web-app/src/lib/coworkSubagent.ts@@ -14,6 +14,7 @@ import {TASK_TOOL_NAME,TODO_TOOL_NAME,} from '@/lib/coworkTools'+import { MONITOR_TOOL_NAME } from '@/lib/coworkMonitor'import { MAX_SUBAGENT_STEPS } from '@/lib/coworkBudget'import {runTurn,@@ -21,7 +22,10 @@ import {type StreamSink,type ToolOutcome,} from '@/lib/coworkRunner'-import { buildSubagentSystemPrompt } from '@/lib/coworkPrompt'+import {+ buildSubagentSystemPrompt,+ type CoworkEnvironment,+} from '@/lib/coworkPrompt'import type { StreamEvent } from '@/hooks/useCoworkRun'/**@@ -130,6 +134,21 @@ export class SubagentInbox {this.wake()}+ /** Queue a ping without closing a running slot: a monitor's non-terminal+ * match, where the watcher is still owed further work. */+ note(notice: SubagentNotice): void {+ this.queue.push(notice)+ this.wake()+ }++ /** Release a running slot with nothing to report: a start that failed after+ * `begin`, or a monitor the model stopped itself (its own tool result already+ * says so). */+ abandon(): void {+ this.running -= 1+ this.wake()+ }+/** Take every queued ping, oldest first. */take(): SubagentNotice[] {const out = this.queue@@ -186,6 +205,10 @@ const WITHHELD_FROM_SUBAGENTS = new Set([TASK_TOOL_NAME,ASK_TOOL_NAME,TODO_TOOL_NAME,+ // A monitor pings the run's inbox, which belongs to the parent's+ // conversation; a child has no inbox, so its watcher would report to no one.+ // (The Rust CLI differs: there a child run owns a registry of its own.)+ MONITOR_TOOL_NAME,])export type SubagentRequest = {@@ -401,6 +424,7 @@ export type RunSubagentOptions = {workspacePath: string | nullreadOnlyFolder: string | nullbashAvailable: boolean+ environment?: CoworkEnvironment | null}/** Runs one of the child's tool calls. Same sandbox as the parent. */dispatch: (call: PendingToolCall, signal: AbortSignal) => Promise<ToolOutcome>@@ -489,6 +513,7 @@ export async function runSubagent(bashAvailable: opts.system.bashAvailable && 'bash' in tools,// Derived, not passed: the intersection above may have dropped them.webSearch: 'web_search' in tools,+ environment: opts.system.environment,})// A fresh history: the child does not see the parent's conversation, so the@@ -504,6 +529,8 @@ export async function runSubagent(let finalText = ''const sink: StreamSink = {onText: (delta) => events.onInner({ type: 'token', text: delta }),+ onReasoning: (delta) =>+ events.onInner({ type: 'reasoning', text: delta }),onToolStart: (id, name) =>events.onInner({ type: 'tool_call_started', id, name }),onToolArgsDelta: (id, delta) =>diff --git a/web-app/src/lib/coworkTools.ts b/web-app/src/lib/coworkTools.tsindex 1a4158db0..00a6fadc7 100644--- a/web-app/src/lib/coworkTools.ts+++ b/web-app/src/lib/coworkTools.ts@@ -8,6 +8,7 @@*/import { jsonSchema, type Tool } from 'ai'import { getAgentToolSchemas } from '@/lib/agentTools'+import { MONITOR_TOOL_NAME, monitorTool } from '@/lib/coworkMonitor'import {WEB_FETCH_DESCRIPTION,WEB_FETCH_INPUT_SCHEMA,@@ -23,6 +24,8 @@ export const PLAN_DENIED_TOOLS = new Set(['memory_write','skill_write','task',+ // Starting one schedules shell scripts, which is exec-class work.+ MONITOR_TOOL_NAME,])/** Named `todo` to match the Rust tool: the plan-mode addendum instructs the@@ -36,6 +39,7 @@ export const CLIENT_TOOL_NAMES = new Set([TODO_TOOL_NAME,ASK_TOOL_NAME,TASK_TOOL_NAME,+ MONITOR_TOOL_NAME,])const todoTool: Tool = {@@ -242,5 +246,8 @@ export async function buildCoworkTools(if (opts.allowSubagents && !opts.planMode) {tools[TASK_TOOL_NAME] = taskTool(opts.subagentNames)}+ if (!opts.planMode) {+ tools[MONITOR_TOOL_NAME] = monitorTool()+ }return tools}diff --git a/web-app/src/lib/coworkTransport.ts b/web-app/src/lib/coworkTransport.tsindex 23c551887..9ed1b5f7c 100644--- a/web-app/src/lib/coworkTransport.ts+++ b/web-app/src/lib/coworkTransport.ts@@ -11,7 +11,11 @@ import {coworkToolSignature,type CoworkToolOptions,} from '@/lib/coworkTools'-import { buildCoworkSystemPrompt } from '@/lib/coworkPrompt'+import {+ buildCoworkSystemPrompt,+ type CoworkEnvironment,+} from '@/lib/coworkPrompt'+import { getCoworkEnvironment } from '@/lib/coworkEnv'export type CoworkRunConfig = CoworkToolOptions & {workspacePath: string | null@@ -46,6 +50,9 @@ export class CoworkChatTransport extends CustomChatTransport {* cache on every step. A note written mid-run appears at the next run.*/private memoryCatalog: MemoryCatalogEntry[] = []+ /** Snapshotted with the tool freeze: the date line changing mid-run would+ * discard the prompt prefix on every step, exactly like a catalog change. */+ private environment: CoworkEnvironment | null = nullconstructor(sessionId: string, config: CoworkRunConfig) {super(undefined, sessionId)@@ -93,6 +100,7 @@ export class CoworkChatTransport extends CustomChatTransport {subagentNames: this.config.allowSubagents ? this.config.subagentNames : [],webSearch: this.config.webSearch,memoryCatalog: this.memoryCatalog,+ environment: this.environment,})const files = this.buildFilesSystemInstruction(messages)return files.trim().length > 0 ? `${base}\n\n${files}` : base@@ -118,6 +126,7 @@ export class CoworkChatTransport extends CustomChatTransport {// Run boundary: re-snapshot the catalog even when the tool set is reused,// since memory moves independently of the tool config.this.memoryCatalog = await getMemoryCatalog()+ this.environment = await getCoworkEnvironment()const sig = coworkToolSignature(this.config, sandboxEnforces())// Between runs, skip the rebuild when nothing that shapes the set changed.if (this.builtTools && this.builtSig === sig) {diff --git a/web-app/src/lib/coworkTurns.ts b/web-app/src/lib/coworkTurns.tsindex ab3604748..ca2c8ef3c 100644--- a/web-app/src/lib/coworkTurns.ts+++ b/web-app/src/lib/coworkTurns.ts@@ -66,6 +66,15 @@ export function coworkTurnsToUIMessages(}if (turn.role === 'assistant') {+ // Natively streamed reasoning rides beside the content (see+ // `CoworkTurn.reasoning`) and becomes a reasoning part ahead of the text,+ // matching emission order.+ if (turn.reasoning) {+ ensureAssistant(i).parts.push({+ type: 'reasoning',+ text: turn.reasoning,+ })+ }// Split out <think>/<thought> reasoning into reasoning parts (same helper// the chat loader uses) so the agent's chain-of-thought renders in the// collapsible reasoning UI instead of leaking into the transcript as text.diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 3de97e338..d4119a9a5 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -641,6 +641,11 @@"taskNoOutput": "The subagent produced no visible output.","subagentToolUses_one": "{{count}} tool use","subagentToolUses_other": "{{count}} tool uses",+ "artifactGroupCode": "Code",+ "artifactGroupImage": "Image",+ "artifactGroupDocument": "Document",+ "artifactGroupVideo": "Video",+ "artifactGroupAudio": "Audio","artifactOpenPreview": "Open preview","artifactOpenExternal": "Open","artifactMoreActions": "More actions",diff --git a/web-app/src/routes/artifacts.tsx b/web-app/src/routes/artifacts.tsxindex f01b778a7..fd0be510b 100644--- a/web-app/src/routes/artifacts.tsx+++ b/web-app/src/routes/artifacts.tsx@@ -2,10 +2,10 @@import { createFileRoute, useNavigate } from '@tanstack/react-router'import { useEffect, useMemo, useState } from 'react'import { IconSearch } from '@tabler/icons-react'-import { ChevronsUpDown, FolderOpen, SquareArrowOutUpRight } from 'lucide-react'+import { ChevronsUpDown } from 'lucide-react'import HeaderPage from '@/containers/HeaderPage'import { Button } from '@/components/ui/button'-import { Card } from '@/components/ui/card'+import { CoworkArtifactCard } from '@/containers/CoworkArtifactCard'import {DropdownMenu,DropdownMenuContent,@@ -16,15 +16,13 @@ import { route } from '@/constants/routes'import { useTranslation } from '@/i18n/react-i18next-compat'import { useCoworkSessions } from '@/hooks/useCoworkSessions'import { useCoworkRun } from '@/hooks/useCoworkRun'-import { getServiceHub, useServiceHub } from '@/hooks/useServiceHub'+import { getServiceHub } from '@/hooks/useServiceHub'import { sessionWorkspacePath } from '@janhq/tauri-plugin-agent-tools-api'import {ARTIFACT_GROUP_NAMES,- ARTIFACT_ICON,artifactsFromTurns,type CoworkArtifact,} from '@/lib/coworkArtifacts'-import { previewKindFor, resolveInRoot } from '@/lib/coworkPreview'export const Route = createFileRoute(route.artifacts as any)({component: ArtifactsPage,@@ -79,7 +77,6 @@ function useSessionWorkspaces(sessionIds: string[]): Record<string, string> {function ArtifactsPage() {const { t } = useTranslation()const navigate = useNavigate()- const serviceHub = useServiceHub()const sessions = useCoworkSessions((s) => s.sessions)const [query, setQuery] = useState('')const [group, setGroup] = useState<CoworkArtifact['group'] | null>(null)@@ -147,7 +144,9 @@ function ArtifactsPage() {<DropdownMenu><DropdownMenuTrigger asChild><Button variant="outline" size="sm" className="shrink-0">- {group ?? t('common:artifactsAll')}+ {group+ ? t(`common:artifactGroup${group}`)+ : t('common:artifactsAll')}<ChevronsUpDown className="ml-2 size-4 shrink-0 text-muted-foreground" /></Button></DropdownMenuTrigger>@@ -157,7 +156,7 @@ function ArtifactsPage() {</DropdownMenuItem>{ARTIFACT_GROUP_NAMES.map((g) => (<DropdownMenuItem key={g} onClick={() => setGroup(g)}>- {g}+ {t(`common:artifactGroup${g}`)}</DropdownMenuItem>))}</DropdownMenuContent>@@ -176,101 +175,15 @@ function ArtifactsPage() {</p>) : (<div className="grid auto-rows-min gap-3 sm:grid-cols-2 lg:grid-cols-3">- {shown.slice(0, limit).map((row) => {- const Icon = ARTIFACT_ICON[row.group]- const kind = previewKindFor(row.path)- const abs = row.root ? resolveInRoot(row.root, row.path) : null- // A real thumbnail only where the browser renders the file on- // its own; HTML would need executing the page.- const thumb =- abs && (kind === 'image' || kind === 'svg')- ? serviceHub.core().convertFileSrc(abs)- : null- return (- <Card- key={`${row.sessionId}:${row.path}`}- className="flex items-center gap-3 p-3 transition-colors hover:border-accent"- >- <button- type="button"- className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 text-left"- onClick={() => open(row)}- title={t('common:artifactOpenPreview')}- >- {thumb ? (- <img- src={thumb}- alt=""- className="size-10 shrink-0 rounded-md border object-contain"- />- ) : (- <div className="flex size-10 shrink-0 items-center justify-center rounded-md border">- <Icon size={18} className="text-muted-foreground" />- </div>- )}- {/* min-w-0 on a block box: `truncate` is inert otherwise. */}- <span className="min-w-0 flex-1">- <span className="block truncate text-sm font-medium">- {row.title}- </span>- <span className="block truncate text-xs text-muted-foreground">- {row.group} · {row.label}- </span>- <span className="block truncate text-xs text-muted-foreground/70">- {row.path}- </span>- </span>- </button>- {abs && (- <div className="flex shrink-0 items-center rounded-md border">- <button- type="button"- onClick={() => void serviceHub.opener().openPath(abs)}- className="flex items-center gap-1.5 rounded-l-md px-2.5 py-1.5 text-xs hover:bg-accent"- title={t('common:artifactOpenExternal')}- >- <SquareArrowOutUpRight- size={13}- className="text-muted-foreground"- />- </button>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- aria-label={t('common:artifactMoreActions')}- className="rounded-r-md border-l px-1.5 py-1.5 hover:bg-accent"- >- <ChevronsUpDown- size={13}- className="text-muted-foreground"- />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- onClick={() =>- void serviceHub.opener().openPath(abs)- }- >- <SquareArrowOutUpRight size={14} />- {t('common:artifactOpenExternal')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={() =>- void serviceHub.opener().revealItemInDir(abs)- }- >- <FolderOpen size={14} />- {t('common:artifactShowInFolder')}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>- )}- </Card>- )- })}+ {shown.slice(0, limit).map((row) => (+ <CoworkArtifactCard+ key={`${row.sessionId}:${row.path}`}+ artifact={row}+ root={row.root}+ onPreview={() => open(row)}+ showPath+ />+ ))}</div>)}{shown.length > limit && (diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex 0814056c6..934e3018a 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -66,6 +66,7 @@ import { CoworkBudgetNotice } from '@/containers/CoworkBudgetNotice'import { CoworkRunNotice } from '@/containers/CoworkRunNotice'import { CoworkAskCard } from '@/containers/CoworkAskCard'import { CoworkChatTransport } from '@/lib/coworkTransport'+import { getCoworkEnvironment } from '@/lib/coworkEnv'import { dispatchCoworkTool } from '@/lib/coworkDispatch'import { applyTodoOp, renderTodoResult } from '@/lib/coworkTodo'import { parseAskRequest, renderAskResult } from '@/lib/coworkAsk'@@ -74,7 +75,9 @@ import {sandboxEnforces,fillSubagentResult,reserveSubagentResult,+ stopAgentSessionMonitors,} from '@/lib/agentTools'+import { MonitorLane } from '@/lib/coworkMonitor'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { MAX_AGENT_STEPS } from '@/lib/coworkBudget'import {@@ -250,6 +253,15 @@ function CoworkPage() {() => coworkTurnsToUIMessages(displayedTurns, session?.id ?? 'cowork'),[displayedTurns, session?.id])+ // While a run streams, the last assistant message is the only one that can+ // still gain parts; its artifact cards wait until the turn finishes.+ const streamingMessageIdx = useMemo(() => {+ if (!viewingRun) return -1+ for (let i = uiMessages.length - 1; i >= 0; i--) {+ if (uiMessages[i].role === 'assistant') return i+ }+ return -1+ }, [viewingRun, uiMessages])const usage = liveUsage ?? session?.lastUsage ?? nullconst tokenSource = useMemo(@@ -348,6 +360,8 @@ function CoworkPage() {// 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+ // One snapshot per run, shared with every child this run dispatches.+ const environment = await getCoworkEnvironment()const transport = new CoworkChatTransport(sid, {planMode: current?.planMode ?? false,subagentNames: subagentDefs.map((d) => d.name),@@ -365,6 +379,9 @@ function CoworkPage() {// Owned by this request: children cannot outlive the run whose signal// aborts them, so a fresh inbox per run can never hold a stale ping.const inbox = new SubagentInbox()+ // Bridges Rust monitor updates into the same inbox, so a watcher parks the+ // run exactly the way a running subagent does.+ const monitors = new MonitorLane(inbox)const sink: StreamSink = {onText: (delta) => {@@ -376,6 +393,18 @@ function CoworkPage() {pushLive([{ role: 'assistant', content: delta }])}},+ // Native reasoning streams beside the content, so the collapsible+ // thinking block fills in live instead of the transcript sitting silent+ // for the whole chain of thought.+ onReasoning: (delta) => {+ const last = liveTurnsRef.current[liveTurnsRef.current.length - 1]+ if (last && last.role === 'assistant') {+ last.reasoning = (last.reasoning ?? '') + delta+ setLiveTurns([...liveTurnsRef.current])+ } else {+ pushLive([{ role: 'assistant', content: '', reasoning: delta }])+ }+ },onToolStart: (callId, name) =>pushLive([{@@ -449,6 +478,7 @@ function CoworkPage() {readOnlyFolder: current?.folder ?? null,planMode: current?.planMode ?? false,webSearch,+ monitors,onTodo: async (input) => {const result = applyTodoOp(useCoworkSessions@@ -513,6 +543,7 @@ function CoworkPage() {workspacePath,readOnlyFolder: current?.folder ?? null,bashAvailable: sandboxEnforces(),+ environment,},signal: controller.signal,sessionTokens: 0,@@ -525,6 +556,8 @@ function CoworkPage() {readOnlyFolder: current?.folder ?? null,planMode: current?.planMode ?? false,webSearch,+ // A child has no inbox for a watcher to ping.+ monitors: null,onTodo: async () => ({output:'The todo list belongs to the agent that dispatched you.',@@ -663,6 +696,9 @@ function CoworkPage() {errorText: e instanceof Error ? e.message : String(e),}} finally {+ // Watchers are run-scoped, like the children the abort signal covers: an+ // update landing after this point would have no run to resume.+ void stopAgentSessionMonitors(sid)useAppState.getState().updateLoadingModel(false)useCoworkSessions.getState()@@ -1048,15 +1084,19 @@ function CoworkPage() {/>{/* Derived from the message's own write parts, so nothingshared with the chat surface needs to know artifacts- exist. */}- {artifactsFromParts(message.parts).map((artifact) => (- <CoworkArtifactCard- key={artifact.path}- artifact={artifact}- root={workspacePath}- onPreview={showPreview}- />- ))}+ exist. Held back on the message still streaming: a card+ mid-run announces a deliverable the agent may yet+ rewrite, and it pushes the live tail around. */}+ {i !== streamingMessageIdx &&+ artifactsFromParts(message.parts).map((artifact) => (+ <CoworkArtifactCard+ key={artifact.path}+ artifact={artifact}+ root={workspacePath}+ onPreview={showPreview}+ className="my-3"+ />+ ))}</Fragment>))}{viewingRun && (diff --git a/web-app/src/types/coworkSession.ts b/web-app/src/types/coworkSession.tsindex 2301a3afb..3ff06f0cf 100644--- a/web-app/src/types/coworkSession.ts+++ b/web-app/src/types/coworkSession.ts@@ -17,6 +17,12 @@export type CoworkTurn = {role: 'user' | 'assistant' | 'tool' | 'system'content: string+ /** Assistant-row only: natively streamed reasoning (`reasoning-*` chunks),+ * kept beside the answer rather than inline in it -- `content` is what goes+ * back as wire history, and reasoning must not ride there as text. Inline+ * `<think>` reasoning stays inside `content` (that is what the model sent)+ * and is split out at render time instead. */+ reasoning?: string/** User-row only: data URLs of images attached via paste/file picker. */images?: string[]callId?: string