Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
import { create } from 'zustand'
import type {
CoworkMediaPart,
CoworkTurn,
MonitorView,
SubagentRun,
Usage,
TodoList,
AskRequestPayload,
} from '@/types/coworkSession'
import type { MonitorUpdate } from '@/lib/agentTools'
import { userTurn } from '@/lib/coworkTurns'
import type { ModelLoadProgress } from '@/hooks/useAppState'
import type { RunOutcome } from '@/lib/coworkRunner'
// The ask shapes live in the store-free types module; re-exported here because
// this store is where the pending-ask queue lives.
export type {
AskOption,
AskQuestion,
AskRequestPayload,
AskAnswer,
} from '@/types/coworkSession'
// StreamEvent shapes emitted by the Rust agent loop (events.rs, tag = "type").
// Owned here because this store is what consumes/dispatches them.
//
// `step_metadata` is the one JS-only variant: a Cowork child's own stream
// produces it (`coworkSubagent`), and it never crosses the Rust boundary.
export type StreamEvent =
| { type: 'token'; text: string }
| { type: 'reasoning'; text: string }
| { type: 'step'; index: number; max: number }
| { type: 'tool_call_started'; id: string; name: string }
| { type: 'tool_call_args_delta'; id: string; delta: string }
| { type: 'tool_call'; id: string; name: string; args: unknown }
| {
type: 'tool_result'
id: string
content: string
is_error: boolean
diff?: string
}
| { type: 'done'; stop_reason: string; usage: Usage | null }
| { type: 'error'; code: string; message: string }
| { type: 'todo_update'; list: TodoList }
| { type: 'ask_request'; request_id: string; request: AskRequestPayload }
| { type: 'subagent_queued'; run_id: string; name: string; waiting: number }
| { type: 'subagent_start'; run_id: string; name: string }
| { type: 'subagent_end'; run_id: string; name: string; usage: Usage | null }
| { type: 'turn_usage'; usage: Usage }
| {
/** A child's finished step, carrying the metadata `MessageItem` renders
* the token-speed popover from. Lane-local: the parent's own steps reach
* the transcript through `turnsFor` instead. */
type: 'step_metadata'
metadata: Record<string, unknown>
}
| { type: 'subagent'; run_id: string; name: string; event: StreamEvent }
// Append a streamed token to the last assistant turn, or start a new one.
// Shared by the main stream (appendToken) and a subagent's wrapped stream
// (applyInnerToTurns) — same merge, different turn lane.
function appendAssistantToken(turns: CoworkTurn[], text: string): CoworkTurn[] {
const last = turns[turns.length - 1]
if (last && last.role === 'assistant')
return [...turns.slice(0, -1), { ...last, content: last.content + text }]
return [...turns, { role: 'assistant', content: text }]
}
// A freshly-dispatched tool call's turn. Shared by the main stream's
// pushToolTurn call site (cowork.tsx) and a subagent's wrapped tool_call.
export function makeToolCallTurn(ev: {
id: string
name: string
args: unknown
}): CoworkTurn {
return {
role: 'tool',
content: '',
callId: ev.id,
name: ev.name,
args: ev.args,
status: 'running',
}
}
// Find the tool turn by callId and merge patch onto it; returns the same
// array reference (no-op) when there's no match, so callers can cheaply
// detect "nothing changed". Shared by updateToolTurn and applyInnerToTurns.
function mergeToolResult(
turns: CoworkTurn[],
callId: string,
patch: Partial<CoworkTurn>
): CoworkTurn[] {
const idx = turns.findIndex(
(tn) => tn.role === 'tool' && tn.callId === callId
)
if (idx === -1) return turns
return [
...turns.slice(0, idx),
{ ...turns[idx], ...patch },
...turns.slice(idx + 1),
]
}
// Apply one wrapped inner subagent event to that subagent's own turn lane
// (token append / tool_call push / tool_result merge). Pure.
function applyInnerToTurns(
turns: CoworkTurn[],
inner: StreamEvent
): CoworkTurn[] {
switch (inner.type) {
case 'token':
return appendAssistantToken(turns, inner.text)
// Native reasoning, merged like a token but into the row's own `reasoning`
// slot: it must not join `content`, which is what the lane treats as the
// child's answer text.
case 'reasoning': {
const last = turns[turns.length - 1]
if (last && last.role === 'assistant')
return [
...turns.slice(0, -1),
{ ...last, reasoning: (last.reasoning ?? '') + inner.text },
]
return [
...turns,
{ role: 'assistant', content: '', reasoning: inner.text },
]
}
case 'tool_call_started': {
if (turns.some((tn) => tn.role === 'tool' && tn.callId === inner.id))
return turns
return [
...turns,
{
role: 'tool',
content: '',
callId: inner.id,
name: inner.name,
args: null,
argsLive: '',
status: 'running',
},
]
}
case 'tool_call_args_delta': {
const idx = turns.findIndex(
(tn) => tn.role === 'tool' && tn.callId === inner.id
)
if (idx === -1) return turns
const prev = turns[idx].argsLive ?? ''
return [
...turns.slice(0, idx),
{ ...turns[idx], argsLive: prev + inner.delta },
...turns.slice(idx + 1),
]
}
case 'tool_call':
return [...turns, makeToolCallTurn(inner)]
case 'tool_result':
return mergeToolResult(turns, inner.id, {
result: inner.content,
isError: inner.is_error,
diff: inner.diff,
status: 'done',
})
// A child's finished step. It lands on the answer row the step streamed
// into, so the lane's last assistant message carries the same metadata the
// main lane's rows do. A step that answered nothing has no row to hang it
// on, and nothing for the popover to describe.
case 'step_metadata': {
const last = turns[turns.length - 1]
if (!last || last.role !== 'assistant') return turns
return [...turns.slice(0, -1), { ...last, metadata: inner.metadata }]
}
default:
return turns // step / anything else: no visible turn
}
}
function omitKey<T>(map: Record<string, T>, key: string): Record<string, T> {
if (!(key in map)) return map
const next = { ...map }
delete next[key]
return next
}
// Transient (non-persisted) run state for the Cowork UI, keyed by session id —
// mirroring useAppState's per-thread Record<id, T> maps. This is what lets a run
// keep updating a background session while another is viewed: every stream write
// targets the session id captured at submit, and rendering reads the viewed id.
//
// No separate `running` flag: a session is running iff it has a runId, so
// that's read directly (runId[sid] != null) instead of a second map that
// would need to be kept in sync with it.
type CoworkRunState = {
liveTurns: Record<string, CoworkTurn[]>
outcomes: Record<string, Pick<RunOutcome, 'stoppedBy' | 'errorText'>>
setOutcome: (
sid: string,
outcome: Pick<RunOutcome, 'stoppedBy' | 'errorText'>
) => void
setLiveTurns: (sid: string, turns: CoworkTurn[]) => void
subagents: Record<string, SubagentRun[]>
// The session's file monitors. Unlike the subagent lanes they survive the
// run: a watcher keeps going after the model has answered, and a later
// match starts a turn of its own. Dropped with the session (`clearMonitors`).
monitors: Record<string, MonitorView[]>
// True while the run is parked on a subagent still running with the model
// idle. A running monitor never parks a run.
parked: Record<string, boolean>
runId: Record<string, string>
// In-flight `ask` tool questions per session. A subagent's wrapped ask is
// attributed to the parent session the same way.
pendingAsks: Record<
string,
{ requestId: string; request: AskRequestPayload }[]
>
// Usage from the latest `done` event, per session. Set once per run (the
// terminal event); untouched by a `null` usage so a provider that doesn't
// report it on a given turn doesn't blank out the last known value.
usage: Record<string, Usage>
/** Set by the artifacts library so Cowork opens that file on mount. */
pendingPreview: { sessionId: string; path: string } | null
// Session ids currently talking to the llamacpp provider, mapped to the
// model id in flight. Cowork sessions aren't chat threads, so they're
// invisible to the chat-only signals the global OOM/backend-error listener
// otherwise keys off; this is how that listener (mounted outside Cowork's
// component tree, so it still sees a session running in the background)
// finds the right session(s) to attribute a router-level failure to, and
// matches load-progress events by model id rather than "whichever session
// ran most recently".
llamacppRuns: Record<string, string>
// A friendlier failure message the listener stashes when the router itself
// reports why (OOM / backend crash) — submitTurn prefers this over whatever
// generic message the resulting connection failure produced.
pendingLlamacppError: Record<string, string>
// Cowork's own mirror of useAppState's thread-keyed loadingModels /
// modelLoadProgressByThread, keyed by session id instead of chat thread id.
// Kept as an entirely separate Record rather than sharing chat's — several
// chat-side functions (hasActiveLlamacppRequest, clearActiveWork) scan
// useAppState.loadingModels' *keys* as their "is a real chat thread active"
// signal; writing Cowork session ids into that same Record would make a
// Cowork-only model load/failure look like chat activity to those checks.
loadingModels: Record<string, boolean>
modelLoadProgress: Record<string, ModelLoadProgress>
beginRun: (
sid: string,
runId: string,
userText: string,
media?: CoworkMediaPart[]
) => void
appendToken: (sid: string, text: string) => void
pushToolTurn: (sid: string, turn: CoworkTurn) => void
updateToolTurn: (
sid: string,
callId: string,
patch: Partial<CoworkTurn>
) => void
/** Empty a session's subagent lanes at the start of a run, so the panel shows
* this run's children rather than every child the session ever had. */
resetSubagents: (sid: string) => void
/** Register later-phase subagents up front as `waiting`, so the panel shows
* them queued behind the phase in flight. Each is promoted in place (matched
* by runId) by its own `queueSubagent`/`startSubagent` when its phase begins.
* Mirrors the Rust `StreamEvent::SubagentPlan`. */
planSubagents: (
sid: string,
pending: { runId: string; name: string; phase: number }[]
) => void
startSubagent: (sid: string, runId: string, name: string) => void
// `subagent_queued`: mark a child as waiting for a concurrency slot.
queueSubagent: (
sid: string,
runId: string,
name: string,
waiting: number
) => void
endSubagent: (sid: string, runId: string, usage?: Usage | null) => void
routeIntoSubagent: (sid: string, runId: string, inner: StreamEvent) => void
attachSubagentOutput: (sid: string, runId: string, content: string) => void
startMonitor: (sid: string, view: MonitorView) => void
/** Close a monitor from its Rust update (a match or the timeout). */
updateMonitor: (sid: string, update: MonitorUpdate) => void
/** An explicit `stop`: closed with the progress it had. */
stopMonitor: (sid: string, monitorId: string) => void
/** Settle any rail row still marked running that Rust no longer lists as
* active (its terminal update went undelivered), so a matched monitor cannot
* be left spinning. `activeIds` is Rust's authoritative active set. */
reconcileMonitors: (sid: string, activeIds: string[]) => void
/** Session teardown: the watchers are stopped in Rust alongside. */
clearMonitors: (sid: string) => void
setParked: (sid: string, parked: boolean) => void
setUsage: (sid: string, usage: Usage | null) => void
requestPreview: (sessionId: string, path: string) => void
clearPendingPreview: () => void
setLlamacppRun: (sid: string, modelId: string) => void
clearLlamacppRun: (sid: string) => void
setPendingLlamacppError: (sid: string, message: string) => void
/** Reads and clears in one step, so a message can't be applied twice. */
takePendingLlamacppError: (sid: string) => string | undefined
setSessionLoadingModel: (sid: string, loading: boolean) => void
setSessionModelLoadProgress: (
sid: string,
progress: ModelLoadProgress | undefined
) => void
addPendingAsk: (
sid: string,
requestId: string,
request: AskRequestPayload
) => void
removePendingAsk: (sid: string, requestId: string) => void
// Mark running tool turns + subagents done (interrupted). Leaves
// liveTurns/subagents in place and returns the final values so the caller
// can commit them before clearCodeRun without a second round of store
// reads. Run-level failure is surfaced separately via `useMessageErrors`,
// not through this function.
finalizeRun: (sid: string) => {
turns: CoworkTurn[]
subagents: SubagentRun[]
}
clearCodeRun: (sid: string) => void
}
export const useCoworkRun = create<CoworkRunState>()((set, get) => ({
liveTurns: {},
outcomes: {},
setOutcome: (sid, outcome) =>
set((s) => ({ outcomes: { ...s.outcomes, [sid]: outcome } })),
setLiveTurns: (sid, turns) =>
set((s) => ({ liveTurns: { ...s.liveTurns, [sid]: turns } })),
subagents: {},
monitors: {},
parked: {},
runId: {},
pendingAsks: {},
usage: {},
pendingPreview: null,
llamacppRuns: {},
pendingLlamacppError: {},
loadingModels: {},
modelLoadProgress: {},
beginRun: (sid, runId, userText, media) =>
set((s) => ({
runId: { ...s.runId, [sid]: runId },
outcomes: omitKey(s.outcomes, sid),
usage: omitKey(s.usage, sid),
liveTurns: {
...s.liveTurns,
[sid]: [userTurn(userText, media)],
},
subagents: { ...s.subagents, [sid]: [] },
parked: omitKey(s.parked, sid),
pendingAsks: { ...s.pendingAsks, [sid]: [] },
})),
appendToken: (sid, text) =>
set((s) => ({
liveTurns: {
...s.liveTurns,
[sid]: appendAssistantToken(s.liveTurns[sid] ?? [], text),
},
})),
pushToolTurn: (sid, turn) =>
set((s) => ({
liveTurns: { ...s.liveTurns, [sid]: [...(s.liveTurns[sid] ?? []), turn] },
})),
updateToolTurn: (sid, callId, patch) =>
set((s) => {
const turns = s.liveTurns[sid] ?? []
const next = mergeToolResult(turns, callId, patch)
return next === turns
? {}
: { liveTurns: { ...s.liveTurns, [sid]: next } }
}),
resetSubagents: (sid) =>
set((s) => ({ subagents: { ...s.subagents, [sid]: [] } })),
planSubagents: (sid, pending) =>
set((s) => {
const runs = s.subagents[sid] ?? []
const known = new Set(runs.map((r) => r.runId))
const added = pending
.filter((p) => !known.has(p.runId))
.map((p) => ({
runId: p.runId,
name: p.name,
status: 'waiting' as const,
phase: p.phase,
startedAt: Date.now(),
turns: [],
}))
return added.length
? { subagents: { ...s.subagents, [sid]: [...runs, ...added] } }
: {}
}),
startSubagent: (sid, runId, name) =>
set((s) => {
const runs = s.subagents[sid] ?? []
// Promote a waiting/queued child in place the moment it starts (preserving
// its phase); otherwise create it.
const idx = runs.findIndex((r) => r.runId === runId)
if (idx !== -1) {
const existing = runs[idx]
if (existing.status === 'waiting' || existing.status === 'queued') {
return {
subagents: {
...s.subagents,
[sid]: [
...runs.slice(0, idx),
{
...existing,
status: 'running' as const,
waiting: undefined,
startedAt: Date.now(),
},
...runs.slice(idx + 1),
],
},
}
}
return {}
}
return {
subagents: {
...s.subagents,
[sid]: [
...runs,
{
runId,
name,
status: 'running',
startedAt: Date.now(),
turns: [],
},
],
},
}
}),
queueSubagent: (sid, runId, name, waiting) =>
set((s) => {
const runs = s.subagents[sid] ?? []
// Promote a waiting later-phase child to queued in place (keeping its
// phase) once its phase dispatches and it lands on the concurrency gate.
const idx = runs.findIndex((r) => r.runId === runId)
if (idx !== -1) {
const existing = runs[idx]
if (existing.status === 'waiting') {
return {
subagents: {
...s.subagents,
[sid]: [
...runs.slice(0, idx),
{
...existing,
status: 'queued' as const,
waiting,
startedAt: Date.now(),
},
...runs.slice(idx + 1),
],
},
}
}
return {}
}
return {
subagents: {
...s.subagents,
[sid]: [
...runs,
{
runId,
name,
status: 'queued',
waiting,
startedAt: Date.now(),
turns: [],
},
],
},
}
}),
endSubagent: (sid, runId, usage) =>
set((s) => ({
subagents: {
...s.subagents,
[sid]: (s.subagents[sid] ?? []).map((r) =>
r.runId === runId && r.status !== 'done'
? {
...r,
status: 'done' as const,
endedAt: Date.now(),
usage: usage ?? undefined,
}
: r
),
},
})),
routeIntoSubagent: (sid, runId, inner) =>
set((s) => ({
subagents: {
...s.subagents,
[sid]: (s.subagents[sid] ?? []).map((r) =>
r.runId === runId
? { ...r, turns: applyInnerToTurns(r.turns, inner) }
: r
),
},
})),
attachSubagentOutput: (sid, runId, content) =>
set((s) => ({
subagents: {
...s.subagents,
[sid]: (s.subagents[sid] ?? []).map((r) =>
r.runId === runId && r.finalOutput == null
? { ...r, finalOutput: content }
: r
),
},
})),
startMonitor: (sid, view) =>
set((s) => ({
monitors: { ...s.monitors, [sid]: [...(s.monitors[sid] ?? []), view] },
})),
updateMonitor: (sid, update) =>
set((s) => ({
monitors: {
...s.monitors,
[sid]: (s.monitors[sid] ?? []).map((m) =>
m.monitorId === update.monitorId && m.status === 'running'
? {
...m,
status: 'done' as const,
outcome: update.matched
? ('matched' as const)
: ('timeout' as const),
endedAt: Date.now(),
}
: m
),
},
})),
stopMonitor: (sid, monitorId) =>
set((s) => ({
monitors: {
...s.monitors,
[sid]: (s.monitors[sid] ?? []).map((m) =>
m.monitorId === monitorId && m.status === 'running'
? {
...m,
status: 'done' as const,
outcome: 'stopped' as const,
endedAt: Date.now(),
}
: m
),
},
})),
reconcileMonitors: (sid, activeIds) =>
set((s) => {
const rows = s.monitors[sid]
if (!rows?.length) return {}
const active = new Set(activeIds)
let changed = false
const next = rows.map((m) => {
if (m.status !== 'running' || active.has(m.monitorId)) return m
changed = true
return {
...m,
status: 'done' as const,
outcome: 'ended' as const,
endedAt: Date.now(),
}
})
return changed ? { monitors: { ...s.monitors, [sid]: next } } : {}
}),
clearMonitors: (sid) => set((s) => ({ monitors: omitKey(s.monitors, sid) })),
setParked: (sid, parked) =>
set((s) => ({
parked: parked ? { ...s.parked, [sid]: true } : omitKey(s.parked, sid),
})),
setUsage: (sid, usage) =>
set((s) => (usage ? { usage: { ...s.usage, [sid]: usage } } : {})),
requestPreview: (sessionId, path) =>
set({ pendingPreview: { sessionId, path } }),
clearPendingPreview: () => set({ pendingPreview: null }),
setLlamacppRun: (sid, modelId) =>
set((s) => ({ llamacppRuns: { ...s.llamacppRuns, [sid]: modelId } })),
clearLlamacppRun: (sid) =>
set((s) => ({ llamacppRuns: omitKey(s.llamacppRuns, sid) })),
setPendingLlamacppError: (sid, message) =>
set((s) => ({
pendingLlamacppError: { ...s.pendingLlamacppError, [sid]: message },
})),
takePendingLlamacppError: (sid) => {
const message = get().pendingLlamacppError[sid]
if (message !== undefined) {
set((s) => ({
pendingLlamacppError: omitKey(s.pendingLlamacppError, sid),
}))
}
return message
},
setSessionLoadingModel: (sid, loading) =>
set((s) => {
const next = { ...s.loadingModels }
if (loading) next[sid] = true
else delete next[sid]
return { loadingModels: next }
}),
setSessionModelLoadProgress: (sid, progress) =>
set((s) => {
const next = { ...s.modelLoadProgress }
if (progress) next[sid] = progress
else delete next[sid]
return { modelLoadProgress: next }
}),
addPendingAsk: (sid, requestId, request) =>
set((s) => ({
pendingAsks: {
...s.pendingAsks,
[sid]: [...(s.pendingAsks[sid] ?? []), { requestId, request }],
},
})),
removePendingAsk: (sid, requestId) =>
set((s) => ({
pendingAsks: {
...s.pendingAsks,
[sid]: (s.pendingAsks[sid] ?? []).filter(
(a) => a.requestId !== requestId
),
},
})),
finalizeRun: (sid) => {
// Run-level failure surfaces via `useMessageErrors` (Generation-failed
// banner), not as a synthetic tool-error turn — that used to render a
// misleading error-styled tool card even though no tool call failed.
const turns: CoworkTurn[] = (get().liveTurns[sid] ?? []).map((tn) =>
tn.role === 'tool' && tn.status === 'running'
? {
...tn,
status: 'done' as const,
isError: true,
result: tn.result || '(interrupted)',
}
: tn
)
const subs = (get().subagents[sid] ?? []).map((r) =>
r.status !== 'done'
? { ...r, status: 'done' as const, endedAt: Date.now() }
: r
)
set((s) => ({
liveTurns: { ...s.liveTurns, [sid]: turns },
subagents: { ...s.subagents, [sid]: subs },
parked: omitKey(s.parked, sid),
}))
return { turns, subagents: subs }
},
clearCodeRun: (sid) =>
set((s) => ({
liveTurns: omitKey(s.liveTurns, sid),
outcomes: omitKey(s.outcomes, sid),
subagents: omitKey(s.subagents, sid),
parked: omitKey(s.parked, sid),
runId: omitKey(s.runId, sid),
pendingAsks: omitKey(s.pendingAsks, sid),
usage: omitKey(s.usage, sid),
llamacppRuns: omitKey(s.llamacppRuns, sid),
pendingLlamacppError: omitKey(s.pendingLlamacppError, sid),
loadingModels: omitKey(s.loadingModels, sid),
modelLoadProgress: omitKey(s.modelLoadProgress, sid),
})),
}))
// Per-session selectors, mirroring useAppState's useIsThreadActive — a
// component reading only one session's slice re-renders on that session's
// changes, not on every other session's.
export const useIsSessionActive = (sid: string | undefined) =>
useCoworkRun((s) => (sid ? s.runId[sid] != null : false))
// Run closures own their transcript and wire history until their finally block
// commits them. Keep this registry outside React so background/unmounted runs
// participate in close just like the session currently on screen.
const closeParticipants = new Set<() => Promise<void>>()
let closing = false
let quiescePromise: Promise<void> | null = null
export function isCoworkClosing(): boolean {
return closing
}
/** Register synchronously when a run is claimed; unregister AFTER its commit. */
export function registerCoworkRunForClose(stopAndCommit: () => Promise<void>): () => void {
closeParticipants.add(stopAndCommit)
return () => { closeParticipants.delete(stopAndCommit) }
}
/** Stop every run before waiting, then await all final commits (even on error). */
export function quiesceCoworkRuns(): Promise<void> {
closing = true
quiescePromise ??= (async () => {
const settled = await Promise.allSettled(
[...closeParticipants].map(async (stopAndCommit) => stopAndCommit())
)
const failed = settled.find((result) => result.status === 'rejected')
if (failed?.status === 'rejected') {
quiescePromise = null
throw failed.reason
}
})()
return quiescePromise
}
/** A prevented close leaves the application usable and the next close retries. */
export function resumeCoworkAfterPreventedClose(): void {
closing = false
quiescePromise = null
}
export function __resetCoworkRunCloseForTests(): void {
closeParticipants.clear()
closing = false
quiescePromise = null
}