Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Unify completed-result notifications and simplify desktop chrome (#444)

Dee805d3deb4a06
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 505671a38..db296f435 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -206,6 +206,7 @@ import { AskQuestionController, parseEngineQuestionPane, pollsQuestions, Questio
import { teamWriteHold } from './teams/preflight.js'
import { TeamError } from './teams/model.js'
import { CommanderMirror, SUBAGENT_IDLE_MS, type CommanderMirrorOpts } from './lib/commander.js'
+import { AgentNotifications } from './lib/agentNotifications.js'
import {
setSummaryPoolDeviceConnected,
shutdownSummaryPool,
@@ -2685,6 +2686,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
let openToolsOf: (sessionId: string) => Array<{ name: string; input: unknown }> = () => []
// What is still being asked, by session — handed to a window that connects later (openQuestions below).
const openQuestions = new Map<string, Record<string, unknown>>()
+ const agentNotifications = new AgentNotifications()
const questionWatcher = new QuestionWatcher({
getSession: (id) => registry.resolve(id),
capture: captureTerminal,
@@ -2698,7 +2700,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
type: 'commander_question',
agentId: agentIdFor(sessionId),
dbSessionId: sessionId,
- payload: { requestId, questions: shaped },
+ payload: { requestId, questions: shaped, notification: agentNotifications.asked(sessionId, requestId) },
}
backend.sendCommander(asked)
// ...and to the window on this computer. `sendCommander` is `webEligible: false`, so until this
@@ -2724,6 +2726,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// waiting, down the SAME path the question itself took, so the dial and the WiFi device cannot
// disagree about whether a question is still open.
onQuestionGone: (sessionId, requestId) => {
+ agentNotifications.answered(sessionId, requestId)
deviceInput.setUserAction(agentIdFor(sessionId), false)
const closed = {
type: 'commander_question_close',
@@ -2784,6 +2787,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
return role?.role === 'worker' || (role?.role === 'director' && role.busy)
}
const mirror = new CommanderMirror({
+ notifications: agentNotifications,
+ notifyWithoutDevice: true,
send: (frame) => backend.sendCommander(frame),
sendWeb: (frame) => backend.send(frame), // turn_summary_pending / turn_summary → web indicator
hasDevice: () => deviceIsWatching(), // device-gate the LLM recap (mirror node)
@@ -3125,7 +3130,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (learnFrom && daemons.on() && !isTerminalEngine(learnFrom.engine)) {
lessonUsage.ingest({ cwd: learnFrom.cwd ?? null }, events, { replay: !!(opts?.resumed || opts?.replay) })
}
- mirror.ingest(events, sessionId)
+ mirror.ingest(events, sessionId, { replay: !!(opts?.resumed || opts?.replay) })
// Subscribed devices only (lib/autonomous-device/stream.ts). A transcript re-read is history, not live.
if (!opts?.replay) autonomousDeviceService?.stream(agentIdFor(sessionId), events)
}
diff --git a/cli/src/engines/codex/normalizer.spec.ts b/cli/src/engines/codex/normalizer.spec.ts
index 2aab9bcfe..54bef5dda 100644
--- a/cli/src/engines/codex/normalizer.spec.ts
+++ b/cli/src/engines/codex/normalizer.spec.ts
@@ -192,6 +192,28 @@ describe('Codex rollout normalizer', () => {
expect(window.hasMore).toBe(true)
})
+ it('never borrows a previous final answer for an unfinished goal turn', () => {
+ const previous = [
+ line('event_msg', { type: 'user_message', message: 'First task' }),
+ line('event_msg', { type: 'agent_message', phase: 'final_answer', message: 'First task done.' }),
+ line('response_item', { type: 'message', role: 'user', content: [{ type: 'input_text',
+ text: '<codex_internal_context source="goal"><objective>Next task</objective></codex_internal_context>' }] }),
+ line('event_msg', { type: 'agent_message', phase: 'commentary', message: 'Working on the next task.' }),
+ ]
+ expect(lastCodexTurnText(previous)).toBeNull()
+ expect(lastCodexTurnText([...previous,
+ line('event_msg', { type: 'agent_message', phase: 'final_answer', message: 'Next task done.' }),
+ ])).toEqual({ userMessage: '/goal Next task', assistantText: 'Next task done.' })
+ })
+
+ it('requires the final phase once the transcript supplies phases', () => {
+ expect(lastCodexTurnText([
+ line('event_msg', { type: 'user_message', message: 'Work' }),
+ line('event_msg', { type: 'agent_message', message: 'An unphased intermediate update.' }),
+ line('event_msg', { type: 'agent_message', phase: 'commentary', message: 'Still working.' }),
+ ])).toBeNull()
+ })
+
it('maps Codex orchestration to a Task tree and deduplicates completion notifications', () => {
const resolver: CodexSubagentResolver = () => ({
events: [
diff --git a/cli/src/engines/codex/normalizer.ts b/cli/src/engines/codex/normalizer.ts
index 1f573c9cf..203bc9dcf 100644
--- a/cli/src/engines/codex/normalizer.ts
+++ b/cli/src/engines/codex/normalizer.ts
@@ -598,7 +598,7 @@ export function lastCodexTurnText(rawLines: string[]): LastTurnText | null {
// A `/goal` turn has no `user_message` — its prompt lives in the injected goal context.
if (raw.type === 'response_item' && string(item.type) === 'message') {
const objective = goalObjective(item)
- if (objective) { userMessage = `/goal ${objective}`; assistantText = '' }
+ if (objective) { userMessage = `/goal ${objective}`; assistantText = ''; finalText = ''; sawPhase = false }
continue
}
if (raw.type !== 'event_msg') continue
@@ -611,7 +611,7 @@ export function lastCodexTurnText(rawLines: string[]): LastTurnText | null {
if (message) take(item, message)
}
}
- const text = sawPhase && finalText ? finalText : assistantText
+ const text = sawPhase ? finalText : assistantText
return text ? { userMessage, assistantText: text } : null
}
diff --git a/cli/src/lib/agentNotifications.spec.ts b/cli/src/lib/agentNotifications.spec.ts
new file mode 100644
index 000000000..1c5b0a24d
--- /dev/null
+++ b/cli/src/lib/agentNotifications.spec.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest'
+import { AgentNotifications } from './agentNotifications.js'
+
+describe('shared desktop/device notification policy', () => {
+ it('announces a completed result once per live turn', () => {
+ const policy = new AgentNotifications()
+ expect(policy.completed('s', 'Old answer', false)).toBeNull()
+ policy.started('s')
+ const first = policy.completed('s', 'Finished the change.', false)
+ expect(first).toEqual({ id: expect.any(String), kind: 'done' })
+ expect(policy.completed('s', 'Finished the change.', false)).toBeNull()
+ policy.started('s')
+ expect(policy.completed('s', 'Another result', false)?.id).not.toBe(first?.id)
+ })
+
+ it('ignores replays, empty results, subagents and cancelled turns', () => {
+ const policy = new AgentNotifications()
+ policy.started('history', true)
+ policy.started('empty')
+ policy.started('worker')
+ policy.started('aborted')
+ policy.cancelled('aborted')
+ for (const [id, text, silent] of [
+ ['history', 'Historical answer', false], ['empty', ' ', false],
+ ['worker', 'Child finished', true], ['aborted', 'Partial work', false],
+ ] as const) expect(policy.completed(id, text, silent)).toBeNull()
+ })
+
+ it('keeps questions actionable and does not announce their answer as done', () => {
+ const policy = new AgentNotifications()
+ policy.started('s')
+ expect(policy.asked('s', 'q')).toEqual({ id: 'q', kind: 'needsYou' })
+ policy.answered('s', 'older-question')
+ expect(policy.completed('s', 'Please choose.', false)).toBeNull()
+ policy.answered('s', 'q')
+ expect(policy.completed('s', 'Please choose.', false)).toBeNull()
+ policy.started('s')
+ expect(policy.completed('s', 'Implemented your choice.', false)?.kind).toBe('done')
+ })
+})
diff --git a/cli/src/lib/agentNotifications.ts b/cli/src/lib/agentNotifications.ts
new file mode 100644
index 000000000..5d8787b94
--- /dev/null
+++ b/cli/src/lib/agentNotifications.ts
@@ -0,0 +1,56 @@
+import { randomUUID } from 'node:crypto'
+
+export type AgentNotification = { id: string; kind: 'done' | 'needsYou' }
+
+/** The notification decision shared by desktop and device. Live device cards
+ * do not pass through this policy: tools, progress and streaming stay live.
+ * CommanderMirror calls completed only after the whole turn has settled and
+ * its final answer has been resolved. QuestionWatcher owns actionable input. */
+export class AgentNotifications {
+ private readonly turns = new Map<string, { id: string; eligible: boolean; replay: boolean }>()
+ private readonly questions = new Map<string, string>()
+
+ started(sessionId: string, replay = false): void {
+ this.turns.set(sessionId, { id: randomUUID(), eligible: !replay, replay })
+ }
+
+ continued(sessionId: string): void {
+ const turn = this.turns.get(sessionId)
+ // Attaching mid-turn replays its opening. The live continuation is still
+ // real work, whereas a completed historical turn stays silent.
+ if (turn?.replay) { turn.replay = false; turn.eligible = true }
+ }
+
+ completed(sessionId: string, result: string, silent: boolean): AgentNotification | null {
+ const turn = this.turns.get(sessionId)
+ if (!turn) return null
+ const eligible = turn.eligible
+ turn.eligible = false // Duplicate completion never creates another alert.
+ turn.replay = false
+ if (!eligible || silent || !result.trim() || this.questions.has(sessionId)) return null
+ return { id: turn.id, kind: 'done' }
+ }
+
+ asked(sessionId: string, requestId: string): AgentNotification {
+ this.questions.set(sessionId, requestId)
+ return { id: requestId, kind: 'needsYou' }
+ }
+
+ answered(sessionId: string, requestId: string): void {
+ if (this.questions.get(sessionId) !== requestId) return
+ this.questions.delete(sessionId)
+ // A stop caused by answering a prompt is not fresh news. A subsequent
+ // real turn_started re-arms completion; no arbitrary time window needed.
+ this.cancelled(sessionId)
+ }
+
+ cancelled(sessionId: string): void {
+ const turn = this.turns.get(sessionId)
+ if (turn) { turn.eligible = false; turn.replay = false }
+ }
+
+ forget(sessionId: string): void {
+ this.turns.delete(sessionId)
+ this.questions.delete(sessionId)
+ }
+}
diff --git a/cli/src/lib/commander.spec.ts b/cli/src/lib/commander.spec.ts
index 3157e836a..1c18144c7 100644
--- a/cli/src/lib/commander.spec.ts
+++ b/cli/src/lib/commander.spec.ts
@@ -320,7 +320,7 @@ describe('CommanderMirror recap events', () => {
'done',
'summary',
])
- expect(deviceFrames.at(-1)?.payload).toEqual({ kind: 'summary', text: 'Long body', recap: 'Short recap' })
+ expect(deviceFrames.at(-1)?.payload).toEqual({ kind: 'summary', text: 'Long body', recap: 'Short recap', notification: { id: expect.any(String), kind: 'done' } })
expect(webFrames.map((f) => f.type)).toEqual(['turn_summary_pending', 'turn_summary'])
})
diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.ts
index df8ef1be5..77d8a8be5 100644
--- a/cli/src/lib/commander.ts
+++ b/cli/src/lib/commander.ts
@@ -1,6 +1,6 @@
/**
- * CommanderMirror — derives the paired hardware device's `commander_event` stream from the same LiveEvent
- * stream the web receives, and produces the per-turn RECAP the way the hosted runtime does:
+ * CommanderMirror — shares completed-turn decisions between desktop and device,
+ * and derives the device's live `commander_event` stream from LiveEvents:
*
* turn_started → {kind:'processing'} (tile busy)
* tool_start → {kind:'tool', text, recap, color, detail}
@@ -10,7 +10,7 @@
* turn_ended (device on) → {kind:'processing', text:'Summarizing…'} then, once the LLM one-shot
* returns, {kind:'summary', text:body, recap} (persisted per session,
* and handed to the NEXT turn's summariser as its previous recap)
- * turn_ended (no device) → nothing (device-gated; the summary map is left untouched)
+ * turn_ended (no device) → local recap + desktop notification when notifyWithoutDevice is on
* turn_ended (empty text) → {kind:'done'} (clear busy)
*
* Every frame carries top-level `agentId` + `dbSessionId` (= the tmux session id). The recap
@@ -21,6 +21,8 @@
import { mkdirSync, readFileSync, writeFileSync } from 'fs'
import { join } from 'path'
import type { LastTurnText, LiveEvent } from './normalize.js'
+import { AgentNotifications } from './agentNotifications.js'
+import { deriveTurnSummary } from './deviceRecap.js'
export type CommanderFrame = {
type: 'commander_event'
@@ -30,6 +32,10 @@ export type CommanderFrame = {
}
export interface CommanderMirrorOpts {
+ /** Shared with QuestionWatcher; both screens receive this policy's decision. */
+ notifications?: AgentNotifications
+ /** Produce desktop results without a device, using a free local excerpt. */
+ notifyWithoutDevice?: boolean
/** Device-audience frame (commander_event cards). */
send: (frame: CommanderFrame) => void
/** Web-audience frame (turn_summary_pending / turn_summary — the "Summarizing…" indicator). */
@@ -278,6 +284,7 @@ function clipBytes(text: string, max: number): string {
}
export class CommanderMirror {
+ private readonly notifications: AgentNotifications
private states = new Map<string, SessionState>()
private summaries = new Map<string, string>() // sessionId → "recap\n\nbody" (the LATEST turn)
/**
@@ -322,6 +329,7 @@ export class CommanderMirror {
private saveTimer: NodeJS.Timeout | null = null
constructor(private opts: CommanderMirrorOpts) {
+ this.notifications = opts.notifications ?? new AgentNotifications()
this.file = join(opts.dataDir, 'summaries.json')
this.historyFile = join(opts.dataDir, 'summaries-history.json')
this.fullTextFile = join(opts.dataDir, 'summaries-fulltext.json')
@@ -389,12 +397,14 @@ export class CommanderMirror {
}
/** Fold one session's LiveEvents into device commander_event frames (live cards + async recap). */
- ingest(events: LiveEvent[], sessionId: string): void {
+ ingest(events: LiveEvent[], sessionId: string, options?: { replay?: boolean }): void {
const st = this.stateFor(sessionId)
+ if (!options?.replay && st.turnOpen) this.notifications.continued(sessionId)
for (const e of events) {
this.trackTool(sessionId, e)
switch (e.type) {
case 'turn_started':
+ this.notifications.started(sessionId, options?.replay)
st.abort?.abort() // supersede any in-flight recap from the previous turn
st.abort = null
// A new prompt supersedes a held turn-end outright: its sub-agents belong to the turn the user
@@ -481,6 +491,7 @@ export class CommanderMirror {
}
case 'turn_ended':
+ if (options?.replay) this.notifications.cancelled(sessionId)
// A killed turn takes the cancel path, not the recap path: clear the tile and stay silent. There
// is nothing to summarize, and a beep for output the user just threw away is worse than nothing.
if (e.payload.aborted) {
@@ -653,7 +664,8 @@ export class CommanderMirror {
// Cost: with SUMMARY_MODE=model this is one engine one-shot per turn, per agent, forever — the very
// cost the device gate used to avoid. SUMMARY_MODE=local makes it free (no model, same-tick excerpt).
const alwaysGenerate = typeof this.opts.alwaysGenerate === 'function' ? this.opts.alwaysGenerate() : this.opts.alwaysGenerate
- if (!device && !this.opts.recapForce && !alwaysGenerate) {
+ const localOnly = !device && !this.opts.recapForce && !alwaysGenerate
+ if (localOnly && !this.opts.notifyWithoutDevice) {
// Console-only: no device and generation is off, so there is no recap flow to watch.
console.log(`[recap] ${sid} turn-end · SKIP (no device connected) · textLen=${fallbackText.length}`)
return
@@ -668,12 +680,12 @@ export class CommanderMirror {
void this.resolveTurnText(sessionId, fallbackText, fallbackUserMessage)
.then(({ text, userMessage, source }) => {
if (ac.signal.aborted) return
- this.startSummary(sessionId, st, ac, t0, sid, text, userMessage, device, source)
+ this.startSummary(sessionId, st, ac, t0, sid, text, userMessage, device, source, localOnly)
})
.catch((err) => {
if (ac.signal.aborted) return
- this.trace(sessionId, `${sid} JSON session read failed: ${err instanceof Error ? err.message : String(err)} — using live buffer`, true)
- this.startSummary(sessionId, st, ac, t0, sid, fallbackText, fallbackUserMessage, device, 'live')
+ this.trace(sessionId, `${sid} JSON session read failed: ${err instanceof Error ? err.message : String(err)} — no verified final result`, true)
+ this.startSummary(sessionId, st, ac, t0, sid, '', fallbackUserMessage, device, 'session-json', localOnly)
})
}
@@ -683,13 +695,18 @@ export class CommanderMirror {
fallbackUserMessage: string,
): Promise<{ text: string; userMessage: string; source: 'session-json' | 'live' }> {
const turn = this.opts.readLastTurn ? await this.opts.readLastTurn(sessionId) : null
- if (turn?.assistantText.trim()) {
+ if (turn) {
return {
text: turn.assistantText.trim(),
userMessage: turn.userMessage || fallbackUserMessage,
source: 'session-json',
}
}
+ // A configured engine reader is authoritative, including "no final answer".
+ // Falling back to live commentary here created empty/premature alerts.
+ if (this.opts.readLastTurn) {
+ return { text: '', userMessage: fallbackUserMessage, source: 'session-json' }
+ }
return { text: fallbackText, userMessage: fallbackUserMessage, source: 'live' }
}
@@ -703,6 +720,7 @@ export class CommanderMirror {
userMessage: string,
device: boolean,
source: 'session-json' | 'live',
+ localOnly = false,
): void {
if (!text) {
// No assistant TEXT block accumulated this turn (thinking/tools don't count) → nothing to
@@ -725,13 +743,16 @@ export class CommanderMirror {
// Both are skipped when the summary is derived locally: it lands in the same tick, so the card
// would be a flash of "Summarizing…" replaced before anyone could read it — a waiting state for a
// wait that no longer happens.
- if (!this.opts.summarizeIsLocal) {
+ const local = localOnly || this.opts.summarizeIsLocal
+ if (!local) {
this.emit(sessionId, { kind: 'processing', text: 'Summarizing…' })
this.opts.sendWeb({ type: 'turn_summary_pending', dbSessionId: sessionId, payload: { sessionId } })
}
- this.opts
- .summarize(text, ac.signal, userMessage, sessionId, previousRecap)
+ const summary = localOnly
+ ? Promise.resolve(deriveTurnSummary(text))
+ : this.opts.summarize(text, ac.signal, userMessage, sessionId, previousRecap)
+ summary
.then((summary) => {
const ms = Date.now() - t0
if (ac.signal.aborted) { this.trace(sessionId, `${sid} superseded after ${ms}ms (newer turn) — dropping result`); return }
@@ -744,15 +765,21 @@ export class CommanderMirror {
this.rememberFullText(sessionId, text)
this.saveSoon()
const { recap, body } = splitSummary(summary)
+ const notification = this.notifications.completed(sessionId, body || recap,
+ (this.opts.isSubagent?.(sessionId) ?? false) || st.abandoned)
try { this.opts.onSummary?.(sessionId, { recap, body }) } catch { /* an observer never costs the recap */ }
this.trace(sessionId, `${sid} done in ${ms}ms · recap="${recap}" · bodyLen=${body.length}`)
this.emit(sessionId, { kind: 'done', text: 'done' })
- this.emit(sessionId, { kind: 'summary', text: body || recap, recap })
- this.opts.sendWeb({ type: 'turn_summary', dbSessionId: sessionId, payload: { summary, sessionId } })
+ // One decision feeds both clients. A silent recap still updates the
+ // device's tile; only real completed results create inbox entries.
+ this.emit(sessionId, { kind: 'summary', text: body || recap, recap,
+ notification, ...(!notification ? { subagent: true } : {}) })
+ this.opts.sendWeb({ type: 'turn_summary', agentId: this.opts.agentIdFor?.(sessionId) ?? sessionId,
+ dbSessionId: sessionId, payload: { summary, sessionId, notification } })
} else {
this.trace(sessionId, `${sid} summarizer returned NULL after ${ms}ms → done`)
this.emit(sessionId, { kind: 'done', text: 'done' })
- if (!this.opts.summarizeIsLocal) {
+ if (!local) {
this.opts.sendWeb({ type: 'turn_summary_pending', dbSessionId: sessionId, payload: { sessionId, done: true } })
}
}
@@ -883,6 +910,7 @@ export class CommanderMirror {
* the device treats as "clear the processing status, keep the last card" (no recap, no beep). The session
* stays alive; the next prompt reopens a fresh turn. Mirrors forget() but WITHOUT dropping the state. */
cancel(sessionId: string): void {
+ this.notifications.cancelled(sessionId)
const st = this.states.get(sessionId)
if (!st) return
st.abort?.abort()
@@ -923,6 +951,7 @@ export class CommanderMirror {
* can reuse it via recent()/project_recent instead of losing the last device recap. SessionEnd alone
* does not call this; process discovery owns lifetime. */
forget(sessionId: string): void {
+ this.notifications.forget(sessionId)
const st = this.states.get(sessionId)
st?.abort?.abort()
// The state object is about to be dropped; a held turn-end timer would fire against a dead session.
diff --git a/cli/src/lib/commanderNotifications.spec.ts b/cli/src/lib/commanderNotifications.spec.ts
new file mode 100644
index 000000000..f82ad9be9
--- /dev/null
+++ b/cli/src/lib/commanderNotifications.spec.ts
@@ -0,0 +1,102 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { AgentNotifications } from './agentNotifications.js'
+import { CommanderMirror, type CommanderFrame, type CommanderMirrorOpts } from './commander.js'
+import type { LiveEvent } from './normalize.js'
+
+let dataDir: string
+beforeEach(() => { vi.useFakeTimers(); dataDir = mkdtempSync(join(tmpdir(), 'harness-notifications-')) })
+afterEach(() => { vi.useRealTimers(); rmSync(dataDir, { recursive: true, force: true }) })
+
+const turn: LiveEvent[] = [
+ { type: 'turn_started', payload: { userMessage: 'Fix it' } },
+ { type: 'text_delta', payload: { content: 'The fix is complete.' } },
+ { type: 'turn_ended', payload: {} },
+]
+
+function setup(options: Partial<CommanderMirrorOpts> = {}) {
+ const device: CommanderFrame[] = [], desktop: Record<string, any>[] = []
+ const summarize = vi.fn(async () => 'The fix is complete.\n\nTests passed.')
+ const policy = new AgentNotifications()
+ const mirror = new CommanderMirror({
+ dataDir, notifications: policy, notifyWithoutDevice: true,
+ send: f => device.push(f), sendWeb: f => desktop.push(f),
+ hasDevice: () => true, summarize, summarizeIsLocal: true,
+ agentIdFor: () => 'agent', ...options,
+ })
+ return { mirror, device, desktop, summarize, policy }
+}
+
+describe('one completed-result decision for desktop and device', () => {
+ it('sends the same notification to both while keeping live cards intact', async () => {
+ const { mirror, device, desktop } = setup()
+ mirror.ingest([
+ turn[0], { type: 'tool_start', payload: { id: 't', tool: 'Read', input: { path: '/work/file' } } },
+ turn[1], turn[2],
+ ], 's')
+ expect(device.map(f => f.payload.kind)).toEqual(['processing', 'tool'])
+ expect(device[1].payload).toEqual({ kind: 'tool', text: 'Read', recap: '/work/file', color: '#61afef', detail: 'path: /work/file' })
+ await vi.runAllTimersAsync()
+ expect(device.map(f => f.payload.kind)).toEqual(['processing', 'tool', 'done', 'summary'])
+ expect(desktop).toHaveLength(1)
+ expect(desktop[0].payload.notification).toEqual(device.at(-1)?.payload.notification)
+ expect(desktop[0].agentId).toBe('agent')
+ expect(desktop[0].payload.notification.kind).toBe('done')
+ })
+
+ it('works without hardware and does not start a paid recap call', async () => {
+ const { mirror, desktop, device, summarize } = setup({ hasDevice: () => false, summarizeIsLocal: false })
+ mirror.ingest(turn, 's')
+ await vi.runAllTimersAsync()
+ expect(summarize).not.toHaveBeenCalled()
+ expect(device).toEqual([])
+ expect(desktop[0].payload.notification.kind).toBe('done')
+ expect(mirror.recent('s')[0].text).toContain('The fix is complete.')
+ })
+
+ it.each(['null', 'empty', 'error'] as const)('does not turn live commentary into an answer when the final reader returns %s', async mode => {
+ const { mirror, desktop, device } = setup({ readLastTurn: async () => {
+ if (mode === 'error') throw new Error('Unavailable transcript')
+ return mode === 'null' ? null : { userMessage: 'Fix it', assistantText: '' }
+ } })
+ mirror.ingest(turn, 's')
+ await vi.runAllTimersAsync()
+ expect(desktop).toEqual([])
+ expect(device.at(-1)?.payload.kind).toBe('done')
+ })
+
+ it.each(['replay', 'subagent', 'question'] as const)('updates device recaps silently for %s, with no desktop notification', async mode => {
+ const { mirror, desktop, device, policy } = setup({ isSubagent: () => mode === 'subagent' })
+ mirror.ingest([turn[0]], 's', { replay: mode === 'replay' })
+ if (mode === 'question') {
+ policy.asked('s', 'q')
+ policy.answered('s', 'q')
+ }
+ mirror.ingest(turn.slice(1), 's', { replay: mode === 'replay' })
+ await vi.runAllTimersAsync()
+ expect(desktop[0].payload.notification).toBeNull()
+ expect(device.at(-1)?.payload.subagent).toBe(true)
+ })
+
+ it('ignores aborted, duplicate and superseded ends', async () => {
+ const { mirror, desktop } = setup()
+ mirror.ingest([turn[0], turn[1], { type: 'turn_ended', payload: { aborted: true } }], 'aborted')
+ mirror.ingest(turn, 'superseded')
+ mirror.ingest([turn[0]], 'superseded')
+ mirror.ingest([...turn, turn[2]], 'finished')
+ await vi.runAllTimersAsync()
+ expect(desktop.filter(f => f.payload.notification)).toHaveLength(1)
+ expect(desktop[0].dbSessionId).toBe('finished')
+ })
+
+ it('announces a live completion after attaching midway through the turn', async () => {
+ const { mirror, desktop } = setup()
+ mirror.ingest([turn[0]], 's', { replay: true })
+ mirror.ingest([turn[1]], 's', { replay: true })
+ mirror.ingest(turn.slice(1), 's')
+ await vi.runAllTimersAsync()
+ expect(desktop[0].payload.notification.kind).toBe('done')
+ })
+})
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index af3fa6c35..e34408e63 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -285,8 +285,8 @@ its headless debug timings do not establish native display or network latency.
`grid.AppTheme.brightness`, which `_GridTokenScope` in `main.dart` sets from `Theme.of(context)`.
Chrome widgets call `grid.AppTheme.watch(context)` at the top of `build` so `const` subtrees still
repaint on a theme flip.
-- The [workspace status bar](design/workspace-status-bar.md) places compact numbered tabs on the left
- and focused-pane context on the right. Automatic names use the strongest shared harness type,
+- The [workspace status bar](design/workspace-status-bar.md) places compact numbered tabs and global actions at the top,
+ with focused machine/repo/branch/PR at the bottom left and the model at the bottom right. Automatic names use the strongest shared harness type,
project, or machine, preferring traits that distinguish tabs and excluding dependent viewers.
The context follows a viewer's owner and uses the compact project label, never a worktree path
or marker. User-renamed tabs always retain their saved name. Customize Harness → Status
diff --git a/desktop/design/daemons.md b/desktop/design/daemons.md
index f552e5299..43c242133 100644
--- a/desktop/design/daemons.md
+++ b/desktop/design/daemons.md
@@ -86,9 +86,9 @@ checks hold the AppKit bar to the same with the daemon hidden.
**Appearing.** When daemons turn on (the first 200, or the preview switched
on), the slot takes its space at the first quiet moment: no mouse button held,
-the pointer off the bar, and no key or pointer event for 800 ms (at once when
+the pointer off the bottom status bar, and no key or pointer event for 800 ms (at once when
nothing has been touched yet). Native holds the slot back the same way while a
-button is down or the pointer is on its strip (`daemonMayAppear`). Tabs never
+button is down or the pointer is on its footer (`daemonMayAppear`). Controls never
move under a click.
**The welcome's steps are not the daemon's habits.** `WorkspaceOnboarding` is
@@ -216,7 +216,8 @@ place to practise it.
## Status slot
-Eight cells plus a one-cell gutter each side, far right of the status bar, in
+Eight cells plus a one-cell gutter each side in the bottom status bar, before
+the optional Share action and model selector, in
the bar's font with ligatures off. The face sends its ten cells as drawn
(`statusCell` centred on the version's base sprite, so a borrowed baton or a
nap's `z` grows to the right and the face never shifts). A status cell is
diff --git a/desktop/design/images/workspace-bottom-bar.png b/desktop/design/images/workspace-bottom-bar.png
new file mode 100644
index 000000000..26290edc1
Binary files /dev/null and b/desktop/design/images/workspace-bottom-bar.png differ
diff --git a/desktop/design/images/workspace-notifications.png b/desktop/design/images/workspace-notifications.png
new file mode 100644
index 000000000..f447babf3
Binary files /dev/null and b/desktop/design/images/workspace-notifications.png differ
diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.md
index d9c43e4ce..33f54aaeb 100644
--- a/desktop/design/terminal-workspace.md
+++ b/desktop/design/terminal-workspace.md
@@ -17,9 +17,13 @@ Standalone actions can use brackets, such as `[ Customize Harness ]`, instead
of rounded buttons with pictograms. A checkbox is
`[x]` or `[ ]`. Harness search has no prefix; `#` selects projects and `>` selects
commands as editable text. `@`, `:`, and `*` scope machines, models, and Store
-inside the same picker. The top bar keeps focused model, machine, and project links plus `+` for New
-Tab. Leave global search in Cmd-P and the app menu. Keep descriptive tooltips
-and accessible names.
+inside the same picker. The top row keeps tabs, `+`, a plain search icon, the
+notification bell, and the rounded Harness Store button. The bottom row holds focused
+machine/repo/branch/PR links on the left and the model selector on the right.
+Keep descriptive tooltips and accessible names. Search and bell are deliberate
+icon exceptions; the bell shows a count only when there is something to see.
+Store restores its colorful polymath mark and a quiet filled pill. The bottom
+context has no separate background or divider.
There is no broadly understood ASCII pencil. Keep `[ Customize Harness ]` after
customization as well as before it. The same action should retain its name and
@@ -52,7 +56,7 @@ text shows a hand cursor and bold text on hover, press, and keyboard focus.
Preserve the underlying colors, including filled status segments. Reserve both
text weights during layout so emphasis never shifts neighboring controls.
Resting controls stay unboxed, except the optional Share action: its flat
-primary accent fill makes collaboration visible at the top-right corner.
+primary accent fill makes collaboration visible in the bottom row, before the model.
Settings → Experimental → Share button enables it; it is off by default.
Tooltips describe the
action, not merely the text. Omit a tooltip that repeats the visible name;
@@ -122,7 +126,7 @@ status, or progress to decorate a theme.
## Make context useful
Show the focused pane's model, machine, compact project name, branch, and PR in the
-shared app bar. A dependent viewer uses its owner's context. Keep internal
+bottom status bar. A dependent viewer uses its owner's context. Keep internal
worktree paths and machinery out of everyday labels.
Machine opens the shared picker scoped to that machine. Project opens its harnesses across
diff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.md
index 63f25e852..fba4bc02b 100644
--- a/desktop/design/workspace-status-bar.md
+++ b/desktop/design/workspace-status-bar.md
@@ -1,12 +1,19 @@
# Workspace status bar
-One shared status line, using compact monospace text and measured character cells.
+A navigation row above the panes and a 37.5 pt status row below them, using compact
+monospace text and measured character cells.
Follow the [terminal workspace design system](terminal-workspace.md).
```text
-1:api ? 2:web ⠹ 3:blender ✓ + M2 autonomous-harness (main) [ Share ]
+1:api ? 2:web ⠹ 3:blender ✓ + Search Bell (✿ Harness Store)
+
+ panes
+
+M2 > openharness > branch-name > #439 GPT-6 Astra · Max
```
+![Top navigation and bottom context, rendered with synthetic data](images/workspace-bottom-bar.png)
+
## Tabs on the left
Each tab shows its number and a compact name. A user-entered name always wins:
@@ -24,8 +31,12 @@ is code, and uses machine names for the same project on different computers.
Tabs with identical contents can still share a name; their numbers distinguish
them. Preserve the full name for inspection when its visible label is truncated.
-Center the text with one cell of padding on each side. Cap long labels at 24
-cells and scroll overflow, revealing the selected tab on keyboard navigation.
+Center the text with one cell of padding on each side. Size each tab to its label
+and activity mark, capped at 24 cells. Keep the remaining space after `+` empty
+for dragging the window; adding tabs fills that space one by one. Tabs never
+stretch to fill the row. Scroll overflow when needed, revealing the selected
+tab on keyboard navigation. An exceptionally narrow viewport may show a smaller
+tab, preserving activity marks before truncating names.
There is no close button or reserved close-button space. Cmd-W closes the active
tab; preserve remapped shortcuts, native menu access, and middle-click closing.
Preserve reorder, rename, keyboard focus, and terminal sessions. Cmd-T opens a
@@ -121,8 +132,8 @@ and size.
## Pane controls
-The shared bar shows the focused harness's model selector before machine and
-project. Pane headers keep the harness title and a hover-only ASCII `x` at their
+The bottom bar shows the focused harness's model selector at the right, with
+machine, project, branch and PR at the left. Pane headers keep the harness title and a hover-only ASCII `x` at their
far right. The `x` closes that pane view, keeps its harness running, and uses the
shared bold hover treatment. Its tooltip names Close Pane and the current shortcut.
Reserve its width so revealing it does not move the title.
@@ -131,6 +142,10 @@ For the model label, prefer
its local model ID or the daemon's observed subscription model (`selectedModel`),
such as `GPT-6 Astra`, `Fable`, or `Opus`. Keep versions when reported; never infer
a version from a family alias. Older daemons fall back to the provider name.
+Append the reported effort in the same control, for example `GPT-6 Astra · Max`.
+Model and effort come from the same validated runtime profile and follow pane
+focus together. Missing effort stays absent; never infer it from a model or
+carry subscription effort onto a local model. Effort-only updates repaint too.
Keep this label visible without requiring hover, including while disconnected;
disable switching when the pane is read-only. Use a hand cursor, bold text on hover
and keyboard focus, and a tooltip explaining subscription/local switching.
@@ -152,10 +167,10 @@ access. Keep the resize gaps available for resizing.
Settings → Experimental → Share button is off by default on desktop and web.
The choice persists locally and updates the bar immediately; when off, no button
or space is reserved. [Settings reference](images/share-experimental.png).
-When enabled, Share is a primary action at the far right
-of the top bar, with a flat accent fill, white text, and the same fixed font and
-control height as the other bar actions. Reserve its width before allocating tabs and context. Web
-keeps Download app as a secondary text action immediately before Share.
+When enabled, Share sits in the bottom bar before the model selector, with a
+flat accent fill, white text, and the same fixed font and control height as the
+other bar actions. Reserve its width before allocating context. Web keeps
+Download app as a secondary text action in the same footer.
Clicking Share or pressing Cmd-Shift-S (Alt-Shift-S on web) opens the existing
public/private link dialog for the focused agent. The tooltip and accessibility
label name that agent; the shortcut hint follows remaps. A dependent viewer
@@ -170,9 +185,61 @@ command search. Viewer and message-composer toggles belong in View and command
search. These actions apply to the focused pane; sharing and viewer visibility
follow a dependent viewer's owner.
-## Focused context on the right
-
-Show the focused model, then `machine project`, then `(branch)` when known.
+## Notifications
+
+A small bell sits in the top row between the search icon and the Harness Store button. Reserve four bar cells on both native macOS and Flutter; counts
+never move the other controls. Put the count at the bell's upper-right corner,
+hide it at zero, show `99+` above 99, and keep the exact count in accessibility text.
+The bell has no background or button well, including on hover and keyboard
+focus; emphasize the glyph itself.
+
+Clicking the bell opens a flat, terminal-themed list below the right edge of the
+toolbar. The first line is the session name with a status glyph on the right:
+yellow `?` for needs input, red `✗` for failed, or green `✓` for finished.
+The second line shows `machine repo branch`, aligned with the name, using the
+same project and branch context as the workspace. Omit missing fields.
+Keep full status descriptions in tooltips and accessibility text.
+The list starts newest first, keeps rows still while open, and appends arrivals. Up/Down selects,
+Enter opens, and Escape or an outside click closes. There is no automatic tour
+or advance to another session.
+
+Opening the list does not acknowledge anything. Opening a result reuses its
+existing pane when possible and acknowledges it after successful navigation.
+Questions remain until answered. Unavailable sessions keep their place with an
+`⊘` glyph and the reason in its tooltip and accessibility text; starting or
+failed launches use their existing `◌` or `✗` marks.
+The existing Needs input shortcut stays available.
+
+This reuses the in-memory unread marks, one per harness, and live questions from
+known harnesses. It is not a durable event history. Desktop retains up to 256
+unread harnesses; the dial still receives its newest eight.
+
+Notification eligibility belongs to the daemon's shared `AgentNotifications`
+policy, fed by `CommanderMirror` and `QuestionWatcher`. Desktop consumes the
+notification attached to `turn_summary`; raw turn endings, errors, tools and
+commentary do not create inbox entries. The same decision controls whether the
+device's recap rings or updates silently. Questions stay until the matching
+request is answered. Replays, cancelled turns, subagents, empty results and
+duplicate completions stay silent. Without a device, the daemon derives the
+result locally and does not start a paid summary call. Existing device live
+cards and streaming are unchanged. Completion alerts require the updated daemon;
+older daemons still supply questions but lack the verified completion marker.
+
+![Notification list rendered with synthetic data](images/workspace-notifications.png)
+
+## Focused context in the bottom bar
+
+Center the 28 pt controls within the full space from the pane's bottom edge to
+the window bottom. The former 9.5 pt pane gutter is part of the status row,
+rather than extra padding only above it. Native and Flutter reserve 37.5 pt and
+keep the same pane height, with equal space above and below the footer content.
+
+Show `machine project`, then `(branch)` and PR when known at the left. Put the
+focused model at the far right. The status row has one-cell outer gutters and no background fill or divider;
+its controls sit directly on the workspace surface. Both sides follow
+the focused pane; changing placement preserves each field's existing action.
+The optional companion and Share control sit before the model. At narrow widths,
+truncate labels inside their allocated space rather than overlap controls.
The model is a separate plain text control so switching themes preserves its
click target. A focus change closes its picker; stale native actions and delayed
model selections cannot retarget a different harness.
@@ -330,11 +397,13 @@ References: [Zsh prompt parameters](https://zsh.sourceforge.io/Doc/Release/Param
[Powerlevel10k](https://github.com/romkatv/powerlevel10k).
Pane headers keep task identity and the hover-only close action. The top bar
-contains tabs, New Tab, focused model/machine/project/branch/PR context, and the
-optional Share button.
-Do not add a standalone Search label or category icons at the right edge.
-Context links open the corresponding scope in the unified picker. Global
-search remains available through Cmd-P and the app menu.
+contains tabs, New Tab, a plain search icon, the bell, and the Harness Store button.
+Search opens the existing unified picker; Store opens the existing Store tab.
+The Store restores its earlier rounded pill, colorful polymath mark, and quiet
+tinted fill. Its label is `Harness Store`, without brackets. Keep the full name
+in accessibility and truncate the visible text at narrow widths.
+Both retain their keyboard commands and resolved shortcut hints. Context links
+in the bottom row open the corresponding scope in the unified picker.
The picker's empty preview contains clickable `@ machines`, `# projects`,
`: models`, `* store`, and `> commands` hints. Each inserts its editable prefix
@@ -343,18 +412,17 @@ including API forms, stays inside the right pane. Store results open their
Store page. Cmd-O, Cmd-M, Cmd-I, and Cmd-Shift-P remain shortcuts into the same
picker; focused context links keep their scope.
-Leave a window drag area between tabs and context and prevent overlap in
+Leave a window drag area between tabs and the top actions and prevent overlap in
narrow windows. Native menus and commands remain available.
Only while daemons are on (the account's `GET /api/zoo` answered 200, or a
-person enabled Settings → Experimental → Focus-bar creature), the daemon sits at the far right, directly
-after the focused context and PR. Off, or before that is known, nothing is
+person enabled Settings → Experimental → Focus-bar creature), the daemon sits
+in the footer before the optional Share control and focused model. Off, or before that is known, nothing is
reserved for it and the bar is exactly the one described above; when it turns
on, the slot waits for a quiet moment (no button held, the pointer off the
-bar) so tabs never move under a click. On:
+footer) so controls never move under a click. On:
the paired daemon's sprite, or the nest while the first egg incubates
-(`\_( )_/` `\_(/\)_/` `\_(*')_/` `\_(oo)_/`). Its one-cell inner gutters provide
-separation; add no extra gap or divider. Use the same 13 pt workspace font as
+(`\_( )_/` `\_(/\)_/` `\_(*')_/` `\_(oo)_/`). Its one-cell inner gutters provide separation from neighboring controls. Use the same 13 pt workspace font as
the status line with ligatures off, and reserve eight character cells plus
one-cell gutters, the sprite centred on its version's base sprite, so moods,
work frames and a nap's `z` never move nearby text. It draws in the status
@@ -367,14 +435,16 @@ enters or leaves, so neither the creature nor its neighbors move.
Its name and progress belong in the tooltip and panel, never beside the
sprite. Clicking a ready egg hatches it; otherwise a click boops the daemon and
opens its panel. When something needs you or failed, its one line replaces the
-context, PR and model in the terminal's yellow for 5.2 s, like tmux's message
-line; a reply to a click is dim. Mood and frame updates repaint only the slot.
+left context and PR in the terminal's yellow for 5.2 s, like tmux's message
+line. The model stays available; a reply to a click is dim. Mood and frame updates repaint only the slot.
The contract is [daemons/README.md](../../daemons/README.md); the desktop's
choices are in [Daemons on the desktop](daemons.md).
Data rules live in `lib/state/workspace_status.dart`; prompt formatting lives in
-`lib/shared/theme/status_line_style.dart`. Flutter draws the fallback bar in
-`SwarmScreen`; macOS draws `SwarmTabStrip` in `macos/Runner/SwarmTitlebar.swift`.
+`lib/shared/theme/status_line_style.dart`. Flutter draws both rows in `SwarmScreen`. On macOS, `SwarmTabStrip` keeps native
+tabs/actions in the titlebar and its native footer attaches to the content
+bottom; Flutter reserves matching footer height. See
+`macos/Runner/SwarmTitlebar.swift`.
Both use the same names, formatted context, resolved text/color segments, and
preferences. `WorkspacePullRequest` owns focused PR state; the native and Flutter
bars receive the same validated label and URL. Checks live in
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 228da6e02..c924df805 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -306,6 +306,9 @@ class Agent {
/// of [gridModel], which determines subscription versus local-model routing.
final String? modelName;
+ /// Effort reported with [modelName], never inferred from a model default.
+ final String? modelEffort;
+
/// The grid model this agent is CURRENTLY running on, or null for its own vendor login.
///
/// Read by the daemon off the live process on every discovery, never bookkept — so it is the
@@ -434,6 +437,7 @@ class Agent {
this.engineIconHint,
this.codexHome,
this.modelName,
+ this.modelEffort,
this.gridModel,
this.gridWebSearch,
this.gridBaseUrl,
@@ -554,6 +558,11 @@ class Agent {
final usage = j['tokenUsage'];
final total = usage is Map ? usage['totalTokens'] : null;
final validTokens = total is int && total >= 0 && total <= 9007199254740991;
+ final model = runtimeModelDetails(
+ j['selectedModel'],
+ agentId: j['id'] as String,
+ engine: _safeEngine(j['engine']),
+ );
return Agent(
id: j['id'] as String,
sessionId: _safeLabel(j['sessionId']),
@@ -563,11 +572,8 @@ class Agent {
engineDisplayName: _safeLabel(j['engineDisplayName']),
engineIconHint: _safeLabel(j['engineIconHint']),
codexHome: j['engine'] == 'codex' ? _safeCodexHome(j['codexHome']) : null,
- modelName: runtimeModelName(
- j['selectedModel'],
- agentId: j['id'] as String,
- engine: _safeEngine(j['engine']),
- ),
+ modelName: model?.name,
+ modelEffort: model?.effort,
gridModel: _safeLabel(grid?['model']),
gridWebSearch: GridWebSearch.fromWire(grid?['webSearch']),
gridBaseUrl: _safeUrl(grid?['baseUrl']),
@@ -632,6 +638,7 @@ class Agent {
engineIconHint: engineIconHint,
codexHome: codexHome,
modelName: modelName,
+ modelEffort: modelEffort,
gridModel: gridModel,
gridWebSearch: gridWebSearch,
gridBaseUrl: gridBaseUrl,
diff --git a/desktop/lib/core/runtime_model_name.dart b/desktop/lib/core/runtime_model_name.dart
index 3d891acef..386949650 100644
--- a/desktop/lib/core/runtime_model_name.dart
+++ b/desktop/lib/core/runtime_model_name.dart
@@ -4,6 +4,14 @@ String? runtimeModelName(
Object? value, {
required String agentId,
String? engine,
+}) => runtimeModelDetails(value, agentId: agentId, engine: engine)?.name;
+
+/// Keep the observed effort with its model and validate both against the same
+/// agent/engine identity. Missing metadata never implies a default effort.
+({String name, String effort})? runtimeModelDetails(
+ Object? value, {
+ required String agentId,
+ String? engine,
}) {
if (value is! String || value.length > 1024) return null;
final match = RegExp(
@@ -29,8 +37,10 @@ String? runtimeModelName(
if (claude != null) {
final family = claude[1]!.toLowerCase();
final version = claude[2]?.replaceAll('-', '.');
- return '${family[0].toUpperCase()}${family.substring(1)}'
+ final name =
+ '${family[0].toUpperCase()}${family.substring(1)}'
'${version == null ? '' : ' $version'}${claude[3] ?? ''}';
+ return (name: name, effort: match[4]!.toLowerCase());
}
final gpt = RegExp(
r'^gpt-(\d+(?:\.\d+)*)(?:-(astra|sol|terra|luna|codex))?$',
@@ -38,13 +48,38 @@ String? runtimeModelName(
).firstMatch(model);
if (gpt != null) {
final family = gpt[2]?.toLowerCase();
- return 'GPT-${gpt[1]}${family == null ? '' : ' ${family[0].toUpperCase()}${family.substring(1)}'}';
+ return (
+ name:
+ 'GPT-${gpt[1]}${family == null ? '' : ' ${family[0].toUpperCase()}${family.substring(1)}'}',
+ effort: match[4]!.toLowerCase(),
+ );
}
// Unknown names, dated IDs and local/provider-qualified IDs stay exact.
- return model;
+ return (name: model, effort: match[4]!.toLowerCase());
} on ArgumentError {
return null;
} on FormatException {
return null;
}
}
+
+/// One compact label for native and Flutter model controls. Unknown effort
+/// words stay exact so a newer daemon does not get mislabeled by an older app.
+String modelLabelWithEffort(String model, String? effort) {
+ if (effort == null || effort.isEmpty) return model;
+ final label = switch (effort) {
+ 'auto' => 'Auto',
+ 'none' => 'None',
+ 'off' => 'Off',
+ 'minimal' => 'Minimal',
+ 'low' => 'Low',
+ 'medium' => 'Medium',
+ 'high' => 'High',
+ 'xhigh' => 'XHigh',
+ 'max' => 'Max',
+ 'ultra' => 'Ultra',
+ 'ultracode' => 'Ultracode',
+ _ => effort,
+ };
+ return '$model · $label';
+}
diff --git a/desktop/lib/notify/agent_alerts.dart b/desktop/lib/notify/agent_alerts.dart
index 542ace6b1..9d7ea4ed4 100644
--- a/desktop/lib/notify/agent_alerts.dart
+++ b/desktop/lib/notify/agent_alerts.dart
@@ -34,6 +34,7 @@ class AgentAlert {
/// What the banner says under the agent's name.
String get sentence => switch (kind) {
AlertKind.done => 'Finished',
+ AlertKind.failed => 'Failed',
AlertKind.needsYou => 'Waiting on you',
};
}
@@ -151,13 +152,10 @@ class AgentAlerts extends ChangeNotifier {
/// until somebody goes looking. Somebody who turned the noisy halves off still
/// wants the window to be able to say which agent moved while they were away.
class AgentUnread extends ChangeNotifier {
- /// As many agents as the dial's drawer holds rows (`NOTIF_MAX`), and dropped
- /// the same way: oldest first.
- ///
- /// A window with no ceiling and a dial with one are two different numbers the
- /// moment a ninth agent has news, whatever else agrees. Dart's map keeps
- /// insertion order, and [mark] re-inserts, so the first key is the oldest.
- static const capacity = 8;
+ /// Bound the desktop inbox independently of the dial's eight visible rows.
+ /// A ninth notification must not silently replace the first on desktop.
+ /// Entries remain per harness and in memory, with oldest-first eviction.
+ static const capacity = 256;
final _unread = <String, AlertKind>{};
diff --git a/desktop/lib/notify/alert_sounds.dart b/desktop/lib/notify/alert_sounds.dart
index 1df0e3ca6..012d3eb85 100644
--- a/desktop/lib/notify/alert_sounds.dart
+++ b/desktop/lib/notify/alert_sounds.dart
@@ -8,11 +8,14 @@ import 'package:flutter/services.dart';
import '../core/harness_file_store.dart';
import '../core/local_key_value_store.dart';
-/// What an alert is FOR. The two moments worth interrupting someone over.
+/// What happened on a harness while the person was looking elsewhere.
enum AlertKind {
/// An agent finished its turn. The work you were waiting on is on screen.
done('Glass'),
+ /// A turn ended with an error. Keep the existing turn-end sound.
+ failed('Glass'),
+
/// An agent stopped and is waiting on a person — a question, a permission.
/// Nothing moves until somebody answers, which is why it is the more
/// insistent of the two sounds.
@@ -104,15 +107,15 @@ class AlertSounds {
final MethodChannel _channel;
final DateTime Function() now;
- /// The least time between two sounds of the same kind.
+ /// The least time between two plays of the same sound.
///
/// A swarm is many agents, and a batch of them finishing together is the
/// ordinary case rather than the rare one — without this it is a burst of
- /// beeps that says nothing more than one beep would. Per KIND, so an agent
+ /// beeps that says nothing more than one beep would. Per sound, so an agent
/// finishing never swallows the more urgent "somebody is waiting on you".
final Duration gap;
- final _lastPlayed = <AlertKind, DateTime>{};
+ final _lastPlayed = <String, DateTime>{};
/// Ask for a sound. Silent when the feature is off, and when the same kind
/// played within [gap].
@@ -123,9 +126,9 @@ class AlertSounds {
void play(AlertKind kind) {
if (!store.value) return;
final at = now();
- final last = _lastPlayed[kind];
+ final last = _lastPlayed[kind.sound];
if (last != null && at.difference(last) < gap) return;
- _lastPlayed[kind] = at;
+ _lastPlayed[kind.sound] = at;
unawaited(
_channel
.invokeMethod<void>('playAlert', {'sound': kind.sound})
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 8d2dfea50..6cc532a5d 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -1,5 +1,6 @@
import 'dart:math' as math;
import 'dart:async';
+
import 'dart:convert';
import 'package:file_selector/file_selector.dart';
@@ -9,6 +10,7 @@ import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:xterm/xterm.dart' show TerminalTheme;
import '../core/runtime_platform.dart';
@@ -40,6 +42,9 @@ import '../shortcuts/keymap_host.dart';
import '../shortcuts/keymap_native.dart';
import '../shortcuts/keymap_settings.dart';
import '../state/app_state.dart';
+import '../state/notification_inbox.dart';
+import '../widgets/notification_inbox.dart';
+import '../widgets/workspace_notifications_button.dart';
import '../state/harness_sessions.dart';
import '../state/harness_activity.dart';
import '../state/harness_placement.dart';
@@ -71,6 +76,7 @@ import '../widgets/workspace_bar_control.dart';
import '../widgets/session_work_dialog.dart';
import '../widgets/web_download_button.dart';
import '../widgets/workspace_share_button.dart';
+import '../widgets/workspace_store_button.dart';
import '../widgets/grid_model_picker.dart';
import '../store/store_mark.dart';
import '../store/store_screen.dart';
@@ -1003,14 +1009,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
int get _attention => _sessions.where((row) => row.needsInput).length;
- /// Agents carrying news nobody has looked at.
- ///
- /// This is what the icon's badge counts now, and it is a wider question than
- /// [_attention]: a harness that FINISHED is also something to go and see, and
- /// the badge that only counted blocked ones said nothing at all about the
- /// work that was actually done while you were away. The panel behind the icon
- /// still separates the two — its "Needs input" tab is exactly [_attention].
- int get _unread => app.agentUnread.count;
+ /// The bell and its list count the same current questions and unread results.
+ int get _unread => notificationInbox(app).length;
/// Whose window this is, or null while a signed-in window still waits for
/// its profile. Syncing earlier keyed the first reads by a temporary scope
@@ -1549,6 +1549,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
'enabled': _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen,
'reduceMotion': _reduceMotion,
'activeId': app.activeSwarmId,
+ 'searchTooltip':
+ 'Search harnesses ${_keymap.hint('harnesses.list') ?? ''}',
+ 'storeTooltip': 'Harness Store ${_keymap.hint('app.store') ?? ''}',
// The selected tab is drawn with keyboard focus: ⏎ goes into it.
'tabsFocused': app.tabStripFocused && _tabStripFocus.hasPrimaryFocus,
// Only once the slot is shown: until then (and whenever daemons are
@@ -1565,10 +1568,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
'focusedModel': focused == null || !modelPickerSupports(focused.engine)
? null
: {
- 'text': focused.provider,
+ 'text': focused.modelLabel,
'segments': [
{
- 'text': focused.provider,
+ 'text': focused.modelLabel,
'foreground': terminalTheme.foreground.toARGB32(),
},
],
@@ -1673,12 +1676,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
},
],
'attention': _attention,
- // The badge the NATIVE titlebar draws. It is a wider question than
- // `attention`, which counts only harnesses that are blocked: a harness
- // that FINISHED is also something to go and see. Sent beside the old key
- // rather than replacing it, because the native side still words its
- // accessibility value from "needs input" and an older Runner ignores a
- // key it does not know.
+ // The native bell uses the same inbox count as its Flutter counterpart.
'unread': _unread,
'sessionsOpen': _harnessesVisible,
'machinesOpen': _machinesVisible,
@@ -2186,6 +2184,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.focusedPane?.session?.find(TerminalFindAction.previous);
case 'notifications':
unawaited(_notifications());
+ case 'notificationInbox':
+ unawaited(_showNotificationInbox());
case 'settings':
await _settings();
case 'addPhone':
@@ -2202,6 +2202,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
'renameActive',
'commands',
'notifications',
+ 'notificationInbox',
'addAgent',
'newAgent',
'newTerminal',
@@ -3556,10 +3557,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
// Until the slot has its place: whether a button is held and whether
// the pointer is on the bar, so it never arrives under a click.
_pointerHeld = event.down;
+ final workspace = context.findRenderObject();
_pointerOverBar =
!_native &&
event is! PointerRemovedEvent &&
- event.position.dy <= _tabBarHeight;
+ workspace is RenderBox &&
+ workspace.globalToLocal(event.position).dy >=
+ workspace.size.height - _statusBarHeight;
_noteWindowInput();
}
if (!_zoo.loaded) return;
@@ -4010,7 +4014,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
setState(() {});
}
- /// The panel and the hatch reveal float beside the status slot, at the top
+ /// The panel and the hatch reveal float above the status slot, at the bottom
/// right, with a barrier that closes them: [cells] terminal cells wide at
/// most (the reveal is wider, for a plate's 56 columns).
Widget _anchoredBesideSlot({
@@ -4020,6 +4024,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
}) => LayoutBuilder(
builder: (context, constraints) {
final top = _native ? 0.0 : _tabBarHeight;
+ final bottom = _statusBarHeight;
return Stack(
children: [
Positioned.fill(
@@ -4031,7 +4036,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
Positioned(
- top: top + 8,
+ bottom: bottom + 8,
right: 10,
width: (constraints.maxWidth - 20).clamp(
0,
@@ -4039,7 +4044,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
child: ConstrainedBox(
constraints: BoxConstraints(
- maxHeight: (constraints.maxHeight - top - 20).clamp(0, 720),
+ maxHeight: (constraints.maxHeight - top - bottom - 20).clamp(
+ 0,
+ 720,
+ ),
),
child: KeymapProvider(keymap: _keymap, child: child),
),
@@ -5218,6 +5226,33 @@ class _SwarmScreenState extends State<SwarmScreen> {
_toggleSessions(filter: SessionFilter.needsInput);
}
+ Future<void> _showNotificationInbox() => _dialog(() async {
+ await showNotificationInbox(
+ context,
+ app: app,
+ topInset: _native ? 0 : _tabBarHeight,
+ onOpen: (row) async {
+ final destination = swarmDestinations(app)
+ .where(
+ (item) =>
+ item.machineId == row.machineId &&
+ item.agentId == row.agentId,
+ )
+ .firstOrNull;
+ if (destination == null) return false;
+ final opened = await activateSwarmDestination(
+ app,
+ destination,
+ destinationSwarmId: app.activeSwarmId,
+ );
+ // Only successful navigation acknowledges a result. Questions remain
+ // pending until the daemon confirms they have been answered.
+ if (opened) app.markAgentSeen(row.machineId, row.agentId);
+ return opened;
+ },
+ );
+ });
+
Future<void> _openSpokenTask(SpokenTaskRequest request) async {
final spoken = SpokenTask(
voiceId: request.voiceId,
@@ -5848,11 +5883,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
? const SizedBox.shrink()
: MediaQuery.withNoTextScaling(child: _tabStrip()),
),
- if (_native)
- _focusedModelPicker(
- WorkspacePaneContext.focused(app),
- menuOnly: true,
- ),
if (_learning.active)
WorkspaceQuickStart(
learning: _learning,
@@ -5960,7 +5990,12 @@ class _SwarmScreenState extends State<SwarmScreen> {
child: Padding(
padding: app.panes.isEmpty
? EdgeInsets.zero
- : const EdgeInsets.all(kWorkspaceInset),
+ : const EdgeInsets.fromLTRB(
+ kWorkspaceInset,
+ kWorkspaceInset,
+ kWorkspaceInset,
+ 0,
+ ),
child: Focus.withExternalFocusNode(
focusNode: _canvasFocus,
includeSemantics: false,
@@ -6086,6 +6121,18 @@ class _SwarmScreenState extends State<SwarmScreen> {
],
),
),
+ MediaQuery.withNoTextScaling(
+ child: _native
+ ? SizedBox(
+ key: const ValueKey('workspace-status-bar'),
+ height: _statusBarHeight,
+ child: _focusedModelPicker(
+ WorkspacePaneContext.focused(app),
+ menuOnly: true,
+ ),
+ )
+ : _statusBar(),
+ ),
],
),
),
@@ -6207,6 +6254,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
machineId: focused.pane.machineId,
currentModel: focused.agent?.gridModel,
subscriptionModel: focused.agent?.modelName,
+ subscriptionEffort: focused.agent?.modelEffort,
webSearch: focused.agent?.gridWebSearch,
engineLabel: focused.engine,
onOpen: () {
@@ -6241,52 +6289,22 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
}
- Widget _tabStrip() => LayoutBuilder(
+ // Include the pane's former bottom gutter in this row, so its controls sit
+ // halfway between the pane edge and window bottom. Pane height is unchanged.
+ double get _statusBarHeight =>
+ workspaceBarControlHeight(context) + kWorkspaceInset;
+
+ Widget _statusBar() => LayoutBuilder(
builder: (context, constraints) {
final cell = workspaceBarCellSizeOf(context);
+ final focused = WorkspacePaneContext.focused(app);
+ final prefs = appearancePrefsStore.value.prompt;
+ final parts = focused?.format(prefs);
+ final pr = _pullRequest.value;
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
);
- final names = workspaceTabNames(app);
- final activities = [for (final tab in app.swarms) tabActivity(app, tab)];
- final labels = [
- for (var index = 0; index < app.swarms.length; index++)
- '${index + 1}:${names[app.swarms[index].id]}',
- ];
- // No space is kept for the slot until it is shown: off (or not decided
- // yet) the bar is exactly the one it was before daemons existed.
- final daemonSpace = _slotShown
- ? cell.width * (_face.roster.rules.statusCells + 2)
- : 0.0;
- final toolHeight = workspaceBarControlHeight(context);
- final pr = _pullRequest.value;
- final downloadWidth = kIsWeb
- ? WebDownloadButton.widthOf(context) + cell.width
- : 0.0;
- final shareWidth = _showShareButton
- ? WorkspaceShareButton.widthOf(context) + cell.width
- : 0.0;
- final contentWidth = math.max(
- 0.0,
- constraints.maxWidth -
- cell.width * 7 -
- downloadWidth -
- shareWidth -
- daemonSpace,
- );
- final focused = WorkspacePaneContext.focused(app);
- final prefs = appearancePrefsStore.value.prompt;
- final parts = focused?.format(prefs);
- final contextWidth = parts == null
- ? 0.0
- : workspaceStatusLineWidthsOf(
- context,
- parts,
- ).fold(0.0, (a, b) => a + b);
- final modelWidth = focused != null && modelPickerSupports(focused.engine)
- ? workspaceBarTextSizeOf(context, focused.provider).width + cell.width
- : 0.0;
final joined =
prefs.statusStyle.segmented &&
parts != null &&
@@ -6304,24 +6322,151 @@ class _SwarmScreenState extends State<SwarmScreen> {
color: prefs.color,
segmentOffset: parts.segments.length,
).single.background;
- final prWidth = pr == null
- ? 0.0
- : WorkspacePullRequestLabel.widthOf(
- context,
- pr.number,
+ final available = math.max(0.0, constraints.maxWidth - cell.width * 2);
+ final daemonWidth = _slotShown
+ ? math.min(
+ cell.width * (_face.roster.rules.statusCells + 2),
+ available * .5,
+ )
+ : 0.0;
+ final shareWidth = _showShareButton
+ ? math.min(WorkspaceShareButton.widthOf(context), available * .3)
+ : 0.0;
+ final downloadWidth = kIsWeb ? available * .16 : 0.0;
+ final modelWidth =
+ math.max(
+ 0.0,
+ available -
+ daemonWidth -
+ shareWidth -
+ downloadWidth -
+ cell.width * 5,
+ ) *
+ .4;
+ final paneContext = Row(
+ children: [
+ if (focused != null)
+ Flexible(
+ child: WorkspaceStatusLine(
+ key: const ValueKey('workspace-pane-context'),
+ parts: parts!,
+ links: _contextLinks(focused),
+ color: prefs.color,
+ nextBackground: prBackground,
+ ),
+ ),
+ if (pr != null) ...[
+ if (!joined) SizedBox(width: cell.width),
+ ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: constraints.maxWidth * .2),
+ child: WorkspaceBarControl(
+ key: const ValueKey('workspace-pull-request'),
+ label: '${pr.label} — Open on GitHub',
+ tooltip: '${pr.label} — Open on GitHub',
+ onPressed: _shortcutsEnabled
+ ? () => _openFocusedPullRequest(pr.url.toString())
+ : null,
+ builder: (context, emphasized) => WorkspacePullRequestLabel(
+ number: pr.number,
+ state: pr.state,
+ emphasized: emphasized,
+ color: prefs.color,
style: prefs.statusStyle,
- ) +
- (joined ? 0 : cell.width);
- // Reserve only the context's actual width, capped at 40% / 52 cells.
- // Tabs get the rest; unused tab space flows back to the full context.
- final statusBudget = math.min(
- math.max(
- contextWidth + modelWidth + prWidth,
- _slotShown ? cell.width * 32 : 0,
+ segmentOffset: parts?.segments.length ?? 0,
+ ),
+ ),
+ ),
+ ],
+ ],
+ );
+ return Material(
+ key: const ValueKey('workspace-status-bar'),
+ type: MaterialType.transparency,
+ child: SizedBox(
+ height: _statusBarHeight,
+ child: Padding(
+ padding: EdgeInsets.symmetric(horizontal: cell.width),
+ child: Row(
+ children: [
+ Expanded(
+ child: _zoo.loaded
+ ? DaemonVoiceLine(
+ face: _face,
+ brain: _brain,
+ onAnswer: _shortcutsEnabled ? _answerDaemon : null,
+ fallback: paneContext,
+ )
+ : paneContext,
+ ),
+ if (kIsWeb) ...[
+ SizedBox(width: cell.width),
+ ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: downloadWidth),
+ child: const WebDownloadButton(),
+ ),
+ ],
+ if (_slotShown)
+ ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: daemonWidth),
+ child: DaemonSlotButton(
+ face: _face,
+ tooltip: () => _daemonTooltip,
+ selected: _daemonOverlay != null,
+ onPressed: _activateDaemon,
+ ),
+ ),
+ if (_showShareButton) ...[
+ SizedBox(width: cell.width),
+ ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: shareWidth),
+ child: WorkspaceShareButton(
+ key: const ValueKey('workspace-share-button'),
+ label: _shareLabel(focused),
+ tooltip: _shareTooltip(focused),
+ onPressed: _canExecuteCommand('agent.share')
+ ? () => _runShortcut('agent.share')
+ : null,
+ ),
+ ),
+ ],
+ if (focused != null && modelPickerSupports(focused.engine)) ...[
+ SizedBox(width: cell.width * 2),
+ ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: modelWidth),
+ child: _focusedModelPicker(focused),
+ ),
+ ],
+ ],
+ ),
+ ),
),
- math.min(contentWidth * .4, cell.width * 52),
);
- final tabBudget = math.max(0.0, contentWidth - statusBudget);
+ },
+ );
+
+ Widget _tabStrip() => LayoutBuilder(
+ builder: (context, constraints) {
+ final cell = workspaceBarCellSizeOf(context);
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ final names = workspaceTabNames(app);
+ final activities = [for (final tab in app.swarms) tabActivity(app, tab)];
+ final labels = [
+ for (var index = 0; index < app.swarms.length; index++)
+ '${index + 1}:${names[app.swarms[index].id]}',
+ ];
+ final toolHeight = workspaceBarControlHeight(context);
+ final prefs = appearancePrefsStore.value.prompt;
+ final storeWidth = math.min(
+ WorkspaceStoreButton.widthOf(context),
+ math.max(0.0, constraints.maxWidth - cell.width * 14),
+ );
+ final tabBudget = math.max(
+ 0.0,
+ constraints.maxWidth - cell.width * 6 - storeWidth - cell.width * 8,
+ );
_tabWidths = [
for (var i = 0; i < labels.length; i++)
math.max(
@@ -6341,71 +6486,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
final total = _tabWidths.fold(0.0, (sum, width) => sum + width);
final tabsWidth = math.min(total, tabBudget);
_revealSelectedTab(tabsWidth);
- // The context, and the pull request beside it: exactly the bar from
- // before daemons existed, which the daemon's line covers only while
- // daemons are on.
- final paneContext = Align(
- alignment: Alignment.centerRight,
- child: SizedBox(
- child: SizedBox(
- key: const ValueKey('workspace-pane-context'),
- child: focused == null
- ? const SizedBox.shrink()
- : LayoutBuilder(
- builder: (context, constraints) => Row(
- mainAxisSize: MainAxisSize.min,
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- if (modelPickerSupports(focused.engine) &&
- constraints.maxWidth >= cell.width * 12) ...[
- ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: constraints.maxWidth * .35,
- ),
- child: _focusedModelPicker(focused),
- ),
- SizedBox(width: cell.width),
- ],
- Flexible(
- child: WorkspaceStatusLine(
- parts: parts!,
- links: _contextLinks(focused),
- color: prefs.color,
- nextBackground: prBackground,
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- );
- final prControl = pr == null
- ? const <Widget>[]
- : <Widget>[
- if (!joined) SizedBox(width: cell.width),
- ConstrainedBox(
- constraints: BoxConstraints(maxWidth: contentWidth * .28),
- child: WorkspaceBarControl(
- key: const ValueKey('workspace-pull-request'),
- label: '${pr.label} — Open on GitHub',
- tooltip: '${pr.label} — Open on GitHub',
- onPressed: _shortcutsEnabled
- ? () => _openFocusedPullRequest(pr.url.toString())
- : null,
- builder: (context, emphasized) => WorkspacePullRequestLabel(
- number: pr.number,
- state: pr.state,
- emphasized: emphasized,
- color: prefs.color,
- style: prefs.statusStyle,
- segmentOffset: parts?.segments.length ?? 0,
- ),
- ),
- ),
- ];
return Material(
- key: const ValueKey('workspace-status-bar'),
+ key: const ValueKey('workspace-tab-bar'),
color: grid.AppPalette.swarmTabBar,
child: SizedBox(
height: math.max(_tabBarHeight, cell.height * 2),
@@ -6568,55 +6650,41 @@ class _SwarmScreenState extends State<SwarmScreen> {
theme,
tooltip: 'New Tab ${_keymap.hint('swarm.new') ?? ''}',
),
- SizedBox(width: cell.width * 2),
- Expanded(
- // While the daemon speaks, its line replaces the context, as
- // tmux's message line replaces the status line.
- child: _zoo.loaded
- ? DaemonVoiceLine(
- face: _face,
- brain: _brain,
- onAnswer: _shortcutsEnabled ? _answerDaemon : null,
- fallback: paneContext,
- )
- : paneContext,
- ),
- if (pr != null)
- if (_zoo.loaded)
- ValueListenableBuilder<String?>(
- valueListenable: _face.voiceLine,
- builder: (context, voice, _) => voice != null
- ? const SizedBox.shrink()
- : Row(
- mainAxisSize: MainAxisSize.min,
- children: prControl,
- ),
- )
- else
- ...prControl,
- if (kIsWeb) ...[
- SizedBox(width: cell.width),
- const WebDownloadButton(),
- ],
- // Beside Share in the focus bar (desktop/design/daemons.md).
- if (_slotShown)
- DaemonSlotButton(
- face: _face,
- tooltip: () => _daemonTooltip,
- selected: _daemonOverlay != null,
- onPressed: _activateDaemon,
- ),
- if (_showShareButton) ...[
- SizedBox(width: cell.width),
- WorkspaceShareButton(
- key: const ValueKey('workspace-share-button'),
- label: _shareLabel(focused),
- tooltip: _shareTooltip(focused),
- onPressed: _canExecuteCommand('agent.share')
- ? () => _runShortcut('agent.share')
- : null,
+ const Spacer(),
+ WorkspaceBarControl(
+ key: const ValueKey('swarm-search-button'),
+ label: 'Search harnesses',
+ tooltip:
+ 'Search harnesses ${_keymap.hint('harnesses.list') ?? ''}',
+ onPressed: _shortcutsEnabled ? _toggleSessions : null,
+ builder: (context, emphasized) => SizedBox(
+ width: cell.width * 4,
+ height: toolHeight,
+ child: Icon(
+ LucideIcons.search,
+ size: 17,
+ color: theme.foreground.withValues(
+ alpha: !_shortcutsEnabled
+ ? .28
+ : emphasized
+ ? 1
+ : .75,
+ ),
+ ),
),
- ],
+ ),
+ WorkspaceNotificationsButton(
+ key: const ValueKey('workspace-notifications-button'),
+ count: _unread,
+ foreground: theme.foreground,
+ onPressed: _shortcutsEnabled ? _showNotificationInbox : null,
+ ),
+ WorkspaceStoreButton(
+ key: const ValueKey('swarm-store-button'),
+ width: storeWidth,
+ tooltip: 'Harness Store ${_keymap.hint('app.store') ?? ''}',
+ onPressed: _shortcutsEnabled ? _openStore : null,
+ ),
SizedBox(width: cell.width),
],
),
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 4c8fb3669..0a2b9c273 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -543,6 +543,9 @@ class AppNotifier extends ChangeNotifier {
/// Which agents have news nobody has looked at. Marked on the same two
/// moments and NOT behind the banner or sound switches — see [AgentUnread].
final AgentUnread agentUnread;
+ // Delivery deduplication only. The daemon owns notification eligibility for
+ // both desktop and device; a raw turn_ended is not a completed result.
+ final Set<String> _deliveredNotifications = {};
AppConfig config;
late ApiClient api;
@@ -2529,10 +2532,10 @@ class AppNotifier extends ChangeNotifier {
/// The dial belongs to whichever daemon owns the cable, and only a complete
/// roster lets that one judge; the others store a list they never use, which
/// costs nothing and saves the window from having to know which is which.
- /// THE WHOLE UNREAD LIST, for a dial that has just lost its own.
+ /// The newest eight unread harnesses, for a dial that has lost its drawer.
///
/// The dial keeps its drawer in RAM, so a reboot — an OTA, a replug, a flash —
- /// wipes it while this window still holds every mark. Measured: a turn ended
+ /// wipes it while this window still holds its marks. Measured: a turn ended
/// at 17:46:19, the dial came back at 17:46:26, a question arrived at
/// 17:46:28, and the two screens then read 2 and 1 forever.
///
@@ -2540,12 +2543,13 @@ class AppNotifier extends ChangeNotifier {
/// can hand it over the moment a cable attaches, without a round trip to a
/// window that may be busy. Ids and kinds only — the daemon already knows each
/// agent's name, machine and last recap, and re-deriving them here would be a
- /// second place for them to be wrong.
+ /// second place for them to be wrong. The desktop inbox can retain more than
+ /// the dial's eight rows; sending only that window preserves the wire limit.
void _announceUnreadToDial() {
final pool = _pool;
if (pool == null) return;
final items = [
- for (final mark in agentUnread.newestFirst)
+ for (final mark in agentUnread.newestFirst.take(8))
{
'agentId': mark.agentId,
'machineId': mark.machineId,
@@ -5243,6 +5247,7 @@ class AppNotifier extends ChangeNotifier {
prev.engineIconHint != agent.engineIconHint ||
prev.codexHome != agent.codexHome ||
prev.modelName != agent.modelName ||
+ prev.modelEffort != agent.modelEffort ||
prev.parentAgentId != agent.parentAgentId ||
prev.project != agent.project ||
prev.gitContext != agent.gitContext ||
@@ -7271,7 +7276,8 @@ class AppNotifier extends ChangeNotifier {
// times its tab came to the front, and a badge that stopped counting it
// would be saying the work was done because somebody glanced at it. It
// goes when the question is ANSWERED (`commander_question_close`).
- if (agentUnread.kindFor(w.machineId, w.agentId) != AlertKind.done) {
+ final kind = agentUnread.kindFor(w.machineId, w.agentId);
+ if (kind == null || kind == AlertKind.needsYou) {
continue;
}
_forgetUnread(w.machineId, w.agentId);
@@ -7413,7 +7419,8 @@ class AppNotifier extends ChangeNotifier {
/// Same rule as the sweep: arriving at a blocked harness is not answering it,
/// so its mark stays. See [seeWatchedAgents].
void markAgentSeen(String machineId, String agentId) {
- if (agentUnread.kindFor(machineId, agentId) != AlertKind.done) return;
+ final kind = agentUnread.kindFor(machineId, agentId);
+ if (kind == null || kind == AlertKind.needsYou) return;
_forgetUnread(machineId, agentId);
}
@@ -7568,7 +7575,11 @@ class AppNotifier extends ChangeNotifier {
modelStarts.start(machineId, agentId);
}
- void _cancelTurnActivity(String machineId, String agentId) {
+ void _cancelTurnActivity(
+ String machineId,
+ String agentId, {
+ bool clearQuestion = true,
+ }) {
final key = _turnActivityKey(machineId, agentId);
_turnActivityWatchdogs.remove(key)?.cancel();
// Every ordinary end of a turn comes through here — `turn_ended`, a
@@ -7581,11 +7592,9 @@ class AppNotifier extends ChangeNotifier {
modelStarts.end(machineId, agentId);
final machine = machineStates[machineId];
machine?.processingAgentIds.remove(agentId);
- // A question cannot outlive its own turn — the daemon's watcher says the
- // same thing from the other end, tearing down and announcing a close when
- // the turn ends. Clearing here as well means the row cannot survive a close
- // frame that was dropped, and this is also the path a deleted agent takes.
- machine?.blockedAgents.remove(agentId);
+ // Raw turn endings do not decide whether a question is answered. The
+ // shared daemon question-close event does. Disconnect/deletion still clear.
+ if (clearQuestion) machine?.blockedAgents.remove(agentId);
}
void _clearMachineActivity(MachineState machine) {
@@ -10217,8 +10226,7 @@ class AppNotifier extends ChangeNotifier {
paneOfAgent(machineId, agentId) ??
allPanes
.where(
- (pane) =>
- pane.machineId == machineId && pane.agentId == agentId,
+ (pane) => pane.machineId == machineId && pane.agentId == agentId,
)
.firstOrNull;
if (existing == null) {
@@ -12822,46 +12830,12 @@ class AppNotifier extends ChangeNotifier {
final requestId = payload['requestId'];
if (agentId != null) {
final open = machine.blockedAgents[agentId];
- // A stale close must not wipe the question that REPLACED it when a
- // dialog advanced to its next page. That is the only thing the id
- // guards, so it is asked as its own question and nothing else hangs
- // off it.
- final supersededByANewerQuestion =
- open != null &&
- requestId is String &&
- requestId.isNotEmpty &&
- open.requestId != requestId;
- if (!supersededByANewerQuestion) {
+ if (open != null && open.requestId == requestId) {
machine.blockedAgents.remove(agentId);
- // A question stops being unread when it is ANSWERED, wherever that
- // happened — here, in the pane by hand, on the dial, in another
- // window. Being looked at is not enough: the badge counts what is
- // still waiting on a person.
- //
- // ⚠️ NOT nested inside "the dialog is still open". It was, and the
- // mark then outlived its own question: answering makes the turn end
- // too, `_cancelTurnActivity` clears `blockedAgents` on the way past,
- // and whichever of the two frames lands first decides whether this
- // runs at all. The close is the authoritative word that the question
- // is answered; the dialog bookkeeping is a separate thing that may
- // already have been tidied.
- //
- // WHATEVER THE MARK IS, not only a question's.
- //
- // Answering ENDS THE TURN for these engines — measured, one
- // millisecond apart and the turn first:
- //
- // 18:04:58.534 [turn] 395050e8 ended · 65175ms
- // 18:04:58.535 [question] 395050e8 answered elsewhere · closing
- //
- // so the `done` that lands with every answer overwrote the question
- // mark and the badge never went down. Reading it as news is wrong on
- // its face: a turn that ended in the same breath as your own answer
- // is not something that happened while you were away.
- //
- // A close means somebody just dealt with this agent. Anything unread
- // for it at that moment is about the work they were standing over.
- _forgetUnread(machine.machine.machineId, agentId);
+ // An old question close cannot erase a newer completed result.
+ if (agentUnread.kindFor(machineId, agentId) == AlertKind.needsYou) {
+ _forgetUnread(machineId, agentId);
+ }
}
}
break;
@@ -12897,6 +12871,20 @@ class AppNotifier extends ChangeNotifier {
// agent first becomes busy. Expiry and turn end publish separately.
if (!changed) return;
break;
+ case 'turn_summary':
+ final notification = payload['notification'];
+ final agentId = _eventAgentId(machine, event, payload);
+ if (agentId == null || notification is! Map) return;
+ final id = notification['id'];
+ if (id is! String || id.isEmpty || notification['kind'] != 'done') {
+ return;
+ }
+ if (!_deliveredNotifications.add('$machineId/$id')) return;
+ while (_deliveredNotifications.length > 512) {
+ _deliveredNotifications.remove(_deliveredNotifications.first);
+ }
+ _raiseAlert(machine, agentId, AlertKind.done);
+ break;
case 'turn_ended':
final agentId = _eventAgentId(machine, event, payload);
if (agentId != null) {
@@ -12907,7 +12895,7 @@ class AppNotifier extends ChangeNotifier {
// project of four specialists put one row on the dial and five marks
// here. Same predicate now, asked on the daemon: `isSubagentSession`.
if (event['subagent'] != true) {
- _raiseAlert(machine, agentId, AlertKind.done);
+ final failed = event['error'] != null || payload['error'] != null;
final agent = machine.agents
.where((a) => a.id == agentId)
.firstOrNull;
@@ -12921,7 +12909,6 @@ class AppNotifier extends ChangeNotifier {
pane.agentId == agentId &&
pane.session != null,
);
- final failed = event['error'] != null || payload['error'] != null;
// Activity belongs to the harness, even if its pane is currently
// detached. The zoo counters below still count only our own work.
if (agent != null && !isTerminalEngine(agent.engine)) {
@@ -12958,7 +12945,11 @@ class AppNotifier extends ChangeNotifier {
machine.zooTurns++;
}
}
- _cancelTurnActivity(machine.machine.machineId, agentId);
+ _cancelTurnActivity(
+ machine.machine.machineId,
+ agentId,
+ clearQuestion: false,
+ );
} else {
final sessionId = _eventSessionId(event, payload);
if (sessionId != null) {
diff --git a/desktop/lib/state/notification_inbox.dart b/desktop/lib/state/notification_inbox.dart
new file mode 100644
index 000000000..43c6942ff
--- /dev/null
+++ b/desktop/lib/state/notification_inbox.dart
@@ -0,0 +1,77 @@
+import '../notify/alert_sounds.dart';
+import 'app_state.dart';
+import 'harness_activity.dart';
+import 'harness_sessions.dart';
+
+/// A current question or an unread result, using the existing alert ledger.
+class InboxNotification {
+ const InboxNotification({
+ required this.machineId,
+ required this.agentId,
+ required this.title,
+ required this.detail,
+ required this.kind,
+ required this.unavailable,
+ });
+
+ final String machineId, agentId, title, detail;
+ final AlertKind kind;
+ final String? unavailable;
+ String get id => '$machineId/$agentId';
+ String get label => switch (kind) {
+ AlertKind.needsYou => 'Needs input',
+ AlertKind.failed => 'Failed',
+ AlertKind.done => 'Finished',
+ };
+ HarnessActivity get activity => switch (kind) {
+ AlertKind.needsYou => HarnessActivity.needsInput,
+ AlertKind.failed => HarnessActivity.failed,
+ AlertKind.done => HarnessActivity.done,
+ };
+}
+
+List<InboxNotification> notificationInbox(AppNotifier app) {
+ final kinds = <(String, String), AlertKind>{
+ for (final item in app.agentUnread.newestFirst)
+ (item.machineId, item.agentId): item.kind,
+ };
+ // Questions survive a reconnect and remain actionable even if an old unread
+ // mark was evicted. Merely opening this list never acknowledges a question.
+ for (final row in harnessSessions(app)) {
+ if (row.needsInput) {
+ kinds[(row.machineId, row.agent.id)] = AlertKind.needsYou;
+ }
+ }
+ return [
+ for (final entry in kinds.entries)
+ ?_notification(app, entry.key.$1, entry.key.$2, entry.value),
+ ];
+}
+
+InboxNotification? _notification(
+ AppNotifier app,
+ String machineId,
+ String agentId,
+ AlertKind kind,
+) {
+ final machine = app.stateOf(machineId);
+ final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
+ final question = app.questionFor(machineId, agentId);
+ // A question that closed is no longer a notification to answer.
+ if (kind == AlertKind.needsYou && question == null) return null;
+ final current = question != null ? AlertKind.needsYou : kind;
+ final project = agent == null ? null : machine?.projectOf(agent);
+ final branch = agent?.gitContext?.branchLabel ?? project?.shownBranch;
+ return InboxNotification(
+ machineId: machineId,
+ agentId: agentId,
+ title: agent?.displayName ?? 'Unavailable harness',
+ detail: [
+ machine?.machine.displayName ?? 'Unavailable machine',
+ if (project?.label case final name? when name.isNotEmpty) name,
+ if (branch != null && branch.isNotEmpty) branch,
+ ].join(' '),
+ kind: current,
+ unavailable: harnessSessionUnavailable(machine, agent),
+ );
+}
diff --git a/desktop/lib/state/workspace_status.dart b/desktop/lib/state/workspace_status.dart
index 8f5a4c507..0df0be2a2 100644
--- a/desktop/lib/state/workspace_status.dart
+++ b/desktop/lib/state/workspace_status.dart
@@ -1,4 +1,5 @@
import '../core/models.dart';
+import '../core/runtime_model_name.dart';
import '../shared/theme/prompt_style.dart';
import '../shared/theme/status_line_style.dart';
import '../widgets/engine_identity.dart';
@@ -140,6 +141,12 @@ class WorkspacePaneContext {
final String? branch;
String? get agentId => pane.isWeb ? pane.ownerAgentId : pane.agentId;
String? get engine => agent?.engine ?? pane.session?.engineId;
+ String get modelLabel => modelLabelWithEffort(
+ provider,
+ agent?.gridModel == null && agent?.modelName != null
+ ? agent?.modelEffort
+ : null,
+ );
String get suffix => branch == null ? '' : ' ($branch)';
String get text => '$location$suffix';
StatusLineParts format(PromptPrefs prefs) {
diff --git a/desktop/lib/widgets/grid_model_picker.dart b/desktop/lib/widgets/grid_model_picker.dart
index 5dff21272..dfe72de11 100644
--- a/desktop/lib/widgets/grid_model_picker.dart
+++ b/desktop/lib/widgets/grid_model_picker.dart
@@ -11,6 +11,7 @@ import '../terminal/terminal_theme_store.dart';
import 'package:harness/terminal/terminal_text.dart';
import '../core/models.dart';
+import '../core/runtime_model_name.dart';
import '../core/test_run.dart';
import '../state/app_state.dart';
import '../shared/theme/app_type.dart';
@@ -85,6 +86,9 @@ class GridModelPicker extends StatefulWidget {
/// Observed subscription model for the label. Does not select a Local row.
final String? subscriptionModel;
+ /// Effort observed with [subscriptionModel]; never carried onto a Local row.
+ final String? subscriptionEffort;
+
/// Whether the agent can search the web on [currentModel], as the daemon decided when it built
/// the launch. Shown as a subtitle under the current Local row and in the control's tooltip —
/// only for the two degraded values; `on` and null (nothing said) show nothing. Read only when
@@ -113,6 +117,7 @@ class GridModelPicker extends StatefulWidget {
this.onRunLocalModel,
this.currentModel,
this.subscriptionModel,
+ this.subscriptionEffort,
this.webSearch,
this.engineLabel,
this.compact = false,
@@ -518,7 +523,7 @@ class _GridModelPickerState extends State<GridModelPicker> {
TerminalFontScope.watch(context);
if (widget.menuOnly) return const SizedBox.shrink();
final sentence = _webSearchSentence;
- final current =
+ final model =
widget.currentModel ??
widget.subscriptionModel ??
switch (widget.engineLabel?.toLowerCase()) {
@@ -527,6 +532,12 @@ class _GridModelPickerState extends State<GridModelPicker> {
'opencode' => 'OpenCode',
_ => 'Model',
};
+ final current = modelLabelWithEffort(
+ model,
+ widget.currentModel == null && widget.subscriptionModel != null
+ ? widget.subscriptionEffort
+ : null,
+ );
final label = _expecting ? 'Switching…' : current;
if (widget.paneHeader) {
final theme = terminalThemeFor(
diff --git a/desktop/lib/widgets/harness_session_manager.dart b/desktop/lib/widgets/harness_session_manager.dart
index 904d76709..c60069ecc 100644
--- a/desktop/lib/widgets/harness_session_manager.dart
+++ b/desktop/lib/widgets/harness_session_manager.dart
@@ -841,17 +841,21 @@ class _SessionRow extends StatelessWidget {
// the first case. This says the other one — work that is done
// and has not been looked at — in the one place the eye is
// already checking for a row's state.
- else if (unread == AlertKind.done)
+ else if (unread == AlertKind.done || unread == AlertKind.failed)
IconButton(
- key: ValueKey('session-unread-done:${row.id}'),
- tooltip: 'Finished',
+ key: ValueKey('session-unread-${unread!.name}:${row.id}'),
+ tooltip: unread == AlertKind.failed ? 'Failed' : 'Finished',
onPressed: canOpen ? onOpen : null,
- color: _UnreadMark.doneTint,
+ color: unread == AlertKind.failed
+ ? AppPalette.dangerFill
+ : _UnreadMark.doneTint,
icon: Icon(
- LucideIcons.circleCheckBig,
+ unread == AlertKind.failed
+ ? LucideIcons.circleX
+ : LucideIcons.circleCheckBig,
size: 17,
semanticLabel:
- 'Finished, not yet seen: ${row.agent.displayName}',
+ '${unread == AlertKind.failed ? 'Failed' : 'Finished'}, not yet seen: ${row.agent.displayName}',
),
),
Tooltip(
diff --git a/desktop/lib/widgets/notification_inbox.dart b/desktop/lib/widgets/notification_inbox.dart
new file mode 100644
index 000000000..1150b12ac
--- /dev/null
+++ b/desktop/lib/widgets/notification_inbox.dart
@@ -0,0 +1,397 @@
+import 'dart:async';
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../state/app_state.dart';
+import '../state/harness_activity.dart';
+import '../state/notification_inbox.dart';
+import '../terminal/terminal_text.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
+import 'box_chrome.dart';
+import 'harness_activity_mark.dart';
+import 'terminal_text_action.dart';
+
+Future<void> showNotificationInbox(
+ BuildContext context, {
+ required AppNotifier app,
+ required Future<bool> Function(InboxNotification) onOpen,
+ double topInset = 0,
+}) => showAppDialog<void>(
+ context: context,
+ veilTint: Colors.transparent,
+ builder: (_) =>
+ NotificationInbox(app: app, onOpen: onOpen, topInset: topInset),
+);
+
+/// The existing unread notifications in a quiet, live list beside the bell.
+class NotificationInbox extends StatefulWidget {
+ const NotificationInbox({
+ super.key,
+ required this.app,
+ required this.onOpen,
+ this.topInset = 0,
+ });
+
+ final AppNotifier app;
+ final Future<bool> Function(InboxNotification) onOpen;
+ final double topInset;
+
+ @override
+ State<NotificationInbox> createState() => _NotificationInboxState();
+}
+
+class _NotificationInboxState extends State<NotificationInbox> {
+ final _scroll = ScrollController();
+ final _focus = FocusNode(debugLabel: 'Notifications');
+ List<InboxNotification> _rows = [];
+ String? _selected, _opening, _error;
+
+ @override
+ void initState() {
+ super.initState();
+ _refresh();
+ widget.app.addListener(_changed);
+ widget.app.agentUnread.addListener(_changed);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _focus.requestFocus();
+ });
+ }
+
+ void _refresh() {
+ final next = {for (final row in notificationInbox(widget.app)) row.id: row};
+ // Keep the list under the pointer still. New notifications append while
+ // the popup is open; selection follows identity rather than an index.
+ _rows = [for (final row in _rows) ?next.remove(row.id), ...next.values];
+ if (!_rows.any((row) => row.id == _selected)) _selected = null;
+ }
+
+ void _changed() {
+ if (mounted) setState(_refresh);
+ }
+
+ void _move(int delta) {
+ if (_rows.isEmpty || _opening != null) return;
+ final current = _rows.indexWhere((row) => row.id == _selected);
+ final index = current < 0
+ ? (delta > 0 ? 0 : _rows.length - 1)
+ : (current + delta).clamp(0, _rows.length - 1);
+ setState(() => _selected = _rows[index].id);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || !_scroll.hasClients) return;
+ final line = terminalCellSizeOf(context).height;
+ final top = line + index * line * 3;
+ final bottom = top + line * 3;
+ final viewport = _scroll.position.viewportDimension;
+ final offset = top < _scroll.offset
+ ? top
+ : bottom > _scroll.offset + viewport
+ ? bottom - viewport
+ : _scroll.offset;
+ _scroll.jumpTo(offset.clamp(0.0, _scroll.position.maxScrollExtent));
+ });
+ }
+
+ Future<void> _open(InboxNotification row) async {
+ if (_opening != null) return;
+ final current = notificationInbox(widget.app)
+ .where((item) => item.id == row.id)
+ .firstOrNull;
+ if (current == null || current.unavailable != null) return;
+ setState(() {
+ _opening = row.id;
+ _error = null;
+ });
+ try {
+ final opened = await widget.onOpen(current);
+ if (!mounted) return;
+ if (opened) {
+ Navigator.of(context).pop();
+ } else {
+ setState(() => _error = 'Could not open this harness. Try again.');
+ }
+ } catch (_) {
+ if (mounted) {
+ setState(() => _error = 'Could not open this harness. Try again.');
+ }
+ } finally {
+ if (mounted) setState(() => _opening = null);
+ }
+ }
+
+ @override
+ void dispose() {
+ widget.app.removeListener(_changed);
+ widget.app.agentUnread.removeListener(_changed);
+ _scroll.dispose();
+ _focus.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
+ return ValueListenableBuilder(
+ valueListenable: terminalThemeStore,
+ builder: (context, _, _) {
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ final cell = terminalCellSizeOf(context);
+ final style = terminalContentStyle(color: theme.foreground);
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ final width = math.min(
+ cell.width * 64,
+ math.max(0.0, constraints.maxWidth - cell.width * 2),
+ );
+ final available = math.max(
+ 0.0,
+ constraints.maxHeight - widget.topInset - cell.height * 2,
+ );
+ final height = math.min(
+ available,
+ cell.height *
+ (_rows.isEmpty
+ ? 5
+ : math.min(
+ 23,
+ 3 + _rows.length * 3 + (_error == null ? 0 : 2),
+ )),
+ );
+ return Dialog(
+ alignment: Alignment.topRight,
+ insetPadding: EdgeInsets.fromLTRB(
+ cell.width,
+ widget.topInset + cell.height,
+ cell.width,
+ cell.height,
+ ),
+ backgroundColor: theme.background,
+ elevation: 0,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(kTerminalCornerRadius),
+ side: terminalPaneBorder(focused: true),
+ ),
+ child: SizedBox(
+ key: const ValueKey('notification-inbox'),
+ width: width,
+ height: height,
+ child: Focus(
+ focusNode: _focus,
+ autofocus: true,
+ onKeyEvent: (node, event) {
+ if (!node.hasPrimaryFocus ||
+ event is! KeyDownEvent ||
+ HardwareKeyboard.instance.isMetaPressed ||
+ HardwareKeyboard.instance.isControlPressed ||
+ HardwareKeyboard.instance.isAltPressed) {
+ return KeyEventResult.ignored;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.arrowDown ||
+ event.logicalKey == LogicalKeyboardKey.arrowUp) {
+ _move(
+ event.logicalKey == LogicalKeyboardKey.arrowDown
+ ? 1
+ : -1,
+ );
+ return KeyEventResult.handled;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter) {
+ final row = _rows
+ .where((row) => row.id == _selected)
+ .firstOrNull;
+ if (row != null) unawaited(_open(row));
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: DefaultTextStyle(
+ style: style,
+ child: Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: Column(
+ children: [
+ SizedBox(
+ height: cell.height,
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Notifications${_rows.isEmpty ? '' : ' ${_rows.length}'}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ TerminalTextAction(
+ label: 'x',
+ onPressed: () => Navigator.of(context).pop(),
+ ),
+ ],
+ ),
+ ),
+ Expanded(
+ child: _rows.isEmpty
+ ? Center(
+ child: Text(
+ 'No notifications',
+ style: style.copyWith(
+ color: theme.foreground.withValues(
+ alpha: .55,
+ ),
+ ),
+ ),
+ )
+ : ListView.builder(
+ controller: _scroll,
+ itemCount: _rows.length,
+ padding: EdgeInsets.only(top: cell.height),
+ itemExtent: cell.height * 3,
+ itemBuilder: (context, index) {
+ final row = _rows[index];
+ final opening = row.id == _opening;
+ final activity = opening
+ ? HarnessActivity.starting
+ : switch (row.unavailable) {
+ null => row.activity,
+ 'Starting' =>
+ HarnessActivity.starting,
+ 'Start failed' =>
+ HarnessActivity.failed,
+ _ => HarnessActivity.offline,
+ };
+ final statusLabel = opening
+ ? 'Opening…'
+ : row.unavailable == null
+ ? row.label
+ : '${row.label} · ${row.unavailable}';
+ final onTap =
+ row.unavailable == null &&
+ _opening == null
+ ? () => unawaited(_open(row))
+ : null;
+ final selected = row.id == _selected;
+ return Semantics(
+ label:
+ '${row.title}, ${row.label}, ${row.detail}${row.unavailable == null ? '' : ', ${row.unavailable}'}',
+ button: true,
+ excludeSemantics: true,
+ enabled: onTap != null,
+ onTap: onTap,
+ selected: selected,
+ child: MouseRegion(
+ cursor: onTap != null
+ ? SystemMouseCursors.click
+ : SystemMouseCursors.basic,
+ onEnter: (_) {
+ if (_opening == null) {
+ setState(
+ () => _selected = row.id,
+ );
+ }
+ },
+ child: GestureDetector(
+ key: ValueKey(
+ 'notification:${row.id}',
+ ),
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.stretch,
+ children: [
+ ColoredBox(
+ color: selected
+ ? theme.selection
+ : Colors.transparent,
+ child: SizedBox(
+ height: cell.height,
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ row.title,
+ maxLines: 1,
+ overflow:
+ TextOverflow
+ .ellipsis,
+ ),
+ ),
+ SizedBox(
+ width: cell.width,
+ ),
+ Tooltip(
+ message: statusLabel,
+ child: SizedBox(
+ width: cell.width,
+ child: Text(
+ activity.mark,
+ textAlign:
+ TextAlign
+ .center,
+ style: style.copyWith(
+ color:
+ activityColor(
+ activity,
+ theme,
+ ),
+ fontFamilyFallback: [
+ ...?style
+ .fontFamilyFallback,
+ 'Apple Symbols',
+ 'DejaVu Sans',
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ Text(
+ row.detail,
+ maxLines: 1,
+ overflow:
+ TextOverflow.ellipsis,
+ style: style.copyWith(
+ color: theme.foreground
+ .withValues(alpha: .55),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ if (_error != null)
+ Text(
+ _error!,
+ style: style.copyWith(color: theme.red),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ },
+ );
+ }
+}
diff --git a/desktop/lib/widgets/workspace_notifications_button.dart b/desktop/lib/widgets/workspace_notifications_button.dart
new file mode 100644
index 000000000..d49127287
--- /dev/null
+++ b/desktop/lib/widgets/workspace_notifications_button.dart
@@ -0,0 +1,58 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import '../shared/theme/workspace_bar_style.dart';
+import 'workspace_bar_control.dart';
+
+/// A fixed-width bell; changes to its count never move the neighboring ribbon.
+class WorkspaceNotificationsButton extends StatelessWidget {
+ const WorkspaceNotificationsButton({
+ super.key,
+ required this.count,
+ required this.foreground,
+ required this.onPressed,
+ });
+
+ final int count;
+ final Color foreground;
+ final VoidCallback? onPressed;
+
+ static double widthOf(BuildContext context) =>
+ workspaceBarCellSizeOf(context).width * 4;
+
+ @override
+ Widget build(BuildContext context) => WorkspaceBarControl(
+ label: count == 0 ? 'Notifications' : 'Notifications, $count unread',
+ tooltip: count == 0 ? 'Notifications' : 'Notifications · $count unread',
+ onPressed: onPressed,
+ builder: (context, emphasized) => SizedBox(
+ width: widthOf(context),
+ height: workspaceBarControlHeight(context),
+ child: Center(
+ child: Badge(
+ alignment: Alignment.topRight,
+ isLabelVisible: count > 0,
+ backgroundColor: const Color(0xffcf4038),
+ textColor: Colors.white,
+ smallSize: 6,
+ largeSize: 13,
+ label: Text(
+ count > 99 ? '99+' : '$count',
+ style: const TextStyle(fontSize: 9, fontWeight: FontWeight.w600),
+ ),
+ child: Icon(
+ LucideIcons.bell,
+ size: 17,
+ color: foreground.withValues(
+ alpha: onPressed == null
+ ? .28
+ : emphasized
+ ? 1
+ : .75,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/workspace_store_button.dart b/desktop/lib/widgets/workspace_store_button.dart
new file mode 100644
index 000000000..44ba5b324
--- /dev/null
+++ b/desktop/lib/widgets/workspace_store_button.dart
@@ -0,0 +1,74 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/theme/workspace_bar_style.dart';
+import '../store/store_mark.dart';
+import 'workspace_bar_control.dart';
+
+/// The Store's rounded, marked button, restored from the original tab bar.
+class WorkspaceStoreButton extends StatelessWidget {
+ const WorkspaceStoreButton({
+ super.key,
+ required this.width,
+ required this.tooltip,
+ this.onPressed,
+ });
+
+ final double width;
+ final String tooltip;
+ final VoidCallback? onPressed;
+
+ static double widthOf(BuildContext context) =>
+ workspaceBarTextSizeOf(context, 'Harness Store').width + 52;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final enabled = onPressed != null;
+ final accent = grid.AppPalette.swarmAccent;
+ return WorkspaceBarControl(
+ label: 'Harness Store',
+ tooltip: tooltip,
+ onPressed: onPressed,
+ builder: (context, emphasized) => Container(
+ width: width,
+ height: workspaceBarControlHeight(context),
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ decoration: ShapeDecoration(
+ color: Color.alphaBlend(
+ accent.withValues(
+ alpha: !enabled
+ ? .04
+ : emphasized
+ ? .18
+ : .10,
+ ),
+ grid.AppPalette.swarmWelcome,
+ ),
+ shape: StadiumBorder(
+ side: BorderSide(
+ color: accent.withValues(alpha: emphasized ? .85 : .12),
+ width: emphasized ? 1.5 : 1,
+ ),
+ ),
+ ),
+ child: Row(
+ children: [
+ StoreMark(enabled: enabled),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ 'Harness Store',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: workspaceBarTextStyle(
+ color: accent.withValues(alpha: enabled ? 1 : .45),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 9bb4ee5ee..72e3f3edf 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -9,6 +9,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private let channel: FlutterMethodChannel
private let accessory = NSTitlebarAccessoryViewController()
private let strip = SwarmTabStrip(frame: NSRect(x: 0, y: 0, width: 900, height: 40))
+ private var statusBarHeight: NSLayoutConstraint?
private var observers: [NSObjectProtocol] = []
private var configured = false
private var actionsEnabled = false
@@ -55,6 +56,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
self.canGoForward = state["canGoForward"] as? Bool == true
self.updateHistory(state["history"] as? [[String: Any]] ?? [], closed: state["closedHistory"] as? [[String: Any]] ?? [])
self.strip.update(state)
+ self.statusBarHeight?.constant = self.strip.preferredStatusBarHeight
self.window?.backgroundColor = self.strip.palette.tabBar
result(nil)
case "machinesState":
@@ -106,7 +108,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
private func sendTabAction(_ method: String, arguments: Any?) {
- guard ["daemon", "focusedModel", "focusedContext", "harnessControls", "machineControls", "modelControls", "select", "close", "new", "rename", "commands", "notifications", "store", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
+ guard ["daemon", "focusedModel", "focusedContext", "harnessControls", "machineControls", "modelControls", "select", "close", "new", "rename", "commands", "notifications", "notificationInbox", "store", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
channel.invokeMethod(method, arguments: arguments)
return
}
@@ -133,9 +135,10 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
// handling the action. The controller accepts ordinary keys, but Flutter's
// view wrapper only forwards Command equivalents for its input view.
if let current = window.firstResponder as? NSView,
- current.isDescendant(of: content) { return }
+ current.isDescendant(of: content),
+ !current.isDescendant(of: strip.statusBar) { return }
func input(in view: NSView) -> NSView? {
- guard !view.isHidden else { return nil }
+ guard !view.isHidden, view !== strip.statusBar else { return nil }
if view.acceptsFirstResponder { return view }
for child in view.subviews {
if let target = input(in: child) { return target }
@@ -195,6 +198,19 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
accessory.layoutAttribute = .right
accessory.view = strip
window.addTitlebarAccessoryViewController(accessory)
+ if let content = window.contentView {
+ let footer = strip.statusBar
+ footer.translatesAutoresizingMaskIntoConstraints = false
+ content.addSubview(footer)
+ let height = footer.heightAnchor.constraint(equalToConstant: strip.preferredStatusBarHeight)
+ statusBarHeight = height
+ NSLayoutConstraint.activate([
+ footer.leadingAnchor.constraint(equalTo: content.leadingAnchor),
+ footer.trailingAnchor.constraint(equalTo: content.trailingAnchor),
+ footer.bottomAnchor.constraint(equalTo: content.bottomAnchor),
+ height,
+ ])
+ }
resize()
installWorkspaceMenus()
if let keymap { setKeymap(keymap) }
@@ -933,6 +949,83 @@ private final class SwarmStatusSymbolButton: SwarmIconButton {
}
}
+/// Plain toolbar icons emphasize the glyph without a button well.
+private class SwarmPlainIconButton: SwarmIconButton {
+ var foreground = NSColor.white { didSet { needsDisplay = true } }
+
+ override func draw(_ dirtyRect: NSRect) {
+ let emphasized = isEnabled && (hovered || hasKeyboardFocus || isHighlighted)
+ // Draw only the glyph: AppKit can paint a hover bezel even on a borderless
+ // NSButton. Emphasis belongs to the bell, never a background around it.
+ if let symbol = image?.withSymbolConfiguration(NSImage.SymbolConfiguration(
+ pointSize: 17, weight: emphasized ? .semibold : .regular)) {
+ let rect = NSRect(x: (bounds.width - symbol.size.width) / 2,
+ y: (bounds.height - symbol.size.height) / 2,
+ width: symbol.size.width, height: symbol.size.height)
+ NSGraphicsContext.current?.cgContext.beginTransparencyLayer(auxiliaryInfo: nil)
+ symbol.draw(in: rect)
+ foreground.withAlphaComponent(isEnabled ? (emphasized ? 1 : 0.75) : 0.28).setFill()
+ rect.fill(using: .sourceIn)
+ NSGraphicsContext.current?.cgContext.endTransparencyLayer()
+ }
+ }
+}
+
+/// A fixed-width bell with the same unread count as the Flutter popup.
+private final class SwarmNotificationButton: SwarmPlainIconButton {
+ var count = 0 { didSet { needsDisplay = true } }
+ override func draw(_ dirtyRect: NSRect) {
+ super.draw(dirtyRect)
+ guard count > 0 else { return }
+ let label = NSAttributedString(string: count > 99 ? "99+" : "\(count)", attributes: [
+ .font: NSFont.systemFont(ofSize: 9, weight: .semibold), .foregroundColor: NSColor.white,
+ ])
+ let width = max(13, ceil(label.size().width) + 6)
+ let badge = NSRect(x: bounds.maxX - width,
+ y: isFlipped ? bounds.minY : bounds.maxY - 13, width: width, height: 13)
+ NSColor(srgbRed: 207.0 / 255, green: 64.0 / 255, blue: 56.0 / 255, alpha: 1).setFill()
+ NSBezierPath(roundedRect: badge, xRadius: 6.5, yRadius: 6.5).fill()
+ label.draw(at: NSPoint(x: badge.midX - label.size().width / 2, y: badge.midY - label.size().height / 2))
+ }
+}
+
+/// A quiet filled pill, with the Store's colorful mark as its focal point.
+/// Drawing the content keeps the same spacing across AppKit button styles.
+private final class SwarmStoreButton: SwarmIconButton {
+ var palette = SwarmNativePalette() { didSet { needsDisplay = true } }
+ var preferredWidth: CGFloat {
+ ceil(workspaceBarTextWidth(title,
+ font: font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular))) + 52
+ }
+
+ override func draw(_ dirtyRect: NSRect) {
+ let shape = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5),
+ xRadius: bounds.height / 2, yRadius: bounds.height / 2)
+ palette.workspace.setFill()
+ shape.fill()
+ let alpha: CGFloat = !isEnabled ? 0.04 : isHighlighted ? 0.24 : hovered ? 0.18 : 0.10
+ palette.accent.withAlphaComponent(alpha).setFill()
+ shape.fill()
+ palette.accent.withAlphaComponent(hasKeyboardFocus && isEnabled ? 0.85 : 0.12).setStroke()
+ shape.lineWidth = hasKeyboardFocus && isEnabled ? 1.5 : 1
+ shape.stroke()
+ image?.draw(in: NSRect(x: 12, y: (bounds.height - 16) / 2, width: 16, height: 16),
+ from: .zero, operation: .sourceOver, fraction: isEnabled ? 1 : 0.45,
+ respectFlipped: true, hints: [.interpolation: NSImageInterpolation.high])
+ let paragraph = NSMutableParagraphStyle()
+ paragraph.lineBreakMode = .byTruncatingTail
+ let attributes: [NSAttributedString.Key: Any] = [
+ .paragraphStyle: paragraph,
+ .font: font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular),
+ .foregroundColor: palette.accent.withAlphaComponent(isEnabled ? 1 : 0.45),
+ ]
+ let text = title as NSString
+ let height = text.size(withAttributes: attributes).height
+ text.draw(in: NSRect(x: 36, y: (bounds.height - height) / 2,
+ width: max(0, bounds.width - 48), height: height), withAttributes: attributes)
+ }
+}
+
/// Flat primary action; Dart supplies the same colors and text as Flutter.
private final class SwarmShareButton: SwarmIconButton {
var background = NSColor.clear { didSet { needsDisplay = true } }
@@ -1467,8 +1560,18 @@ private struct SwarmTabActivity: Equatable {
}
}
+private final class SwarmStatusBar: NSView {
+ var onLayout: (() -> Void)?
+ override var mouseDownCanMoveWindow: Bool { false }
+ override func layout() { super.layout(); onLayout?() }
+}
+
private final class SwarmTabStrip: NSView {
private(set) var palette = SwarmNativePalette()
+ fileprivate let statusBar = SwarmStatusBar(frame: NSRect(x: 0, y: 0, width: 900, height: 28))
+ // Same gutter as kWorkspaceInset in Flutter. It belongs to the footer's
+ // centering area rather than only above it, leaving equal top/bottom space.
+ var preferredStatusBarHeight: CGFloat { workspaceBarControlHeight(barFont) + 9.5 }
var emit: ((String, Any?) -> Void)?
private let scroll = SwarmStripScrollView()
private let document = NSView()
@@ -1478,6 +1581,9 @@ private final class SwarmTabStrip: NSView {
private var focusedModelTarget: [String: Any]?
fileprivate let pullRequestButton = SwarmContextButton()
fileprivate let shareButton = SwarmShareButton()
+ fileprivate let notificationsButton = SwarmNotificationButton()
+ fileprivate let searchButton = SwarmPlainIconButton()
+ fileprivate let storeButton = SwarmStoreButton()
private var shareTarget: [String: Any]?
private var barFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
fileprivate let daemonButton = SwarmSymbolButton()
@@ -1502,6 +1608,8 @@ private final class SwarmTabStrip: NSView {
override init(frame: NSRect) {
super.init(frame: frame)
+ statusBar.isHidden = true
+ statusBar.onLayout = { [weak self] in self?.layoutStatusBar() }
wantsLayer = true
scroll.drawsBackground = false
scroll.hasHorizontalScroller = false
@@ -1526,27 +1634,27 @@ private final class SwarmTabStrip: NSView {
guard let self, self.actionsEnabled else { return }
self.emit?("focusedContext", ["field": field, "paneId": paneId])
}
- addSubview(contextButton)
+ statusBar.addSubview(contextButton)
focusedModelButton.isBordered = false
focusedModelButton.textAlignment = .center
focusedModelButton.target = self
focusedModelButton.action = #selector(openFocusedModel)
focusedModelButton.setAccessibilityLabel("Switch focused pane model")
focusedModelButton.isHidden = true
- addSubview(focusedModelButton)
+ statusBar.addSubview(focusedModelButton)
pullRequestButton.isBordered = false
pullRequestButton.target = self
pullRequestButton.action = #selector(openFocusedPullRequest)
pullRequestButton.setAccessibilityLabel("Open pull request on GitHub")
pullRequestButton.isHidden = true
- addSubview(pullRequestButton)
+ statusBar.addSubview(pullRequestButton)
voiceLabel.isHidden = true
voiceLabel.onAction = { [weak self] key in
guard let self, self.actionsEnabled, !self.voiceLabel.isHidden else { return }
// The plain channel path: an answer never moves keyboard focus.
self.emit?("daemonAnswer", ["key": key])
}
- addSubview(voiceLabel)
+ statusBar.addSubview(voiceLabel)
daemonButton.isBordered = false
daemonButton.title = ""
daemonButton.isHidden = true
@@ -1557,7 +1665,38 @@ private final class SwarmTabStrip: NSView {
guard let self, self.actionsEnabled, !self.daemonButton.isHidden else { return }
self.emit?("daemonLook", nil)
}
- addSubview(daemonButton)
+ statusBar.addSubview(daemonButton)
+ notificationsButton.isBordered = false
+ notificationsButton.focusRingType = .none
+ notificationsButton.title = ""
+ notificationsButton.image = NSImage(systemSymbolName: "bell", accessibilityDescription: nil)
+ notificationsButton.imagePosition = .imageOnly
+ notificationsButton.target = self
+ notificationsButton.action = #selector(openNotifications)
+ notificationsButton.isEnabled = false
+ notificationsButton.setAccessibilityLabel("Notifications")
+ addSubview(notificationsButton)
+ searchButton.isBordered = false
+ searchButton.focusRingType = .none
+ searchButton.title = ""
+ searchButton.image = NSImage(systemSymbolName: "magnifyingglass", accessibilityDescription: nil)
+ searchButton.imagePosition = .imageOnly
+ searchButton.isEnabled = false
+ searchButton.target = self
+ searchButton.action = #selector(openSearch)
+ searchButton.setAccessibilityLabel("Search harnesses")
+ addSubview(searchButton)
+ storeButton.isBordered = false
+ storeButton.title = "Harness Store"
+ storeButton.font = barFont
+ storeButton.palette = palette
+ storeButton.image = SwarmHistoryIcons().image(engine: "store", asset: "assets/store/polymath.png")
+ storeButton.isEnabled = false
+ storeButton.focusRingType = .none
+ storeButton.target = self
+ storeButton.action = #selector(openStore)
+ storeButton.setAccessibilityLabel("Harness Store")
+ addSubview(storeButton)
shareButton.isBordered = false
shareButton.title = "[ Share ]"
shareButton.target = self
@@ -1565,8 +1704,16 @@ private final class SwarmTabStrip: NSView {
shareButton.isEnabled = false
shareButton.isHidden = true
shareButton.setAccessibilityLabel("Share")
- addSubview(shareButton)
- setAccessibilityChildren([scroll, newButton, focusedModelButton, contextButton, pullRequestButton, voiceLabel, daemonButton, shareButton])
+ statusBar.addSubview(shareButton)
+ // Flutter owns its content view's accessibility children. Expose the
+ // native footer through our native chrome tree while keeping its geometry
+ // attached to the content bottom.
+ statusBar.setAccessibilityElement(true)
+ statusBar.setAccessibilityRole(.group)
+ statusBar.setAccessibilityLabel("Focused pane status")
+ statusBar.setAccessibilityParent(self)
+ setAccessibilityChildren([scroll, newButton, searchButton, notificationsButton, storeButton, statusBar])
+ statusBar.setAccessibilityChildren([contextButton, pullRequestButton, voiceLabel, daemonButton, shareButton, focusedModelButton])
registerForDraggedTypes([swarmPasteboardType])
scroll.contentView.postsBoundsChangedNotifications = true
for name in [NSApplication.didBecomeActiveNotification, NSApplication.didResignActiveNotification,
@@ -1625,6 +1772,7 @@ private final class SwarmTabStrip: NSView {
let nextPalette = SwarmNativePalette(values)
guard nextPalette != palette else { return }
palette = nextPalette
+ storeButton.palette = palette
newButton.contentTintColor = palette.accent
for tab in tabs { tab.palette = palette }
needsDisplay = true
@@ -1635,6 +1783,7 @@ private final class SwarmTabStrip: NSView {
// Workspace teardown clears its controls without changing appearance.
if let palette = state["palette"] as? [String: Any] { updatePalette(palette) }
actionsEnabled = state["enabled"] as? Bool == true
+ statusBar.isHidden = (state["tabs"] as? [Any])?.isEmpty != false
reduceMotion = state["reduceMotion"] as? Bool == true
if let style = state["barStyle"] as? [String: Any] {
let size = CGFloat(min(36, max(8, (style["size"] as? NSNumber)?.doubleValue ?? 13)))
@@ -1648,6 +1797,12 @@ private final class SwarmTabStrip: NSView {
control.foreground = terminalForeground
control.isEnabled = actionsEnabled
}
+ storeButton.font = barFont
+ storeButton.isEnabled = actionsEnabled
+ searchButton.foreground = terminalForeground
+ searchButton.isEnabled = actionsEnabled
+ searchButton.toolTip = state["searchTooltip"] as? String ?? "Search harnesses"
+ storeButton.toolTip = state["storeTooltip"] as? String ?? "Harness Store"
focusedModelButton.font = barFont
focusedModelButton.foreground = terminalForeground
focusedModelButton.contentPadding = ("m" as NSString).size(withAttributes: [.font: barFont]).width
@@ -1671,6 +1826,12 @@ private final class SwarmTabStrip: NSView {
shareButton.setAccessibilityLabel(shareTarget?["label"] as? String ?? "Share")
shareButton.setAccessibilityHelp(shareButton.toolTip)
hasPullRequest = state["pullRequest"] != nil
+ notificationsButton.count = max(0, state["unread"] as? Int ?? 0)
+ notificationsButton.foreground = terminalForeground
+ notificationsButton.isEnabled = actionsEnabled
+ notificationsButton.toolTip = notificationsButton.count == 0
+ ? "Notifications" : "Notifications · \(notificationsButton.count) unread"
+ notificationsButton.setAccessibilityValue("\(notificationsButton.count) unread")
daemonButton.font = barFont
daemonButton.foreground = terminalForeground
voiceLabel.font = barFont
@@ -1744,7 +1905,7 @@ private final class SwarmTabStrip: NSView {
if let gate = daemonMayAppear { return gate() }
guard NSEvent.pressedMouseButtons == 0 else { return false }
guard let window else { return true }
- return !bounds.contains(convert(window.mouseLocationOutsideOfEventStream, from: nil))
+ return !statusBar.bounds.contains(statusBar.convert(window.mouseLocationOutsideOfEventStream, from: nil))
}
/// Try the held state again; the timer stops once it is shown or withdrawn.
@@ -1819,7 +1980,7 @@ private final class SwarmTabStrip: NSView {
private func applyStatusVisibility() {
voiceLabel.isHidden = !voiceActive
contextButton.isHidden = voiceActive
- focusedModelButton.isHidden = !hasFocusedModel || voiceActive
+ focusedModelButton.isHidden = !hasFocusedModel
pullRequestButton.isHidden = !hasPullRequest || voiceActive
voiceLabel.needsDisplay = true
}
@@ -1833,24 +1994,17 @@ private final class SwarmTabStrip: NSView {
let cell = ceil(("m" as NSString).size(withAttributes: [.font: barFont]).width)
let trailing = cell
let toolHeight = workspaceBarControlHeight(barFont)
- let shareWidth = shareButton.isHidden ? 0 : shareButton.preferredWidth
- let shareSpace = shareWidth > 0 ? shareWidth + cell : 0
- shareButton.frame = NSRect(x: bounds.width - trailing - shareWidth,
- y: (bounds.height - toolHeight) / 2, width: shareWidth, height: toolHeight)
- let daemonWidth = daemonButton.isHidden ? 0 : daemonButton.preferredWidth
- let statusRight = bounds.width - trailing - shareSpace - daemonWidth
- daemonButton.frame = NSRect(x: statusRight,
- y: (bounds.height - toolHeight) / 2, width: daemonWidth, height: toolHeight)
- // Compact windows keep a scrolling tab list; context never overlaps it.
- let available = max(0, bounds.width - cell * 7 - shareSpace - daemonWidth)
- let naturalStatus = contextButton.preferredWidth
- + (hasFocusedModel ? focusedModelButton.preferredWidth + cell : 0)
- + (hasPullRequest ? pullRequestButton.preferredWidth + (contextButton.isSegmented && pullRequestButton.isSegmented ? 0 : cell) : 0)
- // Match Flutter: context reserves only what it needs, up to 40% / 52 cells.
- // Extra room from a short tab list returns to the full context below.
- // Keep a usable message line even on an empty tab when the daemon is on.
- let statusBudget = min(max(naturalStatus, daemonWidth > 0 ? cell * 32 : 0), min(available * 0.4, cell * 52))
- let tabBudget = max(0, available - statusBudget)
+ let storeWidth = min(storeButton.preferredWidth,
+ max(0, bounds.width - cell * 14))
+ storeButton.frame = NSRect(x: bounds.width - trailing - storeWidth,
+ y: (bounds.height - toolHeight) / 2, width: storeWidth, height: toolHeight)
+ let iconWidth = cell * 4
+ notificationsButton.frame = NSRect(x: storeButton.frame.minX - iconWidth,
+ y: (bounds.height - toolHeight) / 2, width: iconWidth, height: toolHeight)
+ searchButton.frame = NSRect(x: notificationsButton.frame.minX - iconWidth,
+ y: (bounds.height - toolHeight) / 2, width: iconWidth, height: toolHeight)
+ // Only navigation actions share the tab row. Context has the full footer.
+ let tabBudget = max(0, searchButton.frame.minX - cell * 5)
let widths = tabs.map { max($0.minimumWidth, min($0.preferredWidth, tabBudget)) }
let total = widths.reduce(0, +)
let occupied = min(total, tabBudget)
@@ -1865,24 +2019,10 @@ private final class SwarmTabStrip: NSView {
}
newButton.frame = NSRect(x: scroll.frame.maxX, y: (bounds.height - toolHeight) / 2,
width: cell * 3, height: toolHeight)
- let statusWidth = max(0, statusRight - newButton.frame.maxX - cell * 2)
- voiceLabel.frame = NSRect(x: statusRight - statusWidth, y: (bounds.height - toolHeight) / 2,
- width: statusWidth, height: toolHeight)
- let prWidth = hasPullRequest ? min(pullRequestButton.preferredWidth, statusWidth * 0.45) : 0
- let joined = contextButton.isSegmented && pullRequestButton.isSegmented && prWidth > 0
- let prGap = prWidth > 0 && !joined ? cell : 0
- pullRequestButton.frame = NSRect(x: statusRight - prWidth, y: (bounds.height - toolHeight) / 2,
- width: prWidth, height: toolHeight)
- let remaining = max(0, statusWidth - prWidth - prGap)
- let modelWidth = hasFocusedModel ? min(focusedModelButton.preferredWidth, remaining * 0.35) : 0
- let modelGap = modelWidth > 0 ? min(cell, remaining - modelWidth) : 0
- let contextWidth = min(contextButton.preferredWidth, max(0, remaining - modelWidth - modelGap))
- contextButton.frame = NSRect(x: statusRight - prWidth - prGap - contextWidth, y: (bounds.height - toolHeight) / 2,
- width: contextWidth, height: toolHeight)
- focusedModelButton.frame = NSRect(x: contextButton.frame.minX - modelGap - modelWidth,
- y: (bounds.height - toolHeight) / 2, width: modelWidth, height: toolHeight)
- contextButton.nextBackground = joined && pullRequestButton.drawsSegments
- ? pullRequestButton.firstBackground : nil
+ if statusBar.superview == nil {
+ statusBar.setFrameSize(NSSize(width: bounds.width, height: preferredStatusBarHeight))
+ }
+ layoutStatusBar()
let geometryChanged = scroll.frame.size != previousScrollSize || document.frame.size != previousDocumentSize
if let active, revealActiveAfterLayout || (activeWasVisible && (geometryChanged || tabOrderChanged)) {
document.scrollToVisible(active.frame)
@@ -1891,6 +2031,39 @@ private final class SwarmTabStrip: NSView {
tabOrderChanged = false
syncActivityAnimation()
}
+ private func layoutStatusBar() {
+ let cell = ceil(("m" as NSString).size(withAttributes: [.font: barFont]).width)
+ let height = workspaceBarControlHeight(barFont)
+ let y = (statusBar.bounds.height - height) / 2
+ let available = max(0, statusBar.bounds.width - cell * 2)
+ let daemonWidth = daemonButton.isHidden ? 0 : min(daemonButton.preferredWidth, available * 0.5)
+ let shareWidth = shareButton.isHidden ? 0 : min(shareButton.preferredWidth, available * 0.3)
+ let modelBudget = max(0, available - daemonWidth - shareWidth - cell * 4)
+ let modelWidth = hasFocusedModel ? min(focusedModelButton.preferredWidth, modelBudget * 0.4) : 0
+ focusedModelButton.frame = NSRect(x: statusBar.bounds.width - cell - modelWidth,
+ y: y, width: modelWidth, height: height)
+ let shareRight = focusedModelButton.frame.minX - (modelWidth > 0 ? cell : 0)
+ shareButton.frame = NSRect(x: shareRight - shareWidth, y: y, width: shareWidth, height: height)
+ let daemonRight = shareButton.frame.minX - (shareWidth > 0 ? cell : 0)
+ daemonButton.frame = NSRect(x: daemonRight - daemonWidth, y: y, width: daemonWidth, height: height)
+ let contextRight = daemonButton.frame.minX - cell * 2
+ let statusWidth = max(0, contextRight - cell)
+ voiceLabel.frame = NSRect(x: cell, y: y, width: statusWidth, height: height)
+ let prWidth = hasPullRequest ? min(pullRequestButton.preferredWidth, statusWidth * 0.3) : 0
+ let joined = contextButton.isSegmented && pullRequestButton.isSegmented && prWidth > 0
+ let prGap = prWidth > 0 && !joined ? cell : 0
+ let contextWidth = min(contextButton.preferredWidth, max(0, statusWidth - prWidth - prGap))
+ contextButton.frame = NSRect(x: cell, y: y, width: contextWidth, height: height)
+ pullRequestButton.frame = NSRect(x: contextButton.frame.maxX + prGap,
+ y: y, width: prWidth, height: height)
+ contextButton.nextBackground = joined && pullRequestButton.drawsSegments
+ ? pullRequestButton.firstBackground : nil
+ // The footer has a different parent from the titlebar. Lay out its field
+ // links after allocating their row, including offscreen render fixtures.
+ contextButton.layoutSubtreeIfNeeded()
+ pullRequestButton.layoutSubtreeIfNeeded()
+ focusedModelButton.layoutSubtreeIfNeeded()
+ }
override func draw(_ dirtyRect: NSRect) {
// A fine rule joins the flat tabs to the workspace.
palette.workspace.setFill()
@@ -1926,6 +2099,15 @@ private final class SwarmTabStrip: NSView {
@objc private func openDaemon() {
if actionsEnabled && daemonButton.isEnabled { emit?("daemon", nil) }
}
+ @objc private func openNotifications() {
+ if actionsEnabled && notificationsButton.isEnabled { emit?("notificationInbox", nil) }
+ }
+ @objc private func openSearch() {
+ if actionsEnabled && searchButton.isEnabled { emit?("sessions", nil) }
+ }
+ @objc private func openStore() {
+ if actionsEnabled && storeButton.isEnabled { emit?("store", nil) }
+ }
@objc private func openFocusedPullRequest() {
if actionsEnabled && pullRequestButton.isEnabled, let url = pullRequestButton.actionURL {
emit?("focusedPullRequest", ["url": url])
diff --git a/desktop/test/agent_model_test.dart b/desktop/test/agent_model_test.dart
index e5d6f66d0..6d8731ebd 100644
--- a/desktop/test/agent_model_test.dart
+++ b/desktop/test/agent_model_test.dart
@@ -11,9 +11,25 @@ void main() {
};
final agent = Agent.fromJson(raw);
expect(agent.modelName, 'GPT-6 Astra');
+ expect(agent.modelEffort, 'high');
expect(agent.gridModel, isNull);
expect(agent.copyWith(name: 'Renamed').modelName, 'GPT-6 Astra');
+ expect(agent.copyWith(name: 'Renamed').modelEffort, 'high');
+ expect(Agent.fromJson({'id': 'legacy'}).modelEffort, isNull);
expect(AppNotifier.agentsEqual([agent], [Agent.fromJson(raw)]), isTrue);
+ expect(
+ AppNotifier.agentsEqual(
+ [agent],
+ [
+ Agent.fromJson({
+ ...raw,
+ 'selectedModel': 'runtime-v1:a:codex:gpt-6-astra@max',
+ }),
+ ],
+ ),
+ isFalse,
+ reason: 'effort-only updates must refresh the focused model label',
+ );
expect(
AppNotifier.agentsEqual(
[agent],
diff --git a/desktop/test/agent_unread_test.dart b/desktop/test/agent_unread_test.dart
index 6a72a7cf1..aa1208953 100644
--- a/desktop/test/agent_unread_test.dart
+++ b/desktop/test/agent_unread_test.dart
@@ -74,13 +74,16 @@ void main() {
expect(rebuilds, 1);
});
- // ── Parity with the dial ───────────────────────────────────────────────────
- // The badge here and the pill there count the same finished turns, so this
- // store holds as many agents as the dial's drawer holds rows, and lets go of
- // them the same way.
+ group('bounded desktop inbox', () {
+ test('retains nine notifications without the dial drawer evicting one', () {
+ for (var i = 0; i < 9; i++) {
+ unread.mark('m1', 'a$i', AlertKind.done);
+ }
+ expect(unread.count, 9);
+ expect(unread.kindFor('m1', 'a0'), AlertKind.done);
+ });
- group('as many as the dial holds', () {
- test('at most as many agents as the dial has rows', () {
+ test('evicts the oldest entry only at the desktop capacity', () {
for (var i = 0; i < AgentUnread.capacity + 3; i++) {
unread.mark('m1', 'a$i', AlertKind.done);
}
diff --git a/desktop/test/alert_sounds_test.dart b/desktop/test/alert_sounds_test.dart
index 85e8916ee..f5a8d44c6 100644
--- a/desktop/test/alert_sounds_test.dart
+++ b/desktop/test/alert_sounds_test.dart
@@ -100,7 +100,16 @@ void main() {
expect(played, hasLength(1));
});
- test('the rate limit is per KIND, so a stuck agent is never swallowed by a busy one', () async {
+ test('failed and successful turns share the existing completion sound limit', () async {
+ final player = sounds(await switchedOn());
+ player.play(AlertKind.done);
+ player.play(AlertKind.failed);
+ player.play(AlertKind.needsYou);
+ await Future<void>.delayed(Duration.zero);
+ expect(played, [AlertKind.done.sound, AlertKind.needsYou.sound]);
+ });
+
+ test('the rate limit is per sound, so a stuck agent is never swallowed by a busy one', () async {
var at = DateTime(2026, 9, 23, 12);
final player = sounds(await switchedOn(), clock: () => at);
player.play(AlertKind.done);
diff --git a/desktop/test/fixtures/status_bar_before_daemons.json b/desktop/test/fixtures/status_bar_before_daemons.json
index 0162ff049..f00f3cae8 100644
--- a/desktop/test/fixtures/status_bar_before_daemons.json
+++ b/desktop/test/fixtures/status_bar_before_daemons.json
@@ -7,39 +7,69 @@
40.0
],
[
- 13.0,
0.0,
- 130.0,
- 40.0
+ 762.5,
+ 480.0,
+ 37.5
],
[
- 143.0,
+ 13.0,
0.0,
- 130.0,
+ 78.0,
40.0
],
[
- 152.8,
+ 90.0,
6.0,
39.0,
28.0
],
[
- 217.8,
+ 142.0,
6.0,
- 93.2,
+ 52.0,
28.0
],
[
- 324.0,
+ 194.0,
6.0,
- 143.0,
+ 52.0,
28.0
],
[
- 217.8,
+ 246.0,
6.0,
- 93.2,
+ 221.0,
+ 28.0
+ ],
+ [
+ 416.5,
+ 55.5,
+ 39.0,
+ 28.0
+ ],
+ [
+ 13.0,
+ 767.25,
+ 117.0,
+ 28.0
+ ],
+ [
+ 203.68,
+ 767.25,
+ 136.2,
+ 28.0
+ ],
+ [
+ 365.88,
+ 767.25,
+ 101.12,
+ 28.0
+ ],
+ [
+ 13.0,
+ 767.25,
+ 117.0,
28.0
]
],
@@ -51,45 +81,81 @@
40.0
],
[
- -107.2,
+ 0.0,
+ 762.5,
+ 720.0,
+ 37.5
+ ],
+ [
+ -39.0,
0.0,
130.0,
40.0
],
[
- 22.8,
+ 91.0,
0.0,
130.0,
40.0
],
[
- 296.8,
+ 221.0,
+ 0.0,
+ 130.0,
+ 40.0
+ ],
+ [
+ 330.0,
6.0,
39.0,
28.0
],
[
- 361.8,
+ 382.0,
6.0,
- 66.22,
+ 52.0,
28.0
],
[
- 441.02,
+ 434.0,
6.0,
- 109.98,
+ 52.0,
28.0
],
[
- 564.0,
+ 486.0,
6.0,
+ 221.0,
+ 28.0
+ ],
+ [
+ 656.5,
+ 55.5,
+ 39.0,
+ 28.0
+ ],
+ [
+ 13.0,
+ 767.25,
+ 117.0,
+ 28.0
+ ],
+ [
+ 434.0,
+ 767.25,
143.0,
28.0
],
[
- 361.8,
- 6.0,
- 189.2,
+ 603.0,
+ 767.25,
+ 104.0,
+ 28.0
+ ],
+ [
+ 13.0,
+ 767.25,
+ 117.0,
28.0
]
],
@@ -101,51 +167,81 @@
40.0
],
[
- -93.2,
+ 0.0,
+ 762.5,
+ 1024.0,
+ 37.5
+ ],
+ [
+ -60.0,
0.0,
130.0,
40.0
],
[
- 36.8,
+ 70.0,
0.0,
130.0,
40.0
],
[
- 166.8,
+ 200.0,
0.0,
130.0,
40.0
],
[
- 582.0,
+ 634.0,
6.0,
39.0,
28.0
],
[
- 652.2,
+ 686.0,
6.0,
- 72.8,
+ 52.0,
28.0
],
[
738.0,
6.0,
- 117.0,
+ 52.0,
28.0
],
[
- 868.0,
+ 790.0,
6.0,
+ 221.0,
+ 28.0
+ ],
+ [
+ 960.5,
+ 55.5,
+ 39.0,
+ 28.0
+ ],
+ [
+ 13.0,
+ 767.25,
+ 117.0,
+ 28.0
+ ],
+ [
+ 738.0,
+ 767.25,
143.0,
28.0
],
[
- 652.2,
- 6.0,
- 202.8,
+ 907.0,
+ 767.25,
+ 104.0,
+ 28.0
+ ],
+ [
+ 13.0,
+ 767.25,
+ 117.0,
28.0
]
],
@@ -157,31 +253,37 @@
40.0
],
[
- -68.0,
+ 0.0,
+ 762.5,
+ 1280.0,
+ 37.5
+ ],
+ [
+ -16.0,
0.0,
130.0,
40.0
],
[
- 62.0,
+ 114.0,
0.0,
130.0,
40.0
],
[
- 192.0,
+ 244.0,
0.0,
130.0,
40.0
],
[
- 322.0,
+ 374.0,
0.0,
130.0,
40.0
],
[
- 452.0,
+ 504.0,
0.0,
130.0,
40.0
@@ -193,27 +295,51 @@
28.0
],
[
- 877.0,
+ 942.0,
6.0,
- 104.0,
+ 52.0,
28.0
],
[
994.0,
6.0,
- 117.0,
+ 52.0,
28.0
],
[
- 1124.0,
+ 1046.0,
6.0,
+ 221.0,
+ 28.0
+ ],
+ [
+ 1216.5,
+ 55.5,
+ 39.0,
+ 28.0
+ ],
+ [
+ 13.0,
+ 767.25,
+ 117.0,
+ 28.0
+ ],
+ [
+ 994.0,
+ 767.25,
143.0,
28.0
],
[
- 877.0,
- 6.0,
- 234.0,
+ 1163.0,
+ 767.25,
+ 104.0,
+ 28.0
+ ],
+ [
+ 13.0,
+ 767.25,
+ 117.0,
28.0
]
],
@@ -224,6 +350,12 @@
1728.0,
40.0
],
+ [
+ 0.0,
+ 762.5,
+ 1728.0,
+ 37.5
+ ],
[
13.0,
0.0,
@@ -261,27 +393,51 @@
28.0
],
[
- 1325.0,
+ 1390.0,
6.0,
- 104.0,
+ 52.0,
28.0
],
[
1442.0,
6.0,
- 117.0,
+ 52.0,
28.0
],
[
- 1572.0,
+ 1494.0,
6.0,
+ 221.0,
+ 28.0
+ ],
+ [
+ 1664.5,
+ 55.5,
+ 39.0,
+ 28.0
+ ],
+ [
+ 13.0,
+ 767.25,
+ 117.0,
+ 28.0
+ ],
+ [
+ 1442.0,
+ 767.25,
143.0,
28.0
],
[
- 1325.0,
- 6.0,
- 234.0,
+ 1611.0,
+ 767.25,
+ 104.0,
+ 28.0
+ ],
+ [
+ 13.0,
+ 767.25,
+ 117.0,
28.0
]
]
diff --git a/desktop/test/grid_model_picker_test.dart b/desktop/test/grid_model_picker_test.dart
index d152e04c5..16c02cf73 100644
--- a/desktop/test/grid_model_picker_test.dart
+++ b/desktop/test/grid_model_picker_test.dart
@@ -256,22 +256,24 @@ void main() {
testWidgets(
'observed subscription model updates live and advertises local switching on hover',
(tester) async {
- Future<void> mount(String? model, {String? local}) => tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: Center(
- child: GridModelPicker(
- notifier: notifier,
- machineId: 'local',
- engineLabel: 'codex',
- subscriptionModel: model,
- currentModel: local,
- paneHeader: true,
+ Future<void> mount(String? model, {String? local, String? effort}) =>
+ tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: GridModelPicker(
+ notifier: notifier,
+ machineId: 'local',
+ engineLabel: 'codex',
+ subscriptionModel: model,
+ subscriptionEffort: effort,
+ currentModel: local,
+ paneHeader: true,
+ ),
+ ),
),
),
- ),
- ),
- );
+ );
await mount('GPT-6 Astra');
expect(find.text('GPT-6 Astra'), findsOneWidget);
final hover = await tester.createGesture(kind: PointerDeviceKind.mouse);
@@ -323,10 +325,16 @@ void main() {
expect(subscription.selected, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- await mount('GPT-5.6 Sol', local: 'Local-Exact-Name');
+ await mount('GPT-5.6 Sol', effort: 'max');
+ expect(find.text('GPT-5.6 Sol · Max'), findsOneWidget);
+ await mount('GPT-5.6 Sol', effort: 'low');
+ expect(find.text('GPT-5.6 Sol · Low'), findsOneWidget);
+ expect(find.text('GPT-5.6 Sol · Max'), findsNothing);
+ await mount('GPT-5.6 Sol', local: 'Local-Exact-Name', effort: 'low');
expect(find.text('Local-Exact-Name'), findsOneWidget);
+ expect(find.text('Local-Exact-Name · Low'), findsNothing);
expect(find.text('GPT-5.6 Sol'), findsNothing);
- await mount(null);
+ await mount(null, effort: 'low');
expect(find.text('OpenAI'), findsOneWidget);
},
);
diff --git a/desktop/test/harness_activity_test.dart b/desktop/test/harness_activity_test.dart
index dd6cd8094..99a0460e9 100644
--- a/desktop/test/harness_activity_test.dart
+++ b/desktop/test/harness_activity_test.dart
@@ -143,6 +143,13 @@ void main() {
'type': 'turn_ended',
'agentId': 'a0',
});
+ await app.handleEventForTest('m', {
+ 'type': 'turn_summary',
+ 'agentId': 'a0',
+ 'payload': {
+ 'notification': {'id': 'result-a0', 'kind': 'done'},
+ },
+ });
expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.done);
app.markAgentSeen('m', 'a0');
expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.idle);
@@ -163,6 +170,13 @@ void main() {
'type': 'turn_ended',
'agentId': 'a1',
});
+ await app.handleEventForTest('m', {
+ 'type': 'turn_summary',
+ 'agentId': 'a1',
+ 'payload': {
+ 'notification': {'id': 'result-a1', 'kind': 'done'},
+ },
+ });
expect(harnessActivity(app, 'm', 'a1'), HarnessActivity.done);
app.seeWatchedAgents();
expect(harnessActivity(app, 'm', 'a1'), HarnessActivity.done);
diff --git a/desktop/test/notification_inbox_test.dart b/desktop/test/notification_inbox_test.dart
new file mode 100644
index 000000000..bdf5efea3
--- /dev/null
+++ b/desktop/test/notification_inbox_test.dart
@@ -0,0 +1,418 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/agent_git_context.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/notify/alert_sounds.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/notification_inbox.dart';
+import 'package:harness/terminal/terminal_theme_store.dart';
+import 'package:harness/widgets/notification_inbox.dart';
+import 'package:harness/widgets/workspace_notifications_button.dart';
+
+import 'support/real_fonts.dart';
+import 'swarm_attention_test.dart' show waitingQuestion;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+import 'workspace_activity_test.dart' show captureWorkspace;
+
+void main() {
+ final capture = Platform.environment['HARNESS_NOTIFICATION_CAPTURE_DIR'];
+ final bell = find.byKey(const ValueKey('workspace-notifications-button'));
+ final inbox = find.byKey(const ValueKey('notification-inbox'));
+ Finder row(String agent) => find.byKey(ValueKey('notification:m/$agent'));
+
+ setUpAll(() async {
+ await (FontLoader('packages/lucide_icons_flutter/Lucide')..addFont(
+ rootBundle.load('packages/lucide_icons_flutter/assets/lucide.ttf'),
+ ))
+ .load();
+ if (capture != null && Platform.isMacOS) {
+ for (final (family, path) in [
+ ('SF Mono', '/System/Library/Fonts/SFNSMono.ttf'),
+ ('.AppleSystemUIFontMonospaced', '/System/Library/Fonts/SFNSMono.ttf'),
+ ('Menlo', '/System/Library/Fonts/Menlo.ttc'),
+ ('Apple Symbols', '/System/Library/Fonts/Apple Symbols.ttf'),
+ ('.AppleSystemUIFont', '/System/Library/Fonts/SFNS.ttf'),
+ ('Roboto', '/System/Library/Fonts/Supplemental/Arial.ttf'),
+ ]) {
+ final bytes = ByteData.sublistView(await File(path).readAsBytes());
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ } else {
+ await loadRealFonts();
+ }
+ });
+
+ test(
+ 'keeps all nine results and questions, including restored questions',
+ () {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ for (var i = 0; i < 9; i++) {
+ final kind = i < 2
+ ? AlertKind.done
+ : i < 4
+ ? AlertKind.failed
+ : AlertKind.needsYou;
+ app.agentUnread.mark('m', 'a$i', kind);
+ app.rememberOpenedHarness('m', 'a$i');
+ if (i >= 4) {
+ app.stateOf('m')!.blockedAgents['a$i'] = waitingQuestion('a$i');
+ }
+ }
+ final rows = notificationInbox(app);
+ expect(rows, hasLength(9));
+ expect(rows.where((r) => r.kind == AlertKind.needsYou), hasLength(5));
+ expect(rows.where((r) => r.kind == AlertKind.failed), hasLength(2));
+ expect(rows.where((r) => r.kind == AlertKind.done), hasLength(2));
+ expect(rows.every((r) => r.unavailable == null), isTrue);
+ app.agentUnread.clearAll();
+ expect(
+ notificationInbox(app),
+ hasLength(5),
+ reason: 'live questions survive missing unread marks',
+ );
+ app.stateOf('m')!.blockedAgents.clear();
+ app.agentUnread.mark('m', 'a4', AlertKind.needsYou);
+ expect(
+ notificationInbox(app),
+ isEmpty,
+ reason: 'a closed question is not actionable',
+ );
+ },
+ );
+
+ test('notification context follows the current checkout and omits unknown fields', () {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ final machine = app.stateOf('m')!;
+ machine.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Build notifications',
+ project: AgentProject(
+ name: 'old-checkout',
+ cwd: '/work/old',
+ root: '/work/old',
+ remote: 'https://github.com/example/legacy.git',
+ branch: 'old-branch',
+ ),
+ gitContext: AgentGitContext(
+ state: 'single',
+ current: AgentProject(
+ name: 'generated-worktree',
+ cwd: '/work/current',
+ root: '/work/current',
+ remote: 'https://github.com/example/openharness.git',
+ branch: 'desktop-notifications',
+ ),
+ ),
+ ),
+ const Agent(id: 'a1', name: 'Choose a design'),
+ const Agent(id: 'a2', name: 'No project'),
+ ];
+ machine.localProjects = const {
+ 'a1': AgentProject(
+ name: 'website',
+ cwd: '/work/website',
+ branch: 'new-home',
+ ),
+ };
+ machine.blockedAgents['a1'] = waitingQuestion(
+ 'a1',
+ prompt: 'Which design?',
+ );
+ app.agentUnread.mark('m', 'a0', AlertKind.done);
+ app.agentUnread.mark('m', 'a1', AlertKind.needsYou);
+ app.agentUnread.mark('m', 'a2', AlertKind.failed);
+ final rows = {for (final row in notificationInbox(app)) row.agentId: row};
+ expect(rows['a0']!.title, 'Build notifications');
+ expect(rows['a0']!.detail, 'Test host openharness desktop-notifications');
+ expect(rows['a1']!.detail, 'Test host website new-home');
+ expect(rows['a2']!.detail, 'Test host');
+ machine.agents[0] = machine.agents[0].copyWith(
+ gitContext: const AgentGitContext(state: 'unavailable'),
+ );
+ expect(
+ notificationInbox(app).firstWhere((row) => row.agentId == 'a0').detail,
+ 'Test host legacy Git unavailable',
+ reason: 'an unavailable checkout must not report the launch branch as current',
+ );
+ });
+
+ test(
+ 'completed results are acknowledged independently of questions',
+ () async {
+ final app = createApp(connected: true)..watchedAgents = () => const [];
+ addTearDown(app.dispose);
+ await app.handleEventForTest('m', {
+ 'type': 'turn_summary',
+ 'agentId': 'a0',
+ 'payload': {
+ 'notification': {'id': 'result-a0', 'kind': 'done'},
+ },
+ });
+ expect(app.agentUnread.kindFor('m', 'a0'), AlertKind.done);
+ expect(notificationInbox(app).single.label, 'Finished');
+ app.stateOf('m')!.blockedAgents['a1'] = waitingQuestion('a1');
+ app.agentUnread.mark('m', 'a1', AlertKind.needsYou);
+ app.markAgentSeen('m', 'a0');
+ app.markAgentSeen('m', 'a1');
+ expect(notificationInbox(app).single.agentId, 'a1');
+ await app.handleEventForTest('m', {
+ 'type': 'commander_question_close',
+ 'agentId': 'a1',
+ 'payload': {'requestId': 'question'},
+ });
+ expect(notificationInbox(app), isEmpty);
+ },
+ );
+
+ for (final native in [false, true]) {
+ testWidgets(
+ 'bell opens the list; a result reuses its tab and question stays pending (native=$native)',
+ (tester) async {
+ final updates = <Map>[];
+ const channel = MethodChannel('harness/swarm_tabs');
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(channel, (call) async {
+ if (call.method == 'update') updates.add(call.arguments as Map);
+ return true;
+ });
+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
+ final app = createApp(connected: true);
+ final resultTab = app.activeSwarmId;
+ final result = app.adoptSessionForTest(terminal('a8', []));
+ app.newSwarm(name: 'Desktop');
+ app.adoptSessionForTest(terminal('a0', []));
+ app.agentUnread.mark('m', 'a8', AlertKind.failed);
+ app.stateOf('m')!.blockedAgents['a9'] = waitingQuestion('a9');
+ app.agentUnread.mark('m', 'a9', AlertKind.needsYou);
+ await mount(tester, app, nativeTabs: native);
+ await tester.pumpAndSettle();
+
+ Future<void> open() async {
+ if (native) {
+ final done = Completer<void>();
+ messenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('notificationInbox'),
+ ),
+ (_) => done.complete(),
+ );
+ await tester.pumpAndSettle();
+ expect(done.isCompleted, isTrue);
+ } else {
+ await tester.tap(bell);
+ await tester.pumpAndSettle();
+ }
+ }
+
+ expect(
+ native
+ ? updates.last['unread']
+ : tester.widget<WorkspaceNotificationsButton>(bell).count,
+ 2,
+ );
+ await open();
+ expect(inbox, findsOneWidget);
+ expect(
+ app.agentUnread.count,
+ 2,
+ reason: 'opening the list does not acknowledge its entries',
+ );
+ await tester.tap(row('a8'));
+ await tester.pumpAndSettle();
+ expect(inbox, findsNothing);
+ expect(app.activeSwarmId, resultTab);
+ expect(app.focusedPane, same(result));
+ expect(app.allPanes.where((p) => p.agentId == 'a8'), hasLength(1));
+ expect(app.agentUnread.kindFor('m', 'a8'), isNull);
+ await open();
+ await tester.tap(row('a9'));
+ await tester.pumpAndSettle();
+ expect(inbox, findsNothing);
+ expect(app.focusedPane?.agentId, 'a9');
+ expect(app.agentUnread.kindFor('m', 'a9'), AlertKind.needsYou);
+ await open();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(inbox, findsNothing);
+ expect(app.agentUnread.count, 1);
+ await tester.pump(const Duration(milliseconds: 350));
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+ }
+
+ testWidgets(
+ 'unavailable rows remain, navigation failure retains unread, and new rows append',
+ (tester) async {
+ final app = createApp(connected: true);
+ app.agentUnread.mark('m', 'a0', AlertKind.failed);
+ app.agentUnread.mark('m', 'a1', AlertKind.done);
+ var attempts = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () => unawaited(
+ showNotificationInbox(
+ context,
+ app: app,
+ onOpen: (_) async {
+ attempts++;
+ return false;
+ },
+ ),
+ ),
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ final top = tester.getTopLeft(row('a1'));
+ app.agentUnread.mark('m', 'a2', AlertKind.done);
+ await tester.pump();
+ expect(
+ tester.getTopLeft(row('a1')),
+ top,
+ reason: 'arrivals cannot move a row under the pointer',
+ );
+ expect(
+ tester.getTopLeft(row('a2')).dy,
+ greaterThan(tester.getTopLeft(row('a0')).dy),
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(attempts, 1);
+ expect(
+ find.text('Could not open this harness. Try again.'),
+ findsOneWidget,
+ );
+ expect(app.agentUnread.kindFor('m', 'a0'), AlertKind.failed);
+ app.stateOf('m')!.nodeOnline = false;
+ app.agentUnread.mark('m', 'a3', AlertKind.done);
+ await tester.pump();
+ expect(find.text('⊘'), findsWidgets);
+ expect(find.byTooltip('Failed · Offline'), findsOneWidget);
+ await tester.tap(row('a0'));
+ await tester.pump();
+ expect(attempts, 1, reason: 'offline notification cannot navigate');
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ inbox,
+ findsNothing,
+ reason: 'the close control remains keyboard accessible',
+ );
+ expect(app.agentUnread.count, 4);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
+ testWidgets('nine notifications fit the toolbar popup and narrow windows', (
+ tester,
+ ) async {
+ final app = createApp(connected: true);
+ app.renameSwarm(app.activeSwarmId, 'desktop');
+ app.adoptSessionForTest(terminal('a69', [])..agentName = 'Desktop polish');
+ final machine = app.stateOf('m')!;
+ const names = [
+ 'Authentication',
+ 'Documentation',
+ 'Reconnect tests',
+ 'Linux build',
+ 'Desktop layout',
+ 'Search results',
+ 'Device firmware',
+ 'API integration',
+ 'Release notes',
+ ];
+ machine.agents = [
+ ...machine.agents.where(
+ (a) => !names.asMap().containsKey(int.tryParse(a.id.substring(1))),
+ ),
+ for (var i = 0; i < names.length; i++)
+ Agent(
+ id: 'a$i',
+ name: names[i],
+ engine: 'codex',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'preview-$i',
+ cwd: '/work/preview-$i',
+ root: '/work/preview-$i',
+ remote: 'https://github.com/example/openharness.git',
+ branch: names[i].toLowerCase().replaceAll(' ', '-'),
+ ),
+ ),
+ ];
+ for (var i = 0; i < 9; i++) {
+ final kind = i < 2
+ ? AlertKind.done
+ : i < 4
+ ? AlertKind.failed
+ : AlertKind.needsYou;
+ app.agentUnread.mark('m', 'a$i', kind);
+ if (i >= 4) {
+ machine.blockedAgents['a$i'] = waitingQuestion(
+ 'a$i',
+ prompt: 'Which approach should I use?',
+ );
+ }
+ }
+ await mount(tester, app);
+ await tester.tap(bell);
+ await tester.pumpAndSettle();
+ expect(find.text('Notifications 9'), findsOneWidget);
+ expect(find.byTooltip('Needs input'), findsWidgets);
+ expect(find.byTooltip('Failed'), findsWidgets);
+ expect(find.text('Test host openharness release-notes'), findsOneWidget);
+ expect(find.text('Which approach should I use?'), findsNothing);
+ expect(tester.takeException(), isNull);
+ if (capture != null) {
+ await tester.runAsync(() => Directory(capture).create(recursive: true));
+ await captureWorkspace(tester, '$capture/desktop-notifications.png');
+ }
+ tester.view.physicalSize = const Size(640, 480);
+ terminalThemeStore.value = TerminalThemeChoice.tango;
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ // Keyboard navigation scrolls all the way to the last result.
+ for (var i = 0; i < 9; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ }
+ await tester.pumpAndSettle();
+ expect(row('a0').hitTestable(), findsOneWidget);
+ if (capture != null) {
+ await captureWorkspace(
+ tester,
+ '$capture/desktop-notifications-narrow.png',
+ );
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ terminalThemeStore.value = TerminalThemeChoice.matchApp;
+ await tester.pump(const Duration(milliseconds: 350));
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+}
diff --git a/desktop/test/notification_parity_test.dart b/desktop/test/notification_parity_test.dart
index a7f6d7897..2a81b3b0e 100644
--- a/desktop/test/notification_parity_test.dart
+++ b/desktop/test/notification_parity_test.dart
@@ -52,12 +52,16 @@ void main() {
});
tearDown(() => app.dispose());
- Future<void> turnEnded(String agentId, {bool? subagent}) =>
+ Future<void> completed(String agentId, {bool? subagent}) =>
app.handleEventForTest('m', {
- 'type': 'turn_ended',
+ 'type': 'turn_summary',
'agentId': agentId,
'subagent': ?subagent,
- 'payload': <String, dynamic>{},
+ 'payload': <String, dynamic>{
+ 'summary': 'A real final answer',
+ if (subagent != true)
+ 'notification': {'id': 'result-$agentId', 'kind': 'done'},
+ },
});
Future<void> question(String agentId) => app.handleEventForTest('m', {
@@ -82,13 +86,13 @@ void main() {
});
group('a sub-agent is not news on either screen', () {
- test('an ordinary turn end is counted', () async {
- await turnEnded('a1');
+ test('a verified final result is counted', () async {
+ await completed('a1');
expect(app.agentUnread.count, 1);
});
test('a sub-agent turn end is not', () async {
- await turnEnded('a1', subagent: true);
+ await completed('a1', subagent: true);
expect(app.agentUnread.count, 0);
expect(app.agentUnread.kindFor('m', 'a1'), isNull);
});
@@ -97,20 +101,40 @@ void main() {
// Four specialists and a Director that is still busy: the dial draws ONE
// row, for the wrap-up. This used to be five marks here.
for (final worker in ['w1', 'w2', 'w3', 'w4']) {
- await turnEnded(worker, subagent: true);
+ await completed(worker, subagent: true);
}
- await turnEnded('director', subagent: true); // still busy
+ await completed('director', subagent: true); // still busy
expect(app.agentUnread.count, 0);
- await turnEnded('director'); // the wrap-up
+ await completed('director'); // the wrap-up
expect(app.agentUnread.count, 1);
});
- test('a daemon that does not say is a daemon that did not know', () async {
- // Absent field, not false: every build before this one sent nothing, and
- // reading absence as "sub-agent" would swallow every turn they report.
- await turnEnded('a1');
- expect(app.agentUnread.count, 1);
+ test('raw, failed, aborted and replayed turn ends are silent', () async {
+ for (final payload in <Map<String, dynamic>>[
+ {},
+ {'aborted': true},
+ {'error': 'Failed'},
+ ]) {
+ await app.handleEventForTest('m', {
+ 'type': 'turn_ended',
+ 'agentId': 'a1',
+ 'payload': payload,
+ });
+ }
+ await app.handleEventForTest('m', {
+ 'type': 'turn_summary',
+ 'agentId': 'a1',
+ 'payload': {'summary': 'Historical recap'},
+ });
+ expect(app.agentUnread.count, 0);
+ });
+
+ test('redelivery after acknowledgement stays silent', () async {
+ await completed('a1');
+ app.markAgentSeen('m', 'a1');
+ await completed('a1');
+ expect(app.agentUnread.count, 0);
});
});
@@ -148,7 +172,7 @@ void main() {
// The exception is the QUESTION, not the rule: news about a pane you are
// looking at is still noise about the pane you are looking at.
app.watchedAgents = () => [(machineId: 'm', agentId: 'a1')];
- await turnEnded('a1');
+ await completed('a1');
expect(app.agentUnread.count, 0);
});
@@ -162,15 +186,15 @@ void main() {
});
test('answering clears it even when the turn ended first', () async {
- // Answering makes the turn end too, and the two frames race. `turn_ended`
- // runs `_cancelTurnActivity`, which clears `blockedAgents` on the way
- // past — so a close that arrives second finds no open dialog. The mark is
- // the close's to take either way; hanging it off the dialog bookkeeping
- // left it stranded whenever that order came up.
+ // A raw turn end can beat the question close. Only the matching close
+ // clears the question and its unread mark.
await question('a1');
expect(app.agentUnread.count, 1);
- await turnEnded('a1'); // the turn closes first…
+ await app.handleEventForTest('m', {
+ 'type': 'turn_ended',
+ 'agentId': 'a1',
+ });
await answered('a1'); // …and the close lands after
expect(app.agentUnread.count, 0, reason: 'answered is answered');
@@ -195,14 +219,25 @@ void main() {
expect(app.agentUnread.count, 1);
});
+ test(
+ 'redelivering an old question close cannot erase a newer result',
+ () async {
+ await question('a1');
+ await answered('a1');
+ await completed('a1');
+ await answered('a1');
+ expect(app.agentUnread.kindFor('m', 'a1'), AlertKind.done);
+ },
+ );
+
test('the turn that ends WITH the answer is not news', () async {
- // Measured on the real thing: answering ends the turn, and the two frames
- // land a millisecond apart with the turn first. So `done` overwrites the
- // question mark and the badge never goes down — while the person is
- // standing right over that agent, having just answered it.
+ // Answering can also produce a raw stop. That stop is not fresh news.
await question('a1');
- await turnEnded('a1');
- expect(app.agentUnread.kindFor('m', 'a1'), AlertKind.done);
+ await app.handleEventForTest('m', {
+ 'type': 'turn_ended',
+ 'agentId': 'a1',
+ });
+ expect(app.agentUnread.kindFor('m', 'a1'), AlertKind.needsYou);
await answered('a1');
expect(app.agentUnread.count, 0);
@@ -228,9 +263,11 @@ void main() {
'looking at a marked harness is announced, so the dial drops its row',
() async {
await wired.handleEventForTest('m', {
- 'type': 'turn_ended',
+ 'type': 'turn_summary',
'agentId': 'a1',
- 'payload': <String, dynamic>{},
+ 'payload': <String, dynamic>{
+ 'notification': {'id': 'wired-result', 'kind': 'done'},
+ },
});
expect(wired.agentUnread.count, 1);
diff --git a/desktop/test/pending_question_test.dart b/desktop/test/pending_question_test.dart
index 1f0f75112..ce804dddd 100644
--- a/desktop/test/pending_question_test.dart
+++ b/desktop/test/pending_question_test.dart
@@ -210,10 +210,9 @@ void main() {
expect(n.questionFor('m1', 'a1')!.prompt, 'Which font?');
});
- test('the turn ending clears it even with no close frame', () async {
- // A question cannot outlive its own turn — the daemon's watcher is torn
- // down at turn_ended and says the same thing from its end. This side does
- // not depend on that frame surviving the trip.
+ test('only the shared question-close event clears a pending question', () async {
+ // A raw end can precede the actionable dialog being answered. Match the
+ // device and wait for the daemon's authoritative request-specific close.
final n = notifierWithMachine();
await n.handleMachineEventForTest('m1', asked());
await n.handleMachineEventForTest('m1', {
@@ -221,6 +220,8 @@ void main() {
'agentId': 'a1',
'payload': <String, dynamic>{},
});
+ expect(n.questionFor('m1', 'a1'), isNotNull);
+ await n.handleMachineEventForTest('m1', closed());
expect(n.questionFor('m1', 'a1'), isNull);
});
@@ -341,9 +342,12 @@ void main() {
final app = wired();
addTearDown(app.dispose);
await app.handleMachineEventForTest('m1', {
- 'type': 'turn_ended',
+ 'type': 'turn_summary',
'agentId': 'a1',
- 'payload': {'agentId': 'a1'},
+ 'payload': {
+ 'agentId': 'a1',
+ 'notification': {'id': 'result-a1', 'kind': 'done'},
+ },
});
await Future<void>.delayed(Duration.zero);
expect(played, [AlertKind.done.sound]);
@@ -358,9 +362,12 @@ void main() {
const Agent(id: 'a1', name: 'Respond to greeting', engine: 'codex'),
];
await app.handleMachineEventForTest('m1', {
- 'type': 'turn_ended',
+ 'type': 'turn_summary',
'agentId': 'a1',
- 'payload': {'agentId': 'a1'},
+ 'payload': {
+ 'agentId': 'a1',
+ 'notification': {'id': 'result-a1', 'kind': 'done'},
+ },
});
final raised = app.agentAlerts.alerts;
expect(raised, hasLength(1));
@@ -399,9 +406,12 @@ void main() {
app.machineStates['m1'] = MachineState(_machine);
await app.handleMachineEventForTest('m1', {
- 'type': 'turn_ended',
+ 'type': 'turn_summary',
'agentId': 'a1',
- 'payload': {'agentId': 'a1'},
+ 'payload': {
+ 'agentId': 'a1',
+ 'notification': {'id': 'result-a1', 'kind': 'done'},
+ },
});
expect(app.agentUnread.kindFor('m1', 'a1'), AlertKind.done);
expect(app.agentAlerts.alerts, isEmpty, reason: 'banners were off');
@@ -447,9 +457,12 @@ void main() {
app.machineStates['m1'] = MachineState(_machine);
await app.handleMachineEventForTest('m1', asked());
await app.handleMachineEventForTest('m1', {
- 'type': 'turn_ended',
+ 'type': 'turn_summary',
'agentId': 'a1',
- 'payload': {'agentId': 'a1'},
+ 'payload': {
+ 'agentId': 'a1',
+ 'notification': {'id': 'result-a1', 'kind': 'done'},
+ },
});
await Future<void>.delayed(Duration.zero);
expect(played, isEmpty);
@@ -535,14 +548,18 @@ void main() {
return (app: app, x: x, y: y);
}
+ var resultSequence = 0;
Future<void> finish(
AppNotifier a,
String agentId, {
String machineId = 'm1',
}) => a.handleMachineEventForTest(machineId, {
- 'type': 'turn_ended',
+ 'type': 'turn_summary',
'agentId': agentId,
- 'payload': {'agentId': agentId},
+ 'payload': {
+ 'agentId': agentId,
+ 'notification': {'id': 'result-${resultSequence++}', 'kind': 'done'},
+ },
});
test('harnesses on the tab in front of you finish silently; one on another tab does not', () async {
diff --git a/desktop/test/runtime_model_name_test.dart b/desktop/test/runtime_model_name_test.dart
index ddea45f8d..564395610 100644
--- a/desktop/test/runtime_model_name_test.dart
+++ b/desktop/test/runtime_model_name_test.dart
@@ -25,6 +25,30 @@ void main() {
}
});
+ test('observed effort stays with the validated model', () {
+ for (final (effort, label) in [
+ ('low', 'Low'),
+ ('high', 'High'),
+ ('xhigh', 'XHigh'),
+ ('max', 'Max'),
+ ('auto', 'Auto'),
+ ('none', 'None'),
+ ('future-effort', 'future-effort'),
+ ]) {
+ final details = runtimeModelDetails(
+ 'runtime-v1:a:codex:gpt-6-astra@$effort',
+ agentId: 'a',
+ engine: 'codex',
+ )!;
+ expect(details.effort, effort);
+ expect(
+ modelLabelWithEffort(details.name, details.effort),
+ 'GPT-6 Astra · $label',
+ );
+ }
+ expect(modelLabelWithEffort('GPT-6 Astra', null), 'GPT-6 Astra');
+ });
+
test('missing, stale and malformed runtime metadata has no model label', () {
for (final value in <Object?>[
null,
@@ -48,6 +72,7 @@ void main() {
isNull,
reason: '$value',
);
+ expect(runtimeModelDetails(value, agentId: 'a', engine: 'codex'), isNull);
}
expect(
runtimeModelName('runtime-v1:a:codex:gpt-6-astra@high', agentId: 'a'),
diff --git a/desktop/test/share_toolbar_test.dart b/desktop/test/share_toolbar_test.dart
index ece2a94ab..926e36cec 100644
--- a/desktop/test/share_toolbar_test.dart
+++ b/desktop/test/share_toolbar_test.dart
@@ -287,7 +287,7 @@ void main() {
});
testWidgets(
- 'Share keeps its corner at narrow widths and follows custom shortcuts',
+ 'Share stays in the footer at narrow widths and follows custom shortcuts',
(tester) async {
app.adoptSessionForTest(terminal('a0', input));
await mount(tester, size: const Size(520, 800));
@@ -295,12 +295,13 @@ void main() {
find.byKey(const ValueKey('workspace-status-bar')),
);
expect(tester.getRect(button).right, lessThanOrEqualTo(bar.right));
+ expect(bar.contains(tester.getRect(button).center), isTrue);
expect(
- tester.getRect(button).left,
+ tester.getRect(button).top,
greaterThan(
tester
- .getRect(find.byKey(const ValueKey('swarm-new-tab-button')))
- .right,
+ .getRect(find.byKey(const ValueKey('workspace-tab-bar')))
+ .bottom,
),
);
expect(tester.takeException(), isNull);
diff --git a/desktop/test/support/status_bar_layout.dart b/desktop/test/support/status_bar_layout.dart
index 85c06c870..c5cbb1bd9 100644
--- a/desktop/test/support/status_bar_layout.dart
+++ b/desktop/test/support/status_bar_layout.dart
@@ -47,11 +47,9 @@ Future<Map<String, List<List<double>>>> measureStatusBar(
await tester.pump(const Duration(milliseconds: 100));
final bar = find.byKey(const ValueKey('workspace-status-bar'));
out['${width.toInt()}'] = [
+ box(tester.getRect(find.byKey(const ValueKey('workspace-tab-bar')))),
box(tester.getRect(bar)),
- for (final element
- in find
- .descendant(of: bar, matching: find.byType(WorkspaceBarControl))
- .evaluate())
+ for (final element in find.byType(WorkspaceBarControl).evaluate())
box(tester.getRect(find.byWidget(element.widget))),
box(tester.getRect(find.byKey(const ValueKey('workspace-pane-context')))),
];
diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dart
index dfe52ca26..a85b239af 100644
--- a/desktop/test/swarm_screen_test.dart
+++ b/desktop/test/swarm_screen_test.dart
@@ -523,9 +523,9 @@ void main() {
find.byKey(const ValueKey('harness-start-search')),
findsOneWidget,
);
- expect(find.byKey(const ValueKey('swarm-search-button')), findsNothing);
+ expect(find.byKey(const ValueKey('swarm-search-button')), findsOneWidget);
expect(find.text('Machines'), findsNothing);
- await openHarnessPicker(tester);
+ await tester.tap(find.byKey(const ValueKey('swarm-search-button')));
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
diff --git a/desktop/test/system_notifications_test.dart b/desktop/test/system_notifications_test.dart
index 10a269f6c..674375d02 100644
--- a/desktop/test/system_notifications_test.dart
+++ b/desktop/test/system_notifications_test.dart
@@ -237,9 +237,12 @@ void main() {
Future<void> finish(AppNotifier app) =>
app.handleMachineEventForTest('m1', {
- 'type': 'turn_ended',
+ 'type': 'turn_summary',
'agentId': 'a1',
- 'payload': {'agentId': 'a1'},
+ 'payload': {
+ 'agentId': 'a1',
+ 'notification': {'id': 'result-a1', 'kind': 'done'},
+ },
});
test('an agent that finishes while the window is behind something reaches the system', () async {
diff --git a/desktop/test/workspace_activity_test.dart b/desktop/test/workspace_activity_test.dart
index 79fe621f1..f8348b830 100644
--- a/desktop/test/workspace_activity_test.dart
+++ b/desktop/test/workspace_activity_test.dart
@@ -159,6 +159,13 @@ void main() {
'type': 'turn_ended',
'agentId': 'a2',
});
+ await app.handleEventForTest('m', {
+ 'type': 'turn_summary',
+ 'agentId': 'a2',
+ 'payload': {
+ 'notification': {'id': 'result-a2', 'kind': 'done'},
+ },
+ });
await tester.pump(const Duration(milliseconds: 100));
if (native) {
expect(nativeActivity(second.id)['mark'], '✓');
diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dart
index 8f4316162..41081df21 100644
--- a/desktop/test/workspace_status_test.dart
+++ b/desktop/test/workspace_status_test.dart
@@ -12,6 +12,7 @@ import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/shared/theme/appearance_prefs_store.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/workspace_bar_style.dart';
import 'package:harness/shared/theme/prompt_style.dart';
import 'package:harness/shared/theme/status_line_style.dart';
import 'package:harness/state/swarm.dart';
@@ -113,7 +114,20 @@ void main() {
if (Platform.environment['HARNESS_WORKSPACE_CONTROLS_CAPTURE_DIR'] !=
null) {
await loadRealFonts();
+ await (FontLoader('packages/lucide_icons_flutter/Lucide')..addFont(
+ rootBundle.load('packages/lucide_icons_flutter/assets/lucide.ttf'),
+ ))
+ .load();
if (Platform.isMacOS) {
+ await (FontLoader('Apple Symbols')..addFont(
+ Future.value(
+ ByteData.sublistView(
+ await File('/System/Library/Fonts/Apple Symbols.ttf')
+ .readAsBytes(),
+ ),
+ ),
+ ))
+ .load();
final bytes = ByteData.sublistView(
await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
);
@@ -187,9 +201,9 @@ void main() {
findsNothing,
);
if (native) {
- expect(updates.last['focusedModel']['text'], 'GPT-6 Astra');
+ expect(updates.last['focusedModel']['text'], 'GPT-6 Astra · High');
} else {
- expect(find.text('GPT-6 Astra'), findsOneWidget);
+ expect(find.text('GPT-6 Astra · High'), findsOneWidget);
expect(find.text('Fable'), findsNothing);
await captureControls(tester, 'focused-model');
expect(
@@ -203,12 +217,12 @@ void main() {
app.focusPane(first.id);
await tester.pump();
if (native) {
- expect(updates.last['focusedModel']['text'], 'Fable');
+ expect(updates.last['focusedModel']['text'], 'Fable · High');
await activate(second.id, 'a1');
expect(find.text('Local-Test-Model'), findsNothing);
await activate(first.id, 'a0');
} else {
- expect(find.text('GPT-6 Astra'), findsNothing);
+ expect(find.text('GPT-6 Astra · High'), findsNothing);
await tester.tap(selectors);
}
await tester.pumpAndSettle();
@@ -351,6 +365,7 @@ void main() {
name: 'Feature',
engine: 'codex',
modelName: 'GPT-6 Astra',
+ modelEffort: 'max',
terminalAvailable: true,
project: AgentProject(
name: 'repo',
@@ -513,11 +528,7 @@ void main() {
.emphasized,
isFalse,
);
- await captureControls(
- tester,
- 'bar-hover-${style.name}',
- height: 100,
- );
+ await captureControls(tester, 'bar-hover-${style.name}');
}
}
await mouse.removePointer();
@@ -930,7 +941,7 @@ void main() {
});
testWidgets(
- 'compact tabs sit to the left of one focused context and switch workspaces',
+ 'top navigation and bottom context stay separate while switching workspaces',
(tester) async {
final app = createApp();
addTearDown(app.dispose);
@@ -944,14 +955,21 @@ void main() {
expect(find.text('2:'), findsOneWidget);
final context = find.byKey(const ValueKey('workspace-pane-context'));
expect(
- tester.getRect(context).left,
+ tester.getRect(context).top,
greaterThan(
- tester.getRect(find.byKey(ValueKey(app.activeSwarmId))).right,
+ tester.getRect(find.byKey(ValueKey(app.activeSwarmId))).bottom,
),
);
final secondTab = find.byKey(ValueKey(app.activeSwarmId));
final barControls = find.byType(WorkspaceBarControl);
- final bar = find.byKey(const ValueKey('workspace-status-bar'));
+ final bar = find.byKey(const ValueKey('workspace-tab-bar'));
+ final footer = tester.getRect(
+ find.byKey(const ValueKey('workspace-status-bar')),
+ );
+ expect(footer.bottom, 800);
+ expect(footer.height, 37.5);
+ expect(tester.getRect(context).center.dy, footer.center.dy);
+ expect(footer.contains(tester.getRect(context).center), isTrue);
for (final element in barControls.evaluate()) {
final control = element.widget as WorkspaceBarControl;
final rect = tester.getRect(find.byWidget(control));
@@ -972,9 +990,14 @@ void main() {
expect(tester.getRect(fill).bottom, tester.getRect(bar).bottom);
}
}
- expect(tester.getSize(secondTab).width, lessThan(150));
- expect(find.byKey(const ValueKey('swarm-search-button')), findsNothing);
- for (final old in ['harnesses', 'machines', 'models', 'store', 'help']) {
+ expect(
+ tester.getSize(secondTab).width,
+ lessThan(workspaceBarCellSizeOf(tester.element(secondTab)).width * 12),
+ reason: 'short tab labels keep their compact width in a roomy window',
+ );
+ expect(find.byKey(const ValueKey('swarm-search-button')), findsOneWidget);
+ expect(find.byKey(const ValueKey('swarm-store-button')), findsOneWidget);
+ for (final old in ['harnesses', 'machines', 'models', 'help']) {
expect(find.byKey(ValueKey('swarm-$old-button')), findsNothing);
}
expect(
@@ -1004,7 +1027,7 @@ void main() {
expect(tester.getRect(context).right, lessThan(width));
}
}
- await captureControls(tester, 'unified-search-toolbar', height: 100);
+ await captureControls(tester, 'workspace-bottom-bar');
await tester.pump(const Duration(milliseconds: 100));
await tester.pumpWidget(const SizedBox());
},
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index dc1a603cf..b921948d8 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -18,6 +18,8 @@ private final class TitlebarMouseUpProbe: NSResponder {
private extension NSView {
func renderedBitmap() -> NSBitmapImageRep {
+ precondition(bounds.width >= 1 && bounds.height >= 1,
+ "Cannot render empty \(type(of: self)) at \(frame), after \(titlebarCheckCount) checks")
let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil,
pixelsWide: Int(bounds.width), pixelsHigh: Int(bounds.height),
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
@@ -66,6 +68,7 @@ private extension SwarmTabButton {
["mark": mark, "label": label, "color": Int64(0xff64d2ff)]
}
let width = preferredWidth
+ let displayedWidth = frame.width
let rect = activityRect
try checkTitlebar(label.string == "1:desktop" && activitySpace == cellWidth * 2,
"Activity measures its gap and cell separately from the tab name")
@@ -90,7 +93,7 @@ private extension SwarmTabButton {
"\(label) occupies the same reserved cell")
try checkTitlebar(toolTip == label && selectButton.accessibilityHelp() == label,
"\(label) has readable hover and accessibility descriptions")
- for narrow in [CGFloat(28), CGFloat(56), width] {
+ for narrow in [CGFloat(28), CGFloat(56), width, displayedWidth] {
frame.size.width = narrow
let bitmap = renderedBitmap()
if let capture = ProcessInfo.processInfo.environment["HARNESS_ACTIVITY_CAPTURE_DIR"] {
@@ -111,7 +114,7 @@ private extension SwarmTabButton {
try checkTitlebar(colored == !mark.isEmpty,
"\(label) \(mark.isEmpty ? "stays unmarked" : "remains visible") at tab width \(narrow)")
}
- frame.size.width = width
+ frame.size.width = displayedWidth
}
}
@@ -484,8 +487,8 @@ private extension SwarmTabStrip {
try checkTitlebar(daemonButton.frame.maxX <= bounds.width &&
daemonButton.frame.minX >= pullRequestButton.frame.maxX &&
contextButton.frame.maxX <= pullRequestButton.frame.minX &&
- newButton.frame.maxX < contextButton.frame.minX,
- "Daemon, PR, context, and tabs do not overlap at \(width)px / \(size)pt")
+ contextButton.superview === statusBar && newButton.frame.maxX < searchButton.frame.minX,
+ "Footer controls and top navigation do not overlap at \(width)px / \(size)pt")
try checkTitlebar(abs(daemonButton.frame.width - ceil(workspaceBarTextWidth("m", font: daemonButton.font!)) * 10) < 0.5,
"Eight cells plus a one-cell gutter each side at \(size)pt")
try checkActiveVisible()
@@ -493,9 +496,9 @@ private extension SwarmTabStrip {
}
}
let tab = tabs[0]
- try checkTitlebar(pullRequestButton.frame.maxX == daemonButton.frame.minX &&
- daemonButton.frame.height == newButton.frame.height &&
- daemonButton.frame.midY == newButton.frame.midY,
+ try checkTitlebar(pullRequestButton.frame.maxX <= daemonButton.frame.minX &&
+ daemonButton.frame.height == focusedModelButton.frame.height &&
+ daemonButton.frame.midY == focusedModelButton.frame.midY,
"The daemon follows the focused context and shares the controls' height and inner gutters")
scroll.contentView.scroll(to: .zero)
let scrollFrame = scroll.frame, visible = scroll.documentVisibleRect
@@ -570,11 +573,11 @@ private extension SwarmTabStrip {
voiceLabel.color == statusColor(0xffd7af5f, fallback: .clear) &&
voiceLabel.accessibilityLabel() == voiceLabel.text && voiceLabel.accessibilityRole() == .staticText,
"The daemon's line shows in the message colour")
- try checkTitlebar(contextButton.isHidden && pullRequestButton.isHidden && focusedModelButton.isHidden,
- "Its line replaces the context, PR and model while it speaks")
+ try checkTitlebar(contextButton.isHidden && pullRequestButton.isHidden && !focusedModelButton.isHidden,
+ "Its line replaces the left context while the model stays available on the right")
try checkTitlebar(unmoved(), "Speaking moves no tab, status control or the slot")
- try checkTitlebar(voiceLabel.frame.maxX == daemonButton.frame.minX &&
- voiceLabel.frame.minX == newButton.frame.maxX + ceil(("m" as NSString).size(withAttributes: [.font: daemonButton.font!]).width) * 2,
+ try checkTitlebar(voiceLabel.frame.maxX < daemonButton.frame.minX &&
+ voiceLabel.frame.minX == ceil(("m" as NSString).size(withAttributes: [.font: daemonButton.font!]).width),
"The line spans the status area up to the slot")
let voicePixels = voiceLabel.renderedPixels()
daemon["voice"] = String(repeating: "a very long line ", count: 40)
@@ -583,7 +586,7 @@ private extension SwarmTabStrip {
"A long line truncates in place")
state["daemon"] = daemon
update(state)
- try checkTitlebar(contextButton.isHidden && pullRequestButton.isHidden && focusedModelButton.isHidden && !voiceLabel.isHidden,
+ try checkTitlebar(contextButton.isHidden && pullRequestButton.isHidden && !focusedModelButton.isHidden && !voiceLabel.isHidden,
"A workspace update while it speaks keeps the message line")
try checkTitlebar(unmoved(), "A workspace update while it speaks lays out as if the status were shown")
// The pair brain's line, exactly as sent, keys first: each offered key in
@@ -618,9 +621,9 @@ private extension SwarmTabStrip {
emit = previousEmit
try checkTitlebar(events == ["daemonAnswer"] && (answered.first as? [String: String])?["key"] == "y",
"Clicking a key sends exactly that key, and the line itself is not a button")
- try checkTitlebar(voiceLabel.hitTest(voiceLabel.convert(onLine, to: self)) == nil &&
- voiceLabel.hitTest(voiceLabel.convert(NSPoint(x: yes.midX, y: yes.midY), to: self)) === voiceLabel,
- "Only the keys take the pointer; the rest still drags the window")
+ try checkTitlebar(voiceLabel.hitTest(voiceLabel.convert(onLine, to: statusBar)) == nil &&
+ voiceLabel.hitTest(voiceLabel.convert(NSPoint(x: yes.midX, y: yes.midY), to: statusBar)) === voiceLabel,
+ "Only the offered keys take the pointer")
try checkTitlebar(unmoved(), "Keys move nothing in the bar")
// Until the line is armed (drawn, with its detail, a moment ago) its keys
// are drawn faint and take no click; [g] opens at any time.
@@ -632,7 +635,7 @@ private extension SwarmTabStrip {
let unarmedPixels = voiceLabel.renderedPixels()
try checkTitlebar(voiceLabel.actionRects.map(\.key) == ["g"] && voiceLabel.arming.map(\.key) == ["y", "n"] &&
voiceLabel.arming[0].range == NSRange(location: 1, length: 1) &&
- voiceLabel.hitTest(voiceLabel.convert(NSPoint(x: yes.midX, y: yes.midY), to: self)) == nil,
+ voiceLabel.hitTest(voiceLabel.convert(NSPoint(x: yes.midX, y: yes.midY), to: statusBar)) == nil,
"An unarmed line's y and n are faint and take no click; its g still opens")
daemon["voiceArmed"] = true
updateDaemon(daemon)
@@ -726,6 +729,49 @@ private extension SwarmTabStrip {
"Workspace teardown hides the daemon")
}
+ func checkNotifications() throws {
+ var state: [String: Any] = ["enabled": true, "unread": 9,
+ "tabs": [["id": "work", "name": "Desktop"]], "activeId": "work",
+ "focusedContext": ["text": "Office project", "segments": [["text": "Office project"]]]]
+ var calls: [String] = []
+ emit = { method, _ in calls.append(method) }
+ for width in [CGFloat(360), CGFloat(640), CGFloat(1280)] {
+ setFrameSize(NSSize(width: width, height: 40))
+ update(state)
+ try checkTitlebar(notificationsButton.isEnabled && notificationsButton.frame.width > 0 &&
+ notificationsButton.frame.maxX <= bounds.width &&
+ searchButton.frame.maxX <= notificationsButton.frame.minX &&
+ notificationsButton.frame.maxX <= storeButton.frame.minX &&
+ storeButton.frame.maxX <= bounds.width &&
+ newButton.frame.maxX < searchButton.frame.minX &&
+ contextButton.superview === statusBar,
+ "Search, bell and Store stay visible after the tabs at width \(width)")
+ let frame = notificationsButton.frame
+ state["unread"] = 101
+ update(state)
+ try checkTitlebar(notificationsButton.frame == frame,
+ "Unread count changes do not move the native toolbar")
+ }
+ try checkTitlebar(notificationsButton.accessibilityLabel() == "Notifications" &&
+ notificationsButton.accessibilityValue() as? String == "101 unread",
+ "The native bell exposes its exact count even when its badge reads 99+")
+ notificationsButton.performClick(nil)
+ searchButton.performClick(nil)
+ storeButton.performClick(nil)
+ try checkTitlebar(calls == ["notificationInbox", "sessions", "store"],
+ "Top actions open the existing notifications, search and Store surfaces")
+ state["enabled"] = false
+ update(state)
+ notificationsButton.performClick(nil)
+ searchButton.performClick(nil)
+ storeButton.performClick(nil)
+ try checkTitlebar(!notificationsButton.isEnabled && !searchButton.isEnabled && !storeButton.isEnabled && calls.count == 3,
+ "A modal prevents the bell from dispatching another action")
+ update([:])
+ try checkTitlebar(notificationsButton.count == 0 && !notificationsButton.isEnabled,
+ "Teardown clears the unread badge and disables the bell")
+ }
+
func checkShareAction() throws {
let target: [String: Any] = ["text": "[ Share ]", "label": "Share Website launch",
"tooltip": "Share Website launch · ⇧⌘S", "enabled": true,
@@ -749,8 +795,8 @@ private extension SwarmTabStrip {
shareButton.frame.width == shareButton.preferredWidth &&
shareButton.frame.maxX <= bounds.width &&
contextButton.frame.maxX < shareButton.frame.minX &&
- newButton.frame.maxX < shareButton.frame.minX,
- "Share stays prominent at the right edge without overlapping tabs or context at width \(width)")
+ shareButton.superview === statusBar,
+ "Share stays in the footer without overlapping context at width \(width)")
update(hidden)
try checkTitlebar(barFrames() == withoutShare,
"Turning Share off restores the original toolbar layout at width \(width)")
@@ -811,12 +857,15 @@ private extension SwarmTabStrip {
"Numbered tabs use 13 pt SF Mono regular")
try checkTitlebar(tabs[0].drawnFont == tabs[1].drawnFont && contextButton.font == tabs[0].labelFont,
"Active tabs, inactive tabs, and pane context share one font")
- for control in [newButton] {
- try checkTitlebar(control.font == contextButton.font && control.frame.midY == contextButton.frame.midY,
- "Status symbols share the terminal font and centered text baseline")
+ for control in [newButton, storeButton] {
+ try checkTitlebar(control.font == contextButton.font && control.frame.midY == bounds.midY &&
+ contextButton.frame.midY == statusBar.bounds.midY,
+ "Top actions and footer context share a font and center within their own rows")
}
- try checkTitlebar(tabs[0].frame.width < tabs[1].frame.width,
- "Each tab occupies its own text width and fixed cell gutters")
+ try checkTitlebar(tabs[0].frame.width == tabs[0].preferredWidth &&
+ tabs[1].frame.width == tabs[1].preferredWidth &&
+ tabs[0].frame.width < tabs[1].frame.width,
+ "Tabs keep their label widths instead of expanding to fill the row")
try checkTitlebar(tabs[0].menu?.font == menuFont, "Native context menus retain the system menu font")
}
@@ -886,8 +935,9 @@ private extension SwarmTabStrip {
"Powerline context and PR are adjacent at width \(width)")
try checkTitlebar(contextButton.nextBackground == pullRequestButton.firstBackground,
"The closing arrow joins into the PR background")
- try checkTitlebar(newButton.frame.maxX < contextButton.frame.minX &&
- pullRequestButton.frame.maxX <= bounds.width, "Joined status stays clear of tabs and window edges")
+ try checkTitlebar(contextButton.superview === statusBar && pullRequestButton.superview === statusBar &&
+ contextButton.frame.minX >= 0 && pullRequestButton.frame.maxX <= statusBar.bounds.width,
+ "Joined status stays inside its separate footer")
}
setFrameSize(originalSize)
update(prState)
@@ -969,9 +1019,10 @@ private extension SwarmTabStrip {
update(linked)
try checkTitlebar(!focusedModelButton.isHidden && focusedModelButton.isEnabled,
"Focused model has its own enabled status control")
- try checkTitlebar(focusedModelButton.frame.maxX < contextButton.frame.minX &&
- focusedModelButton.frame.height == newButton.frame.height,
- "Model sits before machine/repo with the shared control height")
+ try checkTitlebar(focusedModelButton.frame.minX > pullRequestButton.frame.maxX &&
+ focusedModelButton.frame.height == contextButton.frame.height &&
+ focusedModelButton.frame.maxX <= statusBar.bounds.width,
+ "Model sits on the right of the footer opposite machine/repo/branch/PR")
try checkTitlebar(focusedModelButton.toolTip == "Switch model · Subscription or local models",
"Model hint explains switching without repeating the visible name")
let modelResting = focusedModelButton.renderedPixels()
@@ -1008,11 +1059,11 @@ private extension SwarmTabStrip {
try tabs[0].checkDoubleClickIsolation()
try checkTitlebar(tabs.count == 24 && newButton.isEnabled, "All overflow tabs and New Tab remain available")
try checkTitlebar(scroll.frame.maxX <= newButton.frame.minX &&
- newButton.frame.maxX < contextButton.frame.minX, "Tabs are left of the right-aligned focused context")
+ newButton.frame.maxX < searchButton.frame.minX, "Tabs precede the search, bell and Store controls")
try checkTitlebar(tabs[0].frame.width < 120 && tabs[0].displayLabel == "1:code",
- "Short numbered labels use text-sized widths")
- try checkTitlebar(subviews.count == 8 && pullRequestButton.isHidden && focusedModelButton.isHidden && daemonButton.isHidden && voiceLabel.isHidden && shareButton.isHidden,
- "Context links fill the bar; standalone search and management controls are absent")
+ "Overflow tabs keep a readable minimum width and their numbered names")
+ try checkTitlebar(subviews.count == 5 && statusBar.subviews.count == 6 && pullRequestButton.isHidden && focusedModelButton.isHidden && daemonButton.isHidden && voiceLabel.isHidden && shareButton.isHidden,
+ "Navigation lives in the titlebar and focused context lives in the footer")
let controls = [newButton]
for (control, symbol) in zip(controls, ["+"]) {
try checkTitlebar(control.image == nil && control.title == symbol && !control.isBordered,
@@ -1060,8 +1111,8 @@ private extension SwarmTabStrip {
needsLayout = true
layoutSubtreeIfNeeded()
try checkActiveVisible()
- try checkTitlebar(newButton.frame.maxX < contextButton.frame.minX &&
- contextButton.frame.maxX <= bounds.width, "Narrow windows have no overlapping controls")
+ try checkTitlebar(newButton.frame.maxX < searchButton.frame.minX &&
+ contextButton.frame.maxX <= statusBar.bounds.width, "Narrow windows have no overlapping controls")
let original = tabs[0]
let reversed = Array(rows.reversed())
update(state(reversed, active: "swarm-0"))
@@ -1518,10 +1569,20 @@ private extension SwarmTitlebar {
"tabs": [["id": "startup-check", "name": "Synthetic swarm"]],
"activeId": "startup-check", "enabled": true, "palette": startupColors,
])
+ window.contentView?.layoutSubtreeIfNeeded()
+ try checkTitlebar(strip.statusBar.superview === window.contentView && !strip.statusBar.isHidden &&
+ strip.statusBar.frame.width == window.contentView!.bounds.width &&
+ strip.statusBar.frame.minY == window.contentView!.bounds.minY &&
+ strip.statusBar.frame.height == strip.preferredStatusBarHeight,
+ "The native footer spans the content bottom without adding another titlebar row")
+ try checkTitlebar(strip.statusBar.isAccessibilityElement() &&
+ strip.statusBar.accessibilityParent() as? NSView === strip &&
+ strip.accessibilityChildren()?.contains(where: { $0 as? NSView === strip.statusBar }) == true,
+ "The footer remains in the native accessibility tree outside Flutter-owned children")
// SwarmScreen.dispose sends this when sign-in or setup takes its place.
_ = try messenger.receive("update", arguments: ["tabs": [], "enabled": false])
- try checkTitlebar(window.backgroundColor == startupPalette.tabBar,
- "Leaving the workspace preserves the saved native background")
+ try checkTitlebar(window.backgroundColor == startupPalette.tabBar && strip.statusBar.isHidden,
+ "Leaving the workspace hides the footer and preserves the saved native background")
try strip.checkStartupPalette(startupPalette)
try window.checkContentCommand()
try checkTitlebar(window.firstResponder === window.contentInput,
@@ -1911,6 +1972,7 @@ do {
try strip.checkAgentIdentity()
try strip.checkSharedTypography()
try strip.checkShareAction()
+ try strip.checkNotifications()
try strip.checkActivityMarks()
try SwarmTabButton(id: "hover-fixture").checkHoverStyleAndTooltips()
try strip.checkDaemon()