Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cowork): session-list hygiene, task/todo panels, slash commands, compact, queue
Akarshan Biswas9ea3da0b7a7b
diff --git a/web-app/src/components/left-sidebar/NavCowork.tsx b/web-app/src/components/left-sidebar/NavCowork.tsxindex b3fe1cea3..db8489fc4 100644--- a/web-app/src/components/left-sidebar/NavCowork.tsx+++ b/web-app/src/components/left-sidebar/NavCowork.tsx@@ -38,8 +38,8 @@ import {type MessageCircleIconHandle,} from '@/components/animated-icon/message-circle'import { useCoworkSessions, type CoworkSession } from '@/hooks/useCoworkSessions'-import { useIsSessionActive } from '@/hooks/useCoworkRun'-import { memo, useCallback, useRef, useState } from 'react'+import { useCoworkRun, useIsSessionActive } from '@/hooks/useCoworkRun'+import { memo, useCallback, useMemo, useRef, useState } from 'react'import SkillsManagerDialog from '@/containers/dialogs/SkillsManagerDialog'type CoworkNavItem = {@@ -48,11 +48,19 @@ type CoworkNavItem = {onClick: () => void}+// Leaving a session behind is the moment an abandoned empty one becomes+// unreachable (it has no sidebar row) — sweep those out of the store, keeping+// any session whose first run is still streaming its turns in useCoworkRun.+const pruneEmpty = () => {+ const running = Object.keys(useCoworkRun.getState().runId)+ useCoworkSessions.getState().pruneEmptySessions(running)+}+// 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.+// running state comes from its own per-session selector (useIsSessionActive),+// 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,@@ -116,6 +124,15 @@ export function NavCowork() {const { isMobile } = useSidebar()const sessions = useCoworkSessions((s) => s.sessions)const currentId = useCoworkSessions((s) => s.currentId)+ // A session only earns a sidebar row once it has messages. A first run's+ // turns are transient in useCoworkRun until committed, so a streaming+ // session stays listed via its active run — otherwise switching away+ // mid-first-run would make it unreachable.+ const runIds = useCoworkRun((s) => s.runId)+ const visibleSessions = useMemo(+ () => sessions.filter((s) => s.turns.length > 0 || runIds[s.id] != null),+ [sessions, runIds]+ )const [skillsOpen, setSkillsOpen] = useState(false)// Session pending deletion; drives the confirm dialog (null = closed).const [pendingDelete, setPendingDelete] = useState<{@@ -127,11 +144,13 @@ export function NavCowork() {const newSessionIconRef = useRef<MessageCircleIconHandle>(null)const newSession = () => {useCoworkSessions.getState().createSession()+ pruneEmpty()goCowork()}const selectSession = useCallback((id: string) => {useCoworkSessions.getState().selectSession(id)+ pruneEmpty()goCowork()},[goCowork]@@ -185,11 +204,11 @@ export function NavCowork() {})}</SidebarMenu>- {sessions.length > 0 && (+ {visibleSessions.length > 0 && (<SidebarGroup className="group-data-[collapsible=icon]:hidden"><SidebarGroupLabel>{t('common:sessions')}</SidebarGroupLabel><SidebarMenu>- {sessions.map((session) => (+ {visibleSessions.map((session) => (<SessionItemkey={session.id}session={session}diff --git a/web-app/src/containers/CoworkTasksChip.tsx b/web-app/src/containers/CoworkTasksChip.tsxnew file mode 100644index 000000000..a4d841405--- /dev/null+++ b/web-app/src/containers/CoworkTasksChip.tsx@@ -0,0 +1,54 @@+import { Loader2, Sparkles } from 'lucide-react'+import { Button } from '@/components/ui/button'+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/components/ui/tooltip'+import { cn } from '@/lib/utils'+import { useTranslation } from '@/i18n/react-i18next-compat'+import type { SubagentRun } from '@/types/coworkSession'++/**+ * Opens the background-tasks rail, and stays out of the way until the agent+ * has dispatched a subagent — the same rule the changes chip follows.+ */+export function CoworkTasksChip({+ subagents,+ open,+ onToggle,+}: {+ subagents: SubagentRun[]+ open: boolean+ onToggle: () => void+}) {+ const { t } = useTranslation()+ if (subagents.length === 0) return null++ const active = subagents.filter((s) => s.status !== 'done').length++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ aria-pressed={open}+ aria-label={t('common:backgroundTasks')}+ onClick={onToggle}+ className={cn('shrink-0', open && 'text-primary')}+ >+ {active > 0 ? (+ <Loader2 className="size-3.5 shrink-0 animate-spin" />+ ) : (+ <Sparkles className="size-3.5 shrink-0" />+ )}+ <span className="font-mono tabular-nums text-muted-foreground">+ {active > 0 ? `${active}/${subagents.length}` : subagents.length}+ </span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>{t('common:backgroundTasks')}</TooltipContent>+ </Tooltip>+ )+}diff --git a/web-app/src/containers/CoworkTasksPanel.tsx b/web-app/src/containers/CoworkTasksPanel.tsxnew file mode 100644index 000000000..2f83301e8--- /dev/null+++ b/web-app/src/containers/CoworkTasksPanel.tsx@@ -0,0 +1,254 @@+/* eslint-disable @typescript-eslint/no-explicit-any */+import { useEffect, useMemo, useState } from 'react'+import { ChevronLeft, ChevronDown, Loader2, Sparkles } from 'lucide-react'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { cn, formatDuration, formatTokenCount } from '@/lib/utils'+import type { CoworkTurn, SubagentRun } from '@/types/coworkSession'+import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'+import { MessageItem } from '@/containers/MessageItem'+import { useAutoScroll } from '@/hooks/useAutoScroll'+import {+ Conversation,+ ConversationContent,+} from '@/components/ai-elements/conversation'+import { CoworkSidePanel } from '@/containers/CoworkSidePanel'++/** One row in the running/queued/finished lists. */+function TaskRow({ run, onSelect }: { run: SubagentRun; onSelect: () => void }) {+ const { t } = useTranslation()+ const running = run.status === 'running'+ // Only rendered for finished rows below — skip the scan while running (it+ // would just be recomputed and discarded on every tick/stream re-render).+ const toolUses = running+ ? 0+ : run.turns.filter((tn) => tn.role === 'tool').length+ return (+ <button+ type="button"+ onClick={onSelect}+ className="flex w-full cursor-pointer flex-col gap-1 rounded-lg border bg-main-view-fg/2 px-3 py-2.5 text-left hover:bg-main-view-fg/5"+ >+ <div className="flex items-center gap-2">+ {running ? (+ <Loader2 size={14} className="shrink-0 animate-spin text-accent" />+ ) : (+ <Sparkles size={14} className="shrink-0 text-main-view-fg/50" />+ )}+ <span className="truncate text-sm font-medium">{run.name}</span>+ </div>+ <span className="pl-6 font-mono text-xs tabular-nums text-main-view-fg/50">+ {formatDuration(run.startedAt, run.endedAt)}+ </span>+ {!running && run.status === 'done' && (+ <span className="pl-6 font-mono text-xs tabular-nums text-main-view-fg/50">+ {run.usage?.total_tokens+ ? `${formatTokenCount(run.usage.total_tokens)} · `+ : ''}+ {t('common:subagentToolUses', { count: toolUses })}+ {' · '}+ <span className="text-accent">{t('common:viewTranscript')}</span>+ </span>+ )}+ </button>+ )+}++/** The run's trace plus its final answer, unless that answer already streamed+ * as the last assistant turn — appending it again would show it twice. */+function visibleSubagentTurns(run: SubagentRun): CoworkTurn[] {+ const last = run.turns.at(-1)+ const finalAlreadyStreamed =+ run.finalOutput != null &&+ last?.role === 'assistant' &&+ last.content === run.finalOutput+ return run.finalOutput != null && !finalAlreadyStreamed+ ? [...run.turns, { role: 'assistant' as const, content: run.finalOutput }]+ : run.turns+}++/** The selected subagent's trace (live progress while running, full output when done). */+function TaskDetail({ run }: { run: SubagentRun }) {+ const { t } = useTranslation()+ const { containerRef, isAtBottom, handleScroll, forceScrollToBottom } =+ useAutoScroll()+ const messages = useMemo(+ () => coworkTurnsToUIMessages(visibleSubagentTurns(run), `sub-${run.runId}`),+ [run]+ )+ if (messages.length === 0) {+ return (+ <div className="flex h-full items-center justify-center px-4 text-center text-sm text-main-view-fg/50">+ {run.status === 'running'+ ? t('common:taskWorking')+ : t('common:taskNoOutput')}+ </div>+ )+ }+ return (+ <Conversation className="h-full text-start">+ <ConversationContent className="px-3">+ {messages.map((message, i) => (+ <MessageItem+ key={message.id}+ message={message as any}+ isFirstMessage={i === 0}+ isLastMessage={i === messages.length - 1}+ status={run.status === 'running' ? 'streaming' : 'ready'}+ reasoningContainerRef={containerRef}+ isReasoningAtBottom={isAtBottom}+ onReasoningScroll={handleScroll}+ onReasoningScrollToBottom={forceScrollToBottom}+ />+ ))}+ </ConversationContent>+ </Conversation>+ )+}++function Section({+ label,+ count,+ collapsible = false,+ children,+}: {+ label: string+ count: number+ collapsible?: boolean+ children: React.ReactNode+}) {+ const [open, setOpen] = useState(true)+ const labelRow = (+ <span className="flex items-center gap-1">+ {label} {count}+ {collapsible && (+ <ChevronDown+ size={12}+ className={cn('transition-transform', !open && '-rotate-90')}+ />+ )}+ </span>+ )+ return (+ <div className="flex flex-col gap-2">+ {collapsible ? (+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ className="px-1 text-left text-xs font-medium uppercase tracking-wide text-main-view-fg/50 hover:text-main-view-fg/70"+ >+ {labelRow}+ </button>+ ) : (+ <span className="px-1 text-xs font-medium uppercase tracking-wide text-main-view-fg/50">+ {labelRow}+ </span>+ )}+ {(!collapsible || open) && children}+ </div>+ )+}++/**+ * Background subagent runs for the viewed session: queued and running ones+ * live in useCoworkRun while a run streams, finished ones persist on the+ * session. Selecting a row opens its own transcript in place.+ */+export function CoworkTasksPanel({+ subagents,+ onClose,+}: {+ subagents: SubagentRun[]+ onClose: () => void+}) {+ const { t } = useTranslation()+ const [selectedRunId, setSelectedRunId] = useState<string | null>(null)++ // Tick once a second while anything is running so the elapsed counters move.+ // Skipped while a detail view is open — that view doesn't render the+ // duration text, so ticking would just re-render the mounted transcript.+ const [, tick] = useState(0)+ const anyRunning = subagents.some((s) => s.status === 'running')+ useEffect(() => {+ if (!anyRunning || selectedRunId) return+ const id = setInterval(() => tick((n) => n + 1), 1000)+ return () => clearInterval(id)+ }, [anyRunning, selectedRunId])++ const selected = selectedRunId+ ? (subagents.find((s) => s.runId === selectedRunId) ?? null)+ : null+ const runningRuns = subagents.filter((s) => s.status === 'running')+ const queuedRuns = subagents.filter((s) => s.status === 'queued')+ const finishedRuns = subagents.filter((s) => s.status === 'done')++ return (+ <CoworkSidePanel+ title={selected ? selected.name : t('common:backgroundTasks')}+ leading={+ selected ? (+ <button+ type="button"+ onClick={() => setSelectedRunId(null)}+ className="text-main-view-fg/60 hover:text-main-view-fg"+ aria-label={t('common:back')}+ >+ <ChevronLeft size={18} />+ </button>+ ) : undefined+ }+ onClose={onClose}+ >+ {selected ? (+ <TaskDetail run={selected} />+ ) : (+ <div className="flex h-full flex-col gap-4 overflow-y-auto p-3">+ {subagents.length === 0 ? (+ <p className="px-1 py-6 text-center text-sm text-main-view-fg/50">+ {t('common:noBackgroundTasks')}+ </p>+ ) : (+ <>+ {runningRuns.length > 0 && (+ <Section label={t('common:running')} count={runningRuns.length}>+ {runningRuns.map((run) => (+ <TaskRow+ key={run.runId}+ run={run}+ onSelect={() => setSelectedRunId(run.runId)}+ />+ ))}+ </Section>+ )}+ {queuedRuns.length > 0 && (+ <Section label={t('common:queued')} count={queuedRuns.length}>+ {queuedRuns.map((run) => (+ <TaskRow+ key={run.runId}+ run={run}+ onSelect={() => setSelectedRunId(run.runId)}+ />+ ))}+ </Section>+ )}+ {finishedRuns.length > 0 && (+ <Section+ label={t('common:finished')}+ count={finishedRuns.length}+ collapsible+ >+ {finishedRuns.map((run) => (+ <TaskRow+ key={run.runId}+ run={run}+ onSelect={() => setSelectedRunId(run.runId)}+ />+ ))}+ </Section>+ )}+ </>+ )}+ </div>+ )}+ </CoworkSidePanel>+ )+}diff --git a/web-app/src/containers/CoworkTodoChip.tsx b/web-app/src/containers/CoworkTodoChip.tsxnew file mode 100644index 000000000..9cf802bd0--- /dev/null+++ b/web-app/src/containers/CoworkTodoChip.tsx@@ -0,0 +1,53 @@+import { ListTodo } from 'lucide-react'+import { Button } from '@/components/ui/button'+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/components/ui/tooltip'+import { cn } from '@/lib/utils'+import { useTranslation } from '@/i18n/react-i18next-compat'+import type { TodoList } from '@/types/coworkSession'++/**+ * Opens the progress rail, and stays out of the way until the agent has+ * written a todo list — the same rule the changes chip follows.+ */+export function CoworkTodoChip({+ todos,+ open,+ onToggle,+}: {+ todos: TodoList | undefined+ open: boolean+ onToggle: () => void+}) {+ const { t } = useTranslation()+ const tasks = (todos?.phases ?? []).flatMap((p) => p.tasks)+ if (tasks.length === 0) return null++ const done = tasks.filter(+ (task) => task.status === 'completed' || task.status === 'abandoned'+ ).length++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ aria-pressed={open}+ aria-label={t('common:todoPanelTitle')}+ onClick={onToggle}+ className={cn('shrink-0', open && 'text-primary')}+ >+ <ListTodo className="size-3.5 shrink-0" />+ <span className="font-mono tabular-nums text-muted-foreground">+ {done}/{tasks.length}+ </span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>{t('common:todoPanelTitle')}</TooltipContent>+ </Tooltip>+ )+}diff --git a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts b/web-app/src/hooks/__tests__/useCoworkSessions.test.tsindex f1a2d905b..ea9fe9f31 100644--- a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts+++ b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts@@ -134,6 +134,87 @@ describe('useCoworkSessions', () => {})})+describe('useCoworkSessions createSession reuse', () => {+ beforeEach(reset)++ it('reuses the current session when it is still empty', () => {+ const first = useCoworkSessions.getState().createSession()+ const second = useCoworkSessions.getState().createSession()+ expect(second).toBe(first)+ expect(useCoworkSessions.getState().sessions).toHaveLength(1)+ })++ it('creates a fresh session once the current one has turns', () => {+ const first = useCoworkSessions.getState().createSession()+ useCoworkSessions+ .getState()+ .commitTurns(first, [{ role: 'user', content: 'hi' }], [], [])+ const second = useCoworkSessions.getState().createSession()+ expect(second).not.toBe(first)+ expect(useCoworkSessions.getState().sessions).toHaveLength(2)+ })+})++describe('useCoworkSessions pruneEmptySessions', () => {+ beforeEach(reset)++ const seed = (id: string, turns: CoworkTurn[] = []) => {+ useCoworkSessions.setState((s) => ({+ sessions: [+ {+ id,+ title: id,+ folder: null,+ turns,+ messages: [],+ updated: Date.now(),+ },+ ...s.sessions,+ ],+ }))+ }++ it('drops sessions with no turns', () => {+ seed('empty')+ seed('full', [{ role: 'user', content: 'hi' }])+ useCoworkSessions.setState({ currentId: 'full' })+ useCoworkSessions.getState().pruneEmptySessions([])+ expect(useCoworkSessions.getState().sessions.map((s) => s.id)).toEqual([+ 'full',+ ])+ })++ it('keeps the current session even when empty', () => {+ seed('stale')+ seed('current')+ useCoworkSessions.setState({ currentId: 'current' })+ useCoworkSessions.getState().pruneEmptySessions([])+ expect(useCoworkSessions.getState().sessions.map((s) => s.id)).toEqual([+ 'current',+ ])+ })++ it('keeps empty sessions named in keepIds (first run still streaming)', () => {+ seed('stale')+ seed('running')+ useCoworkSessions.setState({ currentId: 'stale' })+ useCoworkSessions.getState().pruneEmptySessions(['running'])+ expect(useCoworkSessions.getState().sessions.map((s) => s.id)).toEqual([+ 'running',+ 'stale',+ ])+ })++ it('is a no-op when nothing qualifies', () => {+ seed('b', [{ role: 'user', content: 'hi' }])+ seed('a', [{ role: 'user', content: 'hi' }])+ useCoworkSessions.setState({ currentId: 'a' })+ const before = useCoworkSessions.getState().sessions+ useCoworkSessions.getState().pruneEmptySessions([])+ expect(useCoworkSessions.getState().sessions).toBe(before)+ })+})+describe('useCoworkSessions persist migration', () => {// v0 sessions carry `turns` but no `messages`. Losing the tool turns on// upgrade would leave the agent replaying a conversation with holes in it.diff --git a/web-app/src/hooks/useCoworkSessions.ts b/web-app/src/hooks/useCoworkSessions.tsindex 15d21f9e3..33a2c351b 100644--- a/web-app/src/hooks/useCoworkSessions.ts+++ b/web-app/src/hooks/useCoworkSessions.ts@@ -94,17 +94,27 @@ type CoworkSessionsState = {* history the model sees would disagree. */rewindToLastUser: (id: string) => voidclearSession: (id: string) => void+ /** Drop sessions that never got a message, except the current one and any in+ * `keepIds` — callers pass sessions with a run in flight, whose first turns+ * are still transient in useCoworkRun until the run commits them. */+ pruneEmptySessions: (keepIds: string[]) => void}const now = () => Date.now()export const useCoworkSessions = create<CoworkSessionsState>()(persist(- (set) => ({+ (set, get) => ({sessions: [],currentId: null,createSession: () => {+ // Already viewing an untouched session — reuse it instead of piling+ // up empty ones (e.g. from repeated clicks on "New session").+ const { currentId, sessions } = get()+ const current = sessions.find((s) => s.id === currentId)+ if (current && current.turns.length === 0) return current.id+const id = crypto.randomUUID()const session: CoworkSession = {id,@@ -234,6 +244,15 @@ export const useCoworkSessions = create<CoworkSessionsState>()(: x),})),++ pruneEmptySessions: (keepIds) =>+ set((s) => {+ const keep = new Set(keepIds)+ const sessions = s.sessions.filter(+ (x) => x.turns.length > 0 || x.id === s.currentId || keep.has(x.id)+ )+ return sessions.length === s.sessions.length ? {} : { sessions }+ }),}),{name: localStorageKey.coworkSessions,diff --git a/web-app/src/lib/__tests__/coworkCommands.test.ts b/web-app/src/lib/__tests__/coworkCommands.test.tsnew file mode 100644index 000000000..bf75ae91c--- /dev/null+++ b/web-app/src/lib/__tests__/coworkCommands.test.ts@@ -0,0 +1,112 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'++vi.mock('sonner', () => ({+ toast: Object.assign(vi.fn(), {+ error: vi.fn(),+ success: vi.fn(),+ }),+}))++vi.mock('@/lib/backendStorage', () => ({+ backendStorage: {+ getItem: vi.fn().mockResolvedValue(null),+ setItem: vi.fn().mockResolvedValue(undefined),+ removeItem: vi.fn().mockResolvedValue(undefined),+ },+}))++import { toast } from 'sonner'+import {+ runSlashCommand,+ INIT_PROMPT,+ type SlashCommandDeps,+} from '../coworkCommands'+import { useCoworkSessions } from '@/hooks/useCoworkSessions'++const t = (key: string) => key++const makeDeps = (over: Partial<SlashCommandDeps> = {}): SlashCommandDeps => ({+ t,+ running: false,+ currentId: null,+ submitTurn: vi.fn(),+ openRail: vi.fn(),+ compact: vi.fn(),+ ...over,+})++beforeEach(() => {+ vi.clearAllMocks()+ useCoworkSessions.setState({ sessions: [], currentId: null })+})++describe('runSlashCommand', () => {+ it('/clear wipes the current session when idle', () => {+ const id = useCoworkSessions.getState().createSession()+ useCoworkSessions+ .getState()+ .commitTurns(id, [{ role: 'user', content: 'hi' }], [], [])+ runSlashCommand('/clear', makeDeps({ currentId: id }))+ const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!+ expect(s.turns).toEqual([])+ })++ it('/clear refuses while a run is in flight', () => {+ const id = useCoworkSessions.getState().createSession()+ useCoworkSessions+ .getState()+ .commitTurns(id, [{ role: 'user', content: 'hi' }], [], [])+ runSlashCommand('/clear', makeDeps({ currentId: id, running: true }))+ const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!+ expect(s.turns).toHaveLength(1)+ expect(toast.error).toHaveBeenCalledWith('common:cmdBusy')+ })++ it('/plan toggles the session plan mode both ways', () => {+ const id = useCoworkSessions.getState().createSession()+ const deps = makeDeps({ currentId: id })+ runSlashCommand('/plan', deps)+ expect(+ useCoworkSessions.getState().sessions.find((x) => x.id === id)?.planMode+ ).toBe(true)+ runSlashCommand('/plan', deps)+ expect(+ useCoworkSessions.getState().sessions.find((x) => x.id === id)?.planMode+ ).toBe(false)+ })++ it('/todo and /tasks open their rails', () => {+ const openRail = vi.fn()+ runSlashCommand('/todo', makeDeps({ openRail }))+ runSlashCommand('/tasks', makeDeps({ openRail }))+ expect(openRail).toHaveBeenNthCalledWith(1, 'todos')+ expect(openRail).toHaveBeenNthCalledWith(2, 'tasks')+ })++ it('/init submits the onboarding prompt when idle, refuses mid-run', () => {+ const submitTurn = vi.fn()+ runSlashCommand('/init', makeDeps({ submitTurn }))+ expect(submitTurn).toHaveBeenCalledWith(INIT_PROMPT)++ submitTurn.mockClear()+ runSlashCommand('/init', makeDeps({ submitTurn, running: true }))+ expect(submitTurn).not.toHaveBeenCalled()+ expect(toast.error).toHaveBeenCalledWith('common:cmdBusy')+ })++ it('/compact runs when idle, refuses mid-run', () => {+ const compact = vi.fn()+ runSlashCommand('/compact', makeDeps({ compact }))+ expect(compact).toHaveBeenCalledOnce()++ compact.mockClear()+ runSlashCommand('/compact', makeDeps({ compact, running: true }))+ expect(compact).not.toHaveBeenCalled()+ expect(toast.error).toHaveBeenCalledWith('common:cmdBusy')+ })++ it('an unknown command reports itself instead of failing silently', () => {+ runSlashCommand('/nope', makeDeps())+ expect(toast.error).toHaveBeenCalledWith('common:cmdUnknown')+ })+})diff --git a/web-app/src/lib/coworkCommands.ts b/web-app/src/lib/coworkCommands.tsnew file mode 100644index 000000000..50273d0e1--- /dev/null+++ b/web-app/src/lib/coworkCommands.ts@@ -0,0 +1,114 @@+import { toast } from 'sonner'+import { useCoworkSessions } from '@/hooks/useCoworkSessions'+import { useCoworkRun } from '@/hooks/useCoworkRun'++/**+ * Canned onboarding prompt for `/init`. Sent as a normal user turn so the agent+ * runs it with the regular toolset; unlike the TUI's version it writes no+ * JAN.md — this surface loads no project instructions file, so durable output+ * goes to skills and memory, which every later run does read.+ */+export const INIT_PROMPT = `Onboard yourself to this project so future sessions start informed.++1. Study the project first. Read the README and any contributor docs, map the directory layout, and find the real build, test, lint, and type-check commands (from the manifests and CI config, not from guesswork). Note the conventions the code actually follows.++2. Write skills with skill_write for the project's repeatable procedures - releasing, running migrations, adding a module, debugging a subsystem - one skill per procedure, only where a real multi-step recipe exists. Do not invent skills to fill space.++3. Record durable project facts with memory_write: decisions, constraints, and gotchas that are true beyond this session and not already stated in the code.++Then report what you wrote and why, briefly.`++/**+ * Slash commands available from the composer. Client-side actions — they never+ * reach the agent (except /init, which submits a canned user turn). `descKey`+ * is an i18n key resolved at render time. mode 'run' executes on select;+ * 'args' fills the input so the user can type an argument (/models -> picker).+ */+export const SLASH_COMMANDS = [+ { name: '/help', descKey: 'common:cmdHelp', mode: 'run' },+ { name: '/clear', descKey: 'common:cmdClear', mode: 'run' },+ { name: '/compact', descKey: 'common:cmdCompact', mode: 'run' },+ { name: '/models', descKey: 'common:cmdModels', mode: 'args' },+ { name: '/plan', descKey: 'common:cmdPlan', mode: 'run' },+ { name: '/todo', descKey: 'common:cmdTodo', mode: 'run' },+ { name: '/tasks', descKey: 'common:cmdTasks', mode: 'run' },+ { name: '/init', descKey: 'common:cmdInit', mode: 'run' },+] as const++/**+ * Render-scoped values and callbacks the dispatcher needs but that live in the+ * CoworkPage component. Injected so the dispatch logic is pure and testable;+ * the durable stores are imported directly.+ */+export type SlashCommandDeps = {+ t: (key: string, opts?: Record<string, unknown>) => string+ running: boolean+ currentId: string | null+ submitTurn: (text: string) => void+ openRail: (kind: 'todos' | 'tasks') => void+ compact: () => void+}++export function runSlashCommand(raw: string, deps: SlashCommandDeps): void {+ const { t, running, currentId, submitTurn, openRail, compact } = deps+ const name = raw.trim().split(/\s+/)[0]+ switch (name) {+ case '/compact':+ if (running) {+ toast.error(t('common:cmdBusy'))+ break+ }+ compact()+ break+ case '/help':+ toast(t('common:commands'), {+ description: SLASH_COMMANDS.map(+ (c) => `${c.name} - ${t(c.descKey)}`+ ).join('\n'),+ })+ break+ case '/clear':+ // Clearing mid-run would wipe the session the in-flight run is about to+ // commit its transcript into, leaving it inconsistent.+ if (running) {+ toast.error(t('common:cmdBusy'))+ break+ }+ if (currentId) {+ useCoworkSessions.getState().clearSession(currentId)+ useCoworkRun.getState().clearCodeRun(currentId)+ }+ break+ case '/models':+ // 'args' mode: the picker opens from the menu while "/models" is typed;+ // reaching here means it was submitted with no selection made.+ toast(t('common:cmdModelsHint'))+ break+ case '/plan': {+ if (!currentId) break+ const next = !(+ useCoworkSessions.getState().sessions.find((s) => s.id === currentId)+ ?.planMode ?? false+ )+ useCoworkSessions.getState().setPlanMode(currentId, next)+ toast(t(next ? 'common:cmdPlanOn' : 'common:cmdPlanOff'))+ break+ }+ case '/todo':+ openRail('todos')+ break+ case '/tasks':+ openRail('tasks')+ break+ case '/init':+ if (running) {+ toast.error(t('common:cmdBusy'))+ break+ }+ toast(t('common:cmdInitRunning'))+ submitTurn(INIT_PROMPT)+ break+ default:+ toast.error(t('common:cmdUnknown', { name }))+ }+}diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 842e0af48..543574269 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -51,6 +51,17 @@"cmdModelSwitched": "Switched to {{name}}","cmdUnknown": "Unknown command: {{name}}. Try /help","cmdBusy": "Can't do that while the agent is running",+ "cmdCompact": "Compact the session's context into a summary",+ "cmdCompacted": "Compacted {{before}} -> {{after}} messages",+ "cmdNothingToCompact": "Nothing to compact yet",+ "cmdCompactFailed": "Compaction failed: {{error}}",+ "cmdPlan": "Toggle plan mode (read-only: the agent proposes without writing)",+ "cmdPlanOn": "Plan mode on: the agent reads and proposes without writing",+ "cmdPlanOff": "Plan mode off: normal execution",+ "cmdTodo": "Open the progress panel",+ "cmdTasks": "Open the background tasks panel",+ "cmdInit": "Study the project and write skills and memory",+ "cmdInitRunning": "Onboarding this project","skills": "Skills","skillsInContext": "Skills available to the agent this run","skillsTitle": "Manage skills",@@ -619,6 +630,16 @@"expand": "Expand","todoPanelTitle": "Progress","todoPanelEmpty": "No todo list yet.",+ "backgroundTasks": "Background tasks",+ "noBackgroundTasks": "No background tasks yet.",+ "running": "Running",+ "queued": "Queued",+ "finished": "Finished",+ "viewTranscript": "View transcript",+ "taskWorking": "Working…",+ "taskNoOutput": "The subagent produced no visible output.",+ "subagentToolUses_one": "{{count}} tool use",+ "subagentToolUses_other": "{{count}} tool uses","artifactOpenPreview": "Open preview","artifactOpenExternal": "Open","artifactMoreActions": "More actions",diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex 08eb7ac27..d0e8e8aa3 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -17,7 +17,20 @@ import { toast } from 'sonner'import { invoke } from '@tauri-apps/api/core'import { getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'import { sessionWorkspacePath } from '@janhq/tauri-plugin-agent-tools-api'-import { cn } from '@/lib/utils'+import {+ cn,+ getModelDisplayName,+ getProviderTitle,+} from '@/lib/utils'+import { predefinedProviders } from '@/constants/providers'+import { providerHasRemoteApiKeys } from '@/lib/provider-api-keys'+import { runSlashCommand, SLASH_COMMANDS } from '@/lib/coworkCommands'+import {+ compactMessages,+ type ContextManagerConfig,+} from '@/lib/context-manager'+import { ModelFactory } from '@/lib/model-factory'+import { useMessageQueue } from '@/stores/message-queue-store'import {useCoworkSessions,ensureCurrentSession,@@ -46,7 +59,11 @@ import { artifactsFromParts } from '@/lib/coworkArtifacts'import { CoworkArtifactCard } from '@/containers/CoworkArtifactCard'import { CoworkPreviewPanel } from '@/containers/CoworkPreviewPanel'import { CoworkDiffPanel } from '@/containers/CoworkDiffPanel'+import { CoworkTodoPanel } from '@/containers/CoworkTodoPanel'+import { CoworkTasksPanel } from '@/containers/CoworkTasksPanel'import { CoworkChangesChip } from '@/containers/CoworkChangesChip'+import { CoworkTodoChip } from '@/containers/CoworkTodoChip'+import { CoworkTasksChip } from '@/containers/CoworkTasksChip'import { collectCodeFileDiffs } from '@/lib/coworkDiffs'import { CoworkSandboxChip } from '@/containers/CoworkSandboxChip'import { CoworkBudgetNotice } from '@/containers/CoworkBudgetNotice'@@ -84,10 +101,31 @@ export const Route = createFileRoute(route.cowork as any)({component: CoworkPage,})+// A row in the slash menu — commands and model options share one shape so the+// keyboard navigation works uniformly across both.+type MenuItem = {+ key: string+ label: string+ description: string+ onSelect: () => void+}++/**+ * Manual `/compact` budget. Unlike the transport's auto-compact (which uses the+ * model's real context window and so only fires when genuinely near the limit),+ * a manual compact means "shrink this now": keep only a recent tail and+ * summarize everything older, regardless of how big the window is.+ */+const MANUAL_COMPACT_CONFIG: ContextManagerConfig = {+ maxContextTokens: 8192,+ maxOutputTokens: 2048,+ autoCompact: true,+}+function CoworkPage() {const { t } = useTranslation()const serviceHub = useServiceHub()- const { selectedModel, selectedProvider } = useModelProvider()+ const { selectedModel, selectedProvider, providers } = useModelProvider()const sessions = useCoworkSessions((s) => s.sessions)const currentId = useCoworkSessions((s) => s.currentId)@@ -99,6 +137,10 @@ function CoworkPage() {const planMode = session?.planMode ?? falseconst [running, setRunning] = useState(false)+ // The session the in-flight run belongs to. The live rows are appended to+ // that session's transcript only — without this, switching sessions mid-run+ // rendered the running session's live turns under the viewed one.+ const [runSid, setRunSid] = useState<string | null>(null)const [liveTurns, setLiveTurns] = useState<CoworkTurn[]>([])const liveTurnsRef = useRef<CoworkTurn[]>([])const [stoppedBy, setStoppedBy] = useState<RunOutcome['stoppedBy'] | null>(@@ -111,10 +153,14 @@ function CoworkPage() {// The step just finished, so the counter tracks a run instead of jumping once// at the end. Falls back to the committed usage between runs.const [liveUsage, setLiveUsage] = useState<Usage | null>(null)- // The rail holds one panel at a time: preview and diff both want the width,- // so showing them together starves the transcript (C7).+ // The rail holds one panel at a time: they all want the width, so showing+ // two together starves the transcript (C7).const [rail, setRail] = useState<- { kind: 'preview'; path: string } | { kind: 'diff' } | null+ | { kind: 'preview'; path: string }+ | { kind: 'diff' }+ | { kind: 'todos' }+ | { kind: 'tasks' }+ | null>(null)const showPreview = useCallback((path: string) => setRail({ kind: 'preview', path }),@@ -188,12 +234,13 @@ function CoworkPage() {// `liveTurns` holds only the rows this run has produced — `commitTurns`// appends them — so the committed transcript has to be shown alongside it or// the conversation disappears the moment a follow-up run starts.+ const viewingRun = running && runSid === session?.idconst displayedTurns = useMemo(() =>- running+ viewingRun? [...(session?.turns ?? []), ...liveTurns]: (session?.turns ?? []),- [running, liveTurns, session?.turns]+ [viewingRun, liveTurns, session?.turns])const uiMessages = useMemo(() => coworkTurnsToUIMessages(displayedTurns, session?.id ?? 'cowork'),@@ -219,13 +266,13 @@ function CoworkPage() {const liveSubagents = useCoworkRun((s) =>session?.id ? s.subagents[session.id] : undefined)+ const subagents = useMemo(+ () => liveSubagents ?? session?.subagents ?? [],+ [liveSubagents, session?.subagents]+ )const fileDiffs = useMemo(- () =>- collectCodeFileDiffs(- displayedTurns,- liveSubagents ?? session?.subagents ?? []- ),- [displayedTurns, liveSubagents, session?.subagents]+ () => collectCodeFileDiffs(displayedTurns, subagents),+ [displayedTurns, subagents])const awaitingModel = useMemo(@@ -261,14 +308,20 @@ function CoworkPage() {return}if (text && current?.title === 'New session')- store.setTitle(sid, text.slice(0, 40))+ // Collapse newlines/runs of whitespace so a pasted multi-line prompt+ // doesn't become an unreadable sidebar title.+ store.setTitle(sid, text.trim().replace(/\s+/g, ' ').slice(0, 40))setStoppedBy(null)setRunError(undefined)setLiveUsage(null)liveTurnsRef.current = text ? [{ role: 'user', content: text }] : []setLiveTurns(liveTurnsRef.current)- useCoworkRun.getState().resetSubagents(sid)+ // Marks the session running in the store (and resets its subagent lanes),+ // so surfaces outside this component — the sidebar's per-session spinner+ // and its empty-session filter — can see a run this component owns.+ useCoworkRun.getState().beginRun(sid, crypto.randomUUID(), text ?? '')+ setRunSid(sid)setRunning(true)// Local models load before the first token, but only on a cold start. Probe@@ -521,14 +574,35 @@ function CoworkPage() {useCoworkRun.getState().subagents[sid] ?? [],outcome?.usage ?? undefined)+ useCoworkRun.getState().clearCodeRun(sid)liveTurnsRef.current = []setLiveTurns([])setRunning(false)+ setRunSid(null)abortRef.current = nullaskResolvers.current.clear()setAsk(null)- setStoppedBy(thrown?.stoppedBy ?? outcome?.stoppedBy ?? null)+ const stop = thrown?.stoppedBy ?? outcome?.stoppedBy ?? null+ setStoppedBy(stop)setRunError(thrown?.errorText ?? outcome?.errorText)++ // Message queue (ChatInput enqueues while chatStatus is 'streaming',+ // scoped to this session): a clean finish sends the next queued message;+ // an error discards the queue, mirroring the chat route — errors mean the+ // conversation needs attention, not more unattended sends. A stop or+ // budget halt leaves the queue in place, visible as chips in the input.+ if (stop === 'error') {+ useMessageQueue.getState().clearQueue(sid)+ } else if (stop === 'done') {+ // Deferred past the re-render so the next runRequest closure sees+ // running=false; skipped if the user has since switched sessions, since+ // runRequest always targets the current one.+ setTimeout(() => {+ if (useCoworkSessions.getState().currentId !== sid) return+ const next = useMessageQueue.getState().dequeue(sid)+ if (next) void runRequestRef.current(next.text)+ }, 0)+ }}}@@ -537,7 +611,169 @@ function CoworkPage() {const runRequestRef = useRef(runRequest)runRequestRef.current = runRequest- const handleSubmit = (text: string) => void runRequest(text)+ /**+ * `/compact`: summarize everything but the recent tail into one system+ * message, reusing the transport's auto-compact machinery (context-manager).+ * The transcript (`turns`) is untouched — compaction rewrites what the model+ * replays, not what the user reads.+ */+ const handleCompact = async () => {+ const sid = session?.id+ const msgs = session?.messages ?? []+ if (!sid || msgs.length === 0) {+ toast(t('common:cmdNothingToCompact'))+ return+ }+ if (!selectedModel?.id) {+ toast.error(t('common:selectModel'))+ return+ }+ const provider = providers.find((p) => p.provider === selectedProvider)+ if (!provider) {+ toast.error(t('common:selectModel'))+ return+ }+ try {+ const model = await ModelFactory.createModel(selectedModel.id, provider)+ const result = await compactMessages(msgs, MANUAL_COMPACT_CONFIG, model)+ if (result.trimmedCount === 0 || !result.compactedSummary) {+ toast(t('common:cmdNothingToCompact'))+ return+ }+ useCoworkSessions.getState().setMessages(sid, result.messages)+ toast.success(+ t('common:cmdCompacted', {+ before: msgs.length,+ after: result.messages.length,+ })+ )+ } catch (e) {+ toast.error(t('common:cmdCompactFailed', { error: String(e) }))+ }+ }++ const handleSubmit = (text: string) => {+ // Slash commands are client-side actions; they never reach the agent.+ if (text.trim().startsWith('/')) {+ runSlashCommand(text, {+ t,+ running,+ currentId,+ submitTurn: (prompt) => void runRequestRef.current(prompt),+ openRail: (kind) => setRail({ kind }),+ compact: () => void handleCompact(),+ })+ return+ }+ void runRequest(text)+ }++ // Slash-command menu: the input text lives in the shared usePrompt store, so+ // the menu (and its keyboard nav) works without touching ChatInput.+ const prompt = usePrompt((s) => s.prompt)+ const [menuIndex, setMenuIndex] = useState(0)++ // Switchable models for /models — mirrors DropdownModelProvider's filtering+ // (active providers, no embedding models, remote providers only with a key),+ // narrowed to tool-capable models since runRequest refuses the rest anyway.+ const allModels = useMemo(() => {+ const items: { providerName: string; id: string; label: string }[] = []+ providers.forEach((p) => {+ if (!p.active) return+ const isPredefined = predefinedProviders.some((e) =>+ e.provider.includes(p.provider)+ )+ if (+ p.provider !== 'llamacpp' &&+ !providerHasRemoteApiKeys(p) &&+ (isPredefined || p.models.length === 0)+ )+ return+ p.models.forEach((m) => {+ if (!m.capabilities?.includes('tools')) return+ items.push({+ providerName: p.provider,+ id: m.id,+ label: getModelDisplayName(m),+ })+ })+ })+ return items+ }, [providers])++ const switchModel = useCallback(+ (providerName: string, modelId: string) => {+ useModelProvider.getState().selectModelProvider(providerName, modelId)+ usePrompt.getState().setPrompt('')+ toast.success(t('common:cmdModelSwitched', { name: modelId }))+ },+ [t]+ )++ // Build the current menu: model picker when the text is `/models[ filter]`,+ // otherwise the command list filtered by the typed `/token`.+ const menuItems: MenuItem[] = useMemo(() => {+ const inModelMode = prompt === '/models' || prompt.startsWith('/models ')+ if (inModelMode) {+ const filter = prompt.slice('/models'.length).trim().toLowerCase()+ return allModels+ .filter((m) => `${m.id} ${m.label}`.toLowerCase().includes(filter))+ .slice(0, 50)+ .map((m) => ({+ key: `${m.providerName}/${m.id}`,+ label: m.label,+ description: getProviderTitle(m.providerName),+ onSelect: () => switchModel(m.providerName, m.id),+ }))+ }+ if (prompt.startsWith('/') && !prompt.includes(' ')) {+ const q = prompt.slice(1)+ return SLASH_COMMANDS.filter((c) => c.name.slice(1).startsWith(q)).map(+ (c) => ({+ key: c.name,+ label: c.name,+ description: t(c.descKey),+ onSelect: () => {+ if (c.mode === 'args') {+ usePrompt.getState().setPrompt(`${c.name} `)+ } else {+ usePrompt.getState().setPrompt('')+ handleSubmit(c.name)+ }+ },+ })+ )+ }+ return []+ // handleSubmit is recreated every render but only reads refs/stores.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [prompt, allModels, switchModel, t])++ // Reset the highlighted row whenever the menu contents change.+ useEffect(() => setMenuIndex(0), [prompt])++ // Capture-phase keydown so arrows/Enter/Esc drive the menu BEFORE ChatInput's+ // textarea sees them (no ChatInput changes needed).+ const onMenuKeyDown = (e: React.KeyboardEvent) => {+ if (menuItems.length === 0) return+ if (e.key === 'ArrowDown') {+ e.preventDefault()+ e.stopPropagation()+ setMenuIndex((i) => Math.min(i + 1, menuItems.length - 1))+ } else if (e.key === 'ArrowUp') {+ e.preventDefault()+ e.stopPropagation()+ setMenuIndex((i) => Math.max(i - 1, 0))+ } else if (e.key === 'Enter') {+ e.preventDefault()+ e.stopPropagation()+ menuItems[Math.min(menuIndex, menuItems.length - 1)]?.onSelect()+ } else if (e.key === 'Escape') {+ e.preventDefault()+ e.stopPropagation()+ usePrompt.getState().setPrompt('')+ }+ }/*** Take the last turn again. Rewinding to the question and resuming is the@@ -616,7 +852,7 @@ function CoworkPage() {message={message}isFirstMessage={i === 0}isLastMessage={i === uiMessages.length - 1}- status={running ? 'streaming' : 'ready'}+ status={viewingRun ? 'streaming' : 'ready'}onRegenerate={handleRegenerate}reasoningContainerRef={reasoningContainerRef}isReasoningAtBottom={isReasoningAtBottom}@@ -636,7 +872,7 @@ function CoworkPage() {))}</Fragment>))}- {running && (+ {viewingRun && (// Row wrapper as in the chat route: the transcript is a// column flex, which stretches the indicator's own// `inline-flex` box across the whole column.@@ -667,7 +903,7 @@ function CoworkPage() {{stoppedBy === 'tokens' && (<CoworkBudgetNoticekind="tokens"- onCompact={() => toast.info(t('common:budget.compact'))}+ onCompact={() => void handleCompact()}onNewSession={() =>useCoworkSessions.getState().createSession()}@@ -690,7 +926,36 @@ function CoworkPage() {/></div>)}- <ChatInput+ <div className="relative" onKeyDownCapture={onMenuKeyDown}>+ {menuItems.length > 0 && (+ <div className="absolute left-0 right-0 bottom-full mb-2 z-10 max-h-64 overflow-y-auto rounded-md border bg-popover shadow-md">+ {menuItems.map((item, i) => (+ <button+ key={item.key}+ type="button"+ ref={+ i === menuIndex+ ? (el) => el?.scrollIntoView({ block: 'nearest' })+ : undefined+ }+ onClick={item.onSelect}+ onMouseEnter={() => setMenuIndex(i)}+ className={cn(+ 'flex w-full items-center gap-3 px-3 py-2 text-left text-sm',+ i === menuIndex ? 'bg-accent' : 'hover:bg-accent'+ )}+ >+ <span className="font-mono font-medium">+ {item.label}+ </span>+ <span className="truncate text-xs text-muted-foreground">+ {item.description}+ </span>+ </button>+ ))}+ </div>+ )}+ <ChatInputshowSpeedToken={false}initialMessage={true}scopeKey={session?.id}@@ -717,6 +982,24 @@ function CoworkPage() {onDetach={detachFolder}/><CoworkSandboxChip />+ <CoworkTodoChip+ todos={session?.todos}+ open={rail?.kind === 'todos'}+ onToggle={() =>+ setRail((r) =>+ r?.kind === 'todos' ? null : { kind: 'todos' }+ )+ }+ />+ <CoworkTasksChip+ subagents={subagents}+ open={rail?.kind === 'tasks'}+ onToggle={() =>+ setRail((r) =>+ r?.kind === 'tasks' ? null : { kind: 'tasks' }+ )+ }+ /><CoworkChangesChipfiles={fileDiffs}open={rail?.kind === 'diff'}@@ -731,7 +1014,8 @@ function CoworkPage() {</div></>}- />+ />+ </div></div></div></div>@@ -746,6 +1030,15 @@ function CoworkPage() {{rail?.kind === 'diff' && (<CoworkDiffPanel files={fileDiffs} onClose={() => setRail(null)} />)}+ {rail?.kind === 'todos' && (+ <CoworkTodoPanel+ todos={session?.todos}+ onClose={() => setRail(null)}+ />+ )}+ {rail?.kind === 'tasks' && (+ <CoworkTasksPanel subagents={subagents} onClose={() => setRail(null)} />+ )}</div></div>)