Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cowork): scope the shared chat components to a non-thread surface
Akarshan Biswascdfa71add6c8
diff --git a/web-app/src/components/HtmlArtifact.tsx b/web-app/src/components/HtmlArtifact.tsxindex 7adc327b3..79be1b1f5 100644--- a/web-app/src/components/HtmlArtifact.tsx+++ b/web-app/src/components/HtmlArtifact.tsx@@ -1,8 +1,10 @@import { memo, useMemo, useState } from 'react'import { useTranslation } from '@/i18n/react-i18next-compat'-import { CodeIcon, EyeIcon } from 'lucide-react'+import { CodeIcon, EyeIcon, TriangleAlert } from 'lucide-react'import { cn } from '@/lib/utils'import { CodeBlock } from '@/components/ai-elements/code-block'+import { countUnresolvedAssetRefs } from '@/lib/htmlAssets'+import { buildSrcDoc } from '@/lib/htmlSandbox'import type { BundledLanguage } from 'shiki'interface HtmlArtifactProps {@@ -21,48 +23,6 @@ type View = 'code' | 'preview'// Strict CSP governs what model HTML can reach out to; the iframe is already// sandboxed to an opaque origin (no allow-same-origin).-function buildCsp(allowNetwork: boolean, allowScripts: boolean): string {- if (!allowScripts) {- return [- "default-src 'none'",- 'img-src data: blob:',- "style-src 'unsafe-inline'",- 'font-src data:',- "connect-src 'none'",- ].join('; ')- }- if (allowNetwork) {- return [- "default-src 'none'",- "script-src 'unsafe-inline' https:",- "style-src 'unsafe-inline' https:",- 'img-src data: blob: https:',- 'font-src data: https:',- 'connect-src https:',- ].join('; ')- }- return [- "default-src 'none'",- "script-src 'unsafe-inline'",- "style-src 'unsafe-inline'",- 'img-src data: blob:',- 'font-src data:',- "connect-src 'none'",- ].join('; ')-}--function buildSrcDoc(- code: string,- allowNetwork: boolean,- allowScripts: boolean-): string {- const csp = buildCsp(allowNetwork, allowScripts)- const meta = `<meta http-equiv="Content-Security-Policy" content="${csp}">`- // Always wrap so the CSP meta precedes all model markup — a meta CSP is only- // honored before resource-fetching content, and a later one can't loosen it.- return `<!doctype html><html><head>${meta}</head><body>${code}</body></html>`-}-function HtmlArtifactComponent({code,className,@@ -74,6 +34,13 @@ function HtmlArtifactComponent({const { t } = useTranslation()const [view, setView] = useState<View>('preview')+ // Relative refs (`./logo.png`, `style.css`) cannot resolve inside the+ // opaque-origin sandbox; surface the count instead of a silently broken page.+ const unresolvedAssets = useMemo(+ () => (view === 'preview' ? countUnresolvedAssetRefs(code) : 0),+ [view, code]+ )+const srcDoc = useMemo(() =>view === 'preview' ? buildSrcDoc(code, allowNetwork, allowScripts) : '',@@ -133,14 +100,26 @@ function HtmlArtifactComponent({</div>{activeView === 'preview' ? (- <iframe+ <>+ {unresolvedAssets > 0 && (+ <div+ role="note"+ data-testid="html-artifact-unresolved"+ className="flex items-start gap-2 border-b border-border bg-amber-500/10 px-3 py-2 text-xs text-amber-600 dark:text-amber-400"+ >+ <TriangleAlert size={14} className="mt-0.5 shrink-0" />+ <span>{t('htmlArtifact.unresolvedAssets', { count: unresolvedAssets })}</span>+ </div>+ )}+ <iframetitle={t('htmlArtifact.preview')}data-testid="html-artifact-iframe"className="h-[600px] max-h-[80vh] min-h-64 w-full resize-y overflow-auto border-0 bg-white"sandbox={allowScripts ? 'allow-scripts' : ''}referrerPolicy="no-referrer"srcDoc={srcDoc}- />+ />+ </>) : (<CodeBlock code={code} language={language as BundledLanguage} />)}diff --git a/web-app/src/components/PromptProgress.tsx b/web-app/src/components/PromptProgress.tsxindex b318808b4..dd82e6bc9 100644--- a/web-app/src/components/PromptProgress.tsx+++ b/web-app/src/components/PromptProgress.tsx@@ -1,23 +1,45 @@import { useAppState } from '@/hooks/useAppState'+import { useCodeRun } from '@/hooks/useCodeRun'import { Loader } from 'lucide-react'import { useParams } from '@tanstack/react-router'import { Progress } from '@/components/ui/progress'-export function PromptProgress({ hideIdle = false }: { hideIdle?: boolean }) {+export function PromptProgress({+ hideIdle = false,+ stateKey,+}: {+ hideIdle?: boolean+ /**+ * 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+ * progress has no Cowork equivalent, so it keeps the global fallback;+ * harmless, since Cowork never writes there.+ */+ stateKey?: string+}) {const params = useParams({ strict: false })- const threadId = (params as { threadId?: string })?.threadId+ const threadId = stateKey ?? (params as { threadId?: string })?.threadIdconst promptProgress = useAppState((state) =>(threadId ? state.promptProgresses[threadId] : undefined) ??state.promptProgress)- const loadingModel = useAppState((state) =>- (threadId ? state.loadingModels[threadId] : undefined) ??- state.loadingModel+ const chatLoadingModel = useAppState((state) =>+ (threadId ? state.loadingModels[threadId] : undefined) ?? state.loadingModel)- const loadProgress = useAppState((state) =>+ const coworkLoadingModel = useCodeRun((state) =>+ stateKey ? state.loadingModels[stateKey] : undefined+ )+ const loadingModel = stateKey ? coworkLoadingModel : chatLoadingModel+ const chatLoadProgress = useAppState((state) =>(threadId ? state.modelLoadProgressByThread[threadId] : undefined) ??state.modelLoadProgress)+ const coworkLoadProgress = useCodeRun((state) =>+ stateKey ? state.modelLoadProgress[stateKey] : undefined+ )+ const loadProgress = stateKey ? coworkLoadProgress : chatLoadProgressconst percentage =promptProgress && promptProgress.total > 0diff --git a/web-app/src/components/__tests__/HtmlArtifact.test.tsx b/web-app/src/components/__tests__/HtmlArtifact.test.tsxindex 097513607..a0025db48 100644--- a/web-app/src/components/__tests__/HtmlArtifact.test.tsx+++ b/web-app/src/components/__tests__/HtmlArtifact.test.tsx@@ -5,7 +5,9 @@ import { HtmlArtifact } from '../HtmlArtifact'vi.mock('@/i18n/react-i18next-compat', () => ({useTranslation: () => ({- t: (_key: string, opts?: { defaultValue?: string }) => opts?.defaultValue ?? _key,+ t: (_key: string, opts?: { defaultValue?: string; count?: number }) =>+ opts?.defaultValue ??+ (opts?.count === undefined ? _key : `${_key}#${opts.count}`),}),}))@@ -110,4 +112,41 @@ describe('HtmlArtifact', () => {doc.indexOf('<title>t</title>'))})++ it('shows a notice when the HTML has unresolved relative asset refs', () => {+ render(<HtmlArtifact code={'<img src="./logo.png"><h1>hi</h1>'} />)+ expect(screen.getByTestId('html-artifact-unresolved')).toBeInTheDocument()+ })++ // i18next picks the plural form from `count`, so the component's only job is+ // to pass it; both forms must exist in the bundle or it renders the raw key.+ it('passes the ref count through for pluralisation', () => {+ const { unmount } = render(<HtmlArtifact code={'<img src="./a.png">'} />)+ expect(screen.getByTestId('html-artifact-unresolved')).toHaveTextContent(+ 'htmlArtifact.unresolvedAssets#1'+ )+ unmount()+ render(<HtmlArtifact code={'<img src="./a.png"><img src="./b.png">'} />)+ expect(screen.getByTestId('html-artifact-unresolved')).toHaveTextContent(+ 'htmlArtifact.unresolvedAssets#2'+ )+ })++ it('has both plural forms for the unresolved-assets notice', async () => {+ const common = (await import('@/locales/en/common.json')).default+ expect(common.htmlArtifact.unresolvedAssets_one).toBeTruthy()+ expect(common.htmlArtifact.unresolvedAssets_other).toContain('{{count}}')+ })++ it('shows no notice for self-contained HTML', () => {+ render(<HtmlArtifact code={'<h1>hi</h1><img src="https://x.dev/a.png">'} />)+ expect(screen.queryByTestId('html-artifact-unresolved')).not.toBeInTheDocument()+ })++ it('hides the notice in the Code view', async () => {+ const user = userEvent.setup()+ render(<HtmlArtifact code={'<img src="a.png">'} />)+ await user.click(screen.getByRole('tab', { name: /code/i }))+ expect(screen.queryByTestId('html-artifact-unresolved')).not.toBeInTheDocument()+ })})diff --git a/web-app/src/components/ai-elements/tool.tsx b/web-app/src/components/ai-elements/tool.tsxindex 6b68e3eb4..c784e1a39 100644--- a/web-app/src/components/ai-elements/tool.tsx+++ b/web-app/src/components/ai-elements/tool.tsx@@ -7,7 +7,7 @@ import {} from '@/components/ui/collapsible'import { cn } from '@/lib/utils'import type { ToolUIPart } from 'ai'-import { ChevronDownIcon, WrenchIcon } from 'lucide-react'+import { ChevronDownIcon, WrenchIcon, SearchIcon, GlobeIcon } from 'lucide-react'import type { ComponentProps, ReactNode } from 'react'import {createContext,@@ -192,6 +192,10 @@ export const ToolHeader = memo(>{awaitingApproval ? (<ShieldAlertIcon className="size-4 shrink-0 text-amber-500" />+ ) : toolName === 'web_search' ? (+ <SearchIcon className="size-4 shrink-0" />+ ) : toolName === 'web_fetch' ? (+ <GlobeIcon className="size-4 shrink-0" />) : (<WrenchIcon className="size-4 shrink-0" />)}diff --git a/web-app/src/components/left-sidebar/NavCode.tsx b/web-app/src/components/left-sidebar/NavCode.tsxindex 000f3a092..e44a7f5ed 100644--- a/web-app/src/components/left-sidebar/NavCode.tsx+++ b/web-app/src/components/left-sidebar/NavCode.tsx@@ -26,15 +26,20 @@ import { useTranslation } from '@/i18n/react-i18next-compat'import { useNavigate } from '@tanstack/react-router'import { route } from '@/constants/routes'import {- MessageSquarePlus,Box,SlidersHorizontal,MoreHorizontal,Trash2,+ Loader2,type LucideIcon,} from 'lucide-react'-import { useCodeSessions } from '@/hooks/useCodeSessions'-import { useState } from 'react'+import {+ MessageCircleIcon,+ type MessageCircleIconHandle,+} from '@/components/animated-icon/message-circle'+import { useCodeSessions, type CodeSession } from '@/hooks/useCodeSessions'+import { useIsSessionActive } from '@/hooks/useCodeRun'+import { memo, useCallback, useRef, useState } from 'react'import SkillsManagerDialog from '@/containers/dialogs/SkillsManagerDialog'type CodeNavItem = {@@ -43,6 +48,68 @@ type CodeNavItem = {onClick: () => void}+// Own component (not inlined in a .map()) so it can be memoized: each row's+// running/needs-input state now comes from its own per-session selector+// (useIsSessionActive/useSessionHasPendingPerms), so a session starting or+// stopping a run only re-renders its own row, not the whole session list —+// mirroring ThreadList.tsx's memoized ThreadItem + useIsThreadActive.+const SessionItem = memo(function SessionItem({+ session,+ isCurrent,+ isMobile,+ onSelect,+ onRequestDelete,+}: {+ session: CodeSession+ isCurrent: boolean+ isMobile: boolean+ onSelect: (id: string) => void+ onRequestDelete: (pending: { id: string; title: string }) => void+}) {+ const { t } = useTranslation()+ const isRunning = useIsSessionActive(session.id)++ return (+ <SidebarMenuItem>+ <SidebarMenuButton+ isActive={isCurrent}+ onClick={() => onSelect(session.id)}+ >+ {isRunning && (+ <Loader2 className="size-3 shrink-0 animate-spin text-muted-foreground" />+ )}+ <span className="truncate">{session.title}</span>+ </SidebarMenuButton>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <SidebarMenuAction+ showOnHover+ className="hover:bg-sidebar-foreground/8"+ >+ <MoreHorizontal />+ <span className="sr-only">More</span>+ </SidebarMenuAction>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ className="w-48"+ side={isMobile ? 'bottom' : 'right'}+ align={isMobile ? 'end' : 'start'}+ >+ <DropdownMenuItem+ variant="destructive"+ onSelect={() =>+ onRequestDelete({ id: session.id, title: session.title })+ }+ >+ <Trash2 />+ <span>{t('common:deleteSession')}</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </SidebarMenuItem>+ )+})+export function NavCode() {const { t } = useTranslation()const navigate = useNavigate()@@ -56,21 +123,25 @@ export function NavCode() {title: string} | null>(null)- const goCode = () => navigate({ to: route.code })+ const goCode = useCallback(() => navigate({ to: route.code }), [navigate])+ const newSessionIconRef = useRef<MessageCircleIconHandle>(null)+ const newSession = () => {+ useCodeSessions.getState().createSession()+ goCode()+ }+ const selectSession = useCallback(+ (id: string) => {+ useCodeSessions.getState().selectSession(id)+ goCode()+ },+ [goCode]+ )const items: CodeNavItem[] = [- {- title: t('common:newSession'),- icon: MessageSquarePlus,- onClick: () => {- useCodeSessions.getState().createSession()- goCode()- },- },{title: t('common:artifacts'),icon: Box,- onClick: goCode,+ onClick: () => navigate({ to: route.artifacts }),},{title: t('common:customize'),@@ -87,6 +158,20 @@ export function NavCode() {return (<><SidebarMenu>+ <SidebarMenuItem>+ <SidebarMenuButton+ onClick={newSession}+ onMouseEnter={() => newSessionIconRef.current?.startAnimation()}+ onMouseLeave={() => newSessionIconRef.current?.stopAnimation()}+ >+ <MessageCircleIcon+ ref={newSessionIconRef}+ className="text-foreground/70"+ size={16}+ />+ <span>{t('common:newSession')}</span>+ </SidebarMenuButton>+ </SidebarMenuItem>{items.map((item) => {const Icon = item.iconreturn (@@ -105,46 +190,14 @@ export function NavCode() {<SidebarGroupLabel>{t('common:sessions')}</SidebarGroupLabel><SidebarMenu>{sessions.map((session) => (- <SidebarMenuItem key={session.id}>- <SidebarMenuButton- isActive={session.id === currentId}- onClick={() => {- useCodeSessions.getState().selectSession(session.id)- goCode()- }}- >- <span className="truncate">{session.title}</span>- </SidebarMenuButton>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <SidebarMenuAction- showOnHover- className="hover:bg-sidebar-foreground/8"- >- <MoreHorizontal />- <span className="sr-only">More</span>- </SidebarMenuAction>- </DropdownMenuTrigger>- <DropdownMenuContent- className="w-48"- side={isMobile ? 'bottom' : 'right'}- align={isMobile ? 'end' : 'start'}- >- <DropdownMenuItem- variant="destructive"- onSelect={() =>- setPendingDelete({- id: session.id,- title: session.title,- })- }- >- <Trash2 />- <span>{t('common:deleteSession')}</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </SidebarMenuItem>+ <SessionItem+ key={session.id}+ session={session}+ isCurrent={session.id === currentId}+ isMobile={isMobile}+ onSelect={selectSession}+ onRequestDelete={setPendingDelete}+ />))}</SidebarMenu></SidebarGroup>diff --git a/web-app/src/components/left-sidebar/NavTabs.tsx b/web-app/src/components/left-sidebar/NavTabs.tsxindex 196442e33..bc203ad9a 100644--- a/web-app/src/components/left-sidebar/NavTabs.tsx+++ b/web-app/src/components/left-sidebar/NavTabs.tsx@@ -1,6 +1,6 @@import { Link, useLocation } from '@tanstack/react-router'-import { HomeIcon, CodeIcon } from 'lucide-react'-import { route } from '@/constants/routes'+import { Handshake, HomeIcon } from 'lucide-react'+import { route, isCoworkRoute } from '@/constants/routes'import { cn } from '@/lib/utils'import { useTranslation } from '@/i18n/react-i18next-compat'@@ -15,7 +15,7 @@ export function NavTabs() {const { t } = useTranslation()const { pathname } = useLocation()- const isCode = pathname === route.code+ const isCode = isCoworkRoute(pathname)// Home owns the chat surfaces (new chat, threads, projects); Code owns /code.const isHome =pathname === route.home ||@@ -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: CodeIcon, isActive: isCode },+ { label: t('common:code'), to: route.code, icon: Handshake, isActive: isCode },]return (diff --git a/web-app/src/components/left-sidebar/index.tsx b/web-app/src/components/left-sidebar/index.tsxindex 02bac2a83..3c899cb5a 100644--- a/web-app/src/components/left-sidebar/index.tsx+++ b/web-app/src/components/left-sidebar/index.tsx@@ -16,12 +16,12 @@ import {import { cn } from '@/lib/utils'import { useTitlebarLayout } from '@/stores/titlebar-layout-store'import { useLocation } from '@tanstack/react-router'-import { route } from '@/constants/routes'+import { isCoworkRoute } from '@/constants/routes'export function LeftSidebar() {const { open: isLeftPanelOpen } = useLeftPanel()const { pathname } = useLocation()- const isCode = pathname === route.code+ const isCode = 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)diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex 25895f104..f50c32945 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -125,6 +125,11 @@ type ChatInputProps = {) => voidonStop?: () => voidchatStatus?: ChatStatus+ // Overrides the conversation scope this input belongs to — both its message+ // queue and its pending attachments (default: useThreads' currentThreadId).+ // 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}// Video containers llama-server can decode via ffmpeg/ffprobe into frames.@@ -153,6 +158,7 @@ const ChatInput = memo(function ChatInput({onSubmit,onStop,chatStatus,+ scopeKey,}: ChatInputProps) {const textareaRef = useRef<HTMLTextAreaElement>(null)const [isFocused, setIsFocused] = useState(false)@@ -434,7 +440,10 @@ const ChatInput = memo(function ChatInput({const maxFileSizeMB = useAttachments((s) => s.maxFileSizeMB)// Derived: any document currently processing (ingestion in progress)- const attachmentsKey = currentThreadId ?? NEW_THREAD_ATTACHMENT_KEY+ // Same scope as the message queue: a surface writing attachments under its+ // own id would have them silently dropped if this read a thread id.+ const attachmentsKey =+ scopeKey ?? currentThreadId ?? NEW_THREAD_ATTACHMENT_KEYconst attachments = useChatAttachments(useCallback((state) => state.getAttachments(attachmentsKey),@@ -468,21 +477,26 @@ const ChatInput = memo(function ChatInput({} | null>(null)// Queued messages for this thread (shown as chips in the input area)+ const queueId = scopeKey ?? currentThreadId ?? ''const queuedMessages = useMessageQueue(- useShallow((s) => s.getQueue(currentThreadId ?? ''))+ useShallow((s) => s.getQueue(queueId)))const queueLength = queuedMessages.lengthconst removeQueuedMessage = useCallback((id: string) => {- useMessageQueue.getState().removeMessage(currentThreadId ?? '', id)+ useMessageQueue.getState().removeMessage(queueId, id)},- [currentThreadId]+ [queueId])const lastTransferredThreadId = useRef<string | null>(null)useEffect(() => {+ // Only the general chat migrates a draft: it composes under the "new+ // thread" key until the thread exists. A scopeKey caller has a stable id+ // from the start, so there is nothing to move.+ if (scopeKey) returnif (currentThreadId &&lastTransferredThreadId.current !== currentThreadId@@ -490,7 +504,7 @@ const ChatInput = memo(function ChatInput({transferAttachments(NEW_THREAD_ATTACHMENT_KEY, currentThreadId)lastTransferredThreadId.current = currentThreadId}- }, [currentThreadId, transferAttachments])+ }, [scopeKey, currentThreadId, transferAttachments])// Check for mmproj existence or vision capability when model changesuseEffect(() => {@@ -549,8 +563,8 @@ const ChatInput = memo(function ChatInput({// Use onSubmit prop if available (AI SDK), otherwise create thread and navigateif (onSubmit) {// When the model is still streaming, queue the message for later- if (isStreaming && currentThreadId) {- useMessageQueue.getState().enqueue(currentThreadId, {+ if (isStreaming && queueId) {+ useMessageQueue.getState().enqueue(queueId, {id: generateId(),text: effectivePrompt,createdAt: Date.now(),@@ -2819,13 +2833,20 @@ const ChatInput = memo(function ChatInput({size="icon-sm"className="rounded-full mr-1 mb-1"onClick={() => {- if (!currentThreadId) return- const queue = useMessageQueue.getState().getQueue(currentThreadId)- if (queue.length > 0) {- useMessageQueue.getState().clearQueue(currentThreadId)- } else {- stopStreaming(currentThreadId)+ // Stopping with messages queued clears the queue —+ // there is nothing to interrupt yet. The old+ // `if (!currentThreadId) return` guard made this button+ // inert for any surface without a thread id.+ if (queueId) {+ const queue = useMessageQueue+ .getState()+ .getQueue(queueId)+ if (queue.length > 0) {+ useMessageQueue.getState().clearQueue(queueId)+ return+ }}+ stopStreaming(currentThreadId ?? '')}}><IconPlayerStopFilled />diff --git a/web-app/src/containers/HeaderPage.tsx b/web-app/src/containers/HeaderPage.tsxindex 2c9c54b67..afa2b8d8c 100644--- a/web-app/src/containers/HeaderPage.tsx+++ b/web-app/src/containers/HeaderPage.tsx@@ -18,6 +18,10 @@ const HeaderPage = memo(function HeaderPage({ children }: HeaderPageProps) {const leftButtons = useTitlebarLayout((s) => s.layout.left.length)const linuxControlsPad =!IS_MACOS && !open && leftButtons > 0 ? leftButtons * 32 + 24 : undefined+ // Right-anchored controls (Windows, and Linux DEs that place them there) sit at+ // right-4 above the header — keep header content clear of them at every width.+ const rightButtons = useTitlebarLayout((s) => s.layout.right.length)+ const rightControlsPad = rightButtons > 0 ? rightButtons * 32 + 24 : undefinedreturn (<div@@ -26,7 +30,10 @@ const HeaderPage = memo(function HeaderPage({ children }: HeaderPageProps) {(IS_MACOS && !open) ? 'pl-24' : ' pl-4',children === undefined && 'border-none')}- style={linuxControlsPad ? { paddingLeft: linuxControlsPad } : undefined}+ style={{+ ...(linuxControlsPad ? { paddingLeft: linuxControlsPad } : {}),+ ...(rightControlsPad ? { paddingRight: rightControlsPad } : {}),+ }}><divclassName={cn(diff --git a/web-app/src/containers/MessageItem.test.tsx b/web-app/src/containers/MessageItem.test.tsxnew file mode 100644index 000000000..572acd17e--- /dev/null+++ b/web-app/src/containers/MessageItem.test.tsx@@ -0,0 +1,77 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, screen, act } from '@testing-library/react'+import { MessageItem } from './MessageItem'+import type { UIMessage } from 'ai'++vi.mock('@/i18n/react-i18next-compat', () => ({+ useTranslation: () => ({ t: (k: string) => k }),+}))+vi.mock('@tanstack/react-router', () => ({+ useParams: () => ({}),+}))++describe('agent activity status', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date(2024, 0, 1, 0, 0, 0))+ })+ afterEach(() => {+ vi.useRealTimers()+ })++ const baseMessage: UIMessage = {+ id: 'm1',+ role: 'assistant',+ parts: [+ {+ type: 'tool-write',+ toolCallId: 'c1',+ state: 'input-available',+ input: { path: '/proj/report.html' },+ } as never,+ ],+ } as UIMessage++ it('shows the active tool label and ticks elapsed time', () => {+ render(+ <MessageItem+ message={baseMessage}+ isFirstMessage={false}+ isLastMessage={true}+ status="streaming"+ />+ )+ expect(screen.getByText(/Writing report\.html/)).toBeInTheDocument()+ expect(screen.getByText(/0ms/)).toBeInTheDocument()++ act(() => {+ vi.advanceTimersByTime(3000)+ })+ expect(screen.getByText(/3s/)).toBeInTheDocument()+ })++ it('removes the status row once the tool result lands', () => {+ const doneMessage: UIMessage = {+ ...baseMessage,+ parts: [+ {+ type: 'tool-write',+ toolCallId: 'c1',+ state: 'output-available',+ input: { path: '/proj/report.html' },+ output: 'ok',+ } as never,+ ],+ } as UIMessage++ render(+ <MessageItem+ message={doneMessage}+ isFirstMessage={false}+ isLastMessage={true}+ status="ready"+ />+ )+ expect(screen.queryByText(/Writing report\.html/)).not.toBeInTheDocument()+ })+})diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex 678c78203..1217bc86b 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -1,8 +1,20 @@/* eslint-disable @typescript-eslint/no-explicit-any */-import { memo, useState, useCallback, useEffect, useMemo } from 'react'+import { memo, useState, useCallback, useEffect, useRef, useMemo } from 'react'import type { UIMessage, ChatStatus } from 'ai'import { RenderMarkdown } from './RenderMarkdown'import { cn } from '@/lib/utils'+import { formatDuration } from '@/lib/utils'+import {+ activeToolPart,+ subagentActivityLabel,+ usedSkillNames,+ type ActivityLabel,+} from '@/lib/agentActivity'+import type { SubagentRun } from '@/types/codeSession'+import { Loader } from 'lucide-react'++/** How close to the cap the step counter becomes visible. */+const BUDGET_WARN_STEPS = 5import { ChainOfThoughtGroup } from './message/ChainOfThoughtGroup'import {CHAT_STATUS,@@ -54,6 +66,13 @@ export type MessageItemProps = {onDelete?: (messageId: string) => voidversionInfo?: { index: number; count: number }onSwitchVersion?: (messageId: string, dir: -1 | 1) => void+ // Cowork only: the session's background subagent runs. Omitted in regular+ // chat threads, which never spawn subagents.+ subagents?: SubagentRun[]+ /** Cowork only: step budget for the running turn. Rendered next to the+ * activity label, and only once it is close to the cap — a counter that is+ * always visible is noise for the 95% of turns that never approach it. */+ budget?: { step: number; max: number }isAnimating?: booleanhideActions?: boolean}@@ -66,6 +85,8 @@ export const MessageItem = memo(status,isAnimating,hideActions,+ subagents,+ budget,reasoningContainerRef,isReasoningAtBottom,onReasoningScroll,@@ -148,6 +169,70 @@ export const MessageItem = memo(})}, [hasPendingToolCall, message.parts, pendingApprovals])+ // Tool parts carry no start timestamp; track first-seen time per+ // toolCallId locally so the elapsed-time readout is stable across+ // re-renders (not reset every render, not reused across a new call+ // with the same id after a session reset -- cleared once a step+ // becomes non-pending in the effect below).+ const toolStartedAtRef = useRef<Map<string, number>>(new Map())++ const pendingTool = useMemo(() => {+ if (!isLastMessage || message.role !== 'assistant') return null+ return activeToolPart(message.parts as never)+ }, [isLastMessage, message.role, message.parts])+ const usedSkills = useMemo(+ () => usedSkillNames(message.parts as never),+ [message.parts]+ )++ useEffect(() => {+ const map = toolStartedAtRef.current+ if (pendingTool) {+ // Keep only the current pending id; purge any stale entry that may+ // have lingered from a previous tool with a different toolCallId.+ map.forEach((_, key) => {+ if (key !== pendingTool.toolCallId) map.delete(key)+ })+ if (!map.has(pendingTool.toolCallId)) {+ map.set(pendingTool.toolCallId, Date.now())+ }+ } else {+ map.clear()+ }+ }, [pendingTool])++ const subagentLabel = useMemo<ActivityLabel>(() => {+ if (!subagents || subagents.length === 0) return null+ return subagentActivityLabel(subagents)+ }, [subagents])++ // `await_subagent` is only the parent's blocking wrapper; the child is the+ // work actually in progress. Show its live activity instead of the+ // misleading "Await subagent" label. Other parent tools retain priority.+ // Memoized so the reference is stable for the elapsed-time interval effect.+ const activityLabel = useMemo<ActivityLabel>(() => {+ if (pendingTool?.toolName === 'await_subagent' && subagentLabel) {+ return subagentLabel+ }+ if (pendingTool) {+ return {+ text: pendingTool.text,+ startedAt:+ toolStartedAtRef.current.get(pendingTool.toolCallId) ?? Date.now(),+ }+ }+ return subagentLabel+ }, [pendingTool, subagentLabel])++ // Re-render once a second while a label is showing, purely to advance the+ // elapsed-time readout -- no state carried, just a tick.+ const [, forceTick] = useState(0)+ useEffect(() => {+ if (!activityLabel) return+ const id = setInterval(() => forceTick((n) => n + 1), 1000)+ return () => clearInterval(id)+ }, [activityLabel])+const isStreaming =(isLastMessage &&(status === CHAT_STATUS.STREAMING ||@@ -516,12 +601,45 @@ export const MessageItem = memo(<WebSourcesRow citations={webCitations} />)}+ {message.role === 'assistant' && !isStreaming && usedSkills.length > 0 && (+ <div+ aria-label={t('common:skillsUsedLabel')}+ className="mt-2 inline-flex rounded-full border border-border bg-muted/40 px-2.5 py-1 text-xs font-medium text-muted-foreground"+ >+ {t('common:skillsUsed', { skills: usedSkills.join(', ') })}+ </div>+ )}+{isLastMessage &&message.role === 'assistant' &&!awaitingApproval &&- (hasPendingToolCall || status === CHAT_STATUS.SUBMITTED) && (+ (hasPendingToolCall || status === CHAT_STATUS.SUBMITTED || activityLabel) && (<div className="mt-2">- <PromptProgress hideIdle={hasPendingToolCall} />+ {activityLabel ? (+ <div+ role="status"+ aria-live="polite"+ className="flex items-center gap-2 text-xs"+ >+ <Loader className="animate-spin w-3.5 h-3.5 text-primary shrink-0" />+ <span className="font-medium text-foreground">+ {activityLabel.text}+ </span>+ <span className="text-muted-foreground tabular-nums">+ {formatDuration(activityLabel.startedAt)}+ </span>+ {budget && budget.step >= budget.max - BUDGET_WARN_STEPS && (+ <span className="ml-auto text-muted-foreground tabular-nums">+ {t('common:budget.steps', {+ step: budget.step,+ max: budget.max,+ })}+ </span>+ )}+ </div>+ ) : (+ <PromptProgress hideIdle={hasPendingToolCall} />+ )}</div>)}diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsxindex f74ac3a88..6b639ddb3 100644--- a/web-app/src/containers/__tests__/ChatInput.test.tsx+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx@@ -141,18 +141,30 @@ vi.mock('@/hooks/useAttachments', () => ({}))let attachmentsList: any[] = []+/** Attachments stored under a specific scope key, for the scopeKey tests. */+let attachmentsByKey: Record<string, any[]> = {}+/** Keys ChatInput actually read this render, so a mismatch is visible. */+let readKeys: string[] = []const setAttachmentsMock = vi.fn()const clearAttachmentsMock = vi.fn()const transferAttachmentsMock = vi.fn()+// Key-aware on purpose: the store is keyed, and a caller reading a different+// key than the writer used is exactly the bug this mock has to be able to see.+const attachmentStore = {+ getAttachments: (key: string) => {+ readKeys.push(key)+ return attachmentsByKey[key] ?? attachmentsList+ },+ setAttachments: setAttachmentsMock,+ clearAttachments: clearAttachmentsMock,+ transferAttachments: transferAttachmentsMock,+}vi.mock('@/hooks/useChatAttachments', () => ({NEW_THREAD_ATTACHMENT_KEY: '__new_thread__',- useChatAttachments: (selector: any) =>- selector({- getAttachments: () => attachmentsList,- setAttachments: setAttachmentsMock,- clearAttachments: clearAttachmentsMock,- transferAttachments: transferAttachmentsMock,- }),+ useChatAttachments: Object.assign(+ (selector: any) => selector(attachmentStore),+ { getState: () => attachmentStore }+ ),}))vi.mock('@/hooks/useJanBrowserExtension', () => ({@@ -310,6 +322,8 @@ const resetAll = () => {promptState = ''appStateOverrides = {}attachmentsList = []+ attachmentsByKey = {}+ readKeys = []agentModeOn = falseselectedModelOverride = {id: 'model-a',@@ -596,4 +610,38 @@ describe('ChatInput', () => {expect(screen.queryByTestId('stub-token-counter')).not.toBeInTheDocument()})})++ // Cowork is not keyed by thread: it passes its session id as scopeKey, and+ // the preview panel writes annotation images under that same id. Reading the+ // thread key here silently dropped every annotation.+ it('reads attachments under scopeKey and shows them in the input', () => {+ attachmentsByKey['code-session-1'] = [+ {+ type: 'image',+ name: 'annotation.png',+ dataUrl: 'data:image/png;base64,annotated',+ mimeType: 'image/png',+ },+ ]+ renderInput({ scopeKey: 'code-session-1' })+ expect(readKeys).toContain('code-session-1')+ const thumb = document.querySelector(+ 'img[src="data:image/png;base64,annotated"]'+ )+ expect(thumb).toBeTruthy()+ })++ it('falls back to the thread key when no scopeKey is given', () => {+ renderInput()+ expect(readKeys.length).toBeGreaterThan(0)+ expect(readKeys).not.toContain('code-session-1')+ })++ // A scopeKey caller owns a stable id from the start; migrating the general+ // chat's "new thread" draft into it would steal another surface's files.+ it('does not migrate the new-thread draft into a scopeKey surface', () => {+ renderInput({ scopeKey: 'code-session-1' })+ expect(transferAttachmentsMock).not.toHaveBeenCalled()+ })+})diff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsxindex b9cae20df..8f49eb4ca 100644--- a/web-app/src/containers/__tests__/MessageItem.test.tsx+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx@@ -5,7 +5,10 @@ import '@testing-library/jest-dom'// ---- Module mocks ----------------------------------------------------------vi.mock('@/i18n/react-i18next-compat', () => ({- useTranslation: () => ({ t: (k: string) => k }),+ useTranslation: () => ({+ t: (k: string, opts?: Record<string, unknown>) =>+ opts ? `${k} ${Object.values(opts).join(' ')}` : k,+ }),}))const selectedModelRef = vi.hoisted(() => ({ current: { id: 'm1' } as any }))@@ -477,7 +480,101 @@ describe('MessageItem', () => {status={'ready' as any}/>)- expect(screen.getByTestId('prompt-progress')).toBeInTheDocument()+ // A pending tool call renders the new activity-status row, not PromptProgress.+ expect(screen.queryByTestId('prompt-progress')).not.toBeInTheDocument()+ expect(screen.getByRole('status')).toHaveTextContent(/Search/)+ })++ it('shows a persistent badge for a successfully loaded skill', () => {+ render(+ <MessageItem+ message={+ makeMsg({+ parts: [+ {+ type: 'tool-skill_read',+ state: 'output-available',+ toolCallId: 'skill-1',+ input: { name: 'pptx' },+ output: 'skill instructions',+ },+ { type: 'text', text: 'Done' },+ ],+ }) as any+ }+ isFirstMessage+ isLastMessage+ status={'ready' as any}+ />+ )++ expect(+ screen.getByText('common:skillsUsed pptx')+ ).toBeInTheDocument()+ expect(screen.getByText('Used pptx')).toBeInTheDocument()+ })++ it('defers the persistent skills badge until generation finishes', () => {+ render(+ <MessageItem+ message={+ makeMsg({+ parts: [+ {+ type: 'tool-skill_read',+ state: 'output-available',+ toolCallId: 'skill-1',+ input: { name: 'pptx' },+ output: 'skill instructions',+ },+ ],+ }) as any+ }+ isFirstMessage+ isLastMessage+ status={'streaming' as any}+ />+ )++ expect(+ screen.queryByLabelText('common:skillsUsedLabel')+ ).not.toBeInTheDocument()+ })++ it('shows child activity while the parent awaits that subagent', () => {+ render(+ <MessageItem+ message={+ makeMsg({+ parts: [+ {+ type: 'tool-await_subagent',+ state: 'input-available',+ toolCallId: 'tc-await',+ input: { run_id: 'sub-robotics-researcher-1' },+ },+ ],+ }) as any+ }+ isFirstMessage+ isLastMessage+ status={'ready' as any}+ subagents={[+ {+ runId: 'sub-robotics-researcher-1',+ name: 'robotics-researcher',+ status: 'running',+ startedAt: Date.now() - 1_000,+ turns: [],+ },+ ]}+ />+ )++ expect(screen.getByRole('status')).toHaveTextContent(+ 'robotics-researcher: working'+ )+ expect(screen.getByRole('status')).not.toHaveTextContent('Await subagent')})it('hides progress while a tool call awaits approval', () => {diff --git a/web-app/src/containers/message/ToolCallCard.tsx b/web-app/src/containers/message/ToolCallCard.tsxindex 429f341cc..f5cc8d07d 100644--- a/web-app/src/containers/message/ToolCallCard.tsx+++ b/web-app/src/containers/message/ToolCallCard.tsx@@ -10,6 +10,7 @@ import {import { ToolProgressRow } from '@/components/ai-elements/tool-runtime'import { useToolOrigin } from '@/hooks/useToolOrigin'import { useTranslation } from '@/i18n/react-i18next-compat'+import { completedToolLabel } from '@/lib/agentActivity'import { describeNativeToolCall } from '@/lib/toolPresentation'import { isToolPart, type MessagePartLike } from './types'import { RagToolWidget } from './RagToolWidget'@@ -55,6 +56,13 @@ export const ToolCallCard = memo(// the raw payload is still one click away in the header.const bar = describeNativeToolCall(origin, toolName, part.input)+ // `skill_read` reads as a bare tool name otherwise; the label names the+ // skill actually being loaded, which is the only interesting part of it.+ const title =+ toolName === 'skill_read'+ ? completedToolLabel(toolName, part.input, part.state)+ : toolName+return (<Toolstate={part.state}@@ -63,7 +71,7 @@ export const ToolCallCard = memo(className={className}><ToolHeader- title={toolName}+ title={title}type={`tool-${toolName}` as `tool-${string}`}state={part.state}origin={originLabel}@@ -108,7 +116,7 @@ export const ToolCallCard = memo()}</div>)}- <ToolContent title={toolName}>+ <ToolContent title={title}>{Boolean(part.input) && <ToolInput input={part.input} />}<ToolApprovalActions />{/* The widget already presents the result for native tools. */}diff --git a/web-app/src/lib/htmlSandbox.ts b/web-app/src/lib/htmlSandbox.tsnew file mode 100644index 000000000..47cf694a2--- /dev/null+++ b/web-app/src/lib/htmlSandbox.ts@@ -0,0 +1,58 @@+import { PREVIEW_INSPECTOR_SCRIPT } from '@/lib/previewInspector'++function buildCsp(allowNetwork: boolean, allowScripts: boolean): string {+ if (!allowScripts) {+ return [+ "default-src 'none'",+ 'img-src data: blob:',+ "style-src 'unsafe-inline'",+ 'font-src data:',+ "connect-src 'none'",+ ].join('; ')+ }+ if (allowNetwork) {+ return [+ "default-src 'none'",+ "script-src 'unsafe-inline' https:",+ "style-src 'unsafe-inline' https:",+ 'img-src data: blob: https:',+ 'font-src data: https:',+ 'connect-src https:',+ ].join('; ')+ }+ return [+ "default-src 'none'",+ "script-src 'unsafe-inline'",+ "style-src 'unsafe-inline'",+ 'img-src data: blob:',+ 'font-src data:',+ "connect-src 'none'",+ ].join('; ')+}++/**+ * Wrap model markup in the sandbox shell (CSP + inspector) used for every+ * artifact preview. Lives here rather than beside the component so the Cowork+ * preview panel can render a bare, panel-filling iframe with identical+ * sandboxing instead of nesting that component's card-and-tabs chrome.+ */+export function buildSrcDoc(+ code: string,+ allowNetwork: boolean,+ allowScripts: boolean+): string {+ const csp = buildCsp(allowNetwork, allowScripts)+ const meta = `<meta http-equiv="Content-Security-Policy" content="${csp}">`+ // Zero the shell's body margin so artifact content sits flush and the+ // element inspector can treat full-viewport wrappers as background.+ const shellStyle = '<style>html,body{margin:0}</style>'+ // Element inspection (hover outline / click-to-pin bbox) needs a script in+ // the iframe's own document, which is only possible when scripts run at all+ // (allowScripts=false is the static SVG mode).+ const inspector = allowScripts+ ? `<script>${PREVIEW_INSPECTOR_SCRIPT}</script>`+ : ''+ // Always wrap so the CSP meta precedes all model markup — a meta CSP is only+ // honored before resource-fetching content, and a later one can't loosen it.+ return `<!doctype html><html><head>${meta}${shellStyle}${inspector}</head><body>${code}</body></html>`+}