Skip to content

armgit / jan

Public Imported from GitHub
0

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

feat(cowork): model settings rail, alignment pass, and CoT fixes

Akarshan Biswasfc175444fa55
diff --git a/web-app/src/components/ai-elements/__tests__/chain-of-thought-duration.test.tsx b/web-app/src/components/ai-elements/__tests__/chain-of-thought-duration.test.tsx
index bcc0f9877..4a218c947 100644
--- a/web-app/src/components/ai-elements/__tests__/chain-of-thought-duration.test.tsx
+++ b/web-app/src/components/ai-elements/__tests__/chain-of-thought-duration.test.tsx
@@ -101,4 +101,33 @@ describe('ChainOfThought duration', () => {
render(<Trace streaming />)
expect(screen.getByTestId('shimmer')).toBeInTheDocument()
})
+
+ // A reloaded trace never streams in this mount, so it reports the persisted
+ // duration instead of "a while".
+ it('seeds the header from a persisted duration on reload', () => {
+ start()
+ render(
+ <ChainOfThought isStreaming={false} durationMs={7000}>
+ <ChainOfThoughtHeader completedVariant="worked" />
+ </ChainOfThought>
+ )
+ expect(label()).toBe('chat:reasoning.workedFor(7)')
+ })
+
+ it('reports the settled duration so the caller can persist it', () => {
+ start()
+ const onDurationSettled = vi.fn()
+ const { rerender } = render(
+ <ChainOfThought isStreaming onDurationSettled={onDurationSettled}>
+ <ChainOfThoughtHeader completedVariant="worked" />
+ </ChainOfThought>
+ )
+ advanceTo(1_008_000)
+ rerender(
+ <ChainOfThought isStreaming={false} onDurationSettled={onDurationSettled}>
+ <ChainOfThoughtHeader completedVariant="worked" />
+ </ChainOfThought>
+ )
+ expect(onDurationSettled).toHaveBeenCalledWith(8000)
+ })
})
diff --git a/web-app/src/components/ai-elements/chain-of-thought.tsx b/web-app/src/components/ai-elements/chain-of-thought.tsx
index 0ec53d531..8fec85290 100644
--- a/web-app/src/components/ai-elements/chain-of-thought.tsx
+++ b/web-app/src/components/ai-elements/chain-of-thought.tsx
@@ -24,6 +24,7 @@ import {
useContext,
useEffect,
useMemo,
+ useRef,
useState,
} from 'react'
import { Streamdown } from 'streamdown'
@@ -71,6 +72,12 @@ export type ChainOfThoughtProps = ComponentProps<typeof Collapsible> & {
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
+ /** Persisted trace duration (ms), used to seed the header when a restored
+ * trace never streamed in this mount. Live measurement takes over otherwise. */
+ durationMs?: number
+ /** Fired once with the accumulated ms when a live measurement settles, so the
+ * caller can persist it against the message. */
+ onDurationSettled?: (ms: number) => void
}
export const ChainOfThought = memo(
@@ -82,9 +89,13 @@ export const ChainOfThought = memo(
open,
defaultOpen = true,
onOpenChange,
+ durationMs,
+ onDurationSettled,
children,
...props
}: ChainOfThoughtProps) => {
+ const onSettledRef = useRef(onDurationSettled)
+ onSettledRef.current = onDurationSettled
const [isOpen, setIsOpen] = useControllableState({
prop: open,
defaultProp: defaultOpen,
@@ -110,19 +121,33 @@ export const ChainOfThought = memo(
const [startTime, setStartTime] = useState<number | null>(null)
const [elapsedMs, setElapsedMs] = useState<number | undefined>(undefined)
+ // Seed from a persisted value when this trace never streamed in this mount
+ // (a reload/session-switch): the live measurement below, when it runs, sets
+ // elapsedMs itself and this stays out of its way.
+ useEffect(() => {
+ if (!isStreaming && elapsedMs === undefined && durationMs !== undefined) {
+ setElapsedMs(durationMs)
+ }
+ }, [isStreaming, elapsedMs, durationMs])
+
useEffect(() => {
if (isStreaming) {
if (startTime === null) {
setStartTime(Date.now())
}
- } else if (startTime !== null) {
+ return
+ }
+ if (startTime !== null) {
// Accumulated, not replaced: an agentic turn reasons, answers, then
// reasons again, and each window is part of the same trace.
- const window = Date.now() - startTime
- setElapsedMs((previous) => (previous ?? 0) + window)
+ const total = (elapsedMs ?? 0) + (Date.now() - startTime)
+ setElapsedMs(total)
setStartTime(null)
+ onSettledRef.current?.(total)
}
- }, [isStreaming, startTime])
+ // elapsedMs is read to accumulate; its own change re-runs this to a no-op
+ // (not streaming, startTime cleared), so no measurement is lost.
+ }, [isStreaming, startTime, elapsedMs])
// Rounded up to at least a second: a trace that begins and ends inside one
// tick still ran, and a zero would read as "still going" below.
@@ -140,9 +165,12 @@ export const ChainOfThought = memo(
<ChainOfThoughtContext.Provider value={contextValue}>
<Collapsible
className={cn(
- 'not-prose rounded-2xl transition-colors',
- // Card frame only while expanded; collapsed shows a bare summary row.
- 'data-[state=open]:border data-[state=open]:border-border/50 data-[state=open]:bg-main-view-fg/2 data-[state=open]:p-3',
+ 'not-prose transition-colors',
+ // Expanded: a full-width card frame around the timeline.
+ 'data-[state=open]:w-full data-[state=open]:rounded-2xl data-[state=open]:border data-[state=open]:border-border/50 data-[state=open]:bg-main-view-fg/2 data-[state=open]:p-3',
+ // Collapsed: a compact pill that hugs its label, so the folded trace
+ // reads as a distinct chip between messages, not a full-width row.
+ 'data-[state=closed]:w-fit data-[state=closed]:self-start data-[state=closed]:rounded-full data-[state=closed]:border data-[state=closed]:border-border/50 data-[state=closed]:bg-main-view-fg/2 data-[state=closed]:px-2.5 data-[state=closed]:py-1 data-[state=closed]:hover:bg-main-view-fg/5',
className
)}
onOpenChange={handleOpenChange}
@@ -206,8 +234,12 @@ export const ChainOfThoughtHeader = memo(
? t(keys.aWhile)
: t(keys.withDuration, { duration: formatCompactDuration(duration, t) })
+ // The folded summary is a compact pill, so it reads a notch smaller than
+ // the expanded card's header.
+ const iconSize = isOpen ? 'size-4' : 'size-3.5'
const rowClassName = cn(
- 'flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground',
+ 'flex w-full items-center gap-2 text-muted-foreground transition-colors hover:text-foreground',
+ isOpen ? 'text-sm' : 'text-xs',
className
)
@@ -221,7 +253,7 @@ export const ChainOfThoughtHeader = memo(
const label = (
<>
- <SparklesIcon className="size-4" />
+ <SparklesIcon className={cn(iconSize, 'shrink-0')} />
{isStreaming ? (
<Shimmer duration={1}>
{streamingLabel ?? t('chat:reasoning.label')}
@@ -260,7 +292,8 @@ export const ChainOfThoughtHeader = memo(
{label}
<ChevronDownIcon
className={cn(
- 'size-4 transition-transform',
+ iconSize,
+ 'shrink-0 transition-transform',
isOpen ? 'rotate-180' : 'rotate-0'
)}
/>
diff --git a/web-app/src/components/left-sidebar/NavCowork.tsx b/web-app/src/components/left-sidebar/NavCowork.tsx
index be726b679..1ad8d3478 100644
--- a/web-app/src/components/left-sidebar/NavCowork.tsx
+++ b/web-app/src/components/left-sidebar/NavCowork.tsx
@@ -39,6 +39,10 @@ import {
MessageCircleIcon,
type MessageCircleIconHandle,
} from '@/components/animated-icon/message-circle'
+import {
+ SettingsIcon,
+ type SettingsIconHandle,
+} from '@/components/animated-icon/settings'
import {
startNewSession,
useCoworkSessions,
@@ -148,6 +152,7 @@ export function NavCowork() {
const goCowork = useCallback(() => navigate({ to: route.cowork }), [navigate])
const newSessionIconRef = useRef<MessageCircleIconHandle>(null)
+ const settingsIconRef = useRef<SettingsIconHandle>(null)
const newSession = () => {
startNewSession(Object.keys(useCoworkRun.getState().runId))
goCowork()
@@ -215,6 +220,20 @@ export function NavCowork() {
</SidebarMenuItem>
)
})}
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ onClick={() => navigate({ to: route.settings.general })}
+ onMouseEnter={() => settingsIconRef.current?.startAnimation()}
+ onMouseLeave={() => settingsIconRef.current?.stopAnimation()}
+ >
+ <SettingsIcon
+ ref={settingsIconRef}
+ className="text-foreground/70"
+ size={16}
+ />
+ <span>{t('common:settings')}</span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
</SidebarMenu>
{/* px-0: the group's own p-2 would indent the session rows past the nav
diff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.ts
index 63235c94b..16e44c93b 100644
--- a/web-app/src/constants/localStorage.ts
+++ b/web-app/src/constants/localStorage.ts
@@ -34,6 +34,7 @@ export const localStorageKey = {
pausedDownloads: 'paused-downloads',
// Value predates the Cowork rename; changing it would orphan saved sessions.
coworkSessions: 'code-sessions',
+ cotDuration: 'cot-duration',
}
export const CACHE_EXPIRY_MS = 1000 * 60 * 60 * 24
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 491c7009c..43df7ce3c 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -2809,7 +2809,10 @@ const ChatInput = memo(function ChatInput({
})()}
</div>
{surfaceControls && (
- <div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto scrollbar-hide">
+ // Wrap on narrow widths instead of scrolling behind a hidden
+ // scrollbar: a control strip that overflows off-screen reads as
+ // clipped, and the scroll is undiscoverable on desktop.
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-y-1 gap-x-1">
<Separator
orientation="vertical"
className="mx-1 h-4 shrink-0"
diff --git a/web-app/src/containers/CoworkChangesChip.tsx b/web-app/src/containers/CoworkChangesChip.tsx
index 1691a4638..7935ba01f 100644
--- a/web-app/src/containers/CoworkChangesChip.tsx
+++ b/web-app/src/containers/CoworkChangesChip.tsx
@@ -7,7 +7,11 @@ import {
} from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'
import { useTranslation } from '@/i18n/react-i18next-compat'
-import type { CoworkFileDiff } from '@/lib/coworkDiffs'
+import {
+ DIFF_ADD_TEXT,
+ DIFF_DEL_TEXT,
+ type CoworkFileDiff,
+} from '@/lib/coworkDiffs'
/**
* Opens the diff rail, and stays out of the way until the agent has written
@@ -44,10 +48,10 @@ export function CoworkChangesChip({
className={cn('shrink-0', open && 'text-primary')}
>
<FileDiff className="size-3.5 shrink-0" />
- <span className="font-mono tabular-nums text-muted-foreground">
+ <span className={cn('font-mono tabular-nums', DIFF_ADD_TEXT)}>
+{additions}
</span>
- <span className="font-mono tabular-nums text-muted-foreground">
+ <span className={cn('font-mono tabular-nums', DIFF_DEL_TEXT)}>
-{deletions}
</span>
</Button>
diff --git a/web-app/src/containers/CoworkDiffPanel.tsx b/web-app/src/containers/CoworkDiffPanel.tsx
index 8994b19a6..aaaa65f88 100644
--- a/web-app/src/containers/CoworkDiffPanel.tsx
+++ b/web-app/src/containers/CoworkDiffPanel.tsx
@@ -4,7 +4,11 @@ import { cn } from '@/lib/utils'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { DiffView } from '@/components/DiffView'
import { CoworkSidePanel } from '@/containers/CoworkSidePanel'
-import type { CoworkFileDiff } from '@/lib/coworkDiffs'
+import {
+ DIFF_ADD_TEXT,
+ DIFF_DEL_TEXT,
+ type CoworkFileDiff,
+} from '@/lib/coworkDiffs'
/**
* Every write and edit this session landed, grouped by file.
@@ -41,8 +45,9 @@ export function CoworkDiffPanel({
<CoworkSidePanel
title={t('common:changes.title')}
summary={
- <span className="shrink-0 text-xs font-mono text-main-view-fg/60">
- +{additions} -{deletions}
+ <span className="shrink-0 space-x-1 text-xs font-mono tabular-nums">
+ <span className={DIFF_ADD_TEXT}>+{additions}</span>
+ <span className={DIFF_DEL_TEXT}>-{deletions}</span>
</span>
}
onClose={onClose}
@@ -74,10 +79,20 @@ export function CoworkDiffPanel({
<span className="min-w-0 flex-1 truncate text-xs font-medium">
{file.path}
</span>
- <span className="shrink-0 font-mono text-xs text-green-600">
+ <span
+ className={cn(
+ 'shrink-0 font-mono text-xs tabular-nums',
+ DIFF_ADD_TEXT
+ )}
+ >
+{file.additions}
</span>
- <span className="shrink-0 font-mono text-xs text-red-600">
+ <span
+ className={cn(
+ 'shrink-0 font-mono text-xs tabular-nums',
+ DIFF_DEL_TEXT
+ )}
+ >
-{file.deletions}
</span>
</button>
diff --git a/web-app/src/containers/CoworkEmptyState.tsx b/web-app/src/containers/CoworkEmptyState.tsx
index f4e4f0737..17e92645e 100644
--- a/web-app/src/containers/CoworkEmptyState.tsx
+++ b/web-app/src/containers/CoworkEmptyState.tsx
@@ -30,8 +30,13 @@ export function CoworkEmptyState({ folder, onPick }: Props) {
const scope = name ? 'folder' : 'sandbox'
return (
- <div className="absolute inset-0 flex flex-col justify-end px-3 pb-2">
- <div className="mx-auto w-full md:w-4/5 xl:w-4/6">
+ // No horizontal padding here: the column must match the composer's
+ // (mx-auto w-4/5) exactly so the invitation shares its left edge instead of
+ // a coincidentally-close one. The px-2 below mirrors the input's own text
+ // inset, and the examples pull back by the same amount so their labels line
+ // up under the heading while the hover target keeps its breathing room.
+ <div className="absolute inset-0 flex flex-col justify-end pb-3">
+ <div className="mx-auto w-full px-2 md:w-4/5 xl:w-4/6">
<div className="animate-in fade-in-0 duration-500 motion-reduce:animate-none">
<Handshake size={20} className="text-primary" aria-hidden />
<h1 className="mt-3 font-studio text-2xl font-medium tracking-tight">
@@ -46,7 +51,7 @@ export function CoworkEmptyState({ folder, onPick }: Props) {
<p className="mt-6 text-xs font-medium uppercase tracking-wider text-muted-foreground/60">
{t('common:coworkEmpty.try')}
</p>
- <div className="mt-1 flex flex-col items-start">
+ <div className="mt-1 -mx-2 flex flex-col items-start">
{EXAMPLE_KEYS.map((key) => {
const text = t(`common:coworkEmpty.${scope}.${key}`, {
folder: name,
diff --git a/web-app/src/containers/CoworkModelChip.tsx b/web-app/src/containers/CoworkModelChip.tsx
new file mode 100644
index 000000000..52287da85
--- /dev/null
+++ b/web-app/src/containers/CoworkModelChip.tsx
@@ -0,0 +1,55 @@
+import { SlidersHorizontal } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/ui/tooltip'
+import { cn } from '@/lib/utils'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { coworkModelContext, formatContextSize } from '@/lib/coworkModelControls'
+
+/**
+ * Opens the model rail, and only when there is something to configure -- a
+ * local llamacpp/mlx model with settings. Remote providers have no local knobs,
+ * so the chip stays hidden there like the diff/tasks chips do when empty.
+ */
+export function CoworkModelChip({
+ model,
+ provider,
+ open,
+ onToggle,
+}: {
+ model: Model | undefined
+ provider: ProviderObject | undefined
+ open: boolean
+ onToggle: () => void
+}) {
+ const { t } = useTranslation()
+ if (!model || !provider || !model.settings) return null
+
+ const context = coworkModelContext(provider, model.id)
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="xs"
+ aria-pressed={open}
+ aria-label={t('common:modelPanel.a11y')}
+ onClick={onToggle}
+ className={cn('shrink-0', open && 'text-primary')}
+ >
+ <SlidersHorizontal className="size-3.5 shrink-0" />
+ {context && (
+ <span className="font-mono tabular-nums text-main-view-fg/60">
+ {formatContextSize(context.value)}
+ </span>
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t('common:modelPanel.title')}</TooltipContent>
+ </Tooltip>
+ )
+}
diff --git a/web-app/src/containers/CoworkModelPanel.tsx b/web-app/src/containers/CoworkModelPanel.tsx
new file mode 100644
index 000000000..671f694fe
--- /dev/null
+++ b/web-app/src/containers/CoworkModelPanel.tsx
@@ -0,0 +1,53 @@
+import { CoworkSidePanel } from '@/containers/CoworkSidePanel'
+import { ModelSettingFields } from '@/containers/ModelSetting'
+import ProvidersAvatar from '@/containers/ProvidersAvatar'
+import { coworkModelContext, formatContextSize } from '@/lib/coworkModelControls'
+import { getModelDisplayName } from '@/lib/utils'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+
+/**
+ * Model settings docked as a Cowork rail, so the llamacpp/mlx knobs sit beside
+ * the transcript like the diff/files/todo panels instead of the header Sheet.
+ * The form body itself is shared with ModelSetting (ModelSettingFields).
+ */
+export function CoworkModelPanel({
+ model,
+ provider,
+ onClose,
+}: {
+ model: Model
+ provider: ProviderObject
+ onClose: () => void
+}): React.ReactElement {
+ const { t } = useTranslation()
+ const context = coworkModelContext(provider, model.id)
+
+ return (
+ <CoworkSidePanel
+ title={getModelDisplayName(model)}
+ leading={
+ <div className="shrink-0">
+ <ProvidersAvatar provider={provider} />
+ </div>
+ }
+ summary={
+ context ? (
+ <span
+ className="shrink-0 font-mono text-xs tabular-nums text-main-view-fg/60"
+ title={t('common:modelPanel.contextTooltip', {
+ value: context.value.toLocaleString(),
+ max: context.max.toLocaleString(),
+ })}
+ >
+ {formatContextSize(context.value)}
+ </span>
+ ) : null
+ }
+ onClose={onClose}
+ >
+ <div className="flex h-full flex-col">
+ <ModelSettingFields model={model} provider={provider} />
+ </div>
+ </CoworkSidePanel>
+ )
+}
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index a341c853f..287fe6e7f 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -566,7 +566,7 @@ export const MessageItem = memo(
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"
+ className="mt-3 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>
@@ -579,13 +579,13 @@ export const MessageItem = memo(
message.role === 'assistant' &&
!awaitingApproval &&
(hasPendingToolCall || status === CHAT_STATUS.SUBMITTED) && (
- <div className="mt-2">
+ <div className="mt-3">
<PromptProgress hideIdle={hasPendingToolCall} />
</div>
)}
{typeof messageError === 'string' && messageError.length > 0 && (
- <div className="mt-2 flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm">
+ <div className="mt-3 flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm">
<IconAlertTriangle
size={16}
className="mt-0.5 shrink-0 text-destructive"
@@ -615,49 +615,53 @@ export const MessageItem = memo(
</div>
)}
- {/* Message actions for user messages */}
+ {/* Message actions for user messages. Same shape as the assistant row
+ below -- a timestamp, gap-2, then a gap-1 icon cluster -- so the two
+ meta rows line up across roles. */}
{message.role === 'user' && !hideActions && (
- <div className="flex items-center justify-end gap-1 text-muted-foreground text-xs opacity-0 transition-opacity group-hover/message:opacity-100 focus-within:opacity-100">
+ <div className="mt-3 flex items-center justify-end gap-2 text-muted-foreground text-xs opacity-0 transition-opacity group-hover/message:opacity-100 focus-within:opacity-100">
<span className="text-muted-foreground">
{formatDate(createdAt)}
</span>
- {versionNav}
- <CopyButton text={getFullTextContent()} />
+ <div className="flex items-center gap-1">
+ {versionNav}
+ <CopyButton text={getFullTextContent()} />
- {onEdit &&
- status !== CHAT_STATUS.STREAMING &&
- status !== CHAT_STATUS.SUBMITTED && (
- <EditMessageDialog
- message={getFullTextContent()}
- imageUrls={imageUrls.length > 0 ? imageUrls : undefined}
- onSave={handleEdit}
- />
- )}
+ {onEdit &&
+ status !== CHAT_STATUS.STREAMING &&
+ status !== CHAT_STATUS.SUBMITTED && (
+ <EditMessageDialog
+ message={getFullTextContent()}
+ imageUrls={imageUrls.length > 0 ? imageUrls : undefined}
+ onSave={handleEdit}
+ />
+ )}
- {onRetry &&
- status !== CHAT_STATUS.STREAMING &&
- status !== CHAT_STATUS.SUBMITTED && (
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={() => onRetry(message.id, getFullTextContent())}
- title={t('chat:actions.askAgain')}
- >
- <IconRefresh size={16} className="text-muted-foreground" />
- </Button>
- )}
+ {onRetry &&
+ status !== CHAT_STATUS.STREAMING &&
+ status !== CHAT_STATUS.SUBMITTED && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => onRetry(message.id, getFullTextContent())}
+ title={t('chat:actions.askAgain')}
+ >
+ <IconRefresh size={16} className="text-muted-foreground" />
+ </Button>
+ )}
- {onDelete &&
- status !== CHAT_STATUS.STREAMING &&
- status !== CHAT_STATUS.SUBMITTED && (
- <DeleteMessageDialog onDelete={handleDelete} />
- )}
+ {onDelete &&
+ status !== CHAT_STATUS.STREAMING &&
+ status !== CHAT_STATUS.SUBMITTED && (
+ <DeleteMessageDialog onDelete={handleDelete} />
+ )}
+ </div>
</div>
)}
{/* Message actions for assistant messages (non-tool) */}
{message.role === 'assistant' && !hideActions && (
- <div className="flex items-center gap-2 text-muted-foreground text-xs">
+ <div className="mt-3 flex items-center gap-2 text-muted-foreground text-xs">
{!isStreaming && (
<span className="text-muted-foreground">
{formatDate(createdAt)}
diff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsx
index f036dbad1..82de0a756 100644
--- a/web-app/src/containers/ModelSetting.tsx
+++ b/web-app/src/containers/ModelSetting.tsx
@@ -28,12 +28,14 @@ type ModelSettingProps = {
model: Model
}
-export function ModelSetting({
- model,
- provider,
-}: ModelSettingProps) {
+/**
+ * Shared model-settings form + persistence, driven by both the header Sheet
+ * (ModelSetting) and the Cowork right rail (CoworkModelPanel). Keeping the
+ * handlers here avoids two copies of the debounced yaml-write / router-restart
+ * logic diverging.
+ */
+function useModelSettingControls(model: Model, provider: ProviderObject) {
const { updateProvider } = useModelProvider()
- const { t } = useTranslation()
const serviceHub = useServiceHub()
const setActiveModels = useAppState((state) => state.setActiveModels)
@@ -249,26 +251,28 @@ export function ModelSetting({
true
const fitCtxSetting = provider.settings?.find((s) => s.key === 'fit_ctx')
- return (
- <Sheet>
- <SheetTrigger asChild>
- <Button variant="ghost" size="icon-xs">
- <IconSettings size={18} className="text-muted-foreground" />
- </Button>
- </SheetTrigger>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>
- {t('common:modelSettings.title', {
- modelId: getModelDisplayName(model),
- })}
- </SheetTitle>
- <SheetDescription className='text-xs leading-normal'>
- {t('common:modelSettings.description')}
- </SheetDescription>
- </SheetHeader>
+ return {
+ handleSettingChange,
+ handleTemplateKwargsChange,
+ handleEngineSettingChange,
+ fitEnabled,
+ fitCtxSetting,
+ }
+}
- <div className="px-4 space-y-8 pb-4 flex-1 min-h-0 overflow-y-auto">
+/** The settings body, shared by the header Sheet and the Cowork rail. */
+export function ModelSettingFields({ model, provider }: ModelSettingProps) {
+ const { t } = useTranslation()
+ const {
+ handleSettingChange,
+ handleTemplateKwargsChange,
+ handleEngineSettingChange,
+ fitEnabled,
+ fitCtxSetting,
+ } = useModelSettingControls(model, provider)
+
+ return (
+ <div className="px-4 space-y-8 pb-4 flex-1 min-h-0 overflow-y-auto">
{provider.provider === 'llamacpp' && (
<SpecDraftPanel modelId={model.id} />
)}
@@ -372,7 +376,31 @@ export function ModelSetting({
)
})
})()}
- </div>
+ </div>
+ )
+}
+
+export function ModelSetting({ model, provider }: ModelSettingProps) {
+ const { t } = useTranslation()
+ return (
+ <Sheet>
+ <SheetTrigger asChild>
+ <Button variant="ghost" size="icon-xs">
+ <IconSettings size={18} className="text-muted-foreground" />
+ </Button>
+ </SheetTrigger>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>
+ {t('common:modelSettings.title', {
+ modelId: getModelDisplayName(model),
+ })}
+ </SheetTitle>
+ <SheetDescription className="text-xs leading-normal">
+ {t('common:modelSettings.description')}
+ </SheetDescription>
+ </SheetHeader>
+ <ModelSettingFields model={model} provider={provider} />
</SheetContent>
</Sheet>
)
diff --git a/web-app/src/containers/__tests__/CoworkDiffPanel.test.tsx b/web-app/src/containers/__tests__/CoworkDiffPanel.test.tsx
index a71beeffd..55c990e1d 100644
--- a/web-app/src/containers/__tests__/CoworkDiffPanel.test.tsx
+++ b/web-app/src/containers/__tests__/CoworkDiffPanel.test.tsx
@@ -33,7 +33,9 @@ const files: CoworkFileDiff[] = [
describe('CoworkDiffPanel', () => {
it('summarises the totals across files', () => {
render(<CoworkDiffPanel files={files} onClose={vi.fn()} />)
- expect(screen.getByText('+6 -2')).toBeInTheDocument()
+ // Additions and deletions are separate spans so each carries its own color.
+ expect(screen.getAllByText('+6').length).toBeGreaterThan(0)
+ expect(screen.getAllByText('-2').length).toBeGreaterThan(0)
})
// Collapsed by default: a run touching a dozen files should open as a list,
diff --git a/web-app/src/containers/message/ChainOfThoughtGroup.tsx b/web-app/src/containers/message/ChainOfThoughtGroup.tsx
index 3d24f3fb8..ecb664e11 100644
--- a/web-app/src/containers/message/ChainOfThoughtGroup.tsx
+++ b/web-app/src/containers/message/ChainOfThoughtGroup.tsx
@@ -1,4 +1,4 @@
-import { cloneElement, memo, useState } from 'react'
+import { cloneElement, memo, useCallback, useState } from 'react'
import { twMerge } from 'tailwind-merge'
import { IconArrowDown, IconCircleCheck } from '@tabler/icons-react'
import {
@@ -17,6 +17,7 @@ import {
useToolCallRuntime,
} from '@/hooks/useToolCallRuntime'
import { useTranslation } from '@/i18n/react-i18next-compat'
+import { useCoTDuration } from '@/hooks/useCoTDuration'
import { segmentReasoningSteps } from '@/lib/reasoning'
import { ToolCallCard } from './ToolCallCard'
import { CONTENT_TYPE, isToolPart, type PartEntry } from './types'
@@ -56,6 +57,13 @@ export const ChainOfThoughtGroup = memo(
const { t } = useTranslation()
const pendingApprovals = useToolApprovalRequests((s) => s.pending)
const runningToolCallId = useToolCallRuntime((s) => findRunningToolCallId(s.timings))
+ // Seed the header from a persisted duration on reload; persist the live
+ // measurement so it survives the next one. Keyed by the (stable) message id.
+ const storedDuration = useCoTDuration((s) => s.durations[messageId])
+ const recordDuration = useCallback(
+ (ms: number) => useCoTDuration.getState().record(messageId, ms),
+ [messageId]
+ )
const [view, setView] = useState<'condensed' | 'extended'>('condensed')
if (entries.length === 0) return null
@@ -78,21 +86,30 @@ export const ChainOfThoughtGroup = memo(
return isToolPart(part)
}
const meaningful = entries.filter(isMeaningfulEntry)
- // Tools execute one at a time, so with several calls in a turn the last
- // part is the one at the back of the queue. Follow the call actually doing
- // the work; before execution starts nothing is running and the newest part
- // is still the right thing to show as it streams in.
const running = runningToolCallId
? meaningful.find((e) => e.part.toolCallId === runningToolCallId)
: undefined
const lastMeaningful = running ?? meaningful[meaningful.length - 1]
- // While streaming, show only the current step — but never truncate away a
- // tool part that is awaiting the user's approval, or its approve/deny
- // controls would never mount and the run would hang (multi-tool turns).
+ // The current step while streaming. A model emits parallel tool calls as one
+ // batch of tool parts (all non-terminal at once); execution is serial, but
+ // the whole batch is the step, so showing only the running call hides the
+ // rest of it. Take the trailing run of tool parts as the batch; if the
+ // frontier is reasoning, that single step stands.
+ const frontier = (() => {
+ const batch: PartEntry[] = []
+ for (let i = meaningful.length - 1; i >= 0; i--) {
+ if (isToolPart(meaningful[i].part)) batch.unshift(meaningful[i])
+ else break
+ }
+ return batch.length > 0 ? batch : meaningful.slice(-1)
+ })()
+ // While streaming, show the current step — but never truncate away a tool
+ // part awaiting the user's approval, or its approve/deny controls would
+ // never mount and the run would hang.
const visibleEntries =
groupIsStreaming && meaningful.length > 0
? meaningful.filter((e) => {
- if (e === lastMeaningful) return true
+ if (frontier.includes(e)) return true
const toolCallId = e.part.toolCallId
return Boolean(toolCallId && pendingApprovals[toolCallId])
})
@@ -251,11 +268,13 @@ export const ChainOfThoughtGroup = memo(
return (
<ChainOfThought
- className="w-full text-muted-foreground"
+ className="text-muted-foreground"
isStreaming={groupIsStreaming}
shouldCollapse={shouldCollapse}
forceOpen={awaitingApproval}
defaultOpen={hasDisplayableContent && !hasFollowingContent}
+ durationMs={storedDuration}
+ onDurationSettled={recordDuration}
>
<ChainOfThoughtHeader
// The tool card rendered right below names the call, its origin and
diff --git a/web-app/src/containers/message/__tests__/ChainOfThoughtGroup.test.tsx b/web-app/src/containers/message/__tests__/ChainOfThoughtGroup.test.tsx
index b8ad54922..7cf23defd 100644
--- a/web-app/src/containers/message/__tests__/ChainOfThoughtGroup.test.tsx
+++ b/web-app/src/containers/message/__tests__/ChainOfThoughtGroup.test.tsx
@@ -142,10 +142,10 @@ describe('ChainOfThoughtGroup view switching', () => {
expect(screen.getByTestId('tool-header')).toBeInTheDocument()
})
- // Calls execute one at a time, so with several in a turn the last part is the
- // one at the back of the queue. Showing it would report "queued" while the
- // call actually doing the work is hidden.
- it('shows the running call, not the last one queued', () => {
+ // A model emits parallel tool calls as one batch; execution is serial, but the
+ // whole batch is the current step, so every call in it shows -- not just the
+ // one the executor happens to be running.
+ it('shows every call in a parallel batch while streaming', () => {
const parts = [
{ type: 'tool-alpha', state: 'input-available', toolCallId: 'a' },
{ type: 'tool-beta', state: 'input-available', toolCallId: 'b' },
@@ -156,13 +156,17 @@ describe('ChainOfThoughtGroup view switching', () => {
entries: parts.map((part, index) => ({ part, index })),
totalParts: parts.length,
})
- expect(screen.getByTestId('tool-header')).toHaveTextContent('alpha')
+ const headers = screen
+ .getAllByTestId('tool-header')
+ .map((h) => h.textContent)
+ expect(headers).toEqual(expect.arrayContaining(['alpha', 'beta']))
})
- // Before execution starts nothing is running, so the newest part is still
- // the right thing to show as it streams in.
- it('shows the newest call while the arguments are still streaming', () => {
+ // The batch is the trailing run of tool parts; reasoning ahead of it is not
+ // part of the current step, so it stays truncated in the condensed view.
+ it('shows the whole tool batch but not the reasoning before it', () => {
const parts = [
+ { type: 'reasoning', text: LONG_TEXT },
{ type: 'tool-alpha', state: 'input-available', toolCallId: 'a' },
{ type: 'tool-beta', state: 'input-streaming', toolCallId: 'b' },
]
@@ -170,7 +174,10 @@ describe('ChainOfThoughtGroup view switching', () => {
entries: parts.map((part, index) => ({ part, index })),
totalParts: parts.length,
})
- expect(screen.getByTestId('tool-header')).toHaveTextContent('beta')
+ const headers = screen
+ .getAllByTestId('tool-header')
+ .map((h) => h.textContent)
+ expect(headers).toEqual(expect.arrayContaining(['alpha', 'beta']))
})
it('renders the completed rail with a Done marker and no view switch', () => {
diff --git a/web-app/src/hooks/useCoTDuration.ts b/web-app/src/hooks/useCoTDuration.ts
new file mode 100644
index 000000000..66abc3ca4
--- /dev/null
+++ b/web-app/src/hooks/useCoTDuration.ts
@@ -0,0 +1,48 @@
+import { create } from 'zustand'
+import { persist, createJSONStorage } from 'zustand/middleware'
+import { backendStorage } from '@/lib/backendStorage'
+import { localStorageKey } from '@/constants/localStorage'
+
+/**
+ * Preserves the "thought/worked for Ns" duration of a folded chain-of-thought
+ * across reloads. `ChainOfThought` measures the trace live in component state,
+ * which a reload throws away; keyed by the (stable) message id, that measurement
+ * is stored here and seeded back on restore. Shared by both chat surfaces since
+ * message ids are stable in each.
+ */
+const MAX_ENTRIES = 500
+
+type CoTDurationState = {
+ /** Message id -> accumulated trace duration in ms. */
+ durations: Record<string, number>
+ record: (messageId: string, ms: number) => void
+}
+
+export const useCoTDuration = create<CoTDurationState>()(
+ persist(
+ (set) => ({
+ durations: {},
+ record: (messageId, ms) =>
+ set((state) => {
+ if (state.durations[messageId] === ms) return state
+ const next = { ...state.durations, [messageId]: ms }
+ const keys = Object.keys(next)
+ // Bounded so an old session's ids cannot grow the blob without limit;
+ // a dropped entry just falls back to the live/"a while" label.
+ if (keys.length > MAX_ENTRIES) {
+ for (const key of keys.slice(0, keys.length - MAX_ENTRIES)) {
+ delete next[key]
+ }
+ }
+ return { durations: next }
+ }),
+ }),
+ {
+ name: localStorageKey.cotDuration,
+ storage: createJSONStorage(() => backendStorage),
+ // Async storage: rehydrated in hydrateBackendStores() once the ServiceHub
+ // is ready, like the other backend-backed stores.
+ skipHydration: true,
+ }
+ )
+)
diff --git a/web-app/src/lib/coworkDiffs.ts b/web-app/src/lib/coworkDiffs.ts
index 24da55afb..d6627bd99 100644
--- a/web-app/src/lib/coworkDiffs.ts
+++ b/web-app/src/lib/coworkDiffs.ts
@@ -1,5 +1,12 @@
import type { CoworkTurn, SubagentRun } from '@/types/coworkSession'
+/**
+ * One dark-mode-aware treatment for additions/deletions, shared by the changes
+ * chip and the diff panel so the same +/- figure never reads three ways.
+ */
+export const DIFF_ADD_TEXT = 'text-emerald-600 dark:text-emerald-400'
+export const DIFF_DEL_TEXT = 'text-red-600 dark:text-red-500'
+
export type CoworkDiffOperation = {
diff: string
source: 'main' | 'subagent'
diff --git a/web-app/src/lib/coworkModelControls.ts b/web-app/src/lib/coworkModelControls.ts
index 3584c25b1..06a1ca6e4 100644
--- a/web-app/src/lib/coworkModelControls.ts
+++ b/web-app/src/lib/coworkModelControls.ts
@@ -34,6 +34,13 @@ export function coworkModelContext(
return { value, max, next: nextCoworkContextSize(value, max) }
}
+/** Compact context readout for chips/rail headers: 8192 -> "8K". */
+export function formatContextSize(value: number): string {
+ if (!Number.isFinite(value) || value <= 0) return '-'
+ if (value < 1024) return String(value)
+ return `${Math.round(value / 1024)}K`
+}
+
export function nextCoworkContextSize(
current: number,
max: number
diff --git a/web-app/src/lib/hydrateStores.ts b/web-app/src/lib/hydrateStores.ts
index 38a10c50f..3df02cb15 100644
--- a/web-app/src/lib/hydrateStores.ts
+++ b/web-app/src/lib/hydrateStores.ts
@@ -22,6 +22,7 @@ import { useAgentMode } from '@/hooks/useAgentMode'
import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
import { useCoworkSessions } from '@/hooks/useCoworkSessions'
import { useCoworkConfig } from '@/hooks/useCoworkConfig'
+import { useCoTDuration } from '@/hooks/useCoTDuration'
/**
* Stores persisted through `backendStorage` set `skipHydration: true` so they
@@ -55,6 +56,7 @@ const secondaryStores = [
useWebSearchConfig,
useCoworkSessions,
useCoworkConfig,
+ useCoTDuration,
] as const
export async function hydrateBackendStores(): Promise<void> {
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 64994b3d3..d8d020d15 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -160,6 +160,19 @@
"empty": "Files the agent writes or edits will show up here.",
"a11y": "Agent changes: {{files}} files, {{additions}} added, {{deletions}} removed"
},
+ "modelPanel": {
+ "title": "Model settings",
+ "a11y": "Open model settings",
+ "contextTooltip": "Context window: {{value}} of {{max}} tokens"
+ },
+ "coworkSlash": {
+ "skillUnavailable": "Skill '{{name}}' is not available",
+ "kind": {
+ "skill": "Skill",
+ "command": "Command",
+ "model": "Model"
+ }
+ },
"compactWidth": "Compact Width",
"fullWidth": "Full Width",
"dark": "Dark",
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index 7b502e3cd..a7f2eef85 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -80,6 +80,8 @@ import { CoworkFilesChip } from '@/containers/CoworkFilesChip'
import { CoworkFilesPanel } from '@/containers/CoworkFilesPanel'
import { CoworkTodoChip } from '@/containers/CoworkTodoChip'
import { CoworkTasksChip } from '@/containers/CoworkTasksChip'
+import { CoworkModelChip } from '@/containers/CoworkModelChip'
+import { CoworkModelPanel } from '@/containers/CoworkModelPanel'
import { collectCodeFileDiffs } from '@/lib/coworkDiffs'
import { CoworkSandboxChip } from '@/containers/CoworkSandboxChip'
import { CoworkBudgetNotice } from '@/containers/CoworkBudgetNotice'
@@ -263,6 +265,12 @@ function CoworkPage() {
: undefined
const overflowModel = coworkLocalModel(overflowProvider, selectedModel?.id)
const overflowContext = coworkModelContext(overflowProvider, selectedModel?.id)
+ // The selected provider's own model entry (with settings) drives the model
+ // rail; undefined for remote/inactive providers, which hides its chip.
+ const modelProvider = providers.find(
+ (provider) => provider.provider === selectedProvider
+ )
+ const localModel = coworkLocalModel(modelProvider, selectedModel?.id)
const [gitBranch, setGitBranch] = useState<string | null>(null)
const [subagentDefs, setSubagentDefs] = useState<SubagentDefinition[]>([])
const [workspacePath, setWorkspacePath] = useState<string | null>(null)
@@ -277,6 +285,7 @@ function CoworkPage() {
| { kind: 'files' }
| { kind: 'todos' }
| { kind: 'tasks' }
+ | { kind: 'model' }
| null
>(null)
const showPreview = useCallback(
@@ -988,7 +997,9 @@ function CoworkPage() {
? resolveSkillCommand(skillCommands, skillCommand)
: null
if (skillCommand?.explicit && !skill) {
- toast.error(`Skill '${skillCommand.name}' is not available`)
+ toast.error(
+ t('common:coworkSlash.skillUnavailable', { name: skillCommand.name })
+ )
return
}
@@ -1513,7 +1524,7 @@ function CoworkPage() {
<span className="flex items-center gap-2">
<span className="font-mono font-medium">{item.label}</span>
<span className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
- {item.kind}
+ {t(`common:coworkSlash.kind.${item.kind}`)}
</span>
</span>
<span className="block truncate text-xs text-muted-foreground">
@@ -1589,6 +1600,16 @@ function CoworkPage() {
)
}
/>
+ <CoworkModelChip
+ model={localModel}
+ provider={modelProvider}
+ open={rail?.kind === 'model'}
+ onToggle={() =>
+ setRail((r) =>
+ r?.kind === 'model' ? null : { kind: 'model' }
+ )
+ }
+ />
<div className="ml-auto flex items-center">
<SkillSelector folder={folder} />
</div>
@@ -1631,6 +1652,13 @@ function CoworkPage() {
onClose={() => setRail(null)}
/>
)}
+ {rail?.kind === 'model' && localModel && modelProvider && (
+ <CoworkModelPanel
+ model={localModel}
+ provider={modelProvider}
+ onClose={() => setRail(null)}
+ />
+ )}
</div>
</div>
)