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.

Open Harness Monitor as a reusable DSH process table (#547)

Dee7697816b6ac6
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 2cf074ad5..3b50858e1 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -2248,6 +2248,25 @@ describe('agent_restart RPC', () => {
await socket.stop()
})
+ it('adds monitor activity and readings only when explicitly requested', async () => {
+ const { socket, frames } = localSocket()
+ vi.spyOn(registry, 'advertised').mockReturnValue([BASE_SESSION])
+ vi.spyOn(registry, 'list').mockReturnValue([BASE_SESSION])
+ vi.spyOn(stoppedAgents, 'available').mockReturnValue([{ ...BASE_SESSION, agentId: 'stopped' }])
+ socket.harnessResourcesReader = vi.fn(async () => ({ sampledAt: new Date().toISOString(), agents: [{ agentId: 'agent-1', memoryBytes: 123, cpuPercent: 2, processCount: 1 }] }))
+ socket.monitorActivityProvider = sessionId => sessionId === BASE_SESSION.sessionId ? 'needsInput' : 'idle'
+ for (const [requestId, monitor] of [['plain', false], ['monitor', true]] as const) {
+ socket.handleLocalFrame('local:restart', { type: 'agents_list', payload: { requestId, monitor, includeStopped: true } })
+ }
+ await vi.waitFor(() => expect(frames.filter(f => f.type === 'agents_list_result')).toHaveLength(2))
+ const response = (id: string) => (frames.find(frame => (frame.payload as any).requestId === id)?.payload as any).agents
+ expect(response('plain').every((agent: any) => agent.monitor === undefined)).toBe(true)
+ expect(response('monitor').find((a: any) => a.id === 'agent-1').monitor).toEqual({ activity: 'needsInput', activityKnown: true, rssBytes: 123, cpu: 2, pid: BASE_SESSION.processIdentity?.pid ?? null })
+ expect(response('monitor').find((a: any) => a.id === 'stopped').monitor).toMatchObject({ rssBytes: 0, cpu: 0, pid: null })
+ expect(socket.harnessResourcesReader).toHaveBeenCalledOnce()
+ await socket.unregisterLocalClient('local:restart'); await socket.stop()
+ })
+
it('delegates a resume-only intent and retains its original receipt', async () => {
const { socket, frames } = localSocket()
const creationId = `resume-${randomUUID()}`
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index e655747dd..4407aeadc 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1,5 +1,6 @@
import type { ActivityFrame } from './lib/turnActivity.js'
import { readSessionGitPullRequest } from './lib/sessionGitPullRequest.js'
+import { MonitorCompletions, type MonitorActivity } from './lib/harnessMonitor.js'
import type { HarnessShareOwner } from './sharing/owner.js'
import { SHARE_REQUEST_TYPES } from './sharing/protocol.js'
import { AutonomousDeviceRelay } from './lib/autonomous-device/relay.js'
@@ -751,6 +752,8 @@ export class BackendSocket {
recentProvider: RecentProvider | null = null
/** The person's own last questions for an agent, newest first. See the `agent_recent` case. */
recentAsksProvider: ((agentId: string, n: number) => string[]) | null = null
+ monitorActivityProvider: ((sessionId: string) => MonitorActivity) | null = null
+ private readonly monitorCompletions = new MonitorCompletions()
/** Answers `session_search` from this machine's transcript index (lib/sessionSearch/). Null when
* this Node has no `node:sqlite`. */
sessionSearchProvider: ((query: string, options: { limit?: number; from?: number; to?: number }) => SessionSearchResult) | null = null
@@ -1228,6 +1231,7 @@ export class BackendSocket {
/** Send an up-frame (event or RPC reply) to the WEB audience. Queued while disconnected.
* User-content events are group-encrypted (E2EE) here; system frames pass through as plaintext. */
send(frame: Frame): void {
+ this.monitorCompletions.observe(frame)
// Only an already-open orchestration service observes events; ordinary sessions
// do not create project state or incur disk work. Project payloads stay local.
this.orchestratorService?.ingest(frame)
@@ -2160,7 +2164,8 @@ export class BackendSocket {
return
case 'agents_list': {
- const projects = await Promise.all(registry.advertised().map((s) => this.toProject(s)))
+ const sessions = registry.advertised()
+ const projects = await Promise.all(sessions.map((s) => this.toProject(s)))
// Older clients/devices keep their live-only contract. The desktop picker
// explicitly asks for stopped work and receives no stale terminal routes.
if (payload.includeStopped === true && this.e2ee.sessionRole(connId) !== 'device') {
@@ -2177,7 +2182,23 @@ export class BackendSocket {
reply(type, requestId, { agents: projects.filter(deviceAgentRow).slice(0, DEVICE_AGENT_LIST_LIMIT).map(deviceAgentListItem) })
return
}
- reply(type, requestId, { agents: projects })
+ if (payload.monitor === true) {
+ const snapshot = await this.harnessResourcesReader().catch(() => ({ agents: [] }))
+ const resources = new Map(snapshot.agents.map(row => [row.agentId, row]))
+ const byId = new Map(sessions.map(s => [s.agentId, s]))
+ reply(type, requestId, { agents: projects.map(agent => {
+ const session = byId.get(agent.id)
+ const activity = session ? this.monitorActivityProvider?.(session.sessionId) : null
+ const reading = resources.get(agent.id)
+ return { ...agent, monitor: {
+ activity: activity && activity !== 'idle' ? activity : session ? this.monitorCompletions.state(session) : 'idle',
+ activityKnown: this.monitorActivityProvider !== null,
+ rssBytes: agent.status === 'stopped' ? 0 : reading?.memoryBytes ?? null,
+ cpu: agent.status === 'stopped' ? 0 : reading?.cpuPercent ?? null,
+ pid: reading?.processCount != null ? session?.processIdentity?.pid ?? null : null,
+ } }
+ }) })
+ } else reply(type, requestId, { agents: projects })
return
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 8c7ccebd4..6c227107c 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -2928,6 +2928,8 @@ 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>>()
+ backend.monitorActivityProvider = sessionId => openQuestions.has(sessionId)
+ ? 'needsInput' : sessionTurnOpen(sessionId) ? 'working' : 'idle'
const agentNotifications = new AgentNotifications()
const questionWatcher = new QuestionWatcher({
getSession: (id) => registry.resolve(id),
diff --git a/cli/src/lib/harnessMonitor.spec.ts b/cli/src/lib/harnessMonitor.spec.ts
new file mode 100644
index 000000000..3a4d25a70
--- /dev/null
+++ b/cli/src/lib/harnessMonitor.spec.ts
@@ -0,0 +1,17 @@
+import { expect, it } from 'vitest'
+import { MonitorCompletions } from './harnessMonitor.js'
+import type { RegisteredSession } from './registry.js'
+const session = { agentId: 'one', sessionId: 's' } as RegisteredSession
+
+it('completion matches live tab events, clears on open/new turn and ignores replay/abort', () => {
+ const states = new MonitorCompletions()
+ states.observe({ type: 'turn_ended', agentId: 'one', dbSessionId: 's', replay: true })
+ expect(states.state(session)).toBe('idle')
+ states.observe({ type: 'turn_ended', agentId: 'one', dbSessionId: 's', payload: {} })
+ expect(states.state(session)).toBe('done')
+ states.observe({ type: 'turn_started', agentId: 'one', replay: true })
+ expect(states.state(session)).toBe('done')
+ expect(states.state({ ...session, lastOpenedAt: Date.now() + 1 })).toBe('idle')
+ states.observe({ type: 'turn_started', agentId: 'one' }); expect(states.state(session)).toBe('idle')
+ states.observe({ type: 'turn_ended', agentId: 'one', dbSessionId: 's', payload: { aborted: true } }); expect(states.state(session)).toBe('idle')
+})
diff --git a/cli/src/lib/harnessMonitor.ts b/cli/src/lib/harnessMonitor.ts
new file mode 100644
index 000000000..2ffecee49
--- /dev/null
+++ b/cli/src/lib/harnessMonitor.ts
@@ -0,0 +1,22 @@
+import type { RegisteredSession } from './registry.js'
+
+export type MonitorActivity = 'working' | 'needsInput' | 'done' | 'failed' | 'idle'
+
+/** Same live turn events the tab bar consumes. Replayed history never becomes fresh completion. */
+export class MonitorCompletions {
+ private readonly values = new Map<string, { state: 'done' | 'failed'; at: number; sessionId: unknown }>()
+ observe(frame: { type?: unknown; agentId?: unknown; dbSessionId?: unknown; replay?: unknown; subagent?: unknown; payload?: unknown }): void {
+ if (typeof frame.agentId !== 'string' || frame.replay || frame.subagent) return
+ if (frame.type === 'turn_started' || frame.type === 'agent_deleted') this.values.delete(frame.agentId)
+ if (frame.type !== 'turn_ended') return
+ const payload = frame.payload as { aborted?: boolean; error?: unknown } | undefined
+ if (payload?.aborted) { this.values.delete(frame.agentId); return }
+ this.values.delete(frame.agentId)
+ this.values.set(frame.agentId, { state: payload?.error ? 'failed' : 'done', at: Date.now(), sessionId: frame.dbSessionId })
+ if (this.values.size > 4096) this.values.delete(this.values.keys().next().value!)
+ }
+ state(session: RegisteredSession): 'done' | 'failed' | 'idle' {
+ const value = this.values.get(session.agentId)
+ return value && value.sessionId === session.sessionId && value.at > (session.lastOpenedAt ?? 0) ? value.state : 'idle'
+ }
+}
diff --git a/cli/src/lib/interactiveViewer.spec.ts b/cli/src/lib/interactiveViewer.spec.ts
index da0d5a3fc..60dfef80e 100644
--- a/cli/src/lib/interactiveViewer.spec.ts
+++ b/cli/src/lib/interactiveViewer.spec.ts
@@ -1,10 +1,18 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { InteractiveViewerCapture, InteractiveViewers, surfaceFrame } from './interactiveViewer.js'
+import { InteractiveViewerCapture, InteractiveViewers, monitorHostActions, surfaceFrame } from './interactiveViewer.js'
const frame = (extra = {}) => ({ surfaceId: 'one', agentId: 'agent', op: 'frame', width: 800, height: 600, dark: true, ...extra })
const pointer = { type: 'pointer', event: 'mousePressed', x: .5, y: .25, button: 'left', buttons: 1, clickCount: 1, modifiers: 0 }
describe('interactive viewer input boundary', () => {
+ it('allows only bounded monitor navigation, never executable input or lifecycle writes', () => {
+ expect(monitorHostActions([{ action: 'open', machineId: 'm', agentId: 'a', script: 'ignored' },
+ { action: 'assistant', chooseModel: true, prompt: 'ignored' }, { action: 'stop', agentId: 'a' }, null,
+ { action: 'open', machineId: 'm', agentId: '' }])).toEqual([
+ { action: 'open', machineId: 'm', agentId: 'a' }, { action: 'assistant', chooseModel: true },
+ ])
+ expect(monitorHostActions(Array(9).fill({ action: 'assistant' }))).toEqual([])
+ })
it('maps only ordinary pointer, keyboard, and text input to CDP', () => {
const parsed = surfaceFrame(frame({ events: [pointer,
{ type: 'key', event: 'keyDown', key: 'Enter', code: 'Enter', keyCode: 13, modifiers: 0 },
@@ -51,7 +59,7 @@ describe('owner viewer sessions', () => {
beforeEach(() => {
vi.useFakeTimers(); captures = []; target = 'http://127.0.0.1:8000/'
viewers = new InteractiveViewers(() => target, () => {
- const capture = { start: vi.fn(async () => {}), frame: vi.fn(async () => 'jpeg'), stop: vi.fn(async () => {}) }
+ const capture = { start: vi.fn(async () => {}), frame: vi.fn(async () => 'jpeg'), takeHostActions: vi.fn(async () => []), stop: vi.fn(async () => {}) }
captures.push(capture)
return capture as unknown as InteractiveViewerCapture
})
diff --git a/cli/src/lib/interactiveViewer.ts b/cli/src/lib/interactiveViewer.ts
index 9cca51c87..c8d068eaf 100644
--- a/cli/src/lib/interactiveViewer.ts
+++ b/cli/src/lib/interactiveViewer.ts
@@ -8,6 +8,18 @@ const integer = (value: unknown, min: number, max: number): value is number =>
const coordinate = (value: unknown): value is number =>
typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1
+/** Viewers can request only navigation. Flutter additionally verifies the owning DSH and active tab. */
+export function monitorHostActions(value: unknown): Payload[] {
+ if (!Array.isArray(value) || value.length > 8) return []
+ const id = (v: unknown): v is string => typeof v === 'string' && v.length > 0 && v.length <= 160
+ return value.flatMap<Payload>(action => {
+ if (!action || typeof action !== 'object') return []
+ if (action.action === 'assistant') return [{ action: 'assistant', chooseModel: action.chooseModel === true }]
+ if (action.action === 'open' && id(action.machineId) && id(action.agentId)) return [{ action: 'open', machineId: action.machineId, agentId: action.agentId }]
+ return []
+ })
+}
+
/** Deliberately not a general CDP bridge: a browser can only send ordinary viewer input. */
export function surfaceFrame(payload: Payload): Frame | null {
if (!integer(payload.width, 160, 1920) || !integer(payload.height, 120, 1200)
@@ -50,6 +62,14 @@ export function surfaceFrame(payload: Payload): Frame | null {
export class InteractiveViewerCapture extends ViewerCapture {
private geometry = ''
private dark: boolean | null = null
+ async takeHostActions(target: string): Promise<Payload[]> {
+ const origin = JSON.stringify(new URL(target).origin)
+ const reply = await this.call('Runtime.evaluate', { expression:
+ `location.origin === ${origin} ? (window.harnessEmbedded = true, Array.isArray(window.harnessHostQueue) ? window.harnessHostQueue.splice(0, 8) : []) : []`,
+ returnByValue: true })
+ const result = reply.result as { value?: unknown } | undefined
+ return monitorHostActions(result?.value)
+ }
async frame(frame: Frame): Promise<string> {
const geometry = `${frame.width}x${frame.height}`
if (geometry !== this.geometry) {
@@ -114,8 +134,9 @@ export class InteractiveViewers {
if (!surface.started) { await surface.capture.start(target); surface.started = true }
if (this.surfaces.get(key) !== surface) return { error: 'VIEWER_CLOSED' }
const data = await surface.capture.frame(frame)
+ const hostActions = await surface.capture.takeHostActions(target)
if (this.surfaces.get(key) !== surface) return { error: 'VIEWER_CLOSED' }
- return { data, mime: 'image/jpeg', width: frame.width, height: frame.height }
+ return { data, mime: 'image/jpeg', width: frame.width, height: frame.height, hostActions }
} catch (error) {
if (this.surfaces.get(key) === surface) this.remove(key)
return { error: 'VIEWER_UNAVAILABLE', detail: error instanceof Error ? error.message : 'The viewer could not start.' }
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 3c18190a3..6c9ae46ee 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -261,9 +261,11 @@ there is no title or deferred-close button. Cancel is the default. Previously qu
plans remain compatible. Layout cleanup, moving panes, switching tabs, and sign-out retain their view-only behavior. A failed save
or unconfirmed close keeps the pane. Older daemons retain their existing behavior until updated.
-`HarnessMonitor` drives the bottom-left resource summary and existing session manager. It samples
-connected owned sessions every 15 seconds, every 3 seconds while expanded, and never while the app
-is hidden. RAM is process-tree RSS; CPU is interval use, with 100% representing one core. Unknown
+`HarnessMonitor` drives the bottom-left resource summary. It samples connected owned sessions
+every 15 seconds and never while the app is hidden. Clicking it opens the reusable
+`autonomous/harness-monitor` DSH tab through `HarnessMonitorController`, with its viewer full width
+and the assistant terminal revealed only on request. The DSH table shares the daemon's resource
+sampler and adds opt-in activity metadata to `agents_list`. RAM is process-tree RSS; CPU is interval use, with 100% representing one core. Unknown
readings remain unknown. Shared Codex servers are listed separately and included once in totals;
token counts reuse existing agent data. The monitor never resumes sessions or scans transcripts.
diff --git a/desktop/design/review/harness-monitor-dsh.jpg b/desktop/design/review/harness-monitor-dsh.jpg
new file mode 100644
index 000000000..52c1016b4
Binary files /dev/null and b/desktop/design/review/harness-monitor-dsh.jpg differ
diff --git a/desktop/integration_test/native_resume_e2e_test.dart b/desktop/integration_test/native_resume_e2e_test.dart
index f818b21e3..451a12f3e 100644
--- a/desktop/integration_test/native_resume_e2e_test.dart
+++ b/desktop/integration_test/native_resume_e2e_test.dart
@@ -12,12 +12,9 @@ import 'package:integration_test/integration_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/test_run.dart';
import 'package:harness/state/app_state.dart';
-import 'package:harness/state/swarm_navigation.dart';
-import 'package:harness/widgets/harness_session_manager.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/ws/ws_conn.dart';
-import '../test/support/workspace_tools.dart' show openWorkspaceManagement;
import '../test/swarm_interactions_test.dart' show chord;
import '../test/swarm_screen_test.dart' show mount;
import '../test/swarm_state_test.dart' show createApp;
@@ -199,22 +196,20 @@ void main() {
expect(attached['pane'], previous['pane']);
expect(await app.deleteAgent('m', id), isNull);
- // Exercise the actual manager against native engine processes and disk
- // history, including rapid double clicks and repeated background resume.
- final toggle = find.byKey(
- ValueKey('session-toggle:${agentDestinationId('m', id)}'),
- );
+ // The monitor uses these same lifecycle coordinators. Exercise repeated
+ // and concurrent intents against isolated native engines and disk history;
+ // monitor tab/host navigation is covered by harness_monitor_test.dart.
for (var cycle = 0; cycle < 3; cycle++) {
- debugPrint('Native manager $engine cycle ${cycle + 1}/3');
await until(
() =>
app.stateOf('m')!.agents.any((a) => a.id == id && a.isStopped),
- '$engine saved row before manager cycle $cycle',
+ '$engine saved row before lifecycle cycle $cycle',
);
- await openWorkspaceManagement(tester, 'harnesses');
- await tester.pump();
- await tester.tap(toggle);
- await tester.tap(toggle);
+ final resumes = await Future.wait([
+ app.resumeAgent('m', id),
+ app.resumeAgent('m', id),
+ ]);
+ expect(resumes.every((result) => result.error == null), isTrue);
await until(
() => app
.stateOf('m')!
@@ -222,86 +217,32 @@ void main() {
.any(
(a) => a.id == id && !a.isStopped && a.launchState == 'ready',
),
- '$engine manager resume $cycle',
- );
- await until(
- () => !app.restartAttempt('m', id).busy,
- '$engine resume receipt $cycle',
+ '$engine confirmed resume $cycle',
);
- expect(find.byType(HarnessSessionManager), findsOneWidget);
expect(
app.allPanes.any((p) => p.agentId == id),
isFalse,
- reason: 'Play resumes in the background',
+ reason: 'The lifecycle coordinator resumes without adding a view',
);
final resumed = await get('/verify?id=$id');
expect(resumed['sessionId'], fixture['sessionId']);
expect(resumed['pid'], isNot(previous['pid']));
previous = resumed;
-
- expect(
- tester
- .widget<Semantics>(
- find.byKey(
- ValueKey('session-open:${agentDestinationId('m', id)}'),
- ),
- )
- .properties
- .enabled,
- isTrue,
- );
- await tester.tap(
- find.byKey(ValueKey('session-open:${agentDestinationId('m', id)}')),
- );
- await until(
- () => app.allPanes.any(
- (p) =>
- p.agentId == id &&
- (p.session?.terminal.buffer.getText().contains(marker) ??
- false),
- ),
- '$engine manager restores original terminal history $cycle',
- );
+ await open(LogicalKeyboardKey.keyP);
expect(app.allPanes.any((p) => p.agentId == anchorId), isTrue);
- expect(find.byType(HarnessSessionManager), findsNothing);
- await tester.tap(
- find.byKey(const ValueKey('workspace-harness-monitor')),
- );
- await tester.pump();
- await tester.tap(toggle);
- await tester.pump();
- // A working engine must ask; an idle one can close directly.
+ final stops = await Future.wait([
+ app.pauseAgent('m', id),
+ app.pauseAgent('m', id),
+ ]);
+ expect(stops, [null, null]);
await until(
() =>
- find
- .byKey(const Key('session-close-now'))
- .evaluate()
- .isNotEmpty ||
app.stateOf('m')!.agents.any((a) => a.id == id && a.isStopped),
- '$engine close review',
- );
- if (find
- .byKey(const Key('session-close-now'))
- .evaluate()
- .isNotEmpty) {
- await tester.tap(find.byKey(const Key('session-close-now')));
- }
- await until(
- () =>
- app
- .stateOf('m')!
- .agents
- .any((a) => a.id == id && a.isStopped) &&
- app.pendingAgentPause('m', id) == null,
- '$engine manager pause $cycle',
+ '$engine confirmed stop $cycle',
);
expect((await get('/verify?id=$id'))['stopped'], true);
expect(app.allPanes.any((p) => p.agentId == id), isFalse);
expect(app.allPanes.any((p) => p.agentId == anchorId), isTrue);
- if (find.byType(HarnessSessionManager).evaluate().isNotEmpty) {
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- }
}
}
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 49b131f5d..e4bbf7957 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -91,8 +91,6 @@ import '../widgets/workspace_subscription_usage.dart';
import '../store/store_mark.dart';
import '../store/store_screen.dart';
import '../widgets/harness_start_page.dart';
-import '../widgets/harness_session_manager.dart';
-import '../widgets/onboarding_card.dart';
import '../state/toolbar_notices.dart';
import '../widgets/machine_actions.dart';
import '../widgets/rename_agent_dialog.dart';
@@ -268,8 +266,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
late int _tabStripRequest;
OverlayEntry? _modelsOverlay;
VoidCallback? _unregisterModels;
- OverlayEntry? _harnessesOverlay;
- VoidCallback? _unregisterHarnesses;
late final WorkspacePullRequest _pullRequest;
final _toolbarNotices = ToolbarNotices();
late final _onboarding =
@@ -767,7 +763,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
_closeSearch(restoreFocus: false);
_closeCommandBar(restoreFocus: false);
_closeModelsControls(restoreFocus: false);
- _closeHarnessControls(restoreFocus: false);
_closeDaemon(restoreFocus: false);
_closeHatch(restoreFocus: false);
}
@@ -826,9 +821,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
_unregisterModels?.call();
_modelsOverlay?.remove();
_modelsOverlay?.dispose();
- _unregisterHarnesses?.call();
- _harnessesOverlay?.remove();
- _harnessesOverlay?.dispose();
_onboarding.removeListener(_onboardingChanged);
if (widget.onboarding == null) _onboarding.dispose();
app.modelManager.removeListener(_modelManagerChanged);
@@ -932,8 +924,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
bool get _modelsVisible =>
_modelsOverlay != null || _search?.isModelMode == true;
bool get _machinesVisible => _search?.isMachineMode == true;
- bool get _harnessesVisible =>
- _harnessesOverlay != null || _search?.scopePrefix.isEmpty == true;
+ bool get _harnessesVisible => _search?.scopePrefix.isEmpty == true;
bool get _shortcutsEnabled =>
mounted && _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen;
@@ -971,8 +962,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_commandBarOpen ||
(finding
? (_newHarness != null && !_newHarnessEmbedded) ||
- _modelsOverlay != null ||
- _harnessesOverlay != null
+ _modelsOverlay != null
: _search != null ||
_modelsVisible ||
_machinesVisible ||
@@ -1038,7 +1028,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
_closeDaemonHint();
_closeDaemon(restoreFocus: false);
_closeModelsControls(restoreFocus: false);
- _closeHarnessControls(restoreFocus: false);
if (id != 'navigation.command_bar') _closeCommandBar();
if (id == 'agent.new' && _search != null) {
final target = _search!.targetId;
@@ -1282,7 +1271,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
void _onboardingChanged() {
if (!mounted) return;
_modelsOverlay?.markNeedsBuild();
- _harnessesOverlay?.markNeedsBuild();
if (_menuHost) _syncNative();
setState(() {});
}
@@ -1722,7 +1710,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
void _paletteChanged() {
_modelsOverlay?.markNeedsBuild();
- _harnessesOverlay?.markNeedsBuild();
_searchOverlay?.markNeedsBuild();
if (_menuHost) _syncNative();
}
@@ -2134,7 +2121,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
return;
}
if (call.method == 'harnessControls' || call.method == 'resourceMonitor') {
- _toggleHarnessControls(liveOnly: call.method == 'resourceMonitor');
+ _toggleHarnessControls();
await WidgetsBinding.instance.endOfFrame;
return;
}
@@ -2510,7 +2497,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
String? error,
}) async {
String? result;
- _closeHarnessControls(restoreFocus: false);
await _dialog(() async {
result = await showSessionCloseDialog(
context,
@@ -5027,112 +5013,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
}
- void _toggleHarnessControls({bool liveOnly = false}) {
- if (_harnessesOverlay != null) {
- _closeHarnessControls();
- return;
- }
+ void _toggleHarnessControls() {
+ if (app.harnessMonitor.opening) return;
if (!_shortcutsEnabled || _newHarness?.requestDismiss() == false) return;
_closeNewHarness(restoreFocus: false);
_closeSearch(restoreFocus: false);
_closeCommandBar(restoreFocus: false);
dismissTransientMenus();
- _preparePaneFocus();
_onboarding.acknowledge(OnboardingStep.harnesses);
- final overlay = Overlay.of(context);
- _harnessesOverlay = OverlayEntry(
- builder: (context) => LayoutBuilder(
- builder: (context, constraints) => Stack(
- children: [
- Positioned.fill(
- top: _native ? 0 : _tabBarHeight,
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: _closeHarnessControls,
- child: const SizedBox.expand(),
- ),
- ),
- Positioned(
- bottom: _statusBarHeight + 8,
- left: 10,
- width: (constraints.maxWidth - 20).clamp(0, 640),
- child: ConstrainedBox(
- constraints: BoxConstraints(
- maxHeight:
- (constraints.maxHeight -
- (_native ? 0 : _tabBarHeight) -
- 20)
- .clamp(0, 620),
- ),
- child: KeymapProvider(
- keymap: _keymap,
- child: HarnessSessionManager(
- app: app,
- monitor: _harnessMonitor,
- initialFilter: liveOnly
- ? SessionFilter.running
- : SessionFilter.all,
- introduction: _onboarding.next == OnboardingStep.harnesses
- ? OnboardingCard(
- title: 'Run your first harness',
- description:
- 'Give an agent a task. Watch it get to work.',
- action: 'New harness',
- onAction: () {
- _closeHarnessControls(restoreFocus: false);
- _runShortcut('agent.new');
- },
- onDismiss: () =>
- _onboarding.dismiss(OnboardingStep.harnesses),
- )
- : null,
- recent: _navigation.recent,
- onClose: _closeHarnessControls,
- onOpen: (row) async {
- final destination = swarmDestinations(app)
- .where((item) => item.id == row.id)
- .firstOrNull;
- if (destination == null) return false;
- final opened = await activateSwarmDestination(
- app,
- destination,
- destinationSwarmId: app.activeSwarmId,
- );
- return opened;
- },
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- );
- overlay.insert(_harnessesOverlay!);
- _harnessMonitor.setExpanded(true);
- _unregisterHarnesses = registerTransientMenu(
- () => _closeHarnessControls(restoreFocus: false),
- );
- if (_menuHost) _syncNative();
- setState(() {});
- }
-
- void _closeHarnessControls({bool restoreFocus = true}) {
- if (_harnessesOverlay == null) return;
- _unregisterHarnesses?.call();
- _unregisterHarnesses = null;
- _harnessesOverlay?.remove();
- _harnessesOverlay?.dispose();
- _harnessesOverlay = null;
- _harnessMonitor.setExpanded(false);
- if (!mounted) return;
- if (_menuHost) _syncNative();
- setState(() {});
- if (restoreFocus) {
- _shellFocus.requestFocus();
- final pane = app.focusedPane;
- if (pane != null) app.focusPane(pane.id, reveal: true);
- }
+ unawaited(() async {
+ final error = await app.harnessMonitor.open();
+ if (mounted && error != null) {
+ ScaffoldMessenger.of(context)
+ .showSnackBar(SnackBar(content: Text(error)));
+ }
+ }());
}
void _toggleSessions({SessionFilter? filter}) {
@@ -7173,7 +7068,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
label: _harnessMonitor.detail,
tooltip: _harnessMonitor.detail,
onPressed: _shortcutsEnabled
- ? () => _toggleHarnessControls(liveOnly: true)
+ ? () => _toggleHarnessControls()
: null,
builder: (context, emphasized) => Padding(
padding: EdgeInsets.symmetric(horizontal: cell.width),
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 1161b8ca3..81b6bdc3b 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -16,6 +16,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/model_manager_controller.dart';
import '../companions/coding_memory_connection.dart';
+import 'harness_monitor_controller.dart';
import '../api/api_client.dart';
import '../viewer/sign_in_browser.dart';
import '../viewer/direct_link.dart';
@@ -6851,6 +6852,7 @@ class AppNotifier extends ChangeNotifier {
/// Model Manager keeps the original package ID for installed workspaces.
static const gridHarness = 'autonomous/autonomous-grid';
+ late final harnessMonitor = HarnessMonitorController(this);
ModelManagerController? _modelManager;
ModelManagerController get modelManager =>
_modelManager ??= ModelManagerController(this);
@@ -8130,6 +8132,10 @@ class AppNotifier extends ChangeNotifier {
ownerAgentId: agent.id,
);
swarm.panes.insert(insertion, pane);
+ if (agent.dsh == harnessMonitorId) {
+ swarm.zoomedPaneId = pane.id;
+ swarm.focusedPaneId = pane.id;
+ }
// The same bookkeeping a split does when it grows the grid by one:
// pins past the insertion slide right, and the shape is re-derived.
swarm.pinnedSlots.updateAll(
@@ -8150,6 +8156,95 @@ class AppNotifier extends ChangeNotifier {
return changed;
}
+ /// The monitor opens as a full-width table; the OpenCode terminal remains its DSH owner.
+ void showHarnessMonitorTable(String machineId, String agentId) {
+ final pane = activeSwarm.panes
+ .where(
+ (p) =>
+ p.isWeb && p.machineId == machineId && p.ownerAgentId == agentId,
+ )
+ .firstOrNull;
+ if (pane == null) return;
+ focusPane(pane.id);
+ zoomedPaneId = pane.id;
+ _persistLayout();
+ notifyListeners();
+ }
+
+ /// Only navigation crosses the viewer bridge. Lifecycle operations use the ordinary app APIs.
+ Future<String?> handleHarnessMonitorAction(
+ TerminalPane source,
+ Map<String, dynamic> action,
+ ) async {
+ final owner = stateOf(source.machineId);
+ final monitor = owner?.agents
+ .where((a) => a.id == source.ownerAgentId && a.dsh == harnessMonitorId)
+ .firstOrNull;
+ if (!source.isWeb ||
+ monitor == null ||
+ !activeSwarm.panes.contains(source)) {
+ return 'This monitor is no longer active.';
+ }
+ if (action['action'] == 'assistant') {
+ final terminal = activeSwarm.panes
+ .where(
+ (p) => p.machineId == source.machineId && p.agentId == monitor.id,
+ )
+ .firstOrNull;
+ if (terminal == null) return 'The assistant is unavailable.';
+ zoomedPaneId = null;
+ focusPane(terminal.id, reveal: true);
+ _persistLayout();
+ notifyListeners();
+ return null;
+ }
+ final machineId = action['machineId'], agentId = action['agentId'];
+ if (action['action'] != 'open' ||
+ machineId is! String ||
+ agentId is! String) {
+ return 'Unknown monitor action.';
+ }
+ final machine = stateOf(machineId);
+ if (machine == null ||
+ machine.machine.isShared ||
+ machine.connectionStatus != ConnectionStatus.connected) {
+ return 'Connect the owning machine to open this session.';
+ }
+ await _loadMachineData(machine, force: true);
+ if (!identical(stateOf(machineId), machine) ||
+ !identical(stateOf(source.machineId), owner) ||
+ !activeSwarm.panes.contains(source)) {
+ return null;
+ }
+ if (machine.isOffline || machine.agentsLoadError != null) {
+ return 'Reconnect the owning machine and refresh the monitor.';
+ }
+ final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
+ if (agent == null) {
+ return 'This session is no longer available. Refresh the monitor.';
+ }
+ if (agent.isStopped) {
+ final result = await resumeAgent(machineId, agentId);
+ if (result.error != null) return result.error;
+ if (!identical(stateOf(machineId), machine) ||
+ !activeSwarm.panes.contains(source)) {
+ return null;
+ }
+ } else if (!agent.terminalAvailable) {
+ return 'This session is not ready to open. Refresh the monitor.';
+ }
+ if (!revealAgentView(machineId, agentId)) {
+ newSwarm();
+ await addAgentToSwarm(
+ machineId,
+ agentId,
+ swarmId: activeSwarmId,
+ intent: AttachIntent.person,
+ );
+ }
+ return null;
+ }
+
/// Whether the active tab shows this agent's viewer beside its terminal.
bool viewerPaneShown(String machineId, String agentId) =>
activeSwarm.panes.any(
@@ -14347,6 +14442,7 @@ class AppNotifier extends ChangeNotifier {
viewer?.auth.dispose();
_deviceVisit?.dispose();
_modelManager?.dispose();
+ harnessMonitor.dispose();
_modelsMenu?.dispose();
for (final controller in _teamControllers.values) {
controller.dispose();
diff --git a/desktop/lib/state/harness_monitor_controller.dart b/desktop/lib/state/harness_monitor_controller.dart
new file mode 100644
index 000000000..7c0e38d77
--- /dev/null
+++ b/desktop/lib/state/harness_monitor_controller.dart
@@ -0,0 +1,111 @@
+import '../core/models.dart';
+import '../core/project_folder.dart';
+import 'app_state.dart';
+
+const harnessMonitorId = 'autonomous/harness-monitor';
+const harnessMonitorName = 'Harness Monitor';
+
+/// One explicit dock action, one reusable DSH. A lost create reply keeps its receipt for the next click.
+class HarnessMonitorController {
+ HarnessMonitorController(this.app);
+ final AppNotifier app;
+ Future<String?>? _opening;
+ MachineState? _owner;
+ AgentCreationAttempt? _creation;
+ ProjectFolderRequest? _folder;
+ bool _disposed = false;
+ bool get opening => _opening != null;
+
+ Future<String?> open() =>
+ _opening ??= _open().whenComplete(() => _opening = null);
+ bool _current(MachineState owner) =>
+ !_disposed && identical(app.stateOf(owner.machine.machineId), owner);
+
+ Future<String?> _open() async {
+ final owner = app.ownedActionMachine;
+ if (owner == null) return 'Connect a machine to open Harness Monitor.';
+ if (!identical(_owner, owner)) {
+ _owner = owner;
+ _creation = null;
+ _folder = null;
+ }
+ final machineId = owner.machine.machineId;
+ Agent? monitor() =>
+ owner.agents.where((a) => a.dsh == harnessMonitorId).firstOrNull;
+ try {
+ var agent = monitor();
+ if (agent == null) {
+ await app.probeDsh(machineId);
+ if (!_current(owner)) return null;
+ if (owner.dsh[harnessMonitorId]?.installed != true) {
+ final error = await app.installDsh(machineId, harnessMonitorId);
+ if (!_current(owner)) return null;
+ if (error != null) return error;
+ }
+ agent = monitor();
+ if (agent == null) {
+ if (_creation != null &&
+ !_creation!.awaitingConfirmation &&
+ _creation!.agentId == null) {
+ _creation = null;
+ }
+ _creation ??= AgentCreationAttempt(background: true);
+ _folder ??= ProjectFolderRequest.generated(
+ label: 'harness-monitor',
+ at: DateTime.now(),
+ );
+ final error = await app.createAgent(
+ machineId,
+ engine: 'opencode',
+ folder: null,
+ projectFolder: _folder,
+ dsh: harnessMonitorId,
+ name: harnessMonitorName,
+ attempt: _creation,
+ );
+ if (!_current(owner)) return null;
+ if (error != null) return error;
+ agent = monitor();
+ }
+ }
+ if (agent == null) {
+ return 'Harness Monitor is still starting. Try again in a moment.';
+ }
+ if (agent.isStopped) {
+ final result = await app.resumeAgent(machineId, agent.id);
+ if (!_current(owner)) return null;
+ if (result.error != null) return result.error;
+ }
+ final tab = app.swarms
+ .where(
+ (s) => s.panes.any(
+ (p) => p.machineId == machineId && p.agentId == agent!.id,
+ ),
+ )
+ .firstOrNull;
+ if (tab != null) {
+ app.selectSwarm(tab.id);
+ } else {
+ app.newSwarm(name: harnessMonitorName);
+ if (app.activeSwarm.panes.isNotEmpty) {
+ return 'Close a tab to make room for Harness Monitor.';
+ }
+ await app.assignAgentToPane(null, machineId, agent.id);
+ if (!_current(owner)) return null;
+ }
+ if (!app.viewerPaneShown(machineId, agent.id)) {
+ await app.toggleViewerPane(machineId, agent.id);
+ }
+ app.showHarnessMonitorTable(machineId, agent.id);
+ return null;
+ } catch (_) {
+ return _current(owner)
+ ? 'Could not open Harness Monitor. Try again.'
+ : null;
+ }
+ }
+
+ void dispose() {
+ _disposed = true;
+ }
+}
diff --git a/desktop/lib/viewer/interactive_viewer.dart b/desktop/lib/viewer/interactive_viewer.dart
index 1cb5f224f..f8bba31f9 100644
--- a/desktop/lib/viewer/interactive_viewer.dart
+++ b/desktop/lib/viewer/interactive_viewer.dart
@@ -21,8 +21,9 @@ typedef ViewerSurfaceRequest = Future<Map<String, dynamic>> Function(
/// Pulling the next frame only after the previous reply bounds both rendering and network work.
/// Input is connection-local: a failed request is never replayed into a replacement viewer.
class InteractiveViewerSession extends ChangeNotifier {
- InteractiveViewerSession(this.request);
+ InteractiveViewerSession(this.request, {this.onHostAction});
final ViewerSurfaceRequest request;
+ final void Function(Map<String, dynamic>)? onHostAction;
final String id = hexOf(secureRandomBytes(16));
Uint8List? image;
String? error;
@@ -106,6 +107,12 @@ class InteractiveViewerSession extends ChangeNotifier {
error = 'The viewer sent an invalid image.';
} else {
image = base64Decode(reply['data'] as String);
+ final actions = reply['hostActions'];
+ if (actions is List && actions.length <= 8) {
+ for (final action in actions) {
+ if (action is Map<String, dynamic>) onHostAction?.call(action);
+ }
+ }
}
} on WsRequestTimeout {
if (!_disposed) {
diff --git a/desktop/lib/widgets/harness_session_manager.dart b/desktop/lib/widgets/harness_session_manager.dart
deleted file mode 100644
index fe26f6595..000000000
--- a/desktop/lib/widgets/harness_session_manager.dart
+++ /dev/null
@@ -1,1192 +0,0 @@
-import 'dart:async';
-import 'dart:math' as math;
-
-import 'package:harness/shared/theme/app_icons.dart';
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-
-import '../shared/theme/app_theme.dart';
-import '../shared/widgets/app_menu.dart';
-import '../state/app_state.dart';
-import '../state/harness_sessions.dart';
-import '../state/harness_monitor.dart';
-import '../core/harness_resources.dart';
-import '../state/swarm_navigation.dart';
-import '../core/models.dart';
-import '../usage/ledger/usage_overview.dart' show formatTokens;
-import 'desktop_chrome.dart';
-import 'engine_identity.dart';
-import '../notify/alert_sounds.dart';
-
-/// A compact, live inventory. Action receipts belong to AppNotifier, so
-/// dismissing this surface never cancels a pause or launches a second resume.
-class HarnessSessionManager extends StatefulWidget {
- const HarnessSessionManager({
- super.key,
- required this.app,
- required this.recent,
- required this.onClose,
- required this.onOpen,
- this.initialFilter = SessionFilter.all,
- this.introduction,
- this.monitor,
- });
- final AppNotifier app;
- final List<String> recent;
- final VoidCallback onClose;
- final Future<bool> Function(HarnessSession) onOpen;
- final SessionFilter initialFilter;
- final Widget? introduction;
- final HarnessMonitor? monitor;
-
- @override
- State<HarnessSessionManager> createState() => _HarnessSessionManagerState();
-}
-
-class _HarnessSessionManagerState extends State<HarnessSessionManager> {
- final _search = TextEditingController();
- final _searchFocus = FocusNode(debugLabel: 'Search harnesses');
- final _scroll = ScrollController();
- final _sortMenu = MenuController();
- final _pending = <String, HarnessSession>{};
- final _errors = <String, String>{};
- late SessionFilter _filter;
- Timer? _clock;
- SessionSort _sort = SessionSort.recent;
- String? _selected;
- int _selectedIndex = 0;
- final _rowKeys = <String, GlobalKey>{};
- String? _opening;
-
- @override
- void initState() {
- super.initState();
- _filter = widget.initialFilter;
- _clock = Timer.periodic(const Duration(minutes: 1), (_) => _changed());
- widget.app.addListener(_changed);
- widget.monitor?.addListener(_changed);
- // Its own notifier — marking one agent must not rebuild the workspace — so
- // this list asks for its own redraw while it is open.
- widget.app.agentUnread.addListener(_changed);
- }
-
- void _changed() {
- if (mounted) setState(() {});
- }
-
- @override
- void dispose() {
- widget.app.removeListener(_changed);
- widget.monitor?.removeListener(_changed);
- widget.app.agentUnread.removeListener(_changed);
- _clock?.cancel();
- _search.dispose();
- _searchFocus.dispose();
- _scroll.dispose();
- super.dispose();
- }
-
- List<HarnessSession> get _sessions {
- final rows = {
- for (final row in widget.monitor?.sessions ?? harnessSessions(widget.app))
- row.id: row,
- };
- // Keep the row steady while a confirmed pause refreshes the saved roster.
- for (final row in _pending.values) {
- rows.putIfAbsent(row.id, () => row);
- }
- return rows.values.toList();
- }
-
- Future<void> _toggle(HarnessSession row) async {
- if (_pending.containsKey(row.id) || !row.canControl) return;
- final current = widget.app
- .stateOf(row.machineId)
- ?.agents
- .where((agent) => agent.id == row.agent.id)
- .firstOrNull;
- if (!identical(widget.app.stateOf(row.machineId), row.machine) ||
- current == null ||
- current.sessionId != row.agent.sessionId ||
- current.isStopped != row.agent.isStopped) {
- return;
- }
- setState(() {
- _pending[row.id] = row;
- _errors.remove(row.id);
- });
- String? error;
- try {
- if (row.agent.isStopped) {
- error = (await widget.app.resumeAgent(
- row.machineId,
- row.agent.id,
- )).error;
- } else if (row.agent.closePlanState != null) {
- final result = await widget.app.prepareSessionClose(
- row.machineId,
- row.agent,
- )('cancel');
- if (result['cancelled'] != true) {
- error =
- result['detail'] as String? ??
- 'Could not cancel the scheduled close.';
- }
- } else if (row.agent.closeSupported) {
- final review = widget.app.reviewSessionClose;
- if (review == null) {
- error = 'Open this session to close it safely.';
- } else {
- await review([(row.machineId, row.agent)]);
- }
- } else {
- error = await widget.app.pauseAgent(row.machineId, row.agent.id);
- }
- } catch (_) {
- error =
- 'Could not ${row.agent.isStopped ? 'resume' : 'pause'} this harness. Try again.';
- }
- if (!mounted) return;
- setState(() {
- _pending.remove(row.id);
- if (error != null) {
- _errors[row.id] = error.replaceFirst('Stop failed:', 'Pause failed:');
- }
- });
- }
-
- Future<void> _open(HarnessSession row, {bool answering = false}) async {
- // Going to the harness is what makes its news read. Done here rather than
- // after the open succeeds: the person has decided to look, and a mark that
- // outlived the click would read as the click not having worked.
- widget.app.markAgentSeen(row.machine.machine.machineId, row.agent.id);
- if (answering) {
- final current = widget.app.questionFor(row.machineId, row.agent.id);
- if (current == null || row.question?.sameAs(current) != true) return;
- }
- final awaitingInput =
- row.agent.terminalAvailable && row.agent.launchState == 'starting';
- if (_opening != null ||
- (_pending.containsKey(row.id) && !awaitingInput) ||
- !row.canOpen) {
- return;
- }
- setState(() {
- _opening = row.id;
- _errors.remove(row.id);
- });
- try {
- if (row.agent.closePlanState != null) {
- final result = await widget.app.prepareSessionClose(
- row.machineId,
- row.agent,
- )('cancel');
- if (result['cancelled'] != true) {
- if (mounted) {
- setState(
- () => _errors[row.id] =
- result['detail'] as String? ??
- 'Could not keep this session open. Try again.',
- );
- }
- return;
- }
- }
- final opened = await widget.onOpen(row);
- if (mounted && opened) widget.onClose();
- } on SwarmResumeFailure catch (failure) {
- if (mounted) setState(() => _errors[row.id] = failure.message);
- } catch (_) {
- if (mounted) {
- setState(
- () => _errors[row.id] = 'Could not open this harness. Try again.',
- );
- }
- } finally {
- if (mounted) setState(() => _opening = null);
- }
- }
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final all = _sessions;
- final rows = visibleHarnessSessions(
- all,
- query: _search.text,
- filter: _filter,
- sort: _sort,
- recent: widget.recent,
- memory: {
- for (final row in all)
- row.id: ?widget.monitor?.reading(row)?.memoryBytes,
- },
- cpu: {
- for (final row in all)
- row.id: ?widget.monitor?.reading(row)?.cpuPercent,
- },
- );
- final running = all.where((row) => row.running).length;
- final paused = all.where((row) => row.agent.isStopped).length;
- final needsInput = all.where((row) => row.needsInput).length;
- final now = DateTime.now();
- final showingQuestions = _filter == SessionFilter.needsInput;
- final selected =
- rows.where((row) => row.id == _selected).firstOrNull ??
- (rows.isEmpty
- ? null
- : rows[_selected == null
- ? 0
- : _selectedIndex.clamp(0, rows.length - 1)]);
- if (_selected != null && selected != null) {
- _selected = selected.id;
- _selectedIndex = rows.indexOf(selected);
- }
- final scale = MediaQuery.textScalerOf(context);
- final rowHeight =
- math.max(
- 62.0,
- (scale.scale(AppType.bodySize) * 1.3).ceilToDouble() +
- (scale.scale(AppType.captionSize) * 1.35).ceilToDouble() +
- 26,
- ) +
- (showingQuestions
- ? (scale.scale(AppType.captionSize) * 1.35).ceilToDouble() + 6
- : 0);
- double heightFor(HarnessSession row) =>
- rowHeight +
- (row.agent.hasMonitorStats
- ? (scale.scale(AppType.captionSize) * 1.35).ceilToDouble() + 6
- : 0) +
- (widget.monitor != null
- ? (scale.scale(AppType.captionSize) * 1.35).ceilToDouble() + 6
- : 0);
- return FocusScope(
- child: CallbackShortcuts(
- bindings: {
- const SingleActivator(LogicalKeyboardKey.escape): widget.onClose,
- },
- child: Focus(
- onKeyEvent: (_, event) {
- if (event is! KeyDownEvent ||
- rows.isEmpty ||
- !_searchFocus.hasFocus) {
- return KeyEventResult.ignored;
- }
- final key = event.logicalKey;
- if ((key == LogicalKeyboardKey.enter ||
- key == LogicalKeyboardKey.numpadEnter) &&
- _search.value.composing.isCollapsed) {
- final row = selected!;
- unawaited(_open(row, answering: row.needsInput));
- return KeyEventResult.handled;
- }
- if (key != LogicalKeyboardKey.arrowDown &&
- key != LogicalKeyboardKey.arrowUp) {
- return KeyEventResult.ignored;
- }
- final at = rows.indexOf(selected!);
- final next = _selected == null
- ? (key == LogicalKeyboardKey.arrowDown ? 0 : rows.length - 1)
- : (at + (key == LogicalKeyboardKey.arrowDown ? 1 : -1)).clamp(
- 0,
- rows.length - 1,
- );
- setState(() => _selected = rows[next].id);
- void reveal() {
- final context = _rowKeys[rows[next].id]?.currentContext;
- if (!mounted || context == null) return;
- Scrollable.ensureVisible(
- context,
- alignmentPolicy: key == LogicalKeyboardKey.arrowDown
- ? ScrollPositionAlignmentPolicy.keepVisibleAtEnd
- : ScrollPositionAlignmentPolicy.keepVisibleAtStart,
- );
- }
-
- if (_rowKeys[rows[next].id]?.currentContext != null) {
- reveal();
- } else if (_scroll.hasClients) {
- // Materialize a distant row, then use its real bounds. Question
- // text, errors, row padding and enlarged type all affect height.
- _scroll.jumpTo(
- (6 +
- rows
- .take(next)
- .fold<double>(
- 0,
- (height, row) => height + heightFor(row) + 2,
- ))
- .clamp(0, _scroll.position.maxScrollExtent),
- );
- WidgetsBinding.instance.addPostFrameCallback((_) => reveal());
- }
- return KeyEventResult.handled;
- },
- child: DesktopDialogSurface(
- key: const ValueKey('session-manager'),
- radius: AppDesktop.menuRadius,
- elevation: AppMenu.elevation,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- DesktopDialogHeader(
- title: widget.monitor == null
- ? 'Harnesses'
- : 'Harness Monitor',
- onClose: widget.onClose,
- ),
- if (widget.introduction != null) widget.introduction!,
- if (widget.monitor?.sharedLabel case final String shared)
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: AppDesktop.panelPadding,
- vertical: 6,
- ),
- child: Tooltip(
- message: 'Included once in the total. May also serve sessions outside Harness. Per-session readings exclude these shared servers.',
- child: Text(shared, style: AppType.body(), maxLines: 2),
- ),
- ),
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: AppDesktop.panelPadding,
- ),
- child: TextField(
- key: const ValueKey('session-search'),
- controller: _search,
- focusNode: _searchFocus,
- autofocus: true,
- style: AppType.body(height: 1.25).copyWith(fontSize: 17),
- onChanged: (_) => setState(() => _selected = null),
- onSubmitted: (_) {
- if (selected != null) unawaited(_open(selected));
- },
- decoration: InputDecoration(
- hintText:
- 'Search harnesses, machines, projects, branches',
- hintStyle: AppType.body(
- color: AppPalette.textSecondary,
- height: 1.25,
- ).copyWith(fontSize: 17),
- prefixIcon: Icon(
- AppIcons.search,
- size: 20,
- color: AppPalette.textSecondary,
- ),
- prefixIconConstraints: const BoxConstraints(minWidth: 36),
- suffixIcon: _search.text.isEmpty
- ? null
- : IconButton(
- tooltip: 'Clear search',
- icon: const Icon(AppIcons.close, size: 16),
- onPressed: () {
- _search.clear();
- setState(() => _selected = null);
- _searchFocus.requestFocus();
- },
- ),
- isDense: true,
- filled: true,
- fillColor: AppDesktop.field,
- contentPadding: const EdgeInsets.symmetric(
- vertical: 12,
- horizontal: 12,
- ),
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(
- AppDesktop.fieldRadius,
- ),
- borderSide: BorderSide.none,
- ),
- focusedBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(
- AppDesktop.fieldRadius,
- ),
- borderSide: BorderSide(
- color: AppDesktop.focus,
- width: AppDesktop.focusWidth,
- ),
- ),
- ),
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(24, 12, 24, 16),
- child: Row(
- children: [
- Expanded(
- child: SingleChildScrollView(
- scrollDirection: Axis.horizontal,
- child: Row(
- children: [
- for (final filter in SessionFilter.values)
- Padding(
- padding: const EdgeInsets.only(right: 4),
- child: DesktopPill(
- key: ValueKey(
- 'session-filter:${filter.name}',
- ),
- compact: true,
- selected: _filter == filter,
- onPressed: () => setState(() {
- _filter = filter;
- _selected = null;
- }),
- label: switch (filter) {
- SessionFilter.all => 'All ${all.length}',
- SessionFilter.needsInput =>
- 'Needs input $needsInput',
- SessionFilter.running =>
- 'Running $running',
- SessionFilter.paused => 'Saved $paused',
- },
- ),
- ),
- ],
- ),
- ),
- ),
- const SizedBox(width: AppDesktop.controlGap),
- MenuAnchor(
- controller: _sortMenu,
- onOpen: () => setState(() {}),
- onClose: () => setState(() {}),
- menuChildren: [
- for (final sort in SessionSort.values.where(
- (sort) =>
- widget.monitor != null ||
- (sort != SessionSort.memory &&
- sort != SessionSort.cpu),
- ))
- AppMenuItem(
- label: sort.label,
- selected: _sort == sort,
- onPressed: () {
- _sortMenu.close();
- setState(() {
- _sort = sort;
- _selected = null;
- });
- },
- ),
- ],
- builder: (context, controller, child) => DesktopPill(
- tooltip: 'Sort harnesses',
- semanticLabel: 'Sort harnesses',
- semanticHint: 'Current order: ${_sort.label}',
- compact: true,
- onPressed: () => controller.isOpen
- ? controller.close()
- : controller.open(),
- icon: AppIcons.arrowDownWideNarrow,
- label: _sort == SessionSort.recent
- ? 'Recent'
- : _sort.label,
- ),
- ),
- ],
- ),
- ),
- Divider(height: 1, color: AppPalette.divider),
- Flexible(
- child: rows.isEmpty
- ? Padding(
- padding: const EdgeInsets.symmetric(
- vertical: 42,
- horizontal: 24,
- ),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(
- AppIcons.layers,
- size: 24,
- color: AppPalette.textFaint,
- ),
- const SizedBox(height: 12),
- Text(
- showingQuestions && _search.text.trim().isEmpty
- ? 'No harnesses need your input'
- : all.isEmpty
- ? 'Your harnesses live here'
- : 'No matching harnesses',
- style: AppType.label(height: 1.3),
- ),
- if (!showingQuestions ||
- _search.text.trim().isNotEmpty) ...[
- const SizedBox(height: 6),
- Text(
- all.isEmpty
- ? 'Open a harness to get started.'
- : 'Try another search or filter.',
- style: AppType.body(
- color: AppPalette.textSecondary,
- ),
- ),
- ],
- ],
- ),
- )
- : Scrollbar(
- controller: _scroll,
- child: ListView.builder(
- controller: _scroll,
- shrinkWrap: true,
- padding: const EdgeInsets.symmetric(
- horizontal: 8,
- vertical: 6,
- ),
- itemCount: rows.length,
- itemBuilder: (context, index) {
- final row = rows[index];
- final pendingStop =
- (widget.app.pendingAgentPause(
- row.machineId,
- row.agent.id,
- ) ??
- widget.app.pendingAgentStop(
- row.machineId,
- row.agent.id,
- )) !=
- null;
- final pendingResume = widget.app
- .restartAttempt(row.machineId, row.agent.id)
- .busy;
- final busy =
- _pending.containsKey(row.id) ||
- pendingStop ||
- pendingResume ||
- _opening == row.id;
- return _SessionRow(
- key: _rowKeys.putIfAbsent(
- row.id,
- () => GlobalKey(),
- ),
- row: row,
- resourceLabel: widget.monitor == null
- ? null
- : '${row.status} · ${widget.monitor!.reading(row)?.label ?? const HarnessResources().label}',
- height: heightFor(row),
- now: now,
- showQuestion: showingQuestions,
- unread: widget.app.agentUnread.kindFor(
- row.machine.machine.machineId,
- row.agent.id,
- ),
- selected:
- !_sortMenu.isOpen &&
- _selected != null &&
- selected?.id == row.id,
- onSelect: () {
- if (_selected == row.id) return;
- setState(() {
- _selected = row.id;
- _selectedIndex = index;
- });
- },
- busy: busy,
- pendingLabel: _opening == row.id
- ? 'Opening…'
- : pendingStop
- ? 'Pausing…'
- : row.agent.isStopped
- ? 'Resuming…'
- : row.agent.closeSupported
- ? 'Closing…'
- : 'Pausing…',
- error:
- _errors[row.id] ??
- row.agent.closePlanDetail,
- onOpen: () =>
- _open(row, answering: row.needsInput),
- onAnswer: () => _open(row, answering: true),
- onToggle: () => _toggle(row),
- );
- },
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- );
- }
-}
-
-class _SessionRow extends StatelessWidget {
- const _SessionRow({
- super.key,
- required this.row,
- required this.height,
- required this.now,
- required this.showQuestion,
- required this.unread,
- required this.selected,
- required this.busy,
- required this.pendingLabel,
- required this.onOpen,
- required this.onSelect,
- required this.onToggle,
- required this.onAnswer,
- this.error,
- this.resourceLabel,
- });
- final HarnessSession row;
- final double height;
- final DateTime now;
- final bool selected, busy, showQuestion;
- final String pendingLabel;
-
- /// News nobody has looked at yet, or null. Drawn beside the name, so the mark
- /// sits with the thing it is about rather than in a column of its own.
- final AlertKind? unread;
-
- final VoidCallback onOpen, onSelect, onToggle, onAnswer;
- final String? error;
- final String? resourceLabel;
-
- @override
- Widget build(BuildContext context) {
- final primary = selected ? AppDesktop.onSelection : AppPalette.textPrimary;
- final secondary = selected
- ? AppDesktop.selectionDetail
- : AppPalette.textSecondary;
- final errorInk = Theme.of(context).colorScheme.error;
- Color statusInk(Color color) => selected ? AppDesktop.onSelection : color;
- ButtonStyle actionStyle(Color color) =>
- IconButton.styleFrom(
- foregroundColor: color,
- disabledForegroundColor: secondary.withValues(alpha: .6),
- ).copyWith(
- side: WidgetStateProperty.resolveWith(
- (states) => BorderSide(
- width: MediaQuery.highContrastOf(context)
- ? 2
- : AppDesktop.focusWidth,
- color:
- states.contains(WidgetState.focused) &&
- !states.contains(WidgetState.disabled)
- ? selected
- ? AppDesktop.onSelection
- : AppDesktop.focus
- : Colors.transparent,
- ),
- ),
- );
- // Login or permission review may be required before a native resume hook.
- final canOpen =
- row.canOpen &&
- (!busy ||
- (row.agent.terminalAvailable &&
- row.agent.launchState == 'starting'));
- // Play/pause carries normal state; only exceptions need another label.
- final attention = switch (row.status) {
- 'Ready' || 'Saved' || 'Working' || 'Needs input' => null,
- final status => status,
- };
- // The time the panel sorts by (Recently used), so the ages read in order.
- final lastUsedAt = row.lastUsedAt;
- final age = lastUsedAt == null
- ? null
- : now.difference(lastUsedAt).inMinutes < 1
- ? 'now'
- : harnessActivityAge(lastUsedAt, now);
- final activity = age == null
- ? 'Last use unknown'
- : age == 'now'
- ? 'Last used now'
- : 'Last used $age ago';
- Widget detail(IconData icon, String text, {String? tooltip}) => Tooltip(
- message: tooltip ?? text,
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(icon, size: 16, color: secondary),
- const SizedBox(width: 5),
- Flexible(
- child: Text(
- text,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.caption(color: secondary, height: 1.35),
- ),
- ),
- ],
- ),
- );
- final details = [
- detail(AppIcons.monitor, row.machine.machine.displayName),
- if (row.project case final project?) ...[
- detail(AppIcons.folder, project.label, tooltip: project.cwd),
- if (project.shownBranch case final branch?)
- detail(AppIcons.gitBranch, branch),
- ],
- ];
- return Padding(
- padding: const EdgeInsets.symmetric(vertical: 1),
- child: Focus(
- canRequestFocus: false,
- skipTraversal: true,
- onFocusChange: (focused) {
- if (focused) onSelect();
- },
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: selected ? AppDesktop.selection : Colors.transparent,
- borderRadius: BorderRadius.circular(AppDesktop.rowRadius),
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- SizedBox(
- height: height,
- child: Row(
- children: [
- Expanded(
- child: Semantics(
- key: ValueKey('session-open:${row.id}'),
- selected: selected,
- container: true,
- button: true,
- enabled: canOpen,
- label:
- '${row.agent.isStopped ? 'Resume and open' : 'Open'} ${row.agent.displayName}',
- value: [
- row.machine.machine.displayName,
- row.project?.label,
- row.project?.shownBranch,
- row.question?.prompt,
- activity,
- resourceLabel,
- if (row.agent.tokensUsed case final count?)
- '$count tokens used',
- if (row.agent.outputStats case final stats?) ...[
- if (stats.hasEdits)
- '${stats.linesAdded} lines added, ${stats.linesRemoved} lines removed in recorded edits',
- if (stats.pullRequestsCreated case final count?)
- '$count pull requests created',
- ],
- busy ? pendingLabel : row.status,
- ].whereType<String>().join(', '),
- onTap: canOpen ? onOpen : null,
- excludeSemantics: true,
- child: InkWell(
- onTap: canOpen ? onOpen : null,
- onHover: (hovered) {
- if (hovered && canOpen) onSelect();
- },
- borderRadius: BorderRadius.circular(
- AppDesktop.rowRadius,
- ),
- hoverColor: Colors.transparent,
- focusColor: Colors.transparent,
- child: Padding(
- padding: const EdgeInsets.fromLTRB(12, 10, 6, 10),
- child: Row(
- children: [
- EngineMark(
- engine: row.agent.identityEngine,
- size: AppDesktop.identitySize,
- ),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Flexible(
- child: Tooltip(
- message: row.agent.displayName,
- child: Text(
- row.agent.displayName,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.label(
- color: primary,
- height: 1.3,
- ),
- ),
- ),
- ),
- if (row.lastUsedAt != null)
- Padding(
- padding: const EdgeInsets.only(
- left: 8,
- ),
- child: Tooltip(
- message:
- 'Last used ${row.lastUsedAt!.toLocal()}',
- child: Text(
- '· $age',
- key: ValueKey(
- 'session-age:${row.id}',
- ),
- style: AppType.caption(
- color: secondary,
- ),
- ),
- ),
- ),
- if (attention != null && !busy)
- Padding(
- padding: const EdgeInsets.only(
- left: 12,
- ),
- child: Text(
- attention,
- style: AppType.caption(
- color: secondary,
- ),
- ),
- ),
- ],
- ),
- const SizedBox(height: 6),
- LayoutBuilder(
- builder: (context, constraints) {
- // Cap leading labels without reserving
- // columns: the branch gets all space
- // left over by short machine/project names.
- final leadingWidth = math.max(
- 0.0,
- (constraints.maxWidth -
- 12 * (details.length - 1)) /
- details.length,
- );
- return Row(
- children: [
- for (
- var i = 0;
- i < details.length;
- i++
- ) ...[
- if (i > 0)
- const SizedBox(width: 12),
- if (i == details.length - 1)
- Expanded(child: details[i])
- else
- ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: leadingWidth,
- ),
- child: details[i],
- ),
- ],
- ],
- );
- },
- ),
- if (resourceLabel != null) ...[
- const SizedBox(height: 6),
- Tooltip(
- message: HarnessResources.explanation,
- child: Text(
- resourceLabel!,
- key: ValueKey(
- 'session-resources:${row.id}',
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.caption(
- color: secondary,
- height: 1.35,
- ),
- ),
- ),
- ],
- if (row.agent.hasMonitorStats) ...[
- const SizedBox(height: 6),
- _MonitorStats(
- agent: row.agent,
- id: row.id,
- selected: selected,
- ),
- ],
- if (showQuestion)
- if (row.question
- case final question?) ...[
- const SizedBox(height: 6),
- Tooltip(
- message: question.prompt,
- child: Text(
- question.prompt.replaceAll(
- RegExp(r'\s+'),
- ' ',
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.caption(
- color: statusInk(
- AppPalette.warn,
- ),
- height: 1.35,
- ),
- ),
- ),
- ],
- ],
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- const SizedBox(width: 8),
- if (row.needsInput)
- IconButton(
- key: ValueKey('session-answer:${row.id}'),
- tooltip: 'Needs input: ${row.question!.prompt}',
- onPressed: canOpen ? onAnswer : null,
- style: actionStyle(statusInk(AppPalette.warn)),
- constraints: const BoxConstraints.tightFor(
- width: 32,
- height: 32,
- ),
- padding: const EdgeInsets.all(6),
- icon: Icon(
- AppIcons.messageCircleQuestionMark,
- size: 20,
- semanticLabel:
- 'Needs input for ${row.agent.displayName}',
- ),
- )
- // The SAME SLOT, never both: a row is either waiting on a
- // person or it is not, and the amber question already says
- // 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 ||
- unread == AlertKind.failed)
- IconButton(
- key: ValueKey(
- 'session-unread-${unread!.name}:${row.id}',
- ),
- tooltip: [
- if (canOpen) 'Open harness',
- unread == AlertKind.failed ? 'Failed' : 'Finished',
- ].join(' · '),
- onPressed: canOpen ? onOpen : null,
- style: actionStyle(
- statusInk(
- unread == AlertKind.failed
- ? errorInk
- : AppPalette.online,
- ),
- ),
- constraints: const BoxConstraints.tightFor(
- width: 32,
- height: 32,
- ),
- padding: const EdgeInsets.all(6),
- icon: Icon(
- unread == AlertKind.failed
- ? AppIcons.circleX
- : AppIcons.circleCheckBig,
- size: 20,
- semanticLabel:
- '${unread == AlertKind.failed ? 'Failed' : 'Finished'}, not yet seen: ${row.agent.displayName}',
- ),
- ),
- Tooltip(
- // Every harness pauses; what differs is how much comes
- // back, and the button says which before it is pressed —
- // a shell loses what was running in it, and an engine with
- // no way to reopen its conversation returns to a new one.
- message: busy
- ? pendingLabel
- : row.controlUnavailable ?? _toggleLabel(row),
- child: SizedBox(
- width: 32,
- height: 32,
- child: busy
- ? Semantics(
- liveRegion: true,
- label: '$pendingLabel ${row.agent.displayName}',
- child: Center(
- child: SizedBox(
- width: 15,
- height: 15,
- child: CircularProgressIndicator(
- strokeWidth: 1.5,
- color: secondary,
- ),
- ),
- ),
- )
- : IconButton(
- key: ValueKey('session-toggle:${row.id}'),
- onPressed: row.canControl ? onToggle : null,
- icon: Icon(
- row.agent.isStopped
- ? AppIcons.play
- : row.agent.closePlanState != null
- ? AppIcons.play
- : row.agent.closeSupported
- ? AppIcons.close
- : AppIcons.pause,
- size: 20,
- semanticLabel:
- '${row.agent.isStopped
- ? 'Resume'
- : row.agent.closePlanState != null
- ? 'Keep running'
- : row.agent.closeSupported
- ? 'Close'
- : 'Pause'} ${row.agent.displayName}',
- ),
- padding: const EdgeInsets.all(6),
- style: actionStyle(primary),
- ),
- ),
- ),
- const SizedBox(width: 6),
- ],
- ),
- ),
- if (error != null)
- Padding(
- padding: const EdgeInsets.fromLTRB(
- AppDesktop.identitySize + 24,
- 0,
- 12,
- 12,
- ),
- child: Semantics(
- liveRegion: true,
- child: Text(
- error!,
- style: AppType.body(color: statusInk(errorInk)),
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- );
- }
-}
-
-class _MonitorStats extends StatelessWidget {
- const _MonitorStats({
- required this.agent,
- required this.id,
- required this.selected,
- });
- final Agent agent;
- final String id;
- final bool selected;
-
- @override
- Widget build(BuildContext context) {
- final style = AppType.caption(
- color: selected ? AppDesktop.selectionDetail : AppPalette.textSecondary,
- height: 1.35,
- );
- String measured(DateTime? time) =>
- time == null ? '' : '\nUpdated ${time.toLocal()}';
- final stats = agent.outputStats;
- final items = <Widget>[
- if (agent.tokensUsed case final count?)
- Tooltip(
- message:
- '$count tokens · input, output and cached input${measured(agent.tokensUpdatedAt)}',
- child: Text(
- '${formatTokens(count)} tokens',
- key: ValueKey('session-tokens:$id'),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: style,
- ),
- ),
- if (stats != null && stats.hasEdits)
- Tooltip(
- message:
- '${stats.linesAdded} lines added · ${stats.linesRemoved} removed\n'
- 'Recorded edits by this harness, including repeated edits. Not the current branch diff.'
- '${measured(stats.updatedAt)}',
- child: Text.rich(
- TextSpan(
- children: [
- TextSpan(
- text: '+${formatTokens(stats.linesAdded!)}',
- style: TextStyle(
- color: selected
- ? AppDesktop.onSelection
- : AppPalette.online,
- ),
- ),
- const TextSpan(text: ' '),
- TextSpan(
- text: '−${formatTokens(stats.linesRemoved!)}',
- style: TextStyle(
- color: selected
- ? AppDesktop.onSelection
- : Theme.of(context).colorScheme.error,
- ),
- ),
- ],
- ),
- key: ValueKey('session-edits:$id'),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: style,
- ),
- ),
- if (stats?.pullRequestsCreated case final count?)
- Tooltip(
- message:
- '$count ${count == 1 ? 'pull request' : 'pull requests'} created by this harness\n'
- 'Confirmed creation receipts. Cached; not a live GitHub status.${measured(stats?.updatedAt)}',
- child: Text(
- '$count ${count == 1 ? 'PR' : 'PRs'}',
- key: ValueKey('session-prs:$id'),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: style,
- ),
- ),
- ];
- return Row(
- children: [
- for (var i = 0; i < items.length; i++) ...[
- if (i > 0)
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 8),
- child: Text('·', style: style),
- ),
- Flexible(child: items[i]),
- ],
- ],
- );
- }
-}
-
-/// What the Pause/Resume button promises for this row. Three answers, because
-/// three things can come back: the same shell, the same conversation, or the
-/// harness with a new one (`resumeMode` on the agent frame).
-String _toggleLabel(HarnessSession row) {
- if (!row.agent.isStopped && row.agent.closePlanState != null) {
- return 'Keep running';
- }
- if (!row.agent.isStopped && row.agent.closeSupported) return 'Close session';
- if (isTerminalEngine(row.agent.engine)) {
- return row.agent.isStopped
- ? 'Open a fresh shell here'
- : 'Pause terminal — ends this shell and anything running in it';
- }
- if (row.agent.resumesFreshConversation) {
- return row.agent.isStopped
- ? 'Resume as a new conversation'
- : 'Pause harness — it comes back as a new conversation';
- }
- return row.agent.isStopped ? 'Resume harness' : 'Pause harness';
-}
diff --git a/desktop/lib/widgets/web_pane_panel.dart b/desktop/lib/widgets/web_pane_panel.dart
index 91afe9e49..926bef47e 100644
--- a/desktop/lib/widgets/web_pane_panel.dart
+++ b/desktop/lib/widgets/web_pane_panel.dart
@@ -1,4 +1,7 @@
import 'package:harness/shared/theme/app_icons.dart';
+import 'dart:async';
+import 'dart:convert';
+
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
@@ -12,6 +15,7 @@ import '../shared/theme/app_pane_icon.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/workspace_bar_style.dart';
import '../state/app_state.dart';
+import '../state/harness_monitor_controller.dart';
import '../state/terminal_pane.dart';
import '../theme/app_theme.dart';
import '../viewer/interactive_viewer.dart';
@@ -85,6 +89,16 @@ class WebPanePanel extends StatefulWidget {
}
class _WebPanePanelState extends State<WebPanePanel> {
+ bool get _isMonitor =>
+ widget.notifier
+ .stateOf(widget.pane.machineId)
+ ?.agents
+ .any(
+ (agent) =>
+ agent.id == widget.pane.ownerAgentId &&
+ agent.dsh == harnessMonitorId,
+ ) ==
+ true;
WebViewController? _controller;
InteractiveViewerSession? _remote;
String? _remoteIdentity;
@@ -99,11 +113,14 @@ class _WebPanePanelState extends State<WebPanePanel> {
void initState() {
super.initState();
_mountRemote();
- if (WebPanePanel.webviewAvailable) _mountController();
+ if (WebPanePanel.webviewAvailable) unawaited(_mountController());
}
void _mountRemote() {
- if (!kIsWeb) return;
+ if (!kIsWeb &&
+ !(_isMonitor && !kUnderTest && !WebPanePanel.webviewAvailable)) {
+ return;
+ }
final pane = widget.pane;
final identity = '${pane.machineId}/${pane.ownerAgentId}/${pane.url}';
if (_remoteIdentity == identity) return;
@@ -113,6 +130,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
final machineId = pane.machineId, agentId = pane.ownerAgentId!;
_remote = InteractiveViewerSession(
(payload) => notifier.viewerSurface(machineId, agentId, payload),
+ onHostAction: (action) => unawaited(_hostAction(action)),
);
pane.focusViewerInput = _focusRemote;
}
@@ -128,7 +146,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
super.dispose();
}
- void _mountController() {
+ Future<void> _mountController() async {
// WebKit's default media policy wants a click before any playback, which
// leaves a viewer's muted video sitting at 00:00 with a play button; a
// pane whose whole point is the render the harness just made autoplays it.
@@ -169,7 +187,47 @@ class _WebPanePanelState extends State<WebPanePanel> {
),
);
_controller = controller;
- _load();
+ if (_isMonitor) {
+ await controller.addJavaScriptChannel(
+ 'HarnessHost',
+ onMessageReceived: (message) async {
+ if (message.message.length > 2048) return;
+ final current = await controller.currentUrl();
+ try {
+ if (!mounted ||
+ current == null ||
+ Uri.tryParse(current)?.origin !=
+ Uri.tryParse(widget.pane.url ?? '')?.origin) {
+ return;
+ }
+ final action = jsonDecode(message.message);
+ if (action is Map<String, dynamic>) await _hostAction(action);
+ } catch (_) {
+ /* malformed navigation request */
+ }
+ },
+ );
+ }
+ if (mounted) _load();
+ }
+
+ Future<void> _hostAction(Map<String, dynamic> action) async {
+ if (!mounted || !_isMonitor || !widget.visible) return;
+ final error = await widget.notifier.handleHarnessMonitorAction(
+ widget.pane,
+ action,
+ );
+ final guidance =
+ error ??
+ (action['action'] == 'assistant' && action['chooseModel'] == true
+ ? (widget.ownerEngine == 'opencode'
+ ? 'Use /models in OpenCode to choose a model before sending your question.'
+ : 'Choose a model from your assistant’s model menu before sending your question.')
+ : null);
+ if (mounted && guidance != null) {
+ ScaffoldMessenger.maybeOf(context)
+ ?.showSnackBar(SnackBar(content: Text(guidance)));
+ }
}
void _set(VoidCallback change) {
@@ -311,7 +369,8 @@ class _WebPanePanelState extends State<WebPanePanel> {
agentId: ownerId,
visible: widget.visible,
),
- if (widget.verdict case final verdict?) ...[
+ if (widget.verdict case final verdict?
+ when !_isMonitor) ...[
Text(
' · ',
style: grid.AppType.monoLabel(
@@ -330,6 +389,14 @@ class _WebPanePanelState extends State<WebPanePanel> {
),
),
const SizedBox(width: 8),
+ if (_isMonitor && !widget.zoomed)
+ TextButton(
+ onPressed: () => widget.notifier.showHarnessMonitorTable(
+ widget.pane.machineId,
+ widget.pane.ownerAgentId!,
+ ),
+ child: const Text('Hide assistant'),
+ ),
// coverage:ignore-start
// Only a real webview's navigation sets _loading; none under test.
if (_loading)
diff --git a/desktop/test/harness_monitor_test.dart b/desktop/test/harness_monitor_test.dart
new file mode 100644
index 000000000..363421120
--- /dev/null
+++ b/desktop/test/harness_monitor_test.dart
@@ -0,0 +1,221 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/harness_monitor_controller.dart';
+import 'package:harness/widgets/web_pane_panel.dart';
+
+import 'support/harness_monitor.dart';
+import 'support/workspace_tools.dart';
+import 'swarm_screen_test.dart' show mount, terminal;
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late MonitorConnection connection;
+ late MonitorTestApp app;
+ setUp(() {
+ connection = MonitorConnection();
+ app = MonitorTestApp(connection);
+ });
+ tearDown(() => app.dispose());
+
+ test(
+ 'one monitor tab, full width by default, with no unsolicited prompt',
+ () async {
+ app.installed = false;
+ app.stateOf('m')!.agents = [
+ const Agent(id: 'source', name: 'Work', engine: 'codex'),
+ ];
+ app.adoptSessionForTest(terminal('source', []));
+ final original = app.activeSwarmId;
+ expect(await app.harnessMonitor.open(), isNull);
+ final monitorTab = app.activeSwarmId, count = app.swarms.length;
+ final viewer = app.panes.singleWhere((p) => p.isWeb);
+ expect(monitorTab, isNot(original));
+ expect(app.zoomedPaneId, viewer.id);
+ expect(app.focusedPane, viewer);
+ expect(app.activeSwarm.name, harnessMonitorName);
+ expect(app.installs, 1);
+ expect(connection.creations.single['engine'], 'opencode');
+ expect(connection.creations.single['dsh'], harnessMonitorId);
+ expect(connection.creations.single['prompt'], isNull);
+ expect(app.sent, isEmpty);
+ app.selectSwarm(original);
+ expect(await app.harnessMonitor.open(), isNull);
+ expect(app.activeSwarmId, monitorTab);
+ expect(app.swarms, hasLength(count));
+ expect(connection.creations, hasLength(1));
+ },
+ );
+
+ test(
+ 'concurrent opens and a lost reply retain one durable creation',
+ () async {
+ connection.holdCreation = Completer<void>();
+ connection.loseFirstReply = true;
+ final one = app.harnessMonitor.open(), two = app.harnessMonitor.open();
+ expect(identical(one, two), isTrue);
+ connection.holdCreation!.complete();
+ expect(await one, isNotNull);
+ expect(await app.harnessMonitor.open(), isNull);
+ expect(connection.creations, hasLength(1));
+ expect(app.allPanes.where((p) => p.isWeb), hasLength(1));
+ },
+ );
+
+ test(
+ 'installation failures leave the current tab and do not create an agent',
+ () async {
+ app.installed = false;
+ app.installError = 'Install failed.';
+ final original = app.activeSwarmId;
+ expect(await app.harnessMonitor.open(), 'Install failed.');
+ expect(app.activeSwarmId, original);
+ expect(connection.creations, isEmpty);
+ },
+ );
+
+ test(
+ 'assistant navigation is scoped to the active monitor and keeps its model',
+ () async {
+ await app.harnessMonitor.open();
+ final viewer = app.panes.singleWhere((p) => p.isWeb);
+ final terminal = app.panes.singleWhere((p) => !p.isWeb);
+ expect(
+ await app.handleHarnessMonitorAction(terminal, {'action': 'assistant'}),
+ isNotNull,
+ );
+ expect(
+ await app.handleHarnessMonitorAction(viewer, {
+ 'action': 'assistant',
+ 'chooseModel': true,
+ }),
+ isNull,
+ );
+ expect(app.zoomedPaneId, isNull);
+ expect(app.focusedPane, terminal);
+ expect(app.sent, isEmpty);
+ app.showHarnessMonitorTable('m', 'manager');
+ expect(app.zoomedPaneId, viewer.id);
+ expect(
+ await app.handleHarnessMonitorAction(viewer, {
+ 'action': 'open',
+ 'machineId': 'other',
+ 'agentId': 'x',
+ }),
+ contains('Connect'),
+ );
+ app.newSwarm(name: 'Other');
+ expect(
+ await app.handleHarnessMonitorAction(viewer, {'action': 'assistant'}),
+ contains('no longer active'),
+ );
+ expect(
+ await app.handleHarnessMonitorAction(viewer, {'action': 'stop'}),
+ isNotNull,
+ );
+ },
+ );
+
+ test('a dismissed viewer is restored on the next dock open', () async {
+ await app.harnessMonitor.open();
+ await app.closePane(app.panes.singleWhere((p) => p.isWeb).id);
+ expect(app.viewerPaneShown('m', 'manager'), isFalse);
+ expect(await app.harnessMonitor.open(), isNull);
+ expect(app.viewerPaneShown('m', 'manager'), isTrue);
+ expect(app.zoomedPaneId, app.panes.singleWhere((p) => p.isWeb).id);
+ expect(connection.creations, hasLength(1));
+ });
+
+ test(
+ 'Open refreshes the owning machine and reveals an existing tab',
+ () async {
+ app.stateOf('other')!
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ app.adoptSessionForTest(terminal('target', []));
+ // The view belongs to the remote machine even if its agent ID exists locally too.
+ final target = app.panes.single;
+ target.machineId = 'other';
+ final original = app.activeSwarmId;
+ connection.inventory = [
+ {
+ 'id': 'target',
+ 'name': 'Remote work',
+ 'engine': 'codex',
+ 'terminal': {'available': true},
+ },
+ ];
+ await app.harnessMonitor.open();
+ final count = app.swarms.length;
+ final source = app.panes.singleWhere((p) => p.isWeb);
+ expect(
+ await app.handleHarnessMonitorAction(source, {
+ 'action': 'open',
+ 'machineId': 'other',
+ 'agentId': 'target',
+ }),
+ isNull,
+ );
+ expect(connection.inventoryReads, 1);
+ expect(app.activeSwarmId, original);
+ expect(app.focusedPane, target);
+ expect(app.swarms, hasLength(count));
+ expect(app.resumes, 0);
+ },
+ );
+
+ for (final nativeTabs in [false, true]) {
+ testWidgets('management opens and reuses a DSH tab (native=$nativeTabs)', (
+ tester,
+ ) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ (_) async => null,
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ null,
+ ),
+ );
+ await mount(tester, app, nativeTabs: nativeTabs);
+ Future<void> open() async {
+ if (nativeTabs) {
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('harnessControls'),
+ ),
+ (_) {},
+ );
+ } else {
+ await openWorkspaceManagement(tester, 'harnesses');
+ }
+ await tester.pumpAndSettle();
+ }
+
+ await open();
+ expect(app.activeSwarm.name, harnessMonitorName);
+ expect(find.byType(WebPanePanel), findsOneWidget);
+ expect(app.zoomedPaneId, app.panes.singleWhere((p) => p.isWeb).id);
+ final count = app.swarms.length;
+ await open();
+ expect(app.swarms, hasLength(count));
+ expect(connection.creations, hasLength(1));
+ final viewer = app.panes.singleWhere((p) => p.isWeb);
+ await app.handleHarnessMonitorAction(viewer, {'action': 'assistant'});
+ // The fixture terminal has no daemon to finish its attachment animation.
+ await tester.pump(const Duration(milliseconds: 350));
+ expect(find.text('Hide assistant'), findsOneWidget);
+ await tester.tap(find.text('Hide assistant'));
+ await tester.pumpAndSettle();
+ expect(app.zoomedPaneId, viewer.id);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+}
diff --git a/desktop/test/harness_resources_test.dart b/desktop/test/harness_resources_test.dart
index c8d50eebe..7a056c482 100644
--- a/desktop/test/harness_resources_test.dart
+++ b/desktop/test/harness_resources_test.dart
@@ -6,7 +6,6 @@ import 'package:harness/core/harness_resources.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/harness_monitor.dart';
import 'package:harness/state/app_state.dart' show MachineState;
-import 'package:harness/widgets/harness_session_manager.dart';
import 'package:harness/ws/ws_conn.dart';
import 'swarm_state_test.dart' show createApp;
@@ -228,54 +227,4 @@ void main() {
},
);
- testWidgets(
- 'compact monitor shows status, RAM, CPU and cached tokens at enlarged text',
- (tester) async {
- final connection = _Connection();
- final app = createApp(
- connected: true,
- connectionForTest: (_) => connection,
- );
- final monitor = HarnessMonitor(app);
- addTearDown(monitor.dispose);
- addTearDown(app.dispose);
- app.machineStates['m']!.agents = [
- const Agent(
- id: 'a0',
- name: 'Review',
- engine: 'codex',
- terminalAvailable: true,
- tokensUsed: 9200,
- ),
- ];
- await monitor.refresh();
- await tester.pumpWidget(
- MaterialApp(
- home: MediaQuery(
- data: const MediaQueryData(textScaler: TextScaler.linear(1.4)),
- child: Scaffold(
- body: SizedBox(
- width: 500,
- height: 600,
- child: HarnessSessionManager(
- app: app,
- monitor: monitor,
- recent: const [],
- onClose: () {},
- onOpen: (_) async => true,
- ),
- ),
- ),
- ),
- ),
- );
- await tester.pump();
- expect(find.text('Harness Monitor'), findsOneWidget);
- expect(find.textContaining('1.4 GB RAM'), findsOneWidget);
- expect(find.textContaining('125.5% CPU'), findsOneWidget);
- expect(find.textContaining('tokens'), findsOneWidget);
- expect(tester.takeException(), isNull);
- await tester.pumpWidget(const SizedBox());
- },
- );
}
diff --git a/desktop/test/harness_session_manager_test.dart b/desktop/test/harness_session_manager_test.dart
deleted file mode 100644
index 5cd2780f0..000000000
--- a/desktop/test/harness_session_manager_test.dart
+++ /dev/null
@@ -1,1416 +0,0 @@
-import 'support/workspace_tools.dart';
-
-import 'dart:async';
-import 'dart:io';
-import 'dart:ui' show PointerDeviceKind, SemanticsAction;
-
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/core/models.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/state/app_state.dart';
-import 'package:harness/state/harness_sessions.dart';
-import 'package:harness/state/pending_question.dart';
-import 'package:harness/state/swarm_navigation.dart';
-import 'package:harness/widgets/harness_session_manager.dart';
-import 'package:harness/ws/ws_conn.dart';
-
-import 'box_render_preview_test.dart' show loadPreviewFonts;
-import 'keymap_host_test.dart' show key;
-import 'support/restart_connection.dart';
-import 'support/real_fonts.dart';
-import 'swarm_screen_test.dart' show mount, terminal;
-import 'swarm_state_test.dart' show createApp;
-
-const _project = AgentProject(
- name: 'autonomous-harness',
- cwd: '/work/autonomous-harness',
- branch: 'fix/file-menu-order',
-);
-const _running = Agent(
- id: 'a0',
- name: 'Font styling review',
- engine: 'claude',
- sessionId: 'conversation',
- terminalAvailable: true,
- project: _project,
-);
-const _paused = Agent(
- id: 'saved',
- name: 'Landing page polish',
- engine: 'codex',
- sessionId: 'saved-conversation',
- status: 'stopped',
- project: AgentProject(
- name: 'website',
- cwd: '/work/website',
- branch: 'design/landing',
- ),
-);
-
-void main() {
- setUpAll(loadRealFonts);
-
- late AppNotifier app;
- late RestartConnection connection;
- setUp(() {
- connection = RestartConnection();
- app = createApp(connectionForTest: (_) => connection);
- app.rememberOpenedHarness('m', 'a0');
- app.rememberOpenedHarness('m', 'saved');
- app.machineStates['m']!
- ..machine = const Machine(
- machineId: 'm',
- name: 'iMac — Office',
- authMode: MachineAuthMode.remote,
- )
- ..connectionStatus = ConnectionStatus.connected
- ..nodeOnline = true
- ..agents = [_running, _paused];
- });
- tearDown(() => app.dispose());
-
- Finder toggle(String id) =>
- find.byKey(ValueKey('session-toggle:${agentDestinationId('m', id)}'));
- Future<void> open(WidgetTester tester) async {
- await mount(tester, app);
- await openWorkspaceManagement(tester, 'harnesses');
- await tester.pumpAndSettle();
- }
-
- /// A row past the fold is not built, and a fixture with a few harnesses in it
- /// reaches that fold — the rows carry their token and edit figures now.
- Future<Finder> reveal(WidgetTester tester, Finder target) async {
- if (target.evaluate().isEmpty) {
- await tester.scrollUntilVisible(
- target,
- 120,
- scrollable: find.byType(Scrollable).last,
- );
- await tester.pumpAndSettle();
- }
- await tester.ensureVisible(target);
- await tester.pumpAndSettle();
- return target;
- }
-
- PendingQuestion question(String id, {String request = 'question'}) =>
- PendingQuestion(
- machineId: 'm',
- agentId: id,
- requestId: request,
- answerKey: 'folder',
- prompt: 'Use the shared cache?',
- options: ['Yes', 'No'],
- multi: false,
- since: DateTime(2026, 9, 22),
- );
-
- test(
- 'activity age is compact and safely handles old daemons and clock skew',
- () {
- final now = DateTime(2026, 9, 22, 12);
- expect(harnessActivityAge(null, now), '—');
- expect(
- harnessActivityAge(now.add(const Duration(minutes: 4)), now),
- '0m',
- );
- for (final sample in [
- (59, '0m'),
- (300, '5m'),
- (3599, '59m'),
- (3600, '1h'),
- (86400, '1d'),
- (172800, '2d'),
- ]) {
- expect(
- harnessActivityAge(now.subtract(Duration(seconds: sample.$1)), now),
- sample.$2,
- );
- }
- final parsed = Agent.fromJson({
- 'id': 'fresh',
- 'updatedAt': now.toIso8601String(),
- });
- expect(parsed.lastActivityAt, now);
- expect(parsed.copyWith(name: 'Renamed').lastActivityAt, now);
- expect(
- Agent.fromJson({'id': 'legacy', 'updatedAt': 'invalid'}).lastActivityAt,
- isNull,
- );
- },
- );
-
- test('recent follows real activity before navigation recency', () {
- for (final id in ['older', 'newer', 'unknown']) {
- app.rememberOpenedHarness('m', id);
- }
- app.machineStates['m']!.agents = [
- Agent.fromJson({'id': 'older', 'updatedAt': '2026-09-21T10:00:00Z'}),
- Agent.fromJson({'id': 'newer', 'updatedAt': '2026-09-22T10:00:00Z'}),
- const Agent(id: 'unknown', name: 'Unknown'),
- ];
- expect(
- visibleHarnessSessions(
- harnessSessions(app),
- recent: [agentDestinationId('m', 'older')],
- ).map((row) => row.agent.id),
- ['newer', 'older', 'unknown'],
- );
- });
-
- test(
- 'recent sorts by last use: a harness opened anywhere outranks a busier one',
- () {
- app.machineStates['m']!.agents = [
- Agent.fromJson({'id': 'busy', 'updatedAt': '2026-09-26T11:00:00Z'}),
- // Quiet since nine, but somebody opened it at noon — in any client.
- Agent.fromJson({
- 'id': 'opened',
- 'updatedAt': '2026-09-26T09:00:00Z',
- 'lastOpenedAt': '2026-09-26T12:00:00Z',
- }),
- // Opened long ago and busy since: the later of the two counts.
- Agent.fromJson({
- 'id': 'worked',
- 'updatedAt': '2026-09-26T10:00:00Z',
- 'lastOpenedAt': '2026-09-26T08:00:00Z',
- }),
- const Agent(id: 'unknown', name: 'Unknown'),
- ];
- for (final id in ['busy', 'opened', 'worked', 'unknown']) {
- app.rememberOpenedHarness('m', id);
- }
- expect(SessionSort.recent.label, 'Recently used');
- expect(
- visibleHarnessSessions(harnessSessions(app)).map((row) => row.agent.id),
- ['opened', 'busy', 'worked', 'unknown'],
- );
- expect(
- harnessSessions(app)
- .singleWhere((row) => row.agent.id == 'opened')
- .lastUsedAt,
- DateTime.utc(2026, 9, 26, 12),
- );
- },
- );
-
- testWidgets('each row shows and says the time it is sorted by', (
- tester,
- ) async {
- final now = DateTime.now();
- app.machineStates['m']!.agents = [
- Agent(
- id: _running.id,
- name: _running.name,
- engine: _running.engine,
- sessionId: _running.sessionId,
- terminalAvailable: true,
- project: _project,
- lastActivityAt: now.subtract(const Duration(hours: 3)),
- lastOpenedAt: now.subtract(const Duration(minutes: 5)),
- ),
- _paused,
- ];
- await open(tester);
- final id = agentDestinationId('m', 'a0');
- final age = find.byKey(ValueKey('session-age:$id'));
- expect(tester.widget<Text>(age).data, '· 5m');
- expect(
- tester
- .widget<Tooltip>(
- find.ancestor(of: age, matching: find.byType(Tooltip)).first,
- )
- .message,
- startsWith('Last used '),
- );
- expect(
- tester
- .widget<Semantics>(find.byKey(ValueKey('session-open:$id')))
- .properties
- .value,
- contains('Last used 5m ago'),
- );
- // A daemon with no time for it at all.
- expect(
- tester
- .widget<Semantics>(
- find.byKey(
- ValueKey('session-open:${agentDestinationId('m', 'saved')}'),
- ),
- )
- .properties
- .value,
- contains('Last use unknown'),
- );
- await tester.tap(find.byTooltip('Sort harnesses'));
- await tester.pumpAndSettle();
- expect(find.text('Recently used'), findsOneWidget);
- expect(find.text('Recently active'), findsNothing);
- expect(tester.takeException(), isNull);
- });
-
- testWidgets('recent harness ages show and say now, including clock skew', (
- tester,
- ) async {
- final now = DateTime.now();
- app.machineStates['m']!.agents = [
- for (final (id, age) in [
- ('recent', const Duration(seconds: 30)),
- ('future', const Duration(minutes: -4)),
- ])
- Agent(
- id: id,
- name: '$id harness',
- engine: _running.engine,
- sessionId: '$id-conversation',
- terminalAvailable: true,
- project: _project,
- lastActivityAt: now.subtract(age),
- ),
- ];
- for (final id in ['recent', 'future']) {
- app.rememberOpenedHarness('m', id);
- }
- await open(tester);
- for (final agentId in ['recent', 'future']) {
- final id = agentDestinationId('m', agentId);
- expect(
- tester.widget<Text>(find.byKey(ValueKey('session-age:$id'))).data,
- '· now',
- );
- final spoken = tester
- .widget<Semantics>(find.byKey(ValueKey('session-open:$id')))
- .properties
- .value!;
- expect(spoken, contains('Last used now'));
- expect(spoken, isNot(contains('0m')));
- expect(spoken, isNot(contains('now ago')));
- }
- expect(tester.takeException(), isNull);
- });
-
- testWidgets(
- 'displays remote cached tokens beneath context and leaves missing usage empty',
- (tester) async {
- app.machineStates['m']!.agents = [
- Agent.fromJson({
- 'id': 'a0',
- 'name': 'Measured harness',
- 'engine': 'claude',
- 'sessionId': 'conversation',
- 'terminal': {'available': true},
- 'tokenUsage': {
- 'totalTokens': 1234567,
- 'updatedAt': '2026-09-22T16:00:00Z',
- },
- 'outputStats': {
- 'linesAdded': 124,
- 'linesRemoved': 38,
- 'pullRequestsCreated': 2,
- 'updatedAt': '2026-09-22T16:00:00Z',
- },
- }),
- _paused,
- ];
- await open(tester);
- expect(find.text('1.2M tokens'), findsOneWidget);
- expect(find.text('+124 −38'), findsOneWidget);
- expect(find.text('2 PRs'), findsOneWidget);
- expect(find.text('0 tokens'), findsNothing);
- expect(
- find.byKey(
- ValueKey('session-tokens:${agentDestinationId('m', 'saved')}'),
- ),
- findsNothing,
- );
- expect(
- tester.getTopLeft(find.text('1.2M tokens')).dy,
- greaterThan(tester.getTopLeft(find.text('iMac — Office').first).dy),
- );
- expect(connection.requests, isEmpty);
- expect(tester.takeException(), isNull);
- },
- );
-
- test('attention filters live questions, retains missing agents, excludes paused history', () {
- app.rememberOpenedHarness('m', 'missing');
- app.machineStates['m']!.blockedAgents.addAll({
- 'a0': question('a0'),
- 'saved': question('saved'),
- 'missing': question('missing'),
- });
- final rows = visibleHarnessSessions(
- harnessSessions(app),
- filter: SessionFilter.needsInput,
- );
- expect(rows.map((row) => row.agent.id), containsAll(['a0', 'missing']));
- expect(rows, hasLength(2));
- expect(
- rows.singleWhere((row) => row.agent.id == 'missing').canControl,
- isFalse,
- );
- expect(
- rows.singleWhere((row) => row.agent.id == 'missing').canOpen,
- isFalse,
- );
- expect(
- visibleHarnessSessions(rows, query: 'office shared cache'),
- hasLength(2),
- );
- });
-
- testWidgets(
- 'Needs input exposes the question and opens its existing pane without pausing',
- (tester) async {
- await app.addAgentToSwarm('m', 'a0');
- app.machineStates['m']!.blockedAgents['a0'] = question('a0');
- await mount(tester, app);
- await openWorkspaceManagement(tester, 'harnesses');
- await tester.pump(const Duration(milliseconds: 300));
- expect(
- find.byKey(const ValueKey('swarm-notifications-button')),
- findsNothing,
- );
- await tester.tap(find.byKey(const ValueKey('session-filter:needsInput')));
- await tester.pump(const Duration(milliseconds: 300));
- expect(find.text('Use the shared cache?'), findsOneWidget);
- expect(find.text(_paused.name), findsNothing);
- await tester.tap(
- find.byKey(ValueKey('session-answer:${agentDestinationId('m', 'a0')}')),
- );
- await tester.pump(const Duration(milliseconds: 300));
- expect(find.byType(HarnessSessionManager), findsNothing);
- expect(app.focusedPane?.agentId, 'a0');
- expect(app.panes, hasLength(1));
- expect(connection.stops, isEmpty);
- },
- );
-
- testWidgets(
- 'an outdated question cannot open work and live closure clears the filter',
- (tester) async {
- app.machineStates['m']!.blockedAgents['a0'] = question('a0');
- await open(tester);
- await tester.tap(find.byKey(const ValueKey('session-filter:needsInput')));
- await tester.pumpAndSettle();
- final answer = tester
- .widget<Semantics>(
- find.byKey(
- ValueKey('session-open:${agentDestinationId('m', 'a0')}'),
- ),
- )
- .properties
- .onTap!;
- app.machineStates['m']!.blockedAgents['a0'] = question(
- 'a0',
- request: 'replacement',
- );
- answer();
- await tester.pump();
- expect(app.panes, isEmpty);
- app.machineStates['m']!.blockedAgents.clear();
- app.notifyListeners();
- await tester.pumpAndSettle();
- expect(find.text('No harnesses need your input'), findsOneWidget);
- expect(find.text('Try another search or filter.'), findsNothing);
- },
- );
-
- test('inventory deduplicates views, searches context, and sorts deterministically', () async {
- await app.addAgentToSwarm('m', 'a0');
- app.newSwarm(name: 'Second view');
- await app.addAgentToSwarm('m', 'a0');
- final rows = harnessSessions(app);
- expect(rows, hasLength(2));
- expect(rows.first.open, isTrue);
- expect(
- visibleHarnessSessions(rows, query: 'office file-menu').single.agent.id,
- 'a0',
- );
- expect(
- visibleHarnessSessions(
- rows,
- filter: SessionFilter.paused,
- ).single.agent.id,
- 'saved',
- );
- expect(
- visibleHarnessSessions(
- rows,
- filter: SessionFilter.running,
- ).single.agent.id,
- 'a0',
- );
- expect(
- visibleHarnessSessions(rows, recent: [rows.last.id]).first.agent.id,
- 'saved',
- );
- expect(
- visibleHarnessSessions(rows, sort: SessionSort.project).first.agent.id,
- 'a0',
- );
- app.machineStates['m']!.nodeOnline = false;
- expect(
- harnessSessions(app)
- .every((row) => !row.canControl && row.status == 'Offline'),
- isTrue,
- );
- expect(
- visibleHarnessSessions(
- harnessSessions(app),
- filter: SessionFilter.running,
- ),
- isEmpty,
- );
- });
-
- testWidgets(
- 'search, filters, sort, and Escape work in the titlebar popover',
- (tester) async {
- await open(tester);
- expect(find.byType(HarnessSessionManager), findsOneWidget);
- expect(find.text('Harness Monitor'), findsOneWidget);
- expect(find.text('Running 1'), findsOneWidget);
- expect(find.text('Saved 1'), findsOneWidget);
- expect(find.text('Ready'), findsNothing);
- expect(find.text('Saved'), findsNothing);
- expect(find.textContaining('Pause keeps'), findsNothing);
- expect(
- tester
- .widget<TextField>(find.byKey(const ValueKey('session-search')))
- .decoration
- ?.hintText,
- 'Search harnesses, machines, projects, branches',
- );
- await tester.enterText(
- find.byKey(const ValueKey('session-search')),
- 'office file-menu',
- );
- await tester.pumpAndSettle();
- expect(find.text(_running.name), findsOneWidget);
- expect(find.text(_paused.name), findsNothing);
- await tester.tap(find.byTooltip('Clear search'));
- await tester.tap(find.byKey(const ValueKey('session-filter:paused')));
- await tester.pumpAndSettle();
- expect(find.text(_paused.name), findsOneWidget);
- expect(find.text(_running.name), findsNothing);
- await tester.tap(find.byTooltip('Sort harnesses'));
- await tester.pumpAndSettle();
- await tester.tap(find.text('Project').last);
- await tester.pumpAndSettle();
- expect(find.text('Project'), findsOneWidget);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- expect(find.byType(HarnessSessionManager), findsNothing);
- expect(connection.stops, isEmpty);
- },
- );
-
- testWidgets(
- 'pause sends one stop, retains saved session, then resume sends one durable request',
- (tester) async {
- await open(tester);
- connection.inventory = Completer<Map<String, dynamic>>();
- await tester.tap(toggle('a0'));
- await tester.pump();
- expect(connection.stops, ['a0']);
- expect(find.byTooltip('Pausing…'), findsOneWidget);
- expect(toggle('a0'), findsNothing);
- connection.stopReplies.single.complete({'deleted': true});
- await tester.pump();
- expect(
- find.text(_running.name),
- findsOneWidget,
- reason: 'The row stays visible while the saved inventory loads',
- );
- connection.inventory!.complete({
- 'agents': [
- {
- 'id': 'a0',
- 'name': _running.name,
- 'engine': 'claude',
- 'sessionId': 'conversation',
- 'status': 'stopped',
- 'terminal': {'available': false},
- },
- {
- 'id': 'saved',
- 'name': _paused.name,
- 'engine': 'codex',
- 'sessionId': 'saved-conversation',
- 'status': 'stopped',
- },
- ],
- });
- await tester.pumpAndSettle();
- expect(app.stateOf('m')!.agents.first.isStopped, isTrue);
- expect(find.text('Running 0'), findsOneWidget);
- expect(find.text('Saved 2'), findsOneWidget);
- await tester.tap(toggle('a0'));
- await tester.pump();
- expect(connection.types, ['agent_resume']);
- expect(find.byTooltip('Resuming…'), findsOneWidget);
- connection.restartReplies.single.complete(
- restartReceipt(
- connection.requests.single['creationId'] as String,
- name: _running.name,
- sessionId: 'conversation',
- ),
- );
- await tester.pumpAndSettle();
- expect(
- app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,
- isFalse,
- );
- expect(
- app.allPanes,
- isEmpty,
- reason: 'Resuming in the manager does not force open a pane',
- );
- },
- );
-
- testWidgets('pause failure is inline and leaves the session running', (
- tester,
- ) async {
- connection.inventory = Completer<Map<String, dynamic>>()
- ..complete({
- 'agents': [
- {
- 'id': 'a0',
- 'name': _running.name,
- 'engine': 'claude',
- 'sessionId': 'conversation',
- 'terminal': {'available': true},
- },
- ],
- });
- await open(tester);
- await tester.tap(toggle('a0'));
- await tester.pump();
- connection.stopReplies.single.complete({
- 'error': 'REFUSED',
- 'detail': 'Machine busy. Try again.',
- });
- await tester.pumpAndSettle();
- expect(find.text('Pause failed: Machine busy. Try again.'), findsOneWidget);
- expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
- expect(tester.widget<IconButton>(toggle('a0')).onPressed, isNotNull);
- });
-
- testWidgets(
- 'closing and reopening the manager cannot duplicate an in-flight pause',
- (tester) async {
- connection.inventory = Completer<Map<String, dynamic>>();
- await open(tester);
- await tester.tap(toggle('a0'));
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- connection.stopReplies.single.complete({'deleted': true});
- await tester.pump();
- await openWorkspaceManagement(tester, 'harnesses');
- await tester.pump();
- expect(toggle('a0'), findsNothing);
- expect(find.byTooltip('Pausing…'), findsOneWidget);
- expect(connection.stops, ['a0']);
- connection.inventory!.completeError(StateError('refresh failed'));
- await tester.pumpAndSettle();
- expect(find.text(_running.name), findsOneWidget);
- expect(find.text('Saved 2'), findsOneWidget);
- expect(tester.widget<IconButton>(toggle('a0')).onPressed, isNotNull);
- expect(connection.stops, ['a0']);
- },
- );
-
- testWidgets(
- 'a terminal pauses and comes back as a fresh shell in the same tile',
- (tester) async {
- // A shell holds no conversation, so the saved-conversation rule the
- // engines live under has nothing to protect here — the daemon has always
- // relaunched one (`resumeStoppedAgent.ts` exempts it).
- app
- .stateOf('m')!
- .agents
- .add(
- const Agent(
- id: 'shell',
- name: 'Untitled Pane',
- engine: 'terminal',
- terminalAvailable: true,
- project: _project,
- ),
- );
- app.rememberOpenedHarness('m', 'shell');
- await open(tester);
- await reveal(tester, toggle('shell'));
- expect(tester.widget<IconButton>(toggle('shell')).onPressed, isNotNull);
- expect(
- find.byTooltip(
- 'Pause terminal — ends this shell and anything running in it',
- ),
- findsOneWidget,
- );
-
- connection.inventory = Completer<Map<String, dynamic>>();
- await tester.tap(toggle('shell'));
- await tester.pump();
- expect(connection.stops, ['shell']);
- connection.stopReplies.single.complete({'deleted': true});
- await tester.pump();
- connection.inventory!.complete({
- 'agents': [
- {
- 'id': 'shell',
- 'name': 'Untitled Pane',
- 'engine': 'terminal',
- 'status': 'stopped',
- 'terminal': {'available': false},
- },
- ],
- });
- await tester.pumpAndSettle();
- expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
- // Paused, not "Resume unavailable": it can come back.
- expect(harnessSessions(app).single.status, 'Saved');
- expect(find.text('Saved 1'), findsOneWidget);
- expect(
- tester.widget<IconButton>(toggle('shell')).onPressed,
- isNotNull,
- reason: 'the paused shell offers resume',
- );
- expect(find.byTooltip('Open a fresh shell here'), findsOneWidget);
-
- await tester.tap(toggle('shell'));
- await tester.pump();
- expect(connection.types, ['agent_resume']);
- connection.restartReplies.single.complete(
- restartReceipt(
- connection.requests.single['creationId'] as String,
- agentId: 'shell',
- name: 'Untitled Pane',
- ),
- );
- await tester.pumpAndSettle();
- expect(app.stateOf('m')!.agents.single.isStopped, isFalse);
- },
- );
-
- testWidgets('every engine the daemon reports is pausable, in its own words', (
- tester,
- ) async {
- // The daemon says per engine how much a resume brings back (`resumeMode`).
- // An engine that reopens its conversation and one that cannot both pause;
- // only the sentence differs.
- app.stateOf('m')!.agents.addAll(const [
- Agent(
- id: 'keeps',
- name: 'Keeps its conversation',
- engine: 'opencode',
- sessionId: 'history',
- resumeMode: 'conversation',
- terminalAvailable: true,
- ),
- Agent(
- id: 'fresh',
- name: 'No resume flag',
- engine: 'devin',
- sessionId: 'history',
- resumeMode: 'fresh',
- terminalAvailable: true,
- ),
- ]);
- // The Monitor lists the harnesses this app has opened.
- app.rememberOpenedHarness('m', 'keeps');
- app.rememberOpenedHarness('m', 'fresh');
- await open(tester);
- await reveal(tester, toggle('keeps'));
- expect(tester.widget<IconButton>(toggle('keeps')).onPressed, isNotNull);
- expect(
- find.ancestor(
- of: toggle('keeps'),
- matching: find.byTooltip('Pause harness'),
- ),
- findsOneWidget,
- );
- await reveal(tester, toggle('fresh'));
- expect(tester.widget<IconButton>(toggle('fresh')).onPressed, isNotNull);
- expect(
- find.byTooltip('Pause harness — it comes back as a new conversation'),
- findsOneWidget,
- );
- });
-
- testWidgets(
- 'an engine a pre-resumeMode daemon cannot pause keeps its explanation',
- (tester) async {
- // No `resumeMode` on the frame: an older CLI, whose resume would refuse
- // anything but claude/codex. Offering the button would only fail.
- app
- .stateOf('m')!
- .agents
- .add(
- const Agent(
- id: 'unsupported',
- name: 'Other engine',
- engine: 'opencode',
- sessionId: 'history',
- terminalAvailable: true,
- ),
- );
- app.rememberOpenedHarness('m', 'unsupported');
- await open(tester);
- await reveal(tester, toggle('unsupported'));
- expect(
- tester.widget<IconButton>(toggle('unsupported')).onPressed,
- isNull,
- );
- expect(
- find.byTooltip(
- 'Update the harness CLI on this machine to pause and resume this engine.',
- ),
- findsOneWidget,
- );
- expect(connection.stops, isEmpty);
- },
- );
-
- testWidgets(
- 'a resuming harness can open for native login or permission review',
- (tester) async {
- app.adoptSessionForTest(terminal('saved', []));
- await open(tester);
- await tester.tap(toggle('saved'));
- await tester.pump();
- await app.handleEventForTest('m', {
- 'type': 'agent_synced',
- 'payload': {
- 'agent': {
- 'id': 'saved',
- 'name': _paused.name,
- 'engine': 'codex',
- 'sessionId': 'saved-conversation',
- 'terminal': {'available': true},
- 'launch': {'state': 'starting'},
- },
- },
- });
- await tester.pump();
- expect(toggle('saved'), findsNothing);
- await tester.tap(
- find.byKey(
- ValueKey('session-open:${agentDestinationId('m', 'saved')}'),
- ),
- );
- await tester.pumpAndSettle();
- expect(find.byType(HarnessSessionManager), findsNothing);
- expect(app.focusedPane?.agentId, 'saved');
- expect(connection.types, ['agent_resume']);
- connection.restartReplies.single.complete(
- restartReceipt(
- connection.requests.single['creationId'] as String,
- agentId: 'saved',
- sessionId: 'saved-conversation',
- ),
- );
- await tester.pumpAndSettle();
- },
- );
-
- testWidgets('VoiceOver exposes opening and pausing as separate actions', (
- tester,
- ) async {
- final semantics = tester.ensureSemantics();
- await open(tester);
- final node = tester.getSemantics(
- find.byKey(ValueKey('session-open:${agentDestinationId('m', 'a0')}')),
- );
- expect(node.label, 'Open Font styling review');
- expect(node.value, contains('iMac — Office'));
- expect(node.getSemanticsData().hasAction(SemanticsAction.tap), isTrue);
- semantics.dispose();
- });
-
- testWidgets(
- 'uncertain resume checks its existing receipt instead of relaunching',
- (tester) async {
- await open(tester);
- await tester.tap(toggle('saved'));
- await tester.pump();
- connection.restartReplies.single.completeError(
- const WsRequestTimeout('agent_resume'),
- );
- await tester.pumpAndSettle();
- expect(
- find.textContaining('Still waiting for the resume response'),
- findsOneWidget,
- );
- await tester.tap(toggle('saved'));
- await tester.pump();
- expect(connection.requests, hasLength(1));
- expect(
- connection.checks.single['creationId'],
- connection.requests.single['creationId'],
- );
- connection.checkReplies.single.complete(
- restartReceipt(
- connection.requests.single['creationId'] as String,
- agentId: 'saved',
- sessionId: 'saved-conversation',
- ),
- );
- await tester.pumpAndSettle();
- expect(
- find.textContaining('Still waiting for the resume response'),
- findsNothing,
- );
- },
- );
-
- testWidgets('keyboard search opens its first matching session', (
- tester,
- ) async {
- app.adoptSessionForTest(terminal('a0', []));
- await open(tester);
- await tester.enterText(
- find.byKey(const ValueKey('session-search')),
- 'file-menu',
- );
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(app.focusedPane?.agentId, 'a0');
- expect(find.byType(HarnessSessionManager), findsNothing);
- });
-
- testWidgets(
- 'reduced motion closes immediately and keeps the saved inventory',
- (tester) async {
- await app.addAgentToSwarm('m', 'a0');
- await mount(tester, app);
- tester.platformDispatcher.accessibilityFeaturesTestValue =
- const FakeAccessibilityFeatures(disableAnimations: true);
- addTearDown(
- tester.platformDispatcher.clearAccessibilityFeaturesTestValue,
- );
- await tester.pump();
- await key(tester, LogicalKeyboardKey.keyW, cmd: true, shift: true);
- await tester.pump();
- expect(app.panes, isEmpty);
- expect(connection.stops, isEmpty);
- },
- );
-
- testWidgets('offline and shared rows cannot send lifecycle commands', (
- tester,
- ) async {
- app.machineStates['m']!.nodeOnline = false;
- await open(tester);
- expect(tester.widget<IconButton>(toggle('a0')).onPressed, isNull);
- expect(tester.widget<IconButton>(toggle('saved')).onPressed, isNull);
- expect(find.text('Offline'), findsNWidgets(2));
- expect(connection.requests, isEmpty);
- expect(connection.stops, isEmpty);
- app.machineStates['m']!
- ..nodeOnline = true
- ..machine = const Machine(
- machineId: 'm',
- name: 'Shared Mac',
- authMode: MachineAuthMode.remote,
- isShared: true,
- );
- app.machineStates['m']!.connectionStatus = ConnectionStatus.disconnected;
- app.notifyListeners();
- await tester.pumpAndSettle();
- expect(tester.widget<IconButton>(toggle('a0')).onPressed, isNull);
- expect(find.text('View only'), findsNWidgets(2));
- });
-
- testWidgets(
- 'opening a row reveals its existing pane and restores terminal focus',
- (tester) async {
- app.adoptSessionForTest(terminal('a0', []));
- await app.addAgentToSwarm('m', 'a0');
- final original = app.focusedPane!;
- app.newSwarm(name: 'Another tab');
- await open(tester);
- await tester.tap(find.text(_running.name));
- await tester.pumpAndSettle();
- expect(app.allPanes, [original]);
- expect(app.focusedPane, original);
- expect(find.byType(HarnessSessionManager), findsNothing);
- expect(connection.requests, isEmpty);
- },
- );
-
- testWidgets(
- 'closing a pane removes it immediately without stopping its process',
- (tester) async {
- final live = terminal('a0', [])..agentName = 'Font styling review';
- live.terminal.write('Reviewing typography and spacing.\r\n\r\n');
- for (var i = 0; i < 20; i++) {
- live.terminal.write(
- ' ${i + 1} Checking pane labels and native controls\r\n',
- );
- }
- app.adoptSessionForTest(live);
- await app.addAgentToSwarm('m', 'a0');
- final pane = app.focusedPane!;
- final sibling = app.adoptSessionForTest(terminal('sibling', []));
- await mount(tester, app);
- app.focusPane(pane.id);
- await tester.pump();
- await key(tester, LogicalKeyboardKey.keyW, cmd: true, shift: true);
- await tester.pump();
- expect(app.panes, [sibling]);
- expect(find.byKey(pane.cellKey), findsNothing);
- expect(app.stateOf('m')!.agents.first.isStopped, isFalse);
- expect(connection.stops, isEmpty);
- await openWorkspaceManagement(tester, 'harnesses');
- await tester.pumpAndSettle();
- expect(find.text(_running.name), findsOneWidget);
- },
- );
-
- testWidgets('native titlebar opens and toggles the same manager', (
- tester,
- ) async {
- const channel = MethodChannel('harness/swarm_tabs');
- final updates = <Map>[];
- tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
- call,
- ) async {
- if (call.method == 'update') updates.add(call.arguments as Map);
- return null;
- });
- addTearDown(
- () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
- channel,
- null,
- ),
- );
- await mount(tester, app, nativeTabs: true);
- void nativeClick() =>
- tester.binding.defaultBinaryMessenger.handlePlatformMessage(
- channel.name,
- const StandardMethodCodec().encodeMethodCall(
- const MethodCall('harnessControls'),
- ),
- (_) {},
- );
- nativeClick();
- await tester.pumpAndSettle();
- expect(find.byType(HarnessSessionManager), findsOneWidget);
- expect(
- tester
- .widget<TextField>(find.byKey(const ValueKey('session-search')))
- .focusNode!
- .hasFocus,
- isTrue,
- );
- expect(
- tester
- .widget<TextField>(find.byKey(const ValueKey('session-search')))
- .focusNode!
- .hasFocus,
- isTrue,
- );
- expect(updates.last['sessionsOpen'], isTrue);
- expect(updates.last['runningSessions'], 1);
- nativeClick();
- await tester.pumpAndSettle();
- expect(find.byType(HarnessSessionManager), findsNothing);
- expect(updates.last['sessionsOpen'], isFalse);
- app.machineStates['m']!.blockedAgents['a0'] = question('a0');
- app.notifyListeners();
- await tester.pumpAndSettle();
- expect(updates.last['attention'], 1);
- app.machineStates['m']!.blockedAgents['hidden-worker'] = question(
- 'hidden-worker',
- );
- app.notifyListeners();
- await tester.pumpAndSettle();
- expect(updates.last['attention'], 1);
- app.machineStates['m']!.blockedAgents.clear();
- app.notifyListeners();
- await tester.pumpAndSettle();
- expect(updates.last['attention'], 0);
- });
-
- testWidgets('session manager fits the minimum Mac window and scaled text', (
- tester,
- ) async {
- app.machineStates['m']!.agents = [
- Agent.fromJson({
- 'id': 'a0',
- 'name': 'A long harness name that must leave room for the activity timestamp',
- 'engine': 'claude',
- 'sessionId': 'conversation',
- 'terminal': {'available': true},
- 'project': {
- 'name': 'autonomous-harness-desktop-with-a-long-project-name',
- 'cwd': '/work/autonomous-harness-desktop-with-a-long-project-name',
- 'branch':
- 'feat/centered-new-harness-session-picker-with-long-details',
- },
- 'updatedAt': DateTime.now()
- .subtract(const Duration(minutes: 8))
- .toIso8601String(),
- 'tokenUsage': {'totalTokens': 1234567},
- 'outputStats': {
- 'linesAdded': 124,
- 'linesRemoved': 38,
- 'pullRequestsCreated': 2,
- },
- }),
- _paused,
- ];
- await open(tester);
- tester.view.physicalSize = const Size(880, 560);
- await tester.pumpAndSettle();
- expect(tester.takeException(), isNull);
- final rect = tester.getRect(find.byType(HarnessSessionManager));
- expect(rect.right, lessThanOrEqualTo(880));
- expect(rect.bottom, lessThanOrEqualTo(560));
- tester.platformDispatcher.textScaleFactorTestValue = 1.5;
- addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
- await tester.pumpAndSettle();
- expect(tester.takeException(), isNull);
- });
-
- final renderDir = Platform.environment['SESSION_MANAGER_RENDER_DIR'];
- for (final brightness in Brightness.values) {
- testWidgets('desktop inventory focus and feedback in ${brightness.name}', (
- tester,
- ) async {
- if (renderDir != null) await tester.runAsync(loadPreviewFonts);
- final previousBrightness = grid.AppTheme.brightness.value;
- grid.AppTheme.brightness.value = brightness;
- addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);
- tester.view.devicePixelRatio = 1;
- addTearDown(tester.view.reset);
- app.machineStates['m']!.blockedAgents['a0'] = question('a0');
- app.machineStates['m']!.agents[0] = Agent.fromJson({
- 'id': 'a0',
- 'name': _running.name,
- 'engine': _running.engine,
- 'sessionId': 'fixture-conversation',
- 'terminal': {'available': true},
- 'project': {
- 'name': _project.name,
- 'cwd': _project.cwd,
- 'branch': _project.branch,
- },
- 'tokenUsage': {'totalTokens': 123456},
- 'outputStats': {
- 'linesAdded': 124,
- 'linesRemoved': 38,
- 'pullRequestsCreated': 2,
- },
- });
- final opening = <String>[];
- final field = find.byKey(const ValueKey('session-search'));
- final opener = find.byKey(
- ValueKey('session-open:${agentDestinationId('m', 'a0')}'),
- );
- for (final (size, scale) in [
- (const Size(880, 560), 1.0),
- (const Size(420, 480), 1.7),
- ]) {
- tester.view.physicalSize = size;
- await tester.pumpWidget(
- MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: brightness),
- builder: (context, child) => MediaQuery(
- data: MediaQuery.of(context)
- .copyWith(textScaler: TextScaler.linear(scale)),
- child: child!,
- ),
- home: Scaffold(
- body: Align(
- alignment: Alignment.topCenter,
- child: Padding(
- padding: const EdgeInsets.all(16),
- child: SizedBox(
- width: 640,
- child: HarnessSessionManager(
- key: ValueKey((brightness, scale)),
- app: app,
- recent: const [],
- onClose: () {},
- onOpen: (row) async {
- opening.add(row.id);
- throw StateError('Synthetic open failure');
- },
- ),
- ),
- ),
- ),
- ),
- ),
- );
- await tester.pumpAndSettle();
- Future<void> capture(String state) async {
- expect(tester.takeException(), isNull);
- if (renderDir == null) return;
- final oldShadows = debugDisableShadows;
- debugDisableShadows = false;
- try {
- await tester.runAsync(() async {
- await Future.wait(
- find
- .byType(Image)
- .evaluate()
- .map(
- (element) => precacheImage(
- (element.widget as Image).image,
- element,
- ),
- ),
- );
- });
- for (final object in tester.allRenderObjects) {
- object.markNeedsPaint();
- }
- await tester.pump();
- await expectLater(
- find.byType(MaterialApp),
- matchesGoldenFile(
- Uri.file(
- '$renderDir/inventory-$state-${brightness.name}-$scale.png',
- ),
- ),
- );
- } finally {
- debugDisableShadows = oldShadows;
- }
- }
-
- final editor = tester.widget<TextField>(field);
- expect(editor.focusNode!.hasFocus, isTrue);
- expect(find.byTooltip('Close').hitTestable(), findsOneWidget);
- await capture('list');
- await tester.enterText(field, 'Font');
- editor.controller!.value = const TextEditingValue(
- text: 'Font',
- selection: TextSelection.collapsed(offset: 4),
- composing: TextRange(start: 0, end: 4),
- );
- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
- await mouse.addPointer(location: Offset.zero);
- await mouse.moveTo(tester.getCenter(opener));
- await tester.pumpAndSettle();
- expect(
- tester.widget<TextField>(field).controller,
- same(editor.controller),
- );
- expect(editor.focusNode!.hasFocus, isTrue);
- expect(
- editor.controller!.value.composing,
- const TextRange(start: 0, end: 4),
- );
- expect(tester.widget<Semantics>(opener).properties.selected, isTrue);
- await capture('active');
- await mouse.removePointer();
- editor.controller!.value = const TextEditingValue(
- text: 'Font',
- selection: TextSelection.collapsed(offset: 4),
- );
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(opening.last, agentDestinationId('m', 'a0'));
- await tester.tap(find.byTooltip('Clear search'));
- await tester.pumpAndSettle();
- const failure = 'Could not open this harness. Try again.';
- final error = tester.widget<Text>(find.text(failure)).style!.color!;
- final foreground = error.computeLuminance();
- final background = grid.AppMenu.fill.computeLuminance();
- final contrast = foreground > background
- ? (foreground + .05) / (background + .05)
- : (background + .05) / (foreground + .05);
- expect(contrast, greaterThanOrEqualTo(4.5));
- await capture('error');
- final questions = find.byKey(
- const ValueKey('session-filter:needsInput'),
- );
- await tester.ensureVisible(questions);
- await tester.tap(questions);
- await tester.pumpAndSettle();
- expect(find.text('Use the shared cache?'), findsOneWidget);
- await capture('needs-input');
- expect(connection.requests, isEmpty);
- expect(connection.stops, isEmpty);
- }
- await tester.pumpWidget(const SizedBox());
- });
- }
- testWidgets(
- 'render session manager for visual review',
- skip: renderDir == null,
- (tester) async {
- await tester.runAsync(loadPreviewFonts);
- debugDisableShadows = false;
- addTearDown(() => debugDisableShadows = true);
- app.machineStates['m']!.machine = const Machine(
- machineId: 'm',
- name: 'M2',
- authMode: MachineAuthMode.remote,
- );
- app.machineStates['m']!.agents[0] = const Agent(
- id: 'a0',
- name: 'Improve multiple-machine experience',
- engine: 'codex',
- sessionId: 'conversation',
- terminalAvailable: true,
- project: AgentProject(
- name: 'autonomous-harness',
- cwd: '/work/autonomous-harness',
- branch: 'improve-multiple-machine-experience',
- ),
- );
- app.machineStates['m']!.agents.addAll([
- const Agent(
- id: 'review',
- name: 'File menu ordering',
- engine: 'codex',
- sessionId: 'review-history',
- terminalAvailable: true,
- project: AgentProject(
- name: 'autonomous-harness',
- cwd: '/work/autonomous-harness',
- branch: 'feat/centered-new-harness-session-picker',
- ),
- ),
- const Agent(
- id: 'api',
- name: 'API response caching',
- engine: 'opencode',
- terminalAvailable: true,
- project: AgentProject(
- name: 'backend',
- cwd: '/work/backend',
- branch: 'perf/cache',
- ),
- ),
- const Agent(
- id: 'docs',
- name: 'Getting started guide',
- engine: 'claude',
- sessionId: 'docs-history',
- status: 'stopped',
- project: AgentProject(
- name: 'docs',
- cwd: '/work/docs',
- branch: 'main',
- ),
- ),
- ]);
- for (final agent in app.machineStates['m']!.agents) {
- app.rememberOpenedHarness('m', agent.id);
- }
- final now = DateTime.now();
- final ages = {
- 'a0': 5,
- 'saved': 1440,
- 'review': 12,
- 'api': 60,
- 'docs': 2880,
- };
- app.machineStates['m']!.agents = [
- for (final agent in app.machineStates['m']!.agents)
- Agent.fromJson({
- 'id': agent.id,
- 'name': agent.name,
- 'engine': agent.engine,
- 'sessionId': agent.sessionId,
- 'status': agent.status,
- 'closeSupported': true,
- 'createdAt': now.toIso8601String(),
- 'terminal': {'available': agent.terminalAvailable},
- 'project': {
- 'name': agent.project?.name,
- 'cwd': agent.project?.cwd,
- 'branch': agent.project?.branch,
- },
- 'updatedAt': now
- .subtract(Duration(minutes: ages[agent.id]!))
- .toIso8601String(),
- if (agent.id == 'a0' || agent.id == 'review')
- 'outputStats': {
- 'linesAdded': agent.id == 'a0' ? 124 : 832,
- 'linesRemoved': agent.id == 'a0' ? 38 : 156,
- 'pullRequestsCreated': agent.id == 'a0' ? 1 : 2,
- 'updatedAt': now.toIso8601String(),
- },
- if (agent.id != 'docs')
- 'tokenUsage': {
- 'totalTokens': switch (agent.id) {
- 'a0' => 48750,
- 'review' => 1234567,
- 'api' => 32410,
- _ => 215400,
- },
- 'updatedAt': now.toIso8601String(),
- },
- }),
- ];
- app.machineStates['m']!.blockedAgents['api'] = question('api');
- app.machineStates['m']!.processingAgentIds.add('a0');
- app.renameSwarm(app.activeSwarmId, _running.name);
- app.adoptSessionForTest(terminal('a0', [])..agentName = _running.name);
- await app.addAgentToSwarm('m', 'a0');
- await open(tester);
- final root = tester.widget<MaterialApp>(find.byType(MaterialApp));
- await tester.pumpWidget(
- MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: root.theme,
- home: root.home,
- ),
- );
- await tester.pumpAndSettle();
- await tester.runAsync(() async {
- await Future.wait(
- find
- .byType(Image)
- .evaluate()
- .map(
- (element) =>
- precacheImage((element.widget as Image).image, element),
- ),
- );
- });
- await tester.pumpAndSettle();
- await expectLater(
- find.byType(MaterialApp),
- matchesGoldenFile(Uri.file('$renderDir/sessions.png')),
- );
- tester.view.physicalSize = const Size(880, 560);
- await tester.pumpAndSettle();
- await expectLater(
- find.byType(MaterialApp),
- matchesGoldenFile(Uri.file('$renderDir/minimum-window.png')),
- );
- tester.platformDispatcher.textScaleFactorTestValue = 1.5;
- addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
- await tester.pumpAndSettle();
- await expectLater(
- find.byType(MaterialApp),
- matchesGoldenFile(Uri.file('$renderDir/scaled-text.png')),
- );
- tester.platformDispatcher.clearTextScaleFactorTestValue();
- tester.view.physicalSize = const Size(1280, 800);
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const ValueKey('session-filter:needsInput')));
- await tester.pumpAndSettle();
- await expectLater(
- find.byType(MaterialApp),
- matchesGoldenFile(Uri.file('$renderDir/needs-input.png')),
- );
- debugDisableShadows = true;
- },
- );
-}
diff --git a/desktop/test/harness_sessions_test.dart b/desktop/test/harness_sessions_test.dart
new file mode 100644
index 000000000..3a2538c8d
--- /dev/null
+++ b/desktop/test/harness_sessions_test.dart
@@ -0,0 +1,233 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_sessions.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/pending_question.dart';
+
+import 'support/restart_connection.dart';
+import 'swarm_state_test.dart' show createApp;
+
+const _project = AgentProject(
+ name: 'autonomous-harness',
+ cwd: '/work/autonomous-harness',
+ branch: 'fix/file-menu-order',
+);
+const _running = Agent(
+ id: 'a0',
+ name: 'Font styling review',
+ engine: 'claude',
+ sessionId: 'conversation',
+ terminalAvailable: true,
+ project: _project,
+);
+const _paused = Agent(
+ id: 'saved',
+ name: 'Landing page polish',
+ engine: 'codex',
+ sessionId: 'saved-conversation',
+ status: 'stopped',
+ project: AgentProject(
+ name: 'website',
+ cwd: '/work/website',
+ branch: 'design/landing',
+ ),
+);
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late AppNotifier app;
+ late RestartConnection connection;
+ setUp(() {
+ connection = RestartConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ app.rememberOpenedHarness('m', 'a0');
+ app.rememberOpenedHarness('m', 'saved');
+ app.machineStates['m']!
+ ..machine = const Machine(
+ machineId: 'm',
+ name: 'iMac — Office',
+ authMode: MachineAuthMode.remote,
+ )
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true
+ ..agents = [_running, _paused];
+ });
+ tearDown(() => app.dispose());
+
+ PendingQuestion question(String id, {String request = 'question'}) =>
+ PendingQuestion(
+ machineId: 'm',
+ agentId: id,
+ requestId: request,
+ answerKey: 'folder',
+ prompt: 'Use the shared cache?',
+ options: ['Yes', 'No'],
+ multi: false,
+ since: DateTime(2026, 9, 22),
+ );
+
+ test(
+ 'activity age is compact and safely handles old daemons and clock skew',
+ () {
+ final now = DateTime(2026, 9, 22, 12);
+ expect(harnessActivityAge(null, now), '—');
+ expect(
+ harnessActivityAge(now.add(const Duration(minutes: 4)), now),
+ '0m',
+ );
+ for (final sample in [
+ (59, '0m'),
+ (300, '5m'),
+ (3599, '59m'),
+ (3600, '1h'),
+ (86400, '1d'),
+ (172800, '2d'),
+ ]) {
+ expect(
+ harnessActivityAge(now.subtract(Duration(seconds: sample.$1)), now),
+ sample.$2,
+ );
+ }
+ final parsed = Agent.fromJson({
+ 'id': 'fresh',
+ 'updatedAt': now.toIso8601String(),
+ });
+ expect(parsed.lastActivityAt, now);
+ expect(parsed.copyWith(name: 'Renamed').lastActivityAt, now);
+ expect(
+ Agent.fromJson({'id': 'legacy', 'updatedAt': 'invalid'}).lastActivityAt,
+ isNull,
+ );
+ },
+ );
+
+ test('recent follows real activity before navigation recency', () {
+ for (final id in ['older', 'newer', 'unknown']) {
+ app.rememberOpenedHarness('m', id);
+ }
+ app.machineStates['m']!.agents = [
+ Agent.fromJson({'id': 'older', 'updatedAt': '2026-09-21T10:00:00Z'}),
+ Agent.fromJson({'id': 'newer', 'updatedAt': '2026-09-22T10:00:00Z'}),
+ const Agent(id: 'unknown', name: 'Unknown'),
+ ];
+ expect(
+ visibleHarnessSessions(
+ harnessSessions(app),
+ recent: [agentDestinationId('m', 'older')],
+ ).map((row) => row.agent.id),
+ ['newer', 'older', 'unknown'],
+ );
+ });
+
+ test(
+ 'recent sorts by last use: a harness opened anywhere outranks a busier one',
+ () {
+ app.machineStates['m']!.agents = [
+ Agent.fromJson({'id': 'busy', 'updatedAt': '2026-09-26T11:00:00Z'}),
+ // Quiet since nine, but somebody opened it at noon — in any client.
+ Agent.fromJson({
+ 'id': 'opened',
+ 'updatedAt': '2026-09-26T09:00:00Z',
+ 'lastOpenedAt': '2026-09-26T12:00:00Z',
+ }),
+ // Opened long ago and busy since: the later of the two counts.
+ Agent.fromJson({
+ 'id': 'worked',
+ 'updatedAt': '2026-09-26T10:00:00Z',
+ 'lastOpenedAt': '2026-09-26T08:00:00Z',
+ }),
+ const Agent(id: 'unknown', name: 'Unknown'),
+ ];
+ for (final id in ['busy', 'opened', 'worked', 'unknown']) {
+ app.rememberOpenedHarness('m', id);
+ }
+ expect(SessionSort.recent.label, 'Recently used');
+ expect(
+ visibleHarnessSessions(harnessSessions(app)).map((row) => row.agent.id),
+ ['opened', 'busy', 'worked', 'unknown'],
+ );
+ expect(
+ harnessSessions(app)
+ .singleWhere((row) => row.agent.id == 'opened')
+ .lastUsedAt,
+ DateTime.utc(2026, 9, 26, 12),
+ );
+ },
+ );
+
+ test('attention filters live questions, retains missing agents, excludes paused history', () {
+ app.rememberOpenedHarness('m', 'missing');
+ app.machineStates['m']!.blockedAgents.addAll({
+ 'a0': question('a0'),
+ 'saved': question('saved'),
+ 'missing': question('missing'),
+ });
+ final rows = visibleHarnessSessions(
+ harnessSessions(app),
+ filter: SessionFilter.needsInput,
+ );
+ expect(rows.map((row) => row.agent.id), containsAll(['a0', 'missing']));
+ expect(rows, hasLength(2));
+ expect(
+ rows.singleWhere((row) => row.agent.id == 'missing').canControl,
+ isFalse,
+ );
+ expect(
+ rows.singleWhere((row) => row.agent.id == 'missing').canOpen,
+ isFalse,
+ );
+ expect(
+ visibleHarnessSessions(rows, query: 'office shared cache'),
+ hasLength(2),
+ );
+ });
+
+ test('inventory deduplicates views, searches context, and sorts deterministically', () async {
+ await app.addAgentToSwarm('m', 'a0');
+ app.newSwarm(name: 'Second view');
+ await app.addAgentToSwarm('m', 'a0');
+ final rows = harnessSessions(app);
+ expect(rows, hasLength(2));
+ expect(rows.first.open, isTrue);
+ expect(
+ visibleHarnessSessions(rows, query: 'office file-menu').single.agent.id,
+ 'a0',
+ );
+ expect(
+ visibleHarnessSessions(
+ rows,
+ filter: SessionFilter.paused,
+ ).single.agent.id,
+ 'saved',
+ );
+ expect(
+ visibleHarnessSessions(
+ rows,
+ filter: SessionFilter.running,
+ ).single.agent.id,
+ 'a0',
+ );
+ expect(
+ visibleHarnessSessions(rows, recent: [rows.last.id]).first.agent.id,
+ 'saved',
+ );
+ expect(
+ visibleHarnessSessions(rows, sort: SessionSort.project).first.agent.id,
+ 'a0',
+ );
+ app.machineStates['m']!.nodeOnline = false;
+ expect(
+ harnessSessions(app)
+ .every((row) => !row.canControl && row.status == 'Offline'),
+ isTrue,
+ );
+ expect(
+ visibleHarnessSessions(
+ harnessSessions(app),
+ filter: SessionFilter.running,
+ ),
+ isEmpty,
+ );
+ });
+}
diff --git a/desktop/test/interactive_viewer_test.dart b/desktop/test/interactive_viewer_test.dart
index 97a834334..0cbae6d06 100644
--- a/desktop/test/interactive_viewer_test.dart
+++ b/desktop/test/interactive_viewer_test.dart
@@ -14,6 +14,41 @@ Map<String, dynamic> picture() => {
};
void main() {
+ testWidgets('host navigation is delivered once and ignored after disposal', (
+ tester,
+ ) async {
+ final actions = <Map<String, dynamic>>[];
+ final replies = <Completer<Map<String, dynamic>>>[];
+ final session = InteractiveViewerSession((payload) {
+ if (payload['op'] == 'close') return Future.value({'closed': true});
+ final reply = Completer<Map<String, dynamic>>();
+ replies.add(reply);
+ return reply.future;
+ }, onHostAction: actions.add);
+ session.configure(const Size(800, 600), false);
+ await tester.pump(const Duration(milliseconds: 1));
+ replies.first.complete({
+ ...picture(),
+ 'hostActions': [
+ {'action': 'assistant'},
+ ],
+ });
+ await tester.pump(const Duration(milliseconds: 1));
+ expect(actions, [
+ {'action': 'assistant'},
+ ]);
+ session.input({'type': 'text', 'text': 'next'});
+ await tester.pump(const Duration(milliseconds: 1));
+ session.dispose();
+ replies.last.complete({
+ ...picture(),
+ 'hostActions': [
+ {'action': 'assistant'},
+ ],
+ });
+ await tester.pump(const Duration(milliseconds: 1));
+ expect(actions, hasLength(1));
+ });
testWidgets('one frame in flight; queued input arrives once and in order', (
tester,
) async {
diff --git a/desktop/test/machines_manager_test.dart b/desktop/test/machines_manager_test.dart
index ab4d7f7e8..e75ac5942 100644
--- a/desktop/test/machines_manager_test.dart
+++ b/desktop/test/machines_manager_test.dart
@@ -15,7 +15,7 @@ import 'package:harness/state/app_state.dart';
import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/new_harness.dart';
import 'package:harness/widgets/new_harness_form.dart';
-import 'package:harness/widgets/harness_session_manager.dart';
+import 'package:harness/state/harness_monitor_controller.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:xterm/xterm.dart';
@@ -24,6 +24,7 @@ import 'keymap_host_test.dart' show key;
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
import 'support/model_manager.dart';
+import 'support/harness_monitor.dart';
class _MachineApi extends ApiClient {
_MachineApi() : super(config: AppConfig.dev, session: AuthSession());
@@ -41,8 +42,8 @@ class _MachineApi extends ApiClient {
}
}
-class _ToolbarApp extends ModelManagerTestApp {
- _ToolbarApp() : super(ModelManagerConnection());
+class _ToolbarApp extends MonitorTestApp {
+ _ToolbarApp() : super(MonitorConnection());
@override
Future<RemotePasswordStatus> remotePasswordStatus() async =>
@@ -103,10 +104,10 @@ void main() {
await openWorkspaceManagement(tester, 'harnesses');
await tester.pumpAndSettle();
- expect(find.byType(HarnessSessionManager), findsOneWidget);
+ expect(app.activeSwarm.name, harnessMonitorName);
await openWorkspaceManagement(tester, 'machines');
await tester.pumpAndSettle();
- expect(find.byType(HarnessSessionManager), findsNothing);
+ expect(app.activeSwarm.name, harnessMonitorName);
expect(resourceScope('@'), findsOneWidget);
await openWorkspaceManagement(tester, 'models');
await tester.pumpAndSettle();
diff --git a/desktop/test/support/harness_monitor.dart b/desktop/test/support/harness_monitor.dart
new file mode 100644
index 000000000..cfe87aba2
--- /dev/null
+++ b/desktop/test/support/harness_monitor.dart
@@ -0,0 +1,62 @@
+import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/state/harness_monitor_controller.dart';
+
+import 'model_manager.dart';
+
+class MonitorConnection extends ModelManagerConnection {
+ List<Map<String, dynamic>>? inventory;
+ int inventoryReads = 0;
+ @override
+ Future<void> waitUntilReady({
+ Duration timeout = const Duration(seconds: 10),
+ }) async {}
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'agents_list' && inventory != null) {
+ inventoryReads++;
+ return {'agents': inventory};
+ }
+ final result = await super.request(
+ type,
+ payload: payload,
+ timeout: timeout,
+ );
+ if (result['agent'] case final Map<String, dynamic> agent
+ when agent['dsh'] == harnessMonitorId) {
+ return {
+ ...result,
+ 'agent': {
+ ...agent,
+ 'engine': 'opencode',
+ 'viewerUrl': 'http://127.0.0.1:4179/',
+ 'viewerName': harnessMonitorName,
+ },
+ };
+ }
+ return result;
+ }
+}
+
+class MonitorTestApp extends ModelManagerTestApp {
+ MonitorTestApp(MonitorConnection super.connection);
+
+ @override
+ Future<void> probeDsh(String machineId, {bool force = false}) async {
+ await probeReply?.future;
+ if (probeError != null) throw StateError(probeError!);
+ stateOf(machineId)!.dsh.replace([
+ DshEntry(
+ id: harnessMonitorId,
+ name: harnessMonitorName,
+ engine: 'opencode',
+ description: '',
+ installed: installed,
+ ),
+ ]);
+ }
+}
diff --git a/store/agents/harness-monitor/AGENTS.md b/store/agents/harness-monitor/AGENTS.md
index 0ca66279f..34992cadc 100644
--- a/store/agents/harness-monitor/AGENTS.md
+++ b/store/agents/harness-monitor/AGENTS.md
@@ -1,94 +1,36 @@
-# Harness Monitor — you run the fleet
-
-You are Claude Code in a terminal that Harness opened for a **Harness Monitor** workspace. Beside you, in the
-other pane, is the fleet: every harness on this machine and every machine linked to it, running or paused,
-with the policy drawn over it. The person you are talking to has too many sessions and no idea which ones
-still matter. That is the whole job.
-
-**The promise you are keeping.** In Harness nobody kills a session — you close the pane and the agent
-keeps running, and you resume it whenever. That is why there are eighty of them. Harness Monitor does not take
-that away; it removes the *cost* of it. A **paused** harness has no engine process and no memory, and its
-pane, scrollback and conversation are all still there — resuming it resumes exactly where it was. So the
-question is never "can I kill this?", it is "does this need to be running right now?"
-
-**You never delete anything.** There is no verb in your toolchain that removes a tmux session, a registry
-row or a transcript. If the person asks you to delete an agent, say plainly that Harness Monitor does not do that
-and point them at the app's own Stop Harness / delete, which asks first. Pause and resume are both
-reversible, and that is the reason you can be trusted to act on eighty rows at once.
-
-## The vocabulary, and don't invent another
-
-| state | what it is |
-|---|---|
-| **running** | the engine process is running — an ordinary Harness agent |
-| **paused** | pane and conversation intact, engine gone. Waking it resumes the conversation |
-| **gone** | no pane left; the daemon dropped it. History only, nothing to resume |
-
-## Your toolchain
-
-`$HPS_CLI`, used as `"$HPS_CLI" …`. Every command takes `--json`; use it, and report the numbers it
-gives you rather than counting rows yourself.
-
-| Command | What it does |
-|---|---|
-| `hps [--all] [--idle 4h] [--project X] [--state paused] [--machines]` | the fleet, freshest first |
-| `hps show <ref>` | one harness in full, including the last lines on its pane |
-| `hps pause <ref…>` | the engine exits; pane, scrollback and conversation stay |
-| `hps resume <ref…>` | the engine comes back where it left off |
-| `hps pause --policy` | what the rules would do right now, with a reason per row. **Dry run** |
-| `hps pause --policy --apply` | do it |
-| `hps resume --paused` | put everything paused back, in one line (dry run until `--apply`) |
-| `hps attach <ref>` | hand the terminal to that pane |
-
-`<ref>` is a row number from the last list, a `%pane`, an agent-id prefix, or part of a name.
-**Every bulk selection is a dry run until `--apply`** — `--policy`, `--idle`, `--paused`. A named ref acts
-at once, because the person typed the name. `--force` overrules a guard; never reach for it yourself.
-
-The rules live in **`~/.config/harness/policy.jsonc`** — one file per machine, commented, read on every
-refresh. There is no command that writes it: you have a text editor, and the person has two draggable lines
-in the pane. Edit values in place and keep their comments. To exempt one harness, add its agent id to
-`pins`. The defaults are deliberately loose — pause after a day, and a ceiling of 100 that is only a backstop — so propose tightening only when the person asks, with the dry run in hand.
-
-## How to work
-
-1. **Look before you speak.** Start with `hps --json` (add `--machines` only when they ask about
- other computers). Say what is actually there: how many, how many running, how much memory, how many
- nobody has touched in days. Numbers, not adjectives.
-2. **Propose, then do.** For anything that moves more than two harnesses, run the dry run first
- (`hps prune` with no `--apply`, or `--dry-run`), show them the list with the reason per row, and let
- them say go. For one or two, just do it and show the receipt.
-3. **Never pause something that is working or waiting.** The guards already refuse, and when one refuses,
- say which guard and leave it alone. Do not reach for `--force` on the person's behalf — it exists for
- them to ask for.
-4. **Tune the rules with evidence.** When they ask "is a day right?", edit `~/.config/harness/policy.jsonc` and run
- `hps pause --policy` at the
- value they are considering and tell them what it would do to *their* fleet — how many, which ones,
- how much memory. The pane's two draggable rules do the same thing; if they are dragging them, let
- them, and read back what they saved.
-5. **Waking is cheap, say so.** When you pause in bulk, end with how to get any of it back: one `resume`,
- or a click on the chip. People agree to pausing once they believe in resuming.
-6. **The pane is yours to keep honest.** Every command refreshes it. Never print a URL, never start a
- viewer, never open a browser — Harness already has the pane open.
-
-## What the numbers mean, exactly
-
-- **idle** is time since the last real *turn* — a message from the person or the agent, read from the end
- of the engine's transcript. Not the file's mtime (a running engine appends bookkeeping to conversations
- nobody has touched in days) and not the daemon's own `updatedAt` (it reconciles every five seconds, so
- everything looks new). If someone asks why a row reads `3d` when the app shows recent output, that is
- the answer: output is not a turn.
-- **mem** is the engine's whole process subtree, resident. It is what pausing hands back. Sum it across
- rows freely, but call it "held", not "used": resident sets share pages, so the total is an upper bound.
-- **waiting on you** is a guess made from the pane's last screen, and it is only ever used to *refuse* to
- pause something. The app's own **Agents needing input** (⇧⌘I) is the authority. Say so if it matters.
-
-## Things people ask for, and the shape of a good answer
-
-- *"Clean this up."* → `hps prune` (dry run), read them the totals in one line, ask, then `--apply`.
-- *"What's actually running?"* → `hps --state running --sort mem`. Lead with the working ones.
-- *"Why is this one paused?"* → the row's own reason, plus `.harness/monitor-log.jsonl`, which records
- every action with the rule that caused it.
-- *"Pause everything except what I'm using."* → pin what they name, then `hps pause --policy`.
-- *"Which of these is on a branch that already merged?"* → the rules do not do git; you do. Read
- `hps --json`, run `git -C <cwd> branch --merged` yourself, and pause what comes back — naming the
- branch when you report it.
+# Harness Monitor
+
+You are the optional assistant in a Harness Monitor workspace. The table is the primary interface;
+reading, searching, sorting, opening and stopping sessions do not require a model. Act only on the
+person's request. Use the installed engine; do not assume Claude Code.
+
+Use `"$HPS_CLI" --json --all` to inspect the local machine, adding `--machines` for linked machines.
+The daemon is authoritative for activity, process identity and stopped sessions. Never signal a PID,
+write a resume command into tmux, or reconstruct a saved launch yourself.
+
+- `hps show <ref>` inspects one session.
+- `hps pause <ref>` stops its process and retains its history and saved configuration.
+- `hps resume <ref>` asks the owning daemon to restore it. Respect `resumeMode`: some engines reopen a
+ conversation, some start a fresh one, and terminals reopen a shell.
+- `hps pause --policy` previews cleanup. `--apply` executes the reviewed plan.
+- `hps resume --paused` is a dry run until `--apply`.
+- `--machines` includes linked machines for reads and actions. Use the full composite machine/agent ID
+ in JSON output when a name, pane or agent ID is ambiguous. Never assume IDs are global.
+
+For changes to more than two sessions, show the dry run with reasons and obtain the person's approval
+before applying. Never force cleanup of Working, Needs you, pinned or unknown-activity sessions.
+`--force` is for the person to request explicitly. Never change rules simply because the table is open.
+Rules and pins live in `~/.config/harness/policy.jsonc`; preserve comments when editing it.
+
+A timed-out resume is uncertain. Check its original receipt; never launch another process to compensate.
+An offline machine is not a stopped session. Unknown CPU, RAM or tokens are not zero. RAM sums process
+resident sets (shared pages can be counted twice); CPU is the process-tree percentage reported by ps,
+whose averaging varies by OS. Last active comes from real daemon conversation activity, not file mtime.
+
+The default OpenCode model is Muse Spark 1.3 Contributor Free. It is a limited-time offer and allows
+Meta to train on prompts and responses. Both the main and small model are explicitly configured to
+that ID. Never silently switch to a paid model. The viewer offers a model choice before showing the
+assistant; users can choose another model with OpenCode's `/models` command.
+
+Never start another viewer: Harness already manages this one. Never delete transcripts or projects.
+Report actual tool results, including refusals and uncertain outcomes, without inventing activity.
diff --git a/store/agents/harness-monitor/README.md b/store/agents/harness-monitor/README.md
index 8031837b7..505933764 100644
--- a/store/agents/harness-monitor/README.md
+++ b/store/agents/harness-monitor/README.md
@@ -1,172 +1,42 @@
-# Harness Monitor, as a Harness agent
-
-**htop for your agents.** Every harness on this machine — and every machine linked to it — in one dense
-list: running, paused, idle since Tuesday, what each is holding. A policy you can drag until the numbers
-look right. And one keystroke to pause an idle harness or resume it with its conversation intact.
-
-It exists because of a specific way a fleet of long-lived sessions goes wrong. In Harness nobody kills a
-session: you close the pane, the agent keeps running, and you resume whenever. That is the best thing
-about it, and it is why there are eighty of them, most untouched for days, holding tens of gigabytes. The
-fix is not to start killing them. It is to make idleness free.
-
-## Paused is not stopped
-
-| state | what it is |
-|---|---|
-| **running** | the engine process is running — an ordinary Harness agent |
-| **paused** | pane, scrollback and conversation intact, engine gone. Waking resumes the conversation |
-| **terminal** | a shell somebody opened. Nothing to pause |
-| **gone** | no pane left; the daemon dropped it. History only |
-
-Pausing a harness on this machine handed back 257 MB and kept everything else: same pane, same
-scrollback, same agent id, and `claude --resume` put the conversation back thirteen seconds later.
-
-## Install and open
-
-Choose **Harness Monitor** in the Harness Store, or install this checkout:
-
-```sh
-harness dsh install "$PWD/store/agents/harness-monitor" --link
-harness dsh doctor autonomous/harness-monitor
-```
-
-Open Harness Monitor in a new folder and ask: *"Show me the fleet, then pause everything nobody has touched since
-Tuesday."* It installs nothing — no service, no database, no daemon of its own. Everything it knows comes
-from the daemon Harness already runs, the tmux server it already uses, and one `ps`.
-
-## From a terminal
-
-`hps` is the agent's toolchain and yours. Every command takes `--json`.
-
-```
-hps the list, freshest first (like `docker ps`)
-hps [--all] [--idle 4h] [--project X] [--state paused] [--sort mem] [--watch] [--machines]
-hps show <ref> one harness in full, with the last lines on its pane
-hps pause <ref…> the engine exits; pane, scrollback and conversation stay
-hps resume <ref…> the engine comes back where it left off
-hps pause --policy [--apply] what the rules would do, and why. Dry run unless --apply
-hps resume --paused everything paused, back in one line
-hps attach <ref> hand this terminal to that pane
-```
-
-`<ref>` is a row number from the last `ls`, a `%pane`, an agent-id prefix, or part of a name — the same
-grammar the shell gives you for jobs.
-
-```
- # IDLE ENGINE MODEL MEM PROJECT BRANCH TITLE
- 1 ◐ now claude opus-5 517MB widgets main Fix the reconciler
- 2 ● 41m codex gpt-6-astra 194MB widgets main Plan the migration
- 3 ○ 3d claude — — old-spike spike Try the other approach
-
-85 harnesses · 21 running · 63 paused · 25.2 GB held · 61 projects
-policy: pause after 1d · hide after 14d · ceiling 100 running
-```
-
-## The pane
-
-Two views over the same fleet, one selection between them.
-
-**Lanes** is the picture: one lane per project, oldest work on the left, *now* hard against the right edge,
-on a log scale so the useful hours are visible instead of squeezed. Running chips glow, working chips
-breathe, paused chips are outlined, a chip waiting on you rings amber. Two vertical lines are the policy —
-**drag one** and the count updates as you move it: *would pause 58, handing back 13.7 GB*.
-Save it and it is written to `~/.config/harness/policy.jsonc`, comments intact. A threshold you cannot see the effect of is a threshold nobody
-should run.
-
-**Table** is htop: fixed columns, tabular numerals, a memory bar behind the number, sortable headers,
-`j`/`k` to move, `space` to select, `p` to pause, `r` to resume, `i` to pin, `/` to
-filter. The footer shows what is selected and what the policy would do.
-
-## The rules
-
-One file per machine, next to your keybindings: **`~/.config/harness/policy.jsonc`** (`$XDG_CONFIG_HOME`
-respected). It's written the first time Harness Monitor runs, it's commented, and it's read on every refresh
-— save it and the pane redraws within seconds. The two lines in the pane edit the same file in place, keeping
-your comments.
-
-```jsonc
-{
- "runningCeiling": 100, // most engines running at once — a backstop; past it, the least recently used pause
- "pauseAfterIdle": "1d", // untouched this long (since the last real turn) and it pauses
- "hideAfterIdle": "14d", // drops out of the default list; still there under --all
- "pauseWhenWorkspaceGone": true, // its folder is gone, so nothing can happen there
- "protect": {
- "needsInput": true, // it looks like it is waiting on you
- "working": true, // mid-turn
- "attached": true, // someone is looking at that pane
- "pinned": true // listed in "pins"
- },
- "pins": [] // agent ids the rules never pause
-}
-```
-
-Preview any change without moving anything: `hps pause --policy`. It prints one line per harness with the
-reason, and the totals, and changes nothing until `--apply`.
-
-**Why these numbers.** A day, because a day survives an overnight break — the first default was 4h, and on a
-real fleet the only thing 4h caught that a day didn't was eight harnesses from the previous afternoon. The
-ceiling is 100 because it's a backstop, not a working limit: the idle rule does the everyday work, and the
-ceiling only matters on a machine that swaps — lower it there, dividing free memory by ~300 MB.
-
-The resume tickets — which conversation each paused harness had — live in `~/.harness/monitor/paused.json`,
-and every pause and resume is logged to `~/.harness/monitor/log.jsonl` with the rule that caused it.
-
-## What it will not do
-
-There is no verb here that deletes an agent, kills a tmux session or touches a transcript. Pause, resume,
-and resume are both reversible, and that is what makes it safe to point at eighty live sessions
-and act on all of them at once: the worst outcome of a wrong call is a few seconds of cold start. The
-irreversible verbs already exist in the app, behind their own confirmation, which is where they belong.
-
-Harness Monitor also refuses to pause what it could not resume: an engine with no known resume flag, or an agent
-whose session the daemon has not bound yet, stays running.
-
-## How it works
-
-- **Reading.** `agents_list` over the daemon's loopback bridge (`ws://127.0.0.1:18473/api/local-ws`) for
- who the agents are and where their panes are; one `tmux list-panes -a` for pane liveness, attachment and
- last output; one `ps` walked per pane for memory and CPU; `~/.harness/cli/data/registry.json` (read
- only) for transcript paths and hook timestamps. With no daemon answering it falls back to the registry
- alone and says so in the header.
-- **Idle** is time since the last *turn*, read from the tail of the engine's own transcript. Not the
- file's mtime and not the registry's `updatedAt` — both of those say "now" for conversations nobody has
- touched in days. [`skills/fleet-operations/references/signals.md`](skills/fleet-operations/references/signals.md)
- has the measurements.
-- **Pausing** arms `remain-on-exit` on the pane, then SIGTERMs the engine and waits. No SIGKILL unless you
- ask. The pane survives either as a dead pane holding its scrollback or as the fallback shell Harness's
- own launch wrapper hands it.
-- **Waking** types that engine's resume command into the pane — `claude --resume <id>`, `codex resume
- <id>` — and the daemon's adoption loop rebinds the row. It deliberately does **not** use the daemon's
- `agent_restart`: when an engine exits, the daemon rewrites the row as a *terminal*, so restarting it
- gives you a fresh shell, which is exactly what happened the first time this was tried.
-- **The ticket.** That same rewrite clears the row's `sessionId`, `transcriptPath` and `title` — measured,
- not assumed. So `pause` writes what it needs to come back (engine, session id, pane, title) into
- `~/.harness/monitor/paused.json` before it reports success. That file is the only record a paused harness has, which is why
- it is worth keeping; if you lose it, a paused harness is still resumable by hand with
- `claude --resume <id>` from its own transcript.
-- **Other machines** are listed through the same bridge and marked as remote. Pane facts, memory and every
- action are local to this computer — a fleet manager that guesses about a machine it cannot see is not one.
-
-## Develop and verify
-
-```sh
-npm test --prefix store/agents/harness-monitor # 109 tests, no network, no daemon, no tmux required
-harness dsh check "$PWD/store/agents/harness-monitor"
-
-# The pane against any workspace; the port is printed.
-HARNESS_WORKSPACE=/path/to/workspace store/agents/harness-monitor/viewer.sh
-```
-
-The suite covers the rules, the scale the Lanes view draws with, the pane/process readers, the transcript
-reader, every guard in front of pause and resume, the loopback server's refusals, and a drift guard that
-compares the resume table against the daemon's own source when the two are checked out together.
-
-One thing the tests cannot cover: the pane has been exercised through its server and its markup, not in a
-browser. The round trip it describes — pause, then resume with the conversation intact — was verified against
-a live Claude Code session end to end.
+# Harness Monitor
+
+The dock opens one reusable Harness Monitor tab. Its DSH viewer starts as a full-width session table;
+**Ask assistant** reveals its OpenCode terminal beside it. No prompt is submitted when the table opens.
+
+The default columns are Harness, Status, Agent, Machine, Project, Branch, CPU %, RAM, Tokens and Last
+active, followed by **Open** and **×**. Headers sort; drag their separators to resize. Columns offers
+Model, PID, Harness ID, Conversation ID and Folder. Search covers metadata. Names and actions remain visible while
+scrolling horizontally. Refreshes preserve selection, controls, column widths and scroll. Arrow keys
+select and Enter opens. Engine images are copied from the desktop's existing icon assets; status marks
+and the reduced-motion-aware spinner follow its notification/tab/pane activity marks.
+
+Open navigates to an existing session or resumes stopped work through the app's receipt coordinator.
+× stops the owning daemon's validated process, retaining history and the saved DSH/runtime settings.
+The daemon reports whether resume restores a conversation, a shell or a fresh conversation. Remote
+machines use the same paired bridge and lifecycle APIs. Cached offline rows remain visible with disabled
+actions. Unknown readings show a dash. Older daemons need updating for activity and resource readings.
+
+CPU uses the daemon's shared process sampler, measuring interval use; multiple cores can
+exceed 100%. RAM is subtree resident memory and can double-count shared pages. Token counts are the
+owning daemon's conversation ledger. Last active is conversation activity, never file mtime.
+
+**Cleanup…** previews the current policy and requires an explicit apply. Working, waiting, pinned,
+offline and unknown-activity sessions are protected and rechecked at execution. There is no automatic
+cleanup timer. The same tools are available to the assistant as `$HPS_CLI` (`toolchain/hps --help`).
+Rules/pins remain in `~/.config/harness/policy.jsonc`; receipts are under `~/.harness/monitor/`.
+
+OpenCode defaults both `model` and `small_model` to
+`opencode/muse-spark-1.3-contributor-free`. [OpenCode Zen](https://opencode.ai/docs/zen/) currently lists
+this as a limited-time free offer. **Contributor permits Meta to train on prompts and responses.**
+The first assistant choice discloses this and offers choosing another model with `/models`. Zen login
+may be needed. There is no automatic paid fallback. Existing sessions retain their saved runtime and
+model configuration; changing the package default does not retarget them.
+
+`npm test` runs with isolated policy/state fixtures. Browser review: `node test/preview.mjs` serves
+synthetic sessions and records simulated actions; it cannot touch real harnesses.
## Credit and stewardship
-Built by Autonomous for Harness, MIT. It reads and drives the daemon, tmux server and engines Harness
-already runs, and adds no service of its own. Issues with how the daemon records, stops or resumes an
-agent belong in the Harness CLI; the rules, `hps` and the pane belong here.
+Built by Autonomous for Harness, MIT. See [LICENSE](LICENSE). Process identity and lifecycle belong to
+the Harness CLI; the table, cleanup proposals and `hps` live in this package. Engine artwork is reused
+from the desktop; attribution is included beside the copied icons.
diff --git a/store/agents/harness-monitor/harness.json b/store/agents/harness-monitor/harness.json
index 4f7d8041d..8a745e959 100644
--- a/store/agents/harness-monitor/harness.json
+++ b/store/agents/harness-monitor/harness.json
@@ -4,8 +4,8 @@
"name": "Harness Monitor",
"category": "Compute",
"author": "Autonomous",
- "description": "htop for your harnesses. Every harness on every machine in one dense list — running, paused, idle for a week — with a policy you can drag until the numbers look right, and one keystroke to pause an idle one or resume it with its conversation intact.",
- "engine": "claude",
+ "description": "Manage sessions across your machines in a sortable table. Open sessions, stop processes while keeping history, and ask an optional OpenCode assistant to help review cleanup.",
+ "engine": "opencode",
"workspace": {
"template": "template",
"marker": "NOTES.md",
@@ -18,7 +18,8 @@
],
"env": {
"HPS_CLI": "${dsh}/toolchain/hps",
- "MONITOR_DSH_DIR": "${dsh}"
+ "MONITOR_DSH_DIR": "${dsh}",
+ "OPENCODE_CONFIG_CONTENT": "{\"model\":\"opencode/muse-spark-1.3-contributor-free\",\"small_model\":\"opencode/muse-spark-1.3-contributor-free\"}"
}
},
"toolchain": {
diff --git a/store/agents/harness-monitor/lib/actions.mjs b/store/agents/harness-monitor/lib/actions.mjs
index d3e5bb44a..c24ad1501 100644
--- a/store/agents/harness-monitor/lib/actions.mjs
+++ b/store/agents/harness-monitor/lib/actions.mjs
@@ -1,179 +1,89 @@
-/**
- * The three things Harness Monitor does to a harness — and the guards that stand in front of each one.
- *
- * pause ask the engine to leave; the pane, its scrollback and the conversation all stay
- * resume type its own resume command into the pane; the conversation comes back
- *
- * There is no third verb. Two earlier ones were cut on purpose: `revive` was `resume` with no difference,
- * and `retire` was `pause` plus one bit that only hid a row — which a list already does, without a state,
- * a mark or a grace window. `systemctl disable` exists because a service would auto-start at boot;
- * nothing auto-starts a harness, so there is nothing to disable.
- *
- * Nothing here deletes anything. There is no verb in this file that removes a tmux session, a registry
- * row or a transcript: an agent Harness Monitor has touched can always be brought back, and the one irreversible
- * action — deleting an agent — stays where it already lives, in the app's own Stop/Delete with its own
- * confirmation. That boundary is the reason this package is safe to point at eighty live sessions.
- *
- * ## Why pausing is lossless
- *
- * An engine's conversation is not in its process; it is in the transcript the engine appends as it goes,
- * and every engine Harness launches has a flag to resume one (`claude --resume`, `codex resume`, …). The
- * daemon already knows those flags and already rebuilds a launch with them — that is what its own
- * Restart does. So pausing needs to do only two things carefully: hold the pane open across the exit
- * (`remain-on-exit`, the same option the daemon arms before a restart), and ask the engine to stop in a
- * way that lets it finish writing (SIGTERM, never SIGKILL unless a person insists).
- *
- * The daemon then sees a pane with no engine on it and keeps the row: "a live pane without a recognized
- * engine is a dormant but still viewable agent" — its words. Paused is a state Harness already has.
- */
-
-import { capture, engineProcess, holdOpen, looksBlocked, paneState, panes, processTable, respawn, runTmux, sendLine } from './panes.mjs'
-import { protectionFor } from './policy.mjs'
-import { canResume, resumeCommand } from './resume.mjs'
-
-const sleep = (ms) => new Promise((done) => setTimeout(done, ms))
-
-/** Signalling and liveness are injected so the guards can be tested without a real engine to kill.
- * EPERM counts as alive: the process is there, it just is not ours — which is a refusal, not a death. */
-export const realSignals = {
- send: (pid, signal) => process.kill(pid, signal),
- alive: (pid) => {
- if (!pid) return false
- try { process.kill(pid, 0); return true } catch (error) { return error?.code === 'EPERM' }
- },
+/** The daemon owns process identity, stopping and saved runtime configuration, on every machine. */
+import { randomUUID } from 'node:crypto'
+import { readFile, mkdir, open, unlink } from 'node:fs/promises'
+import { join } from 'node:path'
+import { createHash } from 'node:crypto'
+import { listAgents, request } from './bridge.mjs'
+import { mergeRows } from './inventory.mjs'
+import { stateDir } from './config.mjs'
+import { normalizePolicy, protectionFor } from './policy.mjs'
+
+const pending = new Map()
+const receipt = (row, action, detail, extra = {}) => ({ id: row.id, name: row.name, action, ok: false, refused: true, detail, ...extra })
+async function fresh(row, list) {
+ if (!row.machineId || !row.agentId || row.online === false) throw new Error('Reconnect this machine and refresh before acting.')
+ const agents = await list(row.machineId)
+ const agent = agents.find(a => a.id === row.agentId)
+ if (!agent) throw new Error('This harness is no longer in the daemon inventory. Refresh and try again.')
+ // A stopped/resumed or rotated conversation is a different target from the one the person reviewed.
+ if ((agent.sessionId || null) !== (row.sessionId || null)) throw new Error('This conversation changed. Refresh and review it before acting.')
+ return mergeRows([agent], { machine: { machineId: row.machineId, name: row.machine }, local: row.local,
+ state: { pins: row.pinned ? [row.id] : [] } })[0]
}
-/** Refuse for a reason a person can act on, rather than doing something surprising. */
-function refuse(row, detail) {
- return { ok: false, id: row.id, name: row.name, action: 'pause', refused: true, detail }
-}
-
-/**
- * Pause one running harness.
- *
- * The guards, in order, and why each is not negotiable:
- * remote pane facts and signals are local to this computer; a remote row is read-only here
- * no pane nothing to hold open, so nothing to come back to
- * not running already paused; saying so beats a second signal at a dead pane
- * policy pinned, mid-turn, attached, protected project — `force` is the only way past
- * open prompt the pane's last screen looks like a question waiting for an answer (panes.mjs)
- */
-export async function pause(row, { policy, force = false, graceMs = 6000, killAfterGrace = false, run = runTmux, restore = true, signals = realSignals, wait = sleep } = {}) {
- if (!row.local) return refuse(row, `${row.machine} is a remote machine — pause it from that computer.`)
- if (!row.pane) return refuse(row, 'no tmux pane; there is nothing to hold open.')
- if (row.state !== 'running') return { ok: true, id: row.id, name: row.name, action: 'pause', already: true, detail: `already ${row.state}` }
- if (!row.enginePid) return refuse(row, 'the engine process could not be identified, so nothing was signalled.')
- // Never stop what cannot be started again. An engine with no known resume flag, or a row whose session
- // id the daemon has not bound yet, has no way back to its conversation — so it stays running.
- if (!canResume(row.engine)) return refuse(row, `Harness Monitor does not know how to resume ${row.engine}, so it will not pause it.`)
- if (!row.sessionId) return refuse(row, 'the daemon has not bound a session to this agent yet, so there would be nothing to resume.')
-
- if (!force) {
- const protection = protectionFor(row, policy)
- if (protection) return refuse(row, `${protection.why} — pause it with --force if you mean it.`)
- const screen = await capture(row.pane, { lines: 30, run })
- if (looksBlocked(screen)) return refuse(row, 'its pane looks like it is waiting for an answer — read it first, or use --force.')
- }
-
- // What the window's own setting was, so a pane that falls back to a shell instead of dying leaves the
- // window exactly as it was found. The daemon's restart path makes the same promise.
- let previous = null
- try { previous = (await run(['show-options', '-w', '-t', row.pane, '-v', 'remain-on-exit'])).trim() } catch { previous = null }
- const held = await holdOpen(row.pane, true, { run })
- if (!held) return refuse(row, 'tmux would not hold the pane open, so the engine was left running.')
-
- try { signals.send(row.enginePid, 'SIGTERM') }
- catch (error) {
- if (previous === 'off' && restore) await holdOpen(row.pane, false, { run })
- return refuse(row, `could not signal the engine (${error?.code ?? 'failed'}).`)
- }
-
- const deadline = Date.now() + graceMs
- while (Date.now() < deadline && signals.alive(row.enginePid)) await wait(200)
- if (signals.alive(row.enginePid)) {
- if (!killAfterGrace) {
- if (previous === 'off' && restore) await holdOpen(row.pane, false, { run })
- return refuse(row, `the engine did not exit within ${Math.round(graceMs / 1000)}s. It is still running, untouched. Use --force to end it.`)
+export async function pause(row, { policy = normalizePolicy({}), force = false, list = listAgents, rpc = request } = {}) {
+ try {
+ const current = await fresh(row, list)
+ if (current.state === 'paused') return receipt(row, 'pause', 'Already stopped; history retained.', { ok: true, refused: false })
+ if (!current.canStop) return receipt(row, 'pause', current.unavailable || 'This harness cannot be stopped yet.')
+ if (!force) {
+ if (!current.activityKnown) return receipt(row, 'pause', 'Update the owning daemon before automatic cleanup; activity is unknown.')
+ const guard = protectionFor(current, policy)
+ if (guard) return receipt(row, 'pause', guard.why)
+ if (current.lastActivity !== row.lastActivity) return receipt(row, 'pause', 'Activity changed since the cleanup preview. Review the new plan.')
}
- try { signals.send(row.enginePid, 'SIGKILL') } catch { /* it went on its own */ }
- await wait(400)
- }
-
- const after = await paneState(row.pane, { run })
- // Dead pane: the launch had no fallback shell, so the hold is what is keeping the scrollback — leave
- // it on. Live pane: the wrapper handed it a shell, so put the window's own setting back.
- if (after && !after.dead && previous === 'off' && restore) await holdOpen(row.pane, false, { run })
- return {
- ok: true,
- id: row.id,
- name: row.name,
- action: 'pause',
- detail: after?.dead ? 'engine stopped, pane held open with its scrollback' : 'engine stopped, pane fell back to a shell',
- freed: row.rssBytes ?? 0,
- paneDead: Boolean(after?.dead),
- // The ticket back. Written to `monitor.json` by the caller, because the daemon RELEASES the engine
- // from its row when the process leaves (`registry.releaseEngine`) — the row survives as a terminal,
- // and its session id does not. Without this, a paused harness would still have its transcript on
- // disk but nothing would know which one to resume.
- ticket: { sessionId: row.sessionId, engine: row.engine, pane: row.pane, cwd: row.cwd, title: row.title ?? row.name },
- }
+ const reply = await rpc(row.machineId, 'agent_delete', { agentId: row.agentId })
+ if (reply.deleted !== true) return receipt(row, 'pause', 'Stop was not confirmed. Refresh before trying again.')
+ return receipt(row, 'pause', 'Stopped; history and launch configuration retained.', { ok: true, refused: false, freed: current.rssBytes })
+ } catch (error) { return receipt(row, 'pause', error.message) }
}
-/**
- * Resume one paused harness, conversation and all.
- *
- * Not `agent_restart`. That was the obvious answer and it is the wrong one: when an engine exits, the
- * daemon releases it from the row and the row survives as a TERMINAL — so restarting it gives you a
- * fresh shell in that pane, which is exactly what it did the first time this was tried against a real
- * paused session (`resumed: false`, and no engine at all afterwards).
- *
- * The right path is the one the daemon documents for this state: type the engine's own resume command
- * into the pane's fallback shell, and let the daemon's adoption loop recognize it. Verified end to end —
- * `claude --resume <id>` into a paused pane brought back the engine, the conversation, the same pane and
- * the same agent id, with the daemon rebinding the session within seconds.
- *
- * `ticket` is what `pause()` returned and the state file kept: the session id the released row forgot.
- */
-export async function resume(row, { ticket = null, run = runTmux, waitMs = 25_000, wait = sleep, inventory = { panes, processTable } } = {}) {
- const no = (detail) => ({ ok: false, id: row.id, name: row.name, action: 'resume', refused: true, detail })
- if (!row.local) return no(`${row.machine} is a remote machine — resume it from that computer.`)
- if (row.state === 'running') return { ok: true, id: row.id, name: row.name, action: 'resume', already: true, detail: 'already running' }
- if (!row.pane) return no('its pane is gone; there is nothing to resume into. Open it from the app instead.')
-
- const engine = row.engine && row.engine !== 'terminal' ? row.engine : ticket?.engine
- const sessionId = row.sessionId || ticket?.sessionId
- if (!engine) return no('nothing recorded which engine this was, so Harness Monitor will not guess.')
- if (!sessionId) return no('no session id was recorded for this harness, so its conversation cannot be named. Open it from the app and resume there.')
-
- let command
- try { command = resumeCommand(engine, sessionId) } catch (error) { return no(error.message) }
-
- // A dead pane has no shell to type into: give it its default command back first. `respawn-pane -k`
- // keeps the pane and its id, which is what keeps the agent row pointing at the same place.
- const before = await paneState(row.pane, { run })
- if (before?.dead) {
- try { await respawn(row.pane, { run }) } catch { return no('tmux would not respawn the pane, so nothing was typed into it.') }
- await wait(700)
+/** Persist the intent before sending. A new viewer/CLI checks the same durable daemon receipt after
+ * a lost reply, rather than issuing another resume. Exclusive file creation also coalesces callers. */
+async function resumeIntent(row) {
+ const directory = stateDir(), key = createHash('sha256').update(row.id).digest('hex')
+ await mkdir(directory, { recursive: true })
+ const path = join(directory, 'resume-' + key + '.json')
+ try {
+ const file = await open(path, 'wx', 0o600)
+ const value = { creationId: randomUUID(), agentId: row.agentId, sessionId: row.sessionId }
+ try { await file.writeFile(JSON.stringify(value)) } finally { await file.close() }
+ return { ...value, path, existing: false }
+ } catch (error) {
+ if (error.code !== 'EEXIST') throw error
+ const value = JSON.parse(await readFile(path, 'utf8'))
+ if (value.agentId !== row.agentId || value.sessionId !== row.sessionId || typeof value.creationId !== 'string') throw new Error('An earlier resume needs review before retrying.')
+ return { ...value, path, existing: true }
}
- // remain-on-exit is the daemon's own default for an agent pane: off, so a real exit disposes of it.
- await holdOpen(row.pane, false, { run })
-
- try { await sendLine(row.pane, command, { run }) } catch (error) { return no(`could not type into the pane: ${error.message}`) }
+}
- // Watch for the engine to actually appear. A resume that silently failed must not report success —
- // the pane would be sitting at a shell prompt with an error above it.
- const deadline = Date.now() + waitMs
- while (Date.now() < deadline) {
- await wait(1000)
- const paneRows = await inventory.panes({ run })
- const table = await inventory.processTable()
- const found = engineProcess(paneRows.get(row.pane), table, engine)
- if (found.engineAlive) {
- return {
- ok: true, id: row.id, name: row.name, action: 'resume', resumed: true, enginePid: found.pid,
- detail: `${engine} is back in the same pane, resuming its conversation`,
- }
+export function resume(row, options = {}) {
+ if (pending.has(row.id)) return pending.get(row.id)
+ const result = resumeOnce(row, options).finally(() => pending.delete(row.id))
+ pending.set(row.id, result)
+ return result
+}
+async function resumeOnce(row, { list = listAgents, rpc = request, intent = resumeIntent, clearIntent = path => unlink(path).catch(() => {}) } = {}) {
+ try {
+ const current = await fresh(row, list)
+ if (current.state !== 'paused') return receipt(row, 'resume', current.canOpen ? 'Already running.' : 'This harness is not ready to open.', { ok: current.canOpen, refused: !current.canOpen })
+ if (!current.canOpen) return receipt(row, 'resume', 'This harness cannot be resumed yet.')
+ const operation = await intent(row)
+ let reply
+ if (operation.existing) reply = await rpc(row.machineId, 'agent_create_status', { creationId: operation.creationId })
+ if (!operation.existing || reply.state === 'missing') {
+ try { reply = await rpc(row.machineId, 'agent_resume', { agentId: row.agentId, creationId: operation.creationId }) }
+ catch { reply = await rpc(row.machineId, 'agent_create_status', { creationId: operation.creationId }) }
}
- }
- return { ok: false, id: row.id, name: row.name, action: 'resume', detail: `typed \`${command}\` into its pane, but ${engine} did not come up within ${Math.round(waitMs / 1000)}s — look at the pane.` }
+ if (reply.state === 'created' && reply.agent?.id === row.agentId) {
+ await clearIntent(operation.path)
+ if (reply.agent.status === 'stopped' || reply.agent.terminal?.available === false) return receipt(row, 'resume', 'The earlier resume completed, but this session is no longer running. Review it and try again.')
+ return receipt(row, 'resume', 'Resumed with its saved configuration.', { ok: true, refused: false })
+ }
+ if (reply.state === 'failed') {
+ await clearIntent(operation.path)
+ return receipt(row, 'resume', reply.failure?.detail || reply.failure?.code || reply.detail || reply.error || 'Resume failed.')
+ }
+ return receipt(row, 'resume', 'Resume is not confirmed yet. Check again to read the same operation.', { creationId: operation.creationId, unconfirmed: true })
+ } catch (error) { return receipt(row, 'resume', error.message) }
}
diff --git a/store/agents/harness-monitor/lib/bridge.mjs b/store/agents/harness-monitor/lib/bridge.mjs
index a35767e6a..b2c66f617 100644
--- a/store/agents/harness-monitor/lib/bridge.mjs
+++ b/store/agents/harness-monitor/lib/bridge.mjs
@@ -6,11 +6,9 @@
* wait for `connected`, then typed request/reply frames whose answer is `<type>_result` carrying the
* same `requestId`. Nothing here reaches the network, and no credential passes through this file.
*
- * Exactly one call is ever made: `agents_list` — who the agents are, where their panes are, what they
- * are on. Nothing on this socket writes: pausing is a signal to a process, and resuming is a line typed
- * into a pane (lib/actions.mjs). `agent_delete` and `agent_restart` exist on this protocol and are
- * deliberately never sent — the first destroys, and the second gives a released row a fresh shell
- * rather than its conversation, which is the whole reason resume does not use it.
+ * Inventory and lifecycle use the same daemon APIs as the desktop. `agent_delete` stops the validated
+ * process and retains its history; `agent_resume` restores the daemon's saved launch configuration.
+ * Writes are never automatically retried after a lost reply.
*/
import { randomUUID } from 'node:crypto'
@@ -32,8 +30,8 @@ export function bridgeUrl(env = process.env) {
}
/** Every machine this daemon can reach, the current one flagged, and — when the list could not be
- * read — why. `harness` not on PATH is an answer, not a crash: the caller falls back to reading this
- * machine's registry directly. The command runs from the home folder, never from this package's
+ * read — why. `harness` not on PATH is reported as unavailable; no registry guesses enable actions.
+ * The command runs from the home folder, never from this package's
* directory: a package update swaps that directory out from under a running viewer, and a CLI
* started in a directory that no longer exists fails in a way that reads exactly like a dead daemon. */
export async function machinesReport(env = process.env) {
@@ -123,7 +121,7 @@ function openSession(machineId, { env, timeoutMs, WebSocketImpl, forceReconnect
if (!entry || type !== `${entry.type}_result`) return
pending.delete(payload.requestId)
clearTimeout(entry.deadline)
- if (payload.error) entry.reject(new Error(String(payload.error)))
+ if (payload.error) entry.reject(Object.assign(new Error(String(payload.detail || payload.error)), { code: payload.error }))
else entry.resolve(payload)
})
})
@@ -179,7 +177,7 @@ export async function withBridge(machineId, fn, { env = process.env, timeoutMs =
* ONCE on a fresh one before the machine is reported silent. */
export async function listAgents(machineId, options = {}) {
const ask = async ({ session }) => {
- const reply = await session.rpc('agents_list', {})
+ const reply = await session.rpc('agents_list', { includeStopped: true, monitor: true })
return Array.isArray(reply.agents) ? reply.agents : []
}
const first = await bridgeSession(machineId, options)
@@ -194,6 +192,12 @@ export async function listAgents(machineId, options = {}) {
}
}
+/** A single owner RPC. Only reads above reconnect/retry; callers reconcile uncertain writes by receipt. */
+export async function request(machineId, type, payload = {}, options = {}) {
+ const { session } = await bridgeSession(machineId, options)
+ return session.rpc(type, payload, { callTimeoutMs: options.timeoutMs ?? 30_000 })
+}
+
/** Drop every kept bridge session (the pane is closing). */
export function closeBridges() {
for (const byMachine of sessions.values()) for (const session of [...byMachine.values()]) session.close()
diff --git a/store/agents/harness-monitor/lib/config.mjs b/store/agents/harness-monitor/lib/config.mjs
index e7dfe2863..89a729a6c 100644
--- a/store/agents/harness-monitor/lib/config.mjs
+++ b/store/agents/harness-monitor/lib/config.mjs
@@ -55,13 +55,13 @@ export function stripJsonc(text) {
export function template(policy = DEFAULT_POLICY) {
return `// Harness Monitor — the rules for this machine's harnesses.
//
-// Edit this file, or drag the two lines in the Harness Monitor pane. It is read on every refresh, so a
+// Edit this file and review Cleanup in the Harness Monitor table. It is read on every refresh, so a
// save takes effect within seconds. Preview any change without moving anything: hps pause --policy
//
-// The only thing the rules ever do is PAUSE a harness: its engine exits, and its pane, scrollback and
-// conversation stay. \`hps resume\` brings it back where it left off. Nothing here deletes anything.
+// Rules only propose stopping sessions. Apply a reviewed plan explicitly; nothing runs automatically.
+// The daemon retains history and launch settings. Resume behavior depends on the engine's resumeMode.
{
- // Most engines running at once on this machine — a backstop. Past it, the least recently used are paused.
+ // Most engines running at once on each machine. Cleanup proposes stopping the least recently active.
// Lower it on a machine that swaps: free memory divided by ~300 MB per harness.
"runningCeiling": ${policy.runningCeiling},
@@ -77,13 +77,13 @@ export function template(policy = DEFAULT_POLICY) {
// What is never paused, by any rule.
"protect": {
- "needsInput": ${policy.protect.needsInput}, // it looks like it is waiting on you
- "working": ${policy.protect.working}, // mid-turn: CPU, or output in the last minute
- "attached": ${policy.protect.attached}, // someone is looking at that pane right now
+ "needsInput": ${policy.protect.needsInput}, // daemon reports a pending question
+ "working": ${policy.protect.working}, // daemon reports an open turn
+ "attached": ${policy.protect.attached}, // reserved; current daemon inventory does not report attachment
"pinned": ${policy.protect.pinned} // listed in "pins" below
},
- // Agent ids the rules must never pause. \`hps --json\` shows each harness's id; the pane has a pin button.
+ // Composite machine/agent ids the rules must never pause. \`hps --json --all --machines\` shows each id.
"pins": []
}
`
diff --git a/store/agents/harness-monitor/lib/inventory.mjs b/store/agents/harness-monitor/lib/inventory.mjs
index 3e521d065..9fc156145 100644
--- a/store/agents/harness-monitor/lib/inventory.mjs
+++ b/store/agents/harness-monitor/lib/inventory.mjs
@@ -1,260 +1,125 @@
-/**
- * One row per harness, from every source that knows something about it.
- *
- * The daemon knows who the agents are, where their panes are and when their transcripts last moved.
- * tmux knows whether a pane is alive, dead or attached. The process table knows what the engine is
- * holding. This package's own state file knows what a person decided (pinned, paused). This module is
- * where those four become the single row shape that the policy, the table and the hps all read, and
- * it is the only place that decides what `state` means.
- *
- * Every machine's agents are listed — the local bridge relays `machine_select` to any machine the user
- * has linked — but pane and memory facts, and every action, are local to this computer. A remote row is
- * marked `local: false` and reads as what it is: seen, not managed from here.
- */
-
-import { existsSync } from 'node:fs'
+/** One row per machine/agent. Daemon facts are authoritative; missing readings stay unknown. */
import { homedir } from 'node:os'
import { basename, dirname } from 'node:path'
-import { lastTurns } from './activity.mjs'
+import { existsSync } from 'node:fs'
import { listAgents, machinesReport } from './bridge.mjs'
-import { engineProcess, panes, processTable } from './panes.mjs'
import { humanIdle } from './policy.mjs'
-import { readRegistry, registryAsFrames } from './registry.mjs'
-/** `runtime-v1:<agentId>:<engine>:<model>@<effort>` — the runtime profile's answer, as the daemon
- * sends it. A plain model name (older daemons) is passed through untouched. */
export function parseModel(selected) {
if (typeof selected !== 'string' || !selected) return { model: null, effort: null }
const body = selected.startsWith('runtime-v1:') ? selected.split(':').slice(3).join(':') : selected
const at = body.lastIndexOf('@')
- if (at <= 0) return { model: body || null, effort: null }
- return { model: body.slice(0, at) || null, effort: body.slice(at + 1) || null }
+ return at <= 0 ? { model: body || null, effort: null } : { model: body.slice(0, at), effort: body.slice(at + 1) || null }
}
-
-/** Working directories are shown relative to `~`: a fleet list is read by the person whose home it is,
- * and the absolute prefix is the same eleven characters on every row. */
export function tilde(path, home = homedir()) {
if (typeof path !== 'string' || !path) return ''
- return home && path.startsWith(home) ? `~${path.slice(home.length)}` : path
+ return path === home || path.startsWith(home + '/') ? '~' + path.slice(home.length) : path
}
-
-/** The project a row belongs to: the git root's name when there is one, else the folder's. Two agents
- * in two worktrees of one repo are two projects, on purpose — that is how they are worked on. */
export function projectOf(agent) {
- const project = agent.project
- if (!project) return { project: 'unknown', cwd: '', branch: null, remote: null }
- const cwd = project.cwd || ''
- return {
- project: project.name || basename(project.root || cwd) || basename(dirname(cwd)) || 'unknown',
- cwd,
- branch: project.branch || null,
- remote: project.remote || null,
- }
+ const project = agent.project, cwd = project?.cwd || ''
+ return { project: project?.name || basename(project?.root || cwd) || (cwd ? basename(dirname(cwd)) : '') || '—',
+ cwd, branch: project?.branch || null, remote: project?.remote || null }
}
-
-/** The first of these that is a real moment in time. `Date.parse` answers NaN rather than null, which is
- * exactly the value that must not reach an idle column, so it is filtered here and not by `??`. */
-function firstTime(candidates, fallback) {
- for (const value of candidates) {
- const time = typeof value === 'string' ? Date.parse(value) : Number(value)
- if (Number.isFinite(time) && time > 0) return time
- }
- return fallback
+const time = value => {
+ const n = typeof value === 'number' ? value : Date.parse(value)
+ return Number.isFinite(n) && n > 0 ? n : null
}
+const reading = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null
+export const rowId = (machineId, agentId) => JSON.stringify([machineId, agentId])
-/**
- * Merge one machine's agent frames with local pane and process facts.
- *
- * `state` is decided here and nowhere else:
- * the pane is gone from tmux → gone (nothing to resume; history only)
- * the pane is there and an engine is up → running
- * the pane is there, no engine, a ticket → paused (conversation intact, waiting to be resumed)
- * the pane is there, no engine, no ticket → terminal (a shell somebody opened; nothing to pause)
- * and that is the whole state machine. There is deliberately no fourth state: an earlier version had
- * `retired` as paused-plus-a-decision, and every consumer paid for it — a glyph, a filter, a verb, a
- * grace window — to express something a sorted list already expresses.
- *
- * ## Why a paused row needs the ticket to describe itself
- *
- * When an engine leaves, the daemon does not merely mark the row: it REWRITES it as a terminal. Measured
- * on a real pause, the row kept its `cwd` and lost everything else — `engine` became `terminal`,
- * `sessionId` became empty, `transcriptPath` and `title` became null. So a paused harness would appear in
- * Harness Monitor's own list as a nameless shell, and nothing would know which conversation to resume. The ticket
- * `pause()` wrote into `monitor.json` is the only record, and it is overlaid here.
- */
-export function mergeRows(agents, { paneRows = new Map(), table = { byPid: new Map(), children: new Map() }, state = {}, machine = null, local = true, now = Date.now(), home = homedir(), turns = new Map(), registry = new Map() } = {}) {
- const pauseTickets = state.paused ?? {}
- const pins = new Set(state.pins ?? [])
- return agents.map((agent) => {
- const pane = agent.tmuxPane && local ? paneRows.get(agent.tmuxPane) ?? null : null
- const ticket = pauseTickets[agent.id] ?? null
- // A paused row describes itself from its ticket: the daemon has already forgotten what it was.
- const engine = agent.engine === 'terminal' && ticket?.engine ? ticket.engine : agent.engine
- const sessionId = agent.sessionId || ticket?.sessionId || null
- const proc = local ? engineProcess(pane, table, engine) : { pid: null, rss: 0, cpu: 0, procs: 0, engineAlive: agent.status === 'active' }
- // The one number every rule depends on. `agent.updatedAt` is deliberately NOT in this list: it is
- // the transcript's mtime, which a live engine bumps with bookkeeping between turns (see
- // activity.mjs). Last turn, else the daemon's last hook, else when the agent was registered.
- const reg = registry.get(agent.id)
- const lastActivity = firstTime([turns.get(agent.id), reg?.lastHookAt, Date.parse(agent.createdAt)], now)
- const idleMs = Math.max(0, now - lastActivity)
+export function mergeRows(agents, { state = {}, machine = null, local = true, now = Date.now(), home = homedir(), online = true } = {}) {
+ return agents.map(agent => {
+ const id = rowId(machine?.machineId ?? null, agent.id)
+ const stopped = agent.status === 'stopped'
+ const terminalAvailable = agent.terminal?.available === true && !stopped
const { project, cwd, branch, remote } = projectOf(agent)
- // A remote row cannot be looked up in this machine's tmux, so its liveness is the daemon's word for
- // it. A local row's liveness is the process table — which is the stricter of the two and the one a
- // person can verify, so it wins whenever it is available.
- const present = local ? Boolean(pane) : agent.status !== 'gone'
- let stateName = !present ? 'gone' : proc.engineAlive ? 'running' : 'paused'
- // A shell somebody opened is not a paused agent: it has no conversation and nothing to resume, so it
- // is shown as what it is and left out of every rule.
- if (stateName === 'paused' && engine === 'terminal' && !ticket) stateName = 'terminal'
- const { model, effort } = parseModel(agent.selectedModel)
+ // updatedAt is real conversation activity, not registry touchedAt or transcript mtime.
+ const lastActivity = time(agent.updatedAt) ?? time(agent.createdAt)
+ const idleMs = lastActivity == null ? null : Math.max(0, now - lastActivity)
+ const monitor = agent.monitor
+ let activity = !online ? 'offline' : stopped ? 'stopped'
+ : agent.launch?.state === 'starting' ? 'starting'
+ : agent.launch?.state === 'failed' ? (agent.launch.error === 'RESUME_UNCONFIRMED' ? 'needsInput' : 'failed')
+ : monitor?.activityKnown ? monitor.activity : 'unknown'
+ if (!['working', 'needsInput', 'done', 'idle', 'starting', 'failed', 'stopped', 'offline', 'unknown'].includes(activity)) activity = 'idle'
+ const self = agent.dsh === 'autonomous/harness-monitor'
+ const canControl = online && !self && agent.resumeMode != null && agent.launch?.state !== 'starting'
return {
- id: agent.id,
- sessionId,
- name: agent.name || ticket?.title || 'agent',
- title: agent.title || ticket?.title || null,
- engine,
- model, effort,
- state: stateName,
- stateSince: stateName === 'paused' && ticket ? (ticket.at ?? lastActivity) : lastActivity,
- pausedAt: ticket?.at ?? null,
- pane: agent.tmuxPane || null,
- paneTarget: pane?.target ?? null,
- project, cwd, home: tilde(cwd, home), branch, remote,
- lastActivity, idleMs, idle: humanIdle(idleMs),
- createdAt: firstTime([agent.createdAt], null),
- attached: Boolean(pane?.attached),
- // Mid-turn, as far as anything outside the daemon can tell: the engine is burning CPU, or its
- // transcript moved in the last minute and a half. Both are proxies, and both are only ever used
- // to REFUSE to pause something — never to claim an agent is busy in the interface.
- working: local
- ? proc.cpu > 5 || idleMs < 90_000 || (pane?.lastOutput ? now - pane.lastOutput < 60_000 : false)
- : idleMs < 90_000,
- lastOutput: pane?.lastOutput ?? null,
- transcript: reg?.transcriptPath ?? null,
- needsInput: false,
- pinned: pins.has(agent.id),
- workspaceGone: Boolean(cwd) && local && !existsSync(cwd),
- rssBytes: proc.rss,
- procs: proc.procs,
- cpu: proc.cpu,
- enginePid: proc.pid,
- cwdWas: ticket?.cwd ?? null,
- dsh: agent.dsh ?? null,
- dshName: agent.dshName ?? null,
- verdict: agent.verdict?.ready === undefined ? null : Boolean(agent.verdict.ready),
- machine: machine?.name ?? 'this machine',
- machineId: machine?.machineId ?? null,
- local,
- dead: Boolean(pane?.dead),
+ id, agentId: agent.id, sessionId: agent.sessionId || null,
+ name: agent.name || agent.title || 'Untitled harness', title: agent.title || null,
+ engine: agent.engine, ...parseModel(agent.selectedModel),
+ state: !online ? 'offline' : stopped ? 'paused' : terminalAvailable ? (agent.engine === 'terminal' ? 'terminal' : 'running') : 'gone',
+ activity, activityKnown: monitor?.activityKnown === true,
+ stateSince: lastActivity, pausedAt: stopped ? lastActivity : null,
+ pane: agent.tmuxPane || null, paneTarget: null,
+ project, cwd, home: local ? tilde(cwd, home) : cwd, branch, remote,
+ lastActivity, idleMs, idle: idleMs == null ? '—' : humanIdle(idleMs), createdAt: time(agent.createdAt),
+ attached: false, working: activity === 'working', needsInput: activity === 'needsInput',
+ pinned: self || (state.pins ?? []).includes(id) || (local && (state.pins ?? []).includes(agent.id)),
+ workspaceGone: local && Boolean(cwd) && !existsSync(cwd),
+ rssBytes: online ? stopped ? 0 : reading(monitor?.rssBytes) : null,
+ cpu: online ? stopped ? 0 : reading(monitor?.cpu) : null,
+ enginePid: online && !stopped ? reading(monitor?.pid) : null,
+ tokens: reading(agent.tokenUsage?.totalTokens), dsh: agent.dsh ?? null, dshName: agent.dshName ?? null,
+ verdict: agent.verdict?.ready ?? null,
+ machine: machine?.name ?? 'This machine', machineId: machine?.machineId ?? null,
+ local, online, self, canStop: canControl && terminalAvailable,
+ canOpen: online && (terminalAvailable || (stopped && agent.resumeMode != null)), resumeMode: agent.resumeMode ?? null,
+ unavailable: !online ? 'Reconnect this machine.' : self ? 'Manage this assistant from its monitor tab.' : agent.launch?.detail ?? null,
}
})
}
-/**
- * The whole fleet, from every machine that answers.
- *
- * Failures are per machine and reported, never fatal: a fleet view that refuses to draw because one
- * linked laptop is asleep is worse than one that says which machine it could not reach.
- */
+/** Cache is scoped to this viewer, never an account-global singleton. Offline machines retain rows. */
export async function collect({
- state = {}, now = Date.now(), includeRemote = true, timeoutMs = 8000, home = homedir(), cache = new Map(),
- // Remote machines are asked at most this often; between asks their last answer is re-merged against
- // the current clock. A pane ticks every few seconds for the machine it is on — that is local reads —
- // but every remote ask crosses the relay to another computer, so it gets its own, slower clock.
- // `remote` is the holder for that answer, owned by the caller so it survives across ticks.
- remoteIntervalMs = 60_000, remote = null,
+ state = {}, now = Date.now(), includeRemote = true, timeoutMs = 8000, home = homedir(),
+ remoteIntervalMs = 15_000, remote = { at: 0, answers: new Map() },
+ reportMachines = machinesReport, agentsFor = listAgents,
} = {}) {
- const [paneRows, table, report, registry] = await Promise.all([panes(), processTable(), machinesReport(), readRegistry()])
- const machineList = report.machines
- const turns = await lastTurns(registry.rows.map((row) => ({ id: row.agentId, transcriptPath: row.transcriptPath })), { cache })
- const current = machineList.find((m) => m.current) ?? null
- const remoteMachines = includeRemote ? machineList.filter((m) => !m.current && m.online) : []
- const remoteDue = !remote || remoteIntervalMs <= 0 || now - (remote.at ?? 0) >= remoteIntervalMs
- const targets = [current, ...(remoteDue ? remoteMachines : [])].filter(Boolean)
- const problems = []
- let rows = []
-
- // No daemon, no `harness` on PATH: fall back to the registry file this machine already has. Seeing
- // the fleet must not depend on the app running, and pausing is pure tmux either way. Say which of
- // the two it was: a CLI that failed to run is a different repair from a daemon that is not there.
- if (!targets.length) {
- if (report.error) problems.push({ machine: 'this machine', error: `Read from the registry file — ${report.error}, so models, branches and remote machines are missing.` })
- else if (!registry.rows.length) problems.push({ machine: 'this machine', error: 'No Harness daemon on the local bridge and no registry to read.' })
- else problems.push({ machine: 'this machine', error: 'Read from the registry file — the Harness daemon is not answering, so models, branches and remote machines are missing.' })
- const rowsOffline = mergeRows(registryAsFrames(registry.rows), { paneRows, table, state, machine: null, local: true, now, home, turns, registry: registry.byId })
- rowsOffline.sort((a, b) => a.idleMs - b.idleMs || a.name.localeCompare(b.name))
- return { rows: rowsOffline, machines: machineList, problems, observedAt: now, degraded: true }
- }
-
- // What each remote machine last answered, raw, so an off-tick merge still gets a fresh clock.
- const answers = remoteDue ? new Map() : new Map(remote?.answers ?? [])
- const remoteProblems = remoteDue ? [] : [...(remote?.problems ?? [])]
- await Promise.all(targets.map(async (machine) => {
- try {
- const agents = await listAgents(machine.machineId, { timeoutMs })
- if (machine.current) rows = rows.concat(mergeRows(agents, { paneRows, table, state, machine, local: true, now, home, turns, registry: registry.byId }))
- else answers.set(machine.machineId, agents)
- } catch (error) {
- const problem = { machine: machine.name, error: error instanceof Error ? error.message : String(error) }
- if (machine.current) problems.push(problem)
- else remoteProblems.push(problem)
- }
+ const report = await reportMachines()
+ const machines = report.machines.filter(m => includeRemote || m.current)
+ const problems = report.error ? [{ machine: 'This machine', error: report.error }] : []
+ const answers = remote.answers ??= new Map()
+ const failed = remote.failed ??= new Set()
+ const previouslyOnline = remote.online ??= new Set()
+ const due = remoteIntervalMs <= 0 || !remote.at || now - remote.at >= remoteIntervalMs
+ await Promise.all(machines.filter(m => m.online && (m.current || due || !answers.has(m.machineId) || !previouslyOnline.has(m.machineId) || failed.has(m.machineId))).map(async machine => {
+ try { answers.set(machine.machineId, await agentsFor(machine.machineId, { timeoutMs })); failed.delete(machine.machineId) }
+ catch (error) { failed.add(machine.machineId); problems.push({ machine: machine.name, error: error.message }) }
}))
- for (const machine of remoteMachines) {
- const agents = answers.get(machine.machineId)
- if (agents) rows = rows.concat(mergeRows(agents, { paneRows, table, state, machine, local: false, now, home, turns, registry: registry.byId }))
+ if (due) remote.at = now
+ remote.online = new Set(machines.filter(m => !report.error && m.online).map(m => m.machineId))
+ if (!report.error) {
+ const known = new Set(machines.map(m => m.machineId))
+ for (const id of answers.keys()) if (!known.has(id)) { answers.delete(id); failed.delete(id) }
+ remote.machines = machines
}
- problems.push(...remoteProblems)
- if (remote && remoteDue) { remote.at = now; remote.answers = answers; remote.problems = remoteProblems }
-
- rows.sort((a, b) => a.idleMs - b.idleMs || a.name.localeCompare(b.name))
- return { rows, machines: machineList, problems, observedAt: now }
+ const visibleMachines = report.error ? (remote.machines ?? []) : machines
+ const rows = visibleMachines.flatMap(machine => mergeRows(answers.get(machine.machineId) ?? [], {
+ state, machine, local: machine.current, online: !report.error && machine.online && !remote.failed.has(machine.machineId), now, home,
+ }))
+ for (const machine of visibleMachines.filter(m => !m.online)) problems.push({ machine: machine.name, error: 'Offline — showing the last known sessions.' })
+ rows.sort((a, b) => (a.idleMs ?? Infinity) - (b.idleMs ?? Infinity) || a.id.localeCompare(b.id))
+ return { rows, machines: visibleMachines, problems, observedAt: now, degraded: problems.length > 0 }
}
-/** Totals a person reads before deciding anything: the gauge in the header and the CLI's last line. */
export function summarize(rows) {
- const by = (state) => rows.filter((row) => row.state === state).length
- return {
- total: rows.length,
- running: by('running'),
- paused: by('paused'),
- gone: by('gone'),
- terminals: by('terminal'),
- needsInput: rows.filter((row) => row.needsInput).length,
- working: rows.filter((row) => row.working && row.state === 'running').length,
- held: rows.reduce((sum, row) => sum + (row.rssBytes || 0), 0),
- projects: new Set(rows.map((row) => row.project)).size,
- machines: new Set(rows.map((row) => row.machine)).size,
- }
+ const by = state => rows.filter(row => row.state === state).length
+ return { total: rows.length, running: by('running'), paused: by('paused'), gone: by('gone'), terminals: by('terminal'),
+ needsInput: rows.filter(row => row.needsInput).length, working: rows.filter(row => row.working).length,
+ held: rows.reduce((sum, row) => sum + (row.rssBytes ?? 0), 0),
+ projects: new Set(rows.map(row => row.project)).size, machines: new Set(rows.map(row => row.machineId)).size }
}
-/**
- * Resolve what a person typed to exactly one row, or say why it is ambiguous.
- *
- * Accepted, in order: a row number from the last `ls`, a tmux pane id (`%42`), an agent-id prefix, an
- * exact name, then a unique case-insensitive substring of the name or title. The same grammar the shell
- * gave everyone for job control — `%3` is a pane here and a job there — so it needs no learning.
- */
export function resolveRef(ref, rows) {
const text = String(ref ?? '').trim()
if (!text) return { error: 'Name a harness: a row number, a %pane, an id, or part of its name.' }
- if (/^\d+$/.test(text)) {
- const row = rows[Number(text) - 1]
- return row ? { row } : { error: `There is no row ${text} — the list has ${rows.length}.` }
- }
- if (/^%\d+$/.test(text)) {
- const matches = rows.filter((row) => row.pane === text)
- return matches.length === 1 ? { row: matches[0] } : { error: `No harness is on pane ${text}.` }
- }
- const exactId = rows.filter((row) => row.id === text || row.id.startsWith(text))
- if (exactId.length === 1) return { row: exactId[0] }
- if (exactId.length > 1) return { error: `${text} matches ${exactId.length} agent ids. Use a longer prefix.` }
- const exactName = rows.filter((row) => row.name.toLowerCase() === text.toLowerCase())
- if (exactName.length === 1) return { row: exactName[0] }
- const needle = text.toLowerCase()
- const loose = rows.filter((row) => row.name.toLowerCase().includes(needle) || (row.title ?? '').toLowerCase().includes(needle))
- if (loose.length === 1) return { row: loose[0] }
- if (loose.length > 1) return { error: `${text} matches ${loose.length} harnesses: ${loose.slice(0, 5).map((row) => row.name).join(', ')}${loose.length > 5 ? '…' : ''}` }
- return { error: `No harness matches ${text}.` }
+ if (/^\d+$/.test(text)) return rows[Number(text) - 1] ? { row: rows[Number(text) - 1] } : { error: 'There is no row ' + text + '.' }
+ const exact = rows.filter(row => row.id === text || row.agentId === text || row.id.startsWith(text) || row.agentId?.startsWith(text) || row.pane === text)
+ if (exact.length === 1) return { row: exact[0] }
+ if (exact.length > 1) return { error: text + ' matches ' + exact.length + ' harnesses. Use the full machine/agent id.' }
+ const names = rows.filter(row => row.name.toLowerCase() === text.toLowerCase())
+ if (names.length === 1) return { row: names[0] }
+ const loose = rows.filter(row => (row.name + ' ' + (row.title ?? '')).toLowerCase().includes(text.toLowerCase()))
+ return loose.length === 1 ? { row: loose[0] } : { error: loose.length ? text + ' matches ' + loose.length + ' harnesses.' : 'No harness matches ' + text + '.' }
}
diff --git a/store/agents/harness-monitor/lib/policy.mjs b/store/agents/harness-monitor/lib/policy.mjs
index 50914b329..fe6461ea4 100644
--- a/store/agents/harness-monitor/lib/policy.mjs
+++ b/store/agents/harness-monitor/lib/policy.mjs
@@ -9,9 +9,8 @@
*
* The vocabulary, kept identical everywhere:
* running the engine process is alive — a normal Harness agent
- * paused the pane and the conversation are there, the engine process is not (the daemon's own
- * "dormant but still viewable agent"); resuming it resumes the conversation
- * gone no pane left; the daemon dropped the row. History only, nothing to resume
+ * paused the daemon retains history and launch settings, but the process is stopped
+ * gone the daemon knows the row but its terminal is unavailable
*/
/** Shipped defaults. Every number here is a judgement, and every one of them is meant to be argued
@@ -37,7 +36,7 @@ export const DEFAULT_POLICY = {
needsInput: true,
/** Mid-turn. Pausing here would throw away work in flight. */
working: true,
- /** Somebody is looking at this pane right now. */
+ /** Reserved for inventories that report attachment; current daemon inventory does not. */
attached: true,
/** Listed in `pins`. The one escape hatch the rules must never overrule. */
pinned: true,
@@ -100,6 +99,10 @@ export function normalizePolicy(raw, { home = '' } = {}) {
/** Why this row cannot be touched, or null. Order is the order a person would say them in. */
export function protectionFor(row, policy) {
+ if (row.online === false) return { by: 'offline', why: 'machine is offline' }
+ if (row.activityKnown === false) return { by: 'unknown', why: 'activity is unknown; update the owning daemon' }
+ if (row.self) return { by: 'monitor', why: 'this monitor’s assistant' }
+ if (row.canStop === false) return { by: 'unavailable', why: 'not ready to stop' }
const p = policy.protect
if (p.pinned && row.pinned) return { by: 'pinned', why: 'pinned' }
if (p.needsInput && row.needsInput) return { by: 'needsInput', why: 'waiting on you' }
@@ -121,7 +124,7 @@ const RUNNING = new Set(['running'])
* The plan. One entry per row, in the order given, plus the rules' own totals.
*
* `action` is what the row should become: `pause` or `keep`. Nothing here decides
- * how — `pause.mjs` owns the mechanics, and `forget` never means deleting a transcript.
+ * how — `actions.mjs` asks the owning daemon. Nothing deletes history.
*/
export function decide(rows, rawPolicy, { now = Date.now(), home = '' } = {}) {
const policy = rawPolicy?.pauseAfterIdleMs ? rawPolicy : normalizePolicy(rawPolicy, { home })
@@ -131,10 +134,7 @@ export function decide(rows, rawPolicy, { now = Date.now(), home = '' } = {}) {
for (const row of rows) {
const idle = Math.max(0, Number(row.idleMs) || 0)
if (row.state === 'gone') {
- const goneFor = Math.max(0, now - (row.stateSince ?? now))
- entries.push(goneFor >= policy.forgetAfterRetiredMs
- ? { id: row.id, name: row.name, action: 'forget', rule: 'gone', why: `no pane left, and gone for ${humanIdle(goneFor)} — drop it from the hps (its transcript stays where the engine wrote it)` }
- : keep(row, 'no pane left; kept in history for now'))
+ entries.push(keep(row, 'terminal unavailable; retained in daemon inventory'))
continue
}
// A shell somebody opened is not an agent: no conversation, nothing to resume, no rule applies.
@@ -162,9 +162,11 @@ export function decide(rows, rawPolicy, { now = Date.now(), home = '' } = {}) {
const survivors = rows.filter((row, i) => RUNNING.has(row.state) && entries[i].action === 'keep')
const byId = new Map(rows.map((row, i) => [row.id, entries[i]]))
const ranked = [...survivors].sort((a, b) => (a.idleMs ?? 0) - (b.idleMs ?? 0))
- let slots = policy.runningCeiling
+ const slots = new Map()
for (const row of ranked) {
- if (slots > 0) { slots -= 1; continue }
+ const remaining = slots.get(row.machineId) ?? policy.runningCeiling
+ slots.set(row.machineId, remaining - 1)
+ if (remaining > 0) continue
const entry = byId.get(row.id)
if (entry.protectedBy) continue
entry.action = 'pause'
diff --git a/store/agents/harness-monitor/lib/resume.mjs b/store/agents/harness-monitor/lib/resume.mjs
deleted file mode 100644
index 9a208f012..000000000
--- a/store/agents/harness-monitor/lib/resume.mjs
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * How each engine is asked to come back to a conversation it already had.
- *
- * Mirrors the daemon's own two tables — `LAUNCH_RESUME_FLAG` and `ENGINE_CLI_ALIASES` in
- * `cli/src/lib/engineLaunch.ts` and `engineBin.ts` — because resuming a paused harness types the same
- * command into the pane that the daemon would have built. Mirrored rather than imported: this package
- * installs on its own and cannot reach the daemon's TypeScript.
- *
- * An engine that is NOT in this table cannot be resumed with its conversation, so Harness Monitor refuses to pause
- * it at all. That refusal is the whole safety property: nothing is ever stopped that cannot be brought
- * back. `devin` is deliberately absent (the daemon omits it too — it has no resume flag), and so is
- * `terminal`, which has no conversation to resume.
- */
-
-/** engine → the argv that resumes a session id. A leading token without a dash is a SUBCOMMAND. */
-export const RESUME_ARGS = {
- claude: ['--resume'],
- codex: ['resume'],
- cursor: ['--resume'],
- opencode: ['--session'],
- kilo: ['--session'],
- pi: ['--session'],
- hermes: ['--resume'],
- commandcode: ['--resume'],
- muse: ['resume'],
- amp: ['threads', 'continue'],
- grok: ['--resume'],
- agy: ['--conversation'],
- copilot: ['--resume'],
-}
-
-/** engine → the command a person types. The first alias is the canonical one. */
-export const ENGINE_BIN = {
- claude: 'claude', codex: 'codex', cursor: 'cursor-agent', opencode: 'opencode', pi: 'pi',
- hermes: 'hermes', commandcode: 'cmd', muse: 'muse', amp: 'amp', kilo: 'kilo', grok: 'grok',
- agy: 'agy', copilot: 'copilot', devin: 'devin',
-}
-
-/** A session id as the engines write them: uuid-shaped, or hex/ulid-ish. Checked because this string is
- * about to be typed into a shell — anything with a space, a quote or a semicolon in it is refused here
- * rather than quoted and hoped for. */
-const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{7,127}$/
-
-export function canResume(engine) {
- return Boolean(RESUME_ARGS[engine] && ENGINE_BIN[engine])
-}
-
-/**
- * The one line that brings an engine back: `claude --resume <id>`, `codex resume <id>`.
- *
- * Typed into the pane's fallback shell, which is where a paused harness leaves it. The daemon watches
- * that pane, recognizes the engine, and re-adopts the row — the same path it documents for a person who
- * types the engine's name into a pane whose engine has left (`adoptEngine`). Verified end to end against
- * a real Claude Code session: the conversation, the pane and the agent id all came back.
- */
-export function resumeCommand(engine, sessionId) {
- if (!canResume(engine)) throw new Error(`Harness Monitor does not know how to resume ${engine}, so it will not pause it.`)
- if (!SESSION_ID.test(String(sessionId ?? ''))) throw new Error('That session id is not one an engine wrote.')
- return [ENGINE_BIN[engine], ...RESUME_ARGS[engine], sessionId].join(' ')
-}
diff --git a/store/agents/harness-monitor/skills/fleet-operations/SKILL.md b/store/agents/harness-monitor/skills/fleet-operations/SKILL.md
index df26f0049..4f449dc20 100644
--- a/store/agents/harness-monitor/skills/fleet-operations/SKILL.md
+++ b/store/agents/harness-monitor/skills/fleet-operations/SKILL.md
@@ -1,70 +1,44 @@
---
name: fleet-operations
-description: Run a fleet of long-lived coding-agent sessions — list them, pause idle ones without losing their conversations, resume them where they left off, and tune the policy that decides. Use when someone has many Harness harnesses, wants to know which are actually running, wants memory back from idle agents, asks what to clean up, or asks whether a pause threshold is any good.
+description: Inspect Harness sessions, explain activity and resource readings, preview cleanup, and stop or resume explicitly selected sessions through their owning daemons.
---
# Fleet operations
-A fleet of long-lived agent sessions goes wrong in one specific way: nothing ever ends. Sessions are
-never killed — that is the point of them — so they accumulate until the list is useless and the machine
-is full. This skill is how to fix that without breaking the promise that made people keep them.
+The table is the primary interface. Use this skill when the person asks the assistant to investigate
+sessions or review cleanup. Do not start work simply because the monitor opened.
-## The one idea
+Start with `"$HPS_CLI" ls --json --all --machines`. Read [references/signals.md](references/signals.md)
+before explaining activity or resource readings. Use composite machine/agent IDs when names or IDs
+are ambiguous. Missing measurements are unknown; an offline machine is not a stopped session.
-**Separate the conversation from the process.** A conversation lives in a transcript and can be resumed;
-a process holds memory and can be stopped. Pausing stops the process and keeps everything else. Once
-pausing is free and resuming is reliable, an idle harness costs nothing, and "should I kill this?" stops
-being a question anybody has to answer.
+## Actions
-Everything else follows from that:
+- `hps show <ref> --machines --json` reads one session.
+- `hps pause <ref> --machines --json` asks its owning daemon to stop the process and retain history.
+- `hps resume <ref> --machines --json` restores saved launch settings. Check `resumeMode`: conversation,
+ fresh conversation, or shell. Do not promise every engine resumes the same conversation.
+- `hps pause --policy --machines --json` previews cleanup; `--apply` applies the current plan.
+- `hps resume --paused --machines --json` previews reopening stopped sessions; `--apply` executes it.
-- **A ceiling, not a cleanup.** `runningCeiling` caps how many engines are running at once; the least
- recently active get paused when a new one passes the cap. This is the rule that bounds the steady state
- no matter how many harnesses get created — the one worth defending in an argument.
-- **Idle thresholds, not idle shaming.** `pauseAfterIdle` (default 1d — survives an overnight break) and
- `hideAfterIdle` (default 14d, a list rule) are both reversible, so they can be aggressive.
-- **A grace window, not a delete.** Retired rows are forgotten from the hps after
- `forgetAfterRetired` (30d), and forgetting is bookkeeping: transcripts belong to the engines.
-- **Pins beat rules.** A pinned harness is never paused by policy, whatever the numbers say.
+For more than two sessions, show the dry run with reasons and obtain approval before applying it.
+Recheck the plan after approval; if the targets changed, present the new targets. Named actions must
+still correspond to the person's request. Never use `--force` unless explicitly requested for those
+sessions. The row's × button is an explicit single-session stop and may interrupt work in progress.
-## Reading the fleet
+The daemon owns process identity, stopping and resume configuration on local and linked machines.
+Do not signal PIDs, reconstruct engine flags, respawn a tmux pane, or edit the registry. After a timeout,
+read the original resume receipt; do not invent a new operation to compensate. Explain refusals and
+uncertain outcomes. Receipts are recorded in `~/.harness/monitor/log.jsonl`.
-Always start from data: `"$HPS_CLI" ls --json`. The fields that matter and their traps are in
-[references/signals.md](references/signals.md) — read it before you explain an `idle` number to anyone,
-because the three obvious sources for it are all wrong and one of them is wrong by days.
+## Cleanup rules
-A good first report is four numbers and one sentence: how many harnesses, how many running, how much memory
-held, how many idle past the pause threshold — then what you propose. Not a table of eighty rows.
+[references/policy.md](references/policy.md) explains the proposal rules. They never run automatically.
+Working sessions, questions, pins, unavailable controls and unknown activity are protected by default.
+Attachment is not currently reported; do not promise protection merely because a pane is visible.
-## Acting
+Rules and pins live in `~/.config/harness/policy.jsonc`. Preserve comments and simulate a proposed
+change before applying it. Do not change thresholds to make a refused cleanup succeed.
-| Situation | Do this |
-|---|---|
-| One or two named harnesses | act, then show the receipt line |
-| More than two | dry run → show the plan with a reason per row → ask → `--apply` |
-| "Pause everything but X" | add X's id to `pins` in `~/.config/harness/policy.jsonc`, then `hps pause --policy --apply` |
-| A guard refused | name the guard, leave it, offer `--force` as their choice, never yours |
-| They want a threshold judged | set it in `~/.config/harness/policy.jsonc`, run `hps pause --policy`, report what it would do to *their* fleet |
-| They want it gone for good | Harness Monitor does not delete. Point at the app's Stop Harness, which asks first |
-
-Receipts are not decoration. Every action is appended to `.harness/monitor-log.jsonl` with its reason, and
-"why is this paused?" must always have an answer that is not a guess.
-
-## Tuning the policy
-
-The rules live in `~/.config/harness/policy.jsonc` as data, so they can be simulated before they are believed —
-[references/policy.md](references/policy.md) has each rule, its default, the argument for that default,
-and what makes it wrong for someone. Two habits:
-
-1. **Never change a threshold without simulating it.** Edit `pauseAfterIdle` in `~/.config/harness/policy.jsonc`, then
- `hps pause --policy` reads back exactly which harnesses would move, and why, without moving any.
-2. **Change one rule at a time.** Two thresholds moving at once makes the result unattributable, and the
- person is trying to build an intuition, not just a config.
-
-## The boundary, and why it holds
-
-Harness Monitor can pause and resume. It cannot delete an agent, kill a tmux session or
-touch a transcript. That is what makes it safe to point at eighty live sessions and act on all of them in
-one command — the worst outcome of a wrong decision is a few seconds of cold start. Do not work around
-it, and do not build a workaround for someone who asks: the app already has the irreversible verbs,
-behind their own confirmation, which is where they belong.
+Never delete transcripts or project folders. Stopping a process can interrupt unfinished work, even
+though its history is retained. Report what the tools actually confirmed.
diff --git a/store/agents/harness-monitor/skills/fleet-operations/references/policy.md b/store/agents/harness-monitor/skills/fleet-operations/references/policy.md
index 063fcdb81..c8564efc5 100644
--- a/store/agents/harness-monitor/skills/fleet-operations/references/policy.md
+++ b/store/agents/harness-monitor/skills/fleet-operations/references/policy.md
@@ -1,59 +1,22 @@
-# The rules, their defaults, and the argument for each
-
-`~/.config/harness/policy.jsonc`, one per machine. Change one at a time, and simulate before believing.
-
-## `runningCeiling` — default 100
-
-The most engines running at once on this machine. When more than that survive the idle rules, the least
-recently active are paused until the count fits. Protected rows hold a slot but are never paused.
-
-**Why it matters most:** every other rule is a reaction to time passing; this one is a bound. It makes the
-steady state independent of how many harnesses get created, the way `ulimit` bounds a process. A person
-who creates six harnesses a day and pauses none still ends the month under the ceiling.
-
-**The default is 100, which makes it a backstop.** On a normal day the idle rule does all the work and the
-ceiling never fires. **When it is wrong:** a laptop under memory pressure wants something like 12. Set it to
-what the machine can hold without swapping — free memory divided by ~300 MB — not to what feels tidy.
-
-## `pauseAfterIdle` — default `1d`
-
-Idle this long and a running engine is paused. A day, because a day survives an overnight break: yesterday
-afternoon's work is still warm in the morning. The first default was 4h; on a real fleet the only thing it
-caught that a day does not was eight harnesses from the previous afternoon.
-
-**When it is wrong:** an agent on a long autonomous run that produces no turns for hours would be paused
-mid-thought if the `working` guard somehow missed it — pin those. Someone who works in short bursts across
-a whole day may prefer `8h`; someone on a small machine, `1h`.
-
-## `hideAfterIdle` — default `14d`
-
-Idle this long and the row drops below the fold: out of the default list, one `--all` (or the pane's **show
-all**) away, still resumable. Two weeks is past "I'll get back to it" for anything unpinned.
-
-**This is a list rule, not a state.** An earlier version made it a `retire` verb with its own state, mark
-and thirty-day grace window, and it earned none of that: hiding is what a sorted list does, and
-`systemctl disable` — the analogy used to justify it — exists because a service would otherwise auto-start
-at boot. Nothing auto-starts a harness.
-
-**Never shorter than `pauseAfterIdle`.** A row cannot drop out of the list before it is even paused; the
-policy refuses to load if it is.
-
-## `pauseWhenWorkspaceGone` — default `true`
-
-A harness whose working folder no longer exists has no work left in it. The cheapest correct rule in the
-file, and the only one that fires on a fact rather than a duration.
-
-## `protect` — the guards
-
-`needsInput`, `working`, `attached`, `pinned` default to on, and each refuses an action with its own
-reason. There is deliberately no `projects` list any more: it was a second mechanism for the same job as
-`pin`, and that is how a config file gets fat.
-
-## What the rules deliberately do not do
-
-- **No git.** "Its branch already merged" is a good reason to pause and a bad thing to put in a rule that
- runs every four seconds against sixty repositories. The agent does that check on request, and names the
- branch in `--reason`.
-- **No deleting.** There is no rule, and no flag, that removes an agent. See the skill's last section.
-- **No remote actions.** Other machines are listed, never acted on: pane facts and signals are local, and
- a fleet manager that guesses at a machine it cannot see is not one.
+# Cleanup proposals
+
+The policy file is `~/.config/harness/policy.jsonc` (or under XDG_CONFIG_HOME). The same local rules are
+applied to each linked machine in the monitor. They produce a preview, never a background cleanup job.
+
+| Rule | Default | Meaning |
+|---|---|---|
+| runningCeiling | 100 | Per machine, propose stopping least recently active unprotected sessions above the ceiling. |
+| pauseAfterIdle | 1d | Propose stopping a running session whose last conversation activity is older than this. |
+| hideAfterIdle | 14d | CLI list filter only; --all includes older rows. The monitor table includes all rows. |
+| pauseWhenWorkspaceGone | true | Propose stopping a local session whose folder no longer exists. Remote paths are not checked locally. |
+| protect.needsInput / working / pinned | true | Exclude questions, open turns and pinned sessions. |
+| protect.attached | true | Reserved for inventories that report attachment; current daemon inventory does not. |
+
+Offline sessions, unknown activity, the monitor itself and unavailable controls are also protected.
+A stopped session is retained by its daemon and remains openable when that engine supports resume.
+There is no retire/forget rule and no transcript deletion.
+
+To review a threshold, edit the file while preserving comments, then run `hps pause --policy --machines`.
+`--apply` is an explicit action. The viewer's Cleanup button shows eligible rows and reasons before
+Stop reviewed sessions. If activity changes, the action refuses the stale target. Keep bulk operations
+within the person's approved scope; changing rules is a separate decision.
diff --git a/store/agents/harness-monitor/skills/fleet-operations/references/signals.md b/store/agents/harness-monitor/skills/fleet-operations/references/signals.md
index 55dc09aa0..25a448a95 100644
--- a/store/agents/harness-monitor/skills/fleet-operations/references/signals.md
+++ b/store/agents/harness-monitor/skills/fleet-operations/references/signals.md
@@ -1,59 +1,23 @@
-# The signals, and which ones lie
+# Monitor signals
-Every column in `hps` comes from somewhere, and three of the obvious sources are wrong in ways that
-would pause a working agent or keep a dead one running. This is the reference for explaining a number.
+Every machine answers through its owning Harness daemon. The monitor requests `agents_list` with
+`includeStopped` and `monitor`. Older daemons may omit monitor metadata; show Unknown rather than
+guessing from CPU, terminal text or file modification times.
-## idle — time since the last turn
-
-**Source:** the tail of the engine's own transcript, newest line first, stopping at the first line that is
-a real turn (Claude Code's `user` / `assistant`, a Codex rollout's `message`). Falls back to the daemon's
-`lastHookAt` when a transcript has no turn in its tail, and to the registration time when there is none.
-
-**What it is not, and why:**
-
-| Tempting source | Why it lies |
-|---|---|
-| the registry's `updatedAt` | the daemon reconciles every five seconds; every row reads "now" |
-| the transcript's mtime | a *running* engine appends bookkeeping — task notifications, away summaries, queue operations — to conversations nobody has touched in days. Measured on one real machine: 34 of 85 harnesses looked an hour old when only 5 were |
-| the pane's tmux activity | a spinner redraw is activity, and an engine that exited hours ago leaves its last frame on screen forever |
-
-Output is not a turn. If someone points at recent output on a row that reads `3d`, that is the whole
-explanation, and the row is right.
-
-## mem — what pausing would hand back
-
-The engine's whole process subtree, resident. Say "held", not "used": resident sets share pages, so a sum
-across rows is an upper bound, not an exact figure. It is still the right number for the decision, because
-the decision is comparative.
-
-## state — running, paused, shell, gone
-
-Decided in one place (`lib/inventory.mjs`) from two facts: is the pane still in tmux, and is an engine
-process running under it. `paused` is the daemon's own "dormant but still viewable agent" — a state
-Harness already has, not one Harness Monitor invented.
-
-## working — do not pause this
-
-CPU on the engine subtree above 5%, or a turn in the last 90 seconds, or output drawn in the last 60. All
-proxies, and all used only to *refuse* an action, never to claim in the interface that an agent is busy.
-
-## waiting on you — a guess, and labelled as one
-
-Read from the pane's last screen against a list of prompt shapes (`(y/n)`, a numbered choice list, "do you
-want to proceed"). Broad on purpose: a false positive costs a harness that stays running, a false negative
-costs a question paused before it was read. The app's own **Agents needing input** (⇧⌘I) is the authority —
-say so when it matters.
-
-## Where each fact comes from
-
-| Fact | Source |
+| Field | Source and limits |
|---|---|
-| who the agents are, their panes, engines, models, projects, branches | the daemon, over `ws://127.0.0.1:18473/api/local-ws` (`agents_list`) |
-| transcript paths, hook timestamps | `~/.harness/cli/data/registry.json`, read only |
-| pane alive / dead / attached, last output | one `tmux list-panes -a` |
-| memory, CPU, process count | one `ps` snapshot, walked per pane |
-| the policy and pins | `~/.config/harness/policy.jsonc` |
-| resume tickets, the log | `~/.harness/monitor/` |
-
-Other machines answer `agents_list` through the same bridge, so they appear in the list — but pane facts,
-memory and every action are local to this computer. A remote row says so.
+| Identity | Composite machine ID and agent ID. Agent IDs alone are not fleet-wide identities. |
+| Working / Needs you | The daemon's open-turn and pending-question state, also used by app events. |
+| Done / Failed | Live turn completion events, cleared by a new turn or opening the session. Lost after daemon restart. |
+| Starting / Stopped | Daemon launch and lifecycle state. Offline means the machine or inventory request is unavailable. |
+| Last active | The agent frame's updatedAt (real conversation activity), falling back to createdAt. Never registry touchedAt or transcript mtime. |
+| RAM | Sum of RSS for the recorded process and its children after matching PID and start marker. Shared pages may be counted twice; not a promise of memory freed. |
+| CPU | Process-tree percentage from ps. May exceed 100% across cores; OS averaging differs. |
+| Tokens | Daemon tokenUsage.totalTokens. Missing usage remains unknown. |
+| Model / project / branch | Daemon agent metadata. A path from another machine is not a local filesystem path. |
+| Pins / rules | Local ~/.config/harness/policy.jsonc, applied to the fleet visible from this monitor. |
+
+The viewer refreshes local readings while visible and remote readings less often. Refresh asks every
+online machine. Offline rows keep their last metadata but disable actions and clear resource readings.
+A reconnected machine must answer again before its controls become available. Cleanup rechecks live
+activity; manual stops also revalidate conversation identity.
diff --git a/store/agents/harness-monitor/store.json b/store/agents/harness-monitor/store.json
index c6f79b977..616b45d39 100644
--- a/store/agents/harness-monitor/store.json
+++ b/store/agents/harness-monitor/store.json
@@ -1,10 +1,10 @@
{
"license": "MIT",
- "tagline": "htop for your harnesses: pause the idle ones, resume any of them",
+ "tagline": "Manage sessions across your machines",
"examples": [
{
"prompt": "Show me every harness on this machine, then pause everything nobody has touched in a day.",
- "caption": "The fleet, freshest first · a dry run, then the pause, then how much memory came back"
+ "caption": "Review idle sessions, then stop the approved ones while keeping their history"
},
{
"prompt": "Which of my harnesses are actually doing something right now, and which are just holding memory?",
@@ -12,7 +12,7 @@
},
{
"prompt": "Which harnesses are on a branch that already merged? Pause those and tell me what you kept.",
- "caption": "Paused with the reason recorded; each one resumes with its conversation"
+ "caption": "Stopped with the reason recorded and saved launch settings retained"
}
]
}
diff --git a/store/agents/harness-monitor/template/NOTES.md b/store/agents/harness-monitor/template/NOTES.md
index a013bfb49..0ed7f8957 100644
--- a/store/agents/harness-monitor/template/NOTES.md
+++ b/store/agents/harness-monitor/template/NOTES.md
@@ -1,12 +1,11 @@
-# Your harnesses
+# Harness Monitor
-This folder is Harness Monitor's workspace. Almost nothing lives here, on purpose — there is one fleet per
-machine, so there is one policy per machine:
+The session table works without sending a prompt. Use Ask assistant to reveal OpenCode when needed.
-- **The rules:** `~/.config/harness/policy.jsonc` — commented, hand-edited, read on every refresh. Or drag
- the two lines in the pane. Preview a change without moving anything: `hps pause --policy`.
-- **The resume tickets:** `~/.harness/monitor/paused.json` — which conversation each paused harness had.
-- **What happened, and why:** `~/.harness/monitor/log.jsonl`.
+New monitors default to Muse Spark 1.3 Contributor Free for both main and auxiliary requests. This is a
+limited-time free offer whose prompts and responses may train Meta models. Choose another model with
+`/models` before asking if those terms do not suit your work. A missing free model is an error, not
+permission to switch to a paid model.
-The only file Harness Monitor writes here is `.harness/verdict.json`, the pane header. Deleting this folder
-loses nothing.
+Cleanup is always explicit. Stopping retains history and launch settings; Open resumes through the
+owning daemon. No automatic cleanup runs while you are away.
diff --git a/store/agents/harness-monitor/test/actions.test.mjs b/store/agents/harness-monitor/test/actions.test.mjs
index bba262356..1d9289fde 100644
--- a/store/agents/harness-monitor/test/actions.test.mjs
+++ b/store/agents/harness-monitor/test/actions.test.mjs
@@ -1,161 +1,83 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { pause, resume } from '../lib/actions.mjs'
-import { normalizePolicy } from '../lib/policy.mjs'
-import { HOUR, fakeTmux, pane, row, table } from './fixtures.mjs'
-
-const policy = normalizePolicy({})
-const gone = { send: () => {}, alive: () => false }
-const stubborn = { send: () => {}, alive: () => true }
-const nowait = async () => {}
-
-test('pause refuses a remote row: signals and pane facts are local', async () => {
- const result = await pause(row({ local: false, machine: 'studio' }), { policy })
- assert.equal(result.ok, false)
- assert.match(result.detail, /remote machine/)
-})
-
-test('pause refuses what the policy protects, and names the guard', async () => {
- for (const [field, expected] of [['pinned', /pinned/], ['needsInput', /waiting on you/], ['working', /mid-turn/], ['attached', /looking at it/]]) {
- const result = await pause(row({ [field]: true }), { policy, run: fakeTmux().run, signals: gone, wait: nowait })
- assert.equal(result.ok, false, field)
- assert.match(result.detail, expected)
- assert.match(result.detail, /--force/)
- }
-})
-
-test('pause refuses a pane that looks like it is waiting for an answer', async () => {
- const tmux = fakeTmux({ screen: 'Do you want to proceed?\n❯ 1. Yes\n 2. No' })
- const result = await pause(row(), { policy, run: tmux.run, signals: gone, wait: nowait })
- assert.equal(result.ok, false)
- assert.match(result.detail, /waiting for an answer/)
- assert.equal(tmux.calls.some((call) => call[0] === 'set-option'), false, 'nothing was touched')
-})
-
-test('pause says nothing to do when it is already paused', async () => {
- const result = await pause(row({ state: 'paused' }), { policy })
+import { mergeRows } from '../lib/inventory.mjs'
+import { frame } from './fixtures.mjs'
+const observed = Date.now()
+const agent = extra => frame({ updatedAt: observed, resumeMode: 'conversation', monitor: { activity: 'idle', activityKnown: true }, ...extra })
+const row = extra => mergeRows([agent(extra)], { machine: { machineId: 'remote', name: 'Office' }, local: false })[0]
+const intent = async () => ({ creationId: 'same-operation', path: '/fixture', existing: false })
+const clearIntent = async () => {}
+
+test('remote stop uses daemon identity, never a signal or tmux command', async () => {
+ const calls = []
+ const result = await pause(row(), { list: async () => [agent()], rpc: async (...args) => { calls.push(args); return { deleted: true } } })
assert.equal(result.ok, true)
- assert.equal(result.already, true)
+ assert.deepEqual(calls, [['remote', 'agent_delete', { agentId: 'a1' }]])
})
-
-test('pause holds the pane open before it signals, in that order', async () => {
- const tmux = fakeTmux({ dead: true, remainOnExit: 'off' })
- const sent = []
- const result = await pause(row(), { policy, run: tmux.run, signals: { send: (pid, signal) => sent.push([pid, signal]), alive: () => false }, wait: nowait })
- assert.equal(result.ok, true)
- assert.equal(result.paneDead, true)
- assert.deepEqual(sent, [[100, 'SIGTERM']])
- const order = tmux.calls.map((call) => call[0])
- assert.ok(order.indexOf('set-option') < order.indexOf('display-message'), 'the hold comes before the check')
- assert.match(result.detail, /scrollback/)
- assert.equal(result.freed, 400 * 1024 * 1024)
- assert.equal(result.ticket.sessionId, 's1-0123456789ab')
- assert.equal(result.ticket.engine, 'claude')
-})
-
-test('pause refuses an engine it would not be able to resume', async () => {
- const devin = await pause(row({ engine: 'devin' }), { policy, run: fakeTmux().run, signals: gone, wait: nowait })
- assert.equal(devin.ok, false)
- assert.match(devin.detail, /does not know how to resume devin/)
- const unbound = await pause(row({ sessionId: null }), { policy, run: fakeTmux().run, signals: gone, wait: nowait })
- assert.equal(unbound.ok, false)
- assert.match(unbound.detail, /nothing to resume/)
-})
-
-test('a pane that fell back to a shell has the window setting put back', async () => {
- const tmux = fakeTmux({ dead: false, command: 'zsh', remainOnExit: 'off' })
- const result = await pause(row(), { policy, run: tmux.run, signals: gone, wait: nowait })
- assert.equal(result.ok, true)
- assert.equal(result.paneDead, false)
- const holds = tmux.calls.filter((call) => call[0] === 'set-option')
- assert.deepEqual(holds.map((call) => call.at(-1)), ['on', 'off'])
-})
-
-test('an engine that will not leave is left running, and said so', async () => {
- const tmux = fakeTmux({ remainOnExit: 'off' })
- const result = await pause(row(), { policy, run: tmux.run, signals: stubborn, wait: nowait, graceMs: 10 })
- assert.equal(result.ok, false)
- assert.match(result.detail, /still running, untouched/)
- assert.deepEqual(tmux.calls.filter((call) => call[0] === 'set-option').map((call) => call.at(-1)), ['on', 'off'])
+test('cleanup rechecks live questions, working and unknown activity', async () => {
+ for (const activity of ['needsInput', 'working', null]) {
+ let wrote = false
+ const result = await pause(row(), { list: async () => [agent({ monitor: activity ? { activity, activityKnown: true } : null })], rpc: async () => { wrote = true } })
+ assert.equal(result.ok, false); assert.equal(wrote, false)
+ }
})
-
-test('--force ends it after the grace, and only then', async () => {
- const sent = []
- const tmux = fakeTmux({ dead: true })
- const result = await pause(row(), {
- policy, run: tmux.run, wait: nowait, graceMs: 10, force: true, killAfterGrace: true,
- signals: { send: (pid, signal) => sent.push(signal), alive: () => true },
- })
- assert.equal(result.ok, true)
- assert.deepEqual(sent, ['SIGTERM', 'SIGKILL'])
+test('explicit single stop can stop work; self and rotated sessions remain protected', async () => {
+ assert.equal((await pause(row(), { force: true, list: async () => [agent({ monitor: { activity: 'working', activityKnown: true } })], rpc: async () => ({ deleted: true }) })).ok, true)
+ for (const changed of [{ sessionId: 'another-conversation' }, { dsh: 'autonomous/harness-monitor' }]) {
+ let wrote = false
+ assert.equal((await pause(row(), { force: true, list: async () => [agent(changed)], rpc: async () => { wrote = true } })).ok, false)
+ assert.equal(wrote, false)
+ }
})
-
-test('resume types the engine\'s own resume command into the pane, and waits for it to come up', async () => {
- const tmux = fakeTmux({ dead: false, command: 'zsh' })
- const alivePane = new Map([['%1', pane({ pid: 100 })]])
- const result = await resume(row({ state: 'paused', sessionId: 'abcd1234-aaaa-bbbb-cccc-0123456789ab' }), {
- run: tmux.run, wait: async () => {}, inventory: { panes: async () => alivePane, processTable: async () => table() },
- })
+test('a lost stop reply is uncertain, not retried', async () => {
+ let writes = 0
+ const result = await pause(row(), { list: async () => [agent()], rpc: async () => { writes++; throw Error('Reply lost') } })
+ assert.equal(writes, 1); assert.equal(result.ok, false)
+})
+test('resume checks the same durable receipt after a lost reply', async () => {
+ const calls = []
+ const result = await resume(row({ status: 'stopped' }), { intent, clearIntent, list: async () => [agent({ status: 'stopped' })], rpc: async (machine, type, payload) => {
+ calls.push([machine, type, payload]); if (type === 'agent_resume') throw Error('Disconnected')
+ return { state: 'created', agent: { id: 'a1' } }
+ } })
assert.equal(result.ok, true)
- assert.equal(result.resumed, true)
- const typed = tmux.calls.find((call) => call[0] === 'send-keys')
- assert.deepEqual(typed, ['send-keys', '-t', '%1', 'claude --resume abcd1234-aaaa-bbbb-cccc-0123456789ab', 'Enter'])
- assert.match(result.detail, /same pane/)
-})
-
-test('codex resumes with a subcommand, not a flag', async () => {
- const tmux = fakeTmux({ command: 'zsh' })
- await resume(row({ state: 'paused', engine: 'codex', sessionId: '7f3c2a10-5b8e-4d21-9a6f-3e0d1c2b4a58' }), {
- run: tmux.run, wait: async () => {}, inventory: { panes: async () => new Map([['%1', pane()]]), processTable: async () => table({ comm: '/usr/local/bin/codex' }) },
- })
- assert.deepEqual(tmux.calls.find((call) => call[0] === 'send-keys').at(-2), 'codex resume 7f3c2a10-5b8e-4d21-9a6f-3e0d1c2b4a58')
-})
-
-test('a dead pane is respawned before anything is typed into it', async () => {
- const tmux = fakeTmux({ dead: true })
- await resume(row({ state: 'paused', sessionId: 'abcd1234-aaaa-bbbb-cccc-0123456789ab' }), {
- run: tmux.run, wait: async () => {}, inventory: { panes: async () => new Map([['%1', pane()]]), processTable: async () => table() },
- })
- const order = tmux.calls.map((call) => call[0])
- assert.ok(order.indexOf('respawn-pane') < order.indexOf('send-keys'), 'the pane gets a shell first')
-})
-
-test('an engine that never comes up is reported as a failure, with the command it typed', async () => {
- const tmux = fakeTmux({ command: 'zsh' })
- const result = await resume(row({ state: 'paused', sessionId: 'abcd1234-aaaa-bbbb-cccc-0123456789ab' }), {
- run: tmux.run, wait: async () => {}, waitMs: 3,
- inventory: { panes: async () => new Map([['%1', pane()]]), processTable: async () => table({ comm: '-zsh' }) },
- })
- assert.equal(result.ok, false)
- assert.match(result.detail, /did not come up/)
- assert.match(result.detail, /claude --resume/)
-})
-
-test('resume refuses when nothing recorded which conversation this was', async () => {
- const result = await resume(row({ state: 'paused', sessionId: null }), { run: fakeTmux().run })
- assert.equal(result.ok, false)
- assert.match(result.detail, /no session id/)
-})
-
-test('resume uses the ticket pause left behind when the row has forgotten its session', async () => {
- const tmux = fakeTmux({ command: 'zsh' })
- const result = await resume(row({ state: 'paused', sessionId: null, engine: 'terminal' }), {
- ticket: { sessionId: 'abcd1234-aaaa-bbbb-cccc-0123456789ab', engine: 'claude' },
- run: tmux.run, wait: async () => {}, inventory: { panes: async () => new Map([['%1', pane()]]), processTable: async () => table() },
- })
+ assert.deepEqual(calls.map(c => c[1]), ['agent_resume', 'agent_create_status'])
+ assert.equal(calls[0][2].creationId, calls[1][2].creationId)
+})
+test('unconfirmed saved intent is only checked, never launched again', async () => {
+ const calls = []
+ const result = await resume(row({ status: 'stopped' }), { intent: async () => ({ ...await intent(), existing: true }), clearIntent,
+ list: async () => [agent({ status: 'stopped' })], rpc: async (_, type) => { calls.push(type); return { state: 'unconfirmed' } } })
+ assert.equal(result.unconfirmed, true); assert.deepEqual(calls, ['agent_create_status'])
+})
+test('a reservation that never reached the daemon retries with the same receipt', async () => {
+ const calls = []
+ const result = await resume(row({ status: 'stopped' }), { intent: async () => ({ ...await intent(), existing: true }), clearIntent,
+ list: async () => [agent({ status: 'stopped' })], rpc: async (_, type, payload) => {
+ calls.push([type, payload.creationId]); return type === 'agent_create_status' ? { state: 'missing' } : { state: 'created', agent: { id: 'a1' } }
+ } })
assert.equal(result.ok, true)
- assert.match(tmux.calls.find((call) => call[0] === 'send-keys').at(-2), /^claude --resume /)
+ assert.deepEqual(calls, [['agent_create_status', 'same-operation'], ['agent_resume', 'same-operation']])
+})
+test('completed receipts are cleared, including old resumes followed by another stop', async () => {
+ for (const reply of [{ state: 'failed', failure: { code: 'NO_ENGINE', detail: 'Install OpenCode first.' } },
+ { state: 'created', agent: { id: 'a1', terminal: { available: false } } }]) {
+ let cleared = false
+ const result = await resume(row({ status: 'stopped' }), { intent: async () => ({ ...await intent(), existing: true }),
+ clearIntent: async () => { cleared = true }, list: async () => [agent({ status: 'stopped' })], rpc: async () => reply })
+ assert.equal(result.ok, false); assert.equal(cleared, true)
+ if (reply.failure) assert.equal(result.detail, reply.failure.detail)
+ }
})
-
-test('resume refuses a row whose pane is gone rather than inventing one', async () => {
- const result = await resume(row({ state: 'gone', pane: null }), { run: fakeTmux().run })
- assert.equal(result.ok, false)
- assert.match(result.detail, /pane is gone/)
+test('cleanup refuses a session with activity after the reviewed snapshot', async () => {
+ const result = await pause(row(), { list: async () => [agent({ updatedAt: observed + 1 })], rpc: async () => { throw Error('Must not stop') } })
+ assert.match(result.detail, /Activity changed/)
})
-
-test('nothing in this module can delete anything', async () => {
- const source = await (await import('node:fs/promises')).readFile(new URL('../lib/actions.mjs', import.meta.url), 'utf8')
- for (const word of ['kill-session', 'kill-pane', 'agent_delete', 'unlink', 'rm -rf']) {
- assert.equal(source.includes(word), false, `actions.mjs must not contain ${word}`)
- }
+test('concurrent resume calls share one operation; running sessions need no launch', async () => {
+ let writes = 0
+ const target = row({ status: 'stopped' }), options = { intent, clearIntent, list: async () => [agent({ status: 'stopped' })], rpc: async () => { writes++; return { state: 'created', agent: { id: 'a1' } } } }
+ const [a,b] = await Promise.all([resume(target, options), resume(target, options)])
+ assert.equal(a.ok, true); assert.equal(b.ok, true); assert.equal(writes, 1)
+ assert.equal((await resume(row(), { list: async () => [agent()], rpc: async () => { throw Error('Must not send') } })).ok, true)
})
diff --git a/store/agents/harness-monitor/test/inventory.test.mjs b/store/agents/harness-monitor/test/inventory.test.mjs
index 0571dfcec..ca7b1c4ed 100644
--- a/store/agents/harness-monitor/test/inventory.test.mjs
+++ b/store/agents/harness-monitor/test/inventory.test.mjs
@@ -1,111 +1,66 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { mergeRows, parseModel, projectOf, resolveRef, summarize, tilde } from '../lib/inventory.mjs'
-import { DAY, HOME, HOUR, frame, pane, row, table } from './fixtures.mjs'
+import { collect, mergeRows, parseModel, resolveRef, rowId, tilde } from '../lib/inventory.mjs'
+import { frame, HOME, HOUR } from './fixtures.mjs'
+const now = Date.now(), machine = { machineId: 'm1', name: 'Office' }
+const agent = extra => frame({ resumeMode: 'conversation', monitor: { activity: 'idle', activityKnown: true }, ...extra })
+const merge = (extra = {}, options = {}) => mergeRows([agent(extra)], { machine, now, ...options })[0]
-const now = Date.now()
-const base = { paneRows: new Map([['%1', pane()]]), table: table(), now, home: HOME }
-
-test('a runtime profile is read back as a model and an effort', () => {
- assert.deepEqual(parseModel('runtime-v1:a1:claude:opus-5@high'), { model: 'opus-5', effort: 'high' })
- assert.deepEqual(parseModel('gpt-6-astra'), { model: 'gpt-6-astra', effort: null })
- assert.deepEqual(parseModel(null), { model: null, effort: null })
+test('machine and agent form the identity, including stopped work', () => {
+ const a = merge({ status: 'stopped' }), b = merge({}, { machine: { machineId: 'm2' } })
+ assert.equal(a.id, rowId('m1', 'a1')); assert.notEqual(a.id, b.id)
+ assert.equal(a.state, 'paused'); assert.equal(a.activity, 'stopped'); assert.equal(a.canStop, false); assert.equal(a.canOpen, true)
+ assert.equal(a.engine, 'claude'); assert.equal(a.sessionId, 's1')
})
-
-test('paths are shown against the home they belong to', () => {
- assert.equal(tilde(`${HOME}/code/widgets`, HOME), '~/code/widgets')
- assert.equal(tilde('/opt/thing', HOME), '/opt/thing')
- assert.equal(tilde('', HOME), '')
+test('activity and last active use owning daemon facts, not process guesses', () => {
+ const row = merge({ updatedAt: now - 2 * HOUR, monitor: { activity: 'needsInput', activityKnown: true, cpu: 0 } })
+ assert.equal(row.needsInput, true); assert.equal(row.activity, 'needsInput'); assert.equal(row.idleMs, 2 * HOUR)
+ assert.equal(merge({ monitor: undefined }).activity, 'unknown')
})
-
-test('a project without a frame is named, not left blank', () => {
- assert.equal(projectOf({ project: null }).project, 'unknown')
- assert.equal(projectOf(frame()).project, 'widgets')
+test('unknown is not zero, offline retains metadata and disables actions', () => {
+ const unknown = merge(); assert.equal(unknown.cpu, null); assert.equal(unknown.rssBytes, null); assert.equal(unknown.tokens, null)
+ const zero = merge({ monitor: { activity: 'idle', activityKnown: true, cpu: 0, rssBytes: 0 }, tokenUsage: { totalTokens: 0 } })
+ assert.equal(zero.cpu, 0); assert.equal(zero.tokens, 0)
+ const offline = merge({}, { online: false }); assert.equal(offline.activity, 'offline'); assert.equal(offline.canOpen, false); assert.equal(offline.canStop, false)
})
-
-test('state comes from the pane and the process, not from the daemon status', () => {
- const running = mergeRows([frame()], base)[0]
- assert.equal(running.state, 'running')
-
- const paused = mergeRows([frame()], { ...base, table: table({ comm: '-zsh' }) })[0]
- assert.equal(paused.state, 'paused')
- assert.equal(paused.rssBytes, 0)
-
- const gone = mergeRows([frame()], { ...base, paneRows: new Map() })[0]
- assert.equal(gone.state, 'gone')
+test('monitor cannot stop itself, and starts/failures outrank activity', () => {
+ assert.equal(merge({ dsh: 'autonomous/harness-monitor' }).canStop, false)
+ assert.equal(merge({ launch: { state: 'starting' } }).activity, 'starting')
+ assert.equal(merge({ launch: { state: 'failed', error: 'RESUME_UNCONFIRMED' } }).activity, 'needsInput')
})
-
-test('idle comes from the last turn, never from the transcript mtime the daemon sends', () => {
- const turns = new Map([['a1', now - 5 * DAY]])
- const rows = mergeRows([frame({ updatedAt: now })], { ...base, turns, registry: new Map() })
- assert.equal(rows[0].idleMs, 5 * DAY)
- assert.equal(rows[0].idle, '5d')
+test('cached remote rows survive disconnect; reconnection refreshes and unlinked machines disappear', async () => {
+ const remote = { at: 0, answers: new Map() }; let online = true, linked = true, reads = 0
+ const options = { remote, remoteIntervalMs: 0, reportMachines: async () => ({ machines: linked ? [{ machineId: 'm1', name: 'Office', online }] : [] }),
+ agentsFor: async () => { reads++; return [agent()] } }
+ assert.equal((await collect(options)).rows[0].canOpen, true)
+ online = false
+ assert.equal((await collect(options)).rows[0].activity, 'offline'); assert.equal(reads, 1)
+ online = true; await collect(options); assert.equal(reads, 2)
+ linked = false; assert.equal((await collect(options)).rows.length, 0)
})
-
-test('with no turn to read, the daemon last hook is next, and registration last', () => {
- const registry = new Map([['a1', { lastHookAt: now - 2 * HOUR, transcriptPath: '/nope' }]])
- assert.equal(mergeRows([frame()], { ...base, registry })[0].idleMs, 2 * HOUR)
- const created = now - 9 * DAY
- const bare = mergeRows([frame({ createdAt: created })], { ...base, registry: new Map() })[0]
- assert.equal(bare.idleMs, now - created)
+test('remote read failures keep rows but never leave enabled controls', async () => {
+ const remote = { at: 0, answers: new Map([['m1', [agent()]]]) }
+ const result = await collect({ remote, remoteIntervalMs: 0, reportMachines: async () => ({ machines: [{ ...machine, online: true }] }), agentsFor: async () => { throw Error('Disconnected') } })
+ assert.equal(result.rows[0].activity, 'offline'); assert.equal(result.degraded, true)
})
-
-test('a remote row is marked, and carries no local facts it cannot know', () => {
- const rows = mergeRows([frame()], { ...base, local: false, machine: { name: 'studio', machineId: 'm2' } })
- assert.equal(rows[0].local, false)
- assert.equal(rows[0].machine, 'studio')
- assert.equal(rows[0].rssBytes, 0)
- assert.equal(rows[0].enginePid, null)
- assert.equal(rows[0].state, 'running') // the daemon's word for it is all there is
+test('reconnect and failed reads refresh before the regular remote interval', async () => {
+ const remote = { at: 0, answers: new Map() }; let now = 1000, online = true, fail = false, reads = 0
+ const options = { remote, remoteIntervalMs: 15_000, reportMachines: async () => ({ machines: [{ ...machine, online }] }),
+ agentsFor: async () => { reads++; if (fail) throw Error('Disconnected'); return [agent()] } }
+ const read = () => collect({ ...options, now: now++ })
+ await read(); await read(); assert.equal(reads, 1)
+ online = false; assert.equal((await read()).rows[0].activity, 'offline')
+ online = true; fail = true; assert.equal((await read()).rows[0].canOpen, false); assert.equal(reads, 2)
+ fail = false; assert.equal((await read()).rows[0].canOpen, true); assert.equal(reads, 3)
})
-
-test('working is a refusal signal, and CPU or a fresh turn is enough for it', () => {
- const busy = mergeRows([frame()], { ...base, table: table({ cpu: 40 }), turns: new Map([['a1', now - 9 * DAY]]) })[0]
- assert.equal(busy.working, true)
- const quiet = mergeRows([frame()], { ...base, paneRows: new Map([['%1', pane({ lastOutput: now - 4 * HOUR })]]), turns: new Map([['a1', now - 9 * DAY]]) })[0]
- assert.equal(quiet.working, false)
-})
-
-test('the summary counts what the gauges show', () => {
- const rows = [row({ id: 'a' }), row({ id: 'b', state: 'paused', rssBytes: 0 }), row({ id: 'c', state: 'gone', rssBytes: 0 }), row({ id: 'd', needsInput: true })]
- const summary = summarize(rows)
- assert.equal(summary.total, 4)
- assert.equal(summary.running, 2)
- assert.equal(summary.paused, 1)
- assert.equal(summary.gone, 1)
- assert.equal(summary.needsInput, 1)
- assert.equal(summary.held, 800 * 1024 * 1024)
-})
-
-test('a ref is a row number, a pane, an id prefix, a name, or a unique substring', () => {
- const rows = [row({ id: 'abc123', name: 'widgets', title: 'Fix the reconciler' }), row({ id: 'def456', name: 'gadgets', pane: '%9', title: 'Ship the thing' })]
- assert.equal(resolveRef('1', rows).row.id, 'abc123')
- assert.equal(resolveRef('%9', rows).row.id, 'def456')
- assert.equal(resolveRef('abc', rows).row.id, 'abc123')
- assert.equal(resolveRef('gadgets', rows).row.id, 'def456')
- assert.equal(resolveRef('reconciler', rows).row.id, 'abc123')
- assert.match(resolveRef('3', rows).error, /no row 3/)
- assert.match(resolveRef('%7', rows).error, /pane %7/)
- assert.match(resolveRef('gets', rows).error, /matches 2 harnesses/)
- assert.match(resolveRef('', rows).error, /Name a harness/)
-})
-
-test('a paused row describes itself from the ticket the daemon threw away', () => {
- // Measured against a real pause: the daemon rewrites the row as a terminal and keeps only the cwd.
- const released = frame({ engine: 'terminal', sessionId: '', title: null, name: 'e2e-project' })
- const state = { pins: [], retired: {}, paused: { a1: { at: now - 2 * HOUR, sessionId: 'sess-0123456789ab', engine: 'claude', pane: '%1', title: 'Fix the reconciler' } } }
- const paused = mergeRows([released], { ...base, table: table({ comm: '-zsh' }), state })[0]
- assert.equal(paused.state, 'paused')
- assert.equal(paused.engine, 'claude')
- assert.equal(paused.title, 'Fix the reconciler')
- assert.equal(paused.sessionId, 'sess-0123456789ab')
- assert.equal(paused.pausedAt, now - 2 * HOUR)
+test('ambiguous IDs and pane numbers cannot choose another machine', () => {
+ const a = merge(), b = merge({}, { machine: { machineId: 'm2' } })
+ assert.match(resolveRef('a1', [a, b]).error, /matches 2/)
+ assert.match(resolveRef('%1', [a, b]).error, /matches 2/)
+ assert.equal(resolveRef(a.id, [a, b]).row, a)
+ assert.equal(resolveRef('1', [a, b]).row, a)
})
-
-test('a shell nobody paused is a shell, not a paused agent', () => {
- const shell = frame({ engine: 'terminal', sessionId: '', title: null })
- const row = mergeRows([shell], { ...base, table: table({ comm: '-zsh' }) })[0]
- assert.equal(row.state, 'terminal')
- assert.equal(summarize([row]).terminals, 1)
- assert.equal(summarize([row]).paused, 0)
+test('model and home parsing preserve provider IDs and directory boundaries', () => {
+ assert.deepEqual(parseModel('runtime-v1:a1:opencode:opencode/muse-spark-1.3-contributor-free@auto'), { model: 'opencode/muse-spark-1.3-contributor-free', effort: 'auto' })
+ assert.equal(tilde(HOME + 'other/x', HOME), HOME + 'other/x'); assert.equal(tilde(HOME + '/x', HOME), '~/x')
})
diff --git a/store/agents/harness-monitor/test/page.test.mjs b/store/agents/harness-monitor/test/page.test.mjs
index 085c78a1a..2ad3fafab 100644
--- a/store/agents/harness-monitor/test/page.test.mjs
+++ b/store/agents/harness-monitor/test/page.test.mjs
@@ -39,7 +39,7 @@ test('the page loads only files the server is willing to serve', async () => {
assert.match(server, new RegExp(`'/${file.replace('.', '\\.')}'`), `viewer.mjs does not serve ${file}`)
}
for (const file of await readdir(join(PACKAGE, 'viewer'))) {
- assert.ok(['index.html', 'app.js', 'app.css', 'scale.js'].includes(file), `unexpected file in viewer/: ${file}`)
+ assert.ok(['index.html', 'app.js', 'app.css', 'scale.js', 'table.js', 'icons'].includes(file), `unexpected file in viewer/: ${file}`)
}
})
@@ -82,14 +82,11 @@ test('every dom handle the script touches is one it looked up', async () => {
assert.deepEqual([...used].filter((name) => !defined.has(name)), [])
})
-test('every name the script imports from scale.js is one scale.js exports, and every one it uses is imported', async () => {
- const [js, scale] = await Promise.all([read('viewer/app.js'), read('viewer/scale.js')])
- const exported = new Set([...scale.matchAll(/export (?:const|function) (\w+)/g)].map((m) => m[1]))
- const imported = new Set(js.match(/import \{([^}]+)\} from '\.\/scale\.js'/)[1].split(',').map((name) => name.trim()))
- for (const name of imported) assert.ok(exported.has(name), `scale.js does not export ${name}`)
- for (const name of exported) {
- if (new RegExp(`\\b${name}\\b`).test(js.replace(/import \{[^}]+\} from '\.\/scale\.js'/, ''))) {
- assert.ok(imported.has(name), `app.js uses ${name} from scale.js without importing it`)
- }
+test('engine images reuse the desktop assets', async () => {
+ const icons = await readdir(join(PACKAGE, 'viewer/icons'))
+ for (const file of icons.filter(file => file.endsWith('.png'))) {
+ const source = file === 'claude.png' ? 'model-icons' : 'engine-icons'
+ const original = await readFile(join(PACKAGE, '../../../desktop/assets', source, file))
+ assert.deepEqual(await readFile(join(PACKAGE, 'viewer/icons', file)), original)
}
})
diff --git a/store/agents/harness-monitor/test/policy.test.mjs b/store/agents/harness-monitor/test/policy.test.mjs
index d32661135..fc52b93c5 100644
--- a/store/agents/harness-monitor/test/policy.test.mjs
+++ b/store/agents/harness-monitor/test/policy.test.mjs
@@ -88,6 +88,11 @@ test('the ceiling pauses the least recently active, and never a protected row',
assert.equal(totals.runningAfter, 3) // the pinned one still counts as running
})
+test('each machine has its own ceiling', () => {
+ const plan = decide([row({ id: 'local', machineId: 'm1' }), row({ id: 'remote', machineId: 'm2' })], { runningCeiling: 1 })
+ assert.equal(plan.totals.pause, 0)
+})
+
test('a ceiling of zero still cannot pause what is protected', () => {
const { entries } = decide([row({ id: 'p', pinned: true, idleMs: 3 * HOUR })], { runningCeiling: 0 })
assert.equal(entries[0].action, 'keep')
diff --git a/store/agents/harness-monitor/test/preview.mjs b/store/agents/harness-monitor/test/preview.mjs
new file mode 100644
index 000000000..5be82698c
--- /dev/null
+++ b/store/agents/harness-monitor/test/preview.mjs
@@ -0,0 +1,31 @@
+/** Synthetic browser-review fixture. No bridge, tmux, live inventory or model calls. */
+import { mkdtemp } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { createViewer } from '../viewer.mjs'
+import { mergeRows } from '../lib/inventory.mjs'
+const workspace = await mkdtemp(join(tmpdir(), 'harness-monitor-preview-'))
+process.env.HARNESS_MONITOR_CONFIG = join(workspace, 'policy.jsonc')
+process.env.HARNESS_MONITOR_STATE = join(workspace, 'state')
+const names = ['Replace Harness menu icon', 'Clarify completed-task form logic', 'Local debug', 'Ship workspace search', 'Review terminal reconnect', 'Add project browser', 'Render report', 'Fix session recovery']
+const activities = ['working', 'needsInput', 'done', 'idle', 'working', 'idle', 'failed', 'idle']
+const engines = ['codex', 'claude', 'opencode', 'cursor']
+const rows = Array.from({ length: 202 }, (_, i) => mergeRows([{
+ id: 'session-' + i, sessionId: 'conversation-' + i, name: names[i % names.length] + (i > 7 ? ' ' + (i + 1) : ''),
+ engine: engines[i % engines.length], status: i % 7 === 6 ? 'stopped' : 'active',
+ terminal: { available: true }, resumeMode: 'conversation', launch: { state: 'ready' },
+ project: { name: i % 2 ? 'openharness' : 'autonomous-harness', cwd: '/home/demo/code/openharness', branch: i % 3 ? 'fix/session-recovery' : 'main' },
+ selectedModel: i % 2 ? 'muse-spark-1.3-contributor-free' : 'gpt-6',
+ createdAt: new Date(Date.now() - 86400000 * 3).toISOString(), updatedAt: new Date(Date.now() - i * 85000).toISOString(),
+ tokenUsage: { totalTokens: i % 3 ? 57800000 : 3500000 },
+ monitor: { activity: activities[i % activities.length], activityKnown: true, cpu: i % 6 ? 3.4 : null, rssBytes: (i % 6 + 1) * 260 * 1024 ** 2, pid: 3400 + i },
+}], { machine: { machineId: i % 2 ? 'office' : 'm2', name: i % 2 ? 'office' : 'M2' }, local: false, online: i % 17 !== 16 })[0])
+const viewer = createViewer({ workspace, port: Number(process.env.PREVIEW_PORT || 0), intervalMs: 3000,
+ collect: async () => ({ rows, problems: [], machines: [] }),
+ verbs: { pause: async row => {
+ Object.assign(row, { state: 'paused', activity: 'stopped', canStop: false, cpu: 0, rssBytes: 0 })
+ return { ok: true, action: 'pause', id: row.id, name: row.name }
+ }, resume: async () => ({ ok: false, detail: 'Use the host integration fixture to resume.' }) },
+})
+console.log('Synthetic preview: http://127.0.0.1:' + await viewer.start())
+for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => viewer.close().then(() => process.exit(0)))
diff --git a/store/agents/harness-monitor/test/resume.test.mjs b/store/agents/harness-monitor/test/resume.test.mjs
deleted file mode 100644
index a4e7f5fec..000000000
--- a/store/agents/harness-monitor/test/resume.test.mjs
+++ /dev/null
@@ -1,57 +0,0 @@
-import assert from 'node:assert/strict'
-import { test } from 'node:test'
-import { readFile } from 'node:fs/promises'
-import { ENGINE_BIN, RESUME_ARGS, canResume, resumeCommand } from '../lib/resume.mjs'
-
-const SESSION = '2d9e6b41-8c07-4f3a-b512-6a1e0f7c9d33'
-
-test('the resume line is the one a person would type', () => {
- assert.equal(resumeCommand('claude', SESSION), `claude --resume ${SESSION}`)
- assert.equal(resumeCommand('codex', SESSION), `codex resume ${SESSION}`)
- assert.equal(resumeCommand('opencode', SESSION), `opencode --session ${SESSION}`)
- assert.equal(resumeCommand('amp', SESSION), `amp threads continue ${SESSION}`)
- assert.equal(resumeCommand('commandcode', SESSION), `cmd --resume ${SESSION}`)
- assert.equal(resumeCommand('cursor', SESSION), `cursor-agent --resume ${SESSION}`)
-})
-
-test('an engine with no resume is refused, so it is never paused either', () => {
- assert.equal(canResume('devin'), false)
- assert.equal(canResume('terminal'), false)
- assert.equal(canResume('claude'), true)
- assert.throws(() => resumeCommand('devin', SESSION), /does not know how to resume devin/)
-})
-
-test('a session id that is not one an engine wrote never reaches a shell', () => {
- for (const bad of ['; rm -rf /', 'a b', '$(whoami)', '`id`', "x'y", 'short', '', null, '../../etc/passwd']) {
- assert.throws(() => resumeCommand('claude', bad), /session id/, `accepted ${JSON.stringify(bad)}`)
- }
-})
-
-test('every engine that can be resumed has a binary to resume it with', () => {
- for (const engine of Object.keys(RESUME_ARGS)) {
- assert.ok(ENGINE_BIN[engine], `${engine} has resume args but no command name`)
- assert.match(resumeCommand(engine, SESSION), new RegExp(`^${ENGINE_BIN[engine]} `))
- }
-})
-
-/**
- * The two tables are mirrored from the daemon by hand, because this package installs on its own. This test
- * is the drift guard: it reads the daemon's own source when it is there, and skips when it is not (an
- * installed copy of the package, a release tarball).
- */
-test('the resume table still matches the daemon it was copied from', async (t) => {
- const candidates = ['../../../../cli/src/lib/engineLaunch.ts', '../../../../../cli/src/lib/engineLaunch.ts']
- let source = null
- for (const path of candidates) {
- try { source = await readFile(new URL(path, import.meta.url), 'utf8'); break } catch { /* not this layout */ }
- }
- if (!source) return t.skip('the daemon source is not beside this package')
- const block = source.match(/LAUNCH_RESUME_FLAG[^=]*=\s*\{([\s\S]*?)\n\}/)
- assert.ok(block, 'the daemon no longer declares LAUNCH_RESUME_FLAG the way this test reads it')
- const theirs = {}
- for (const line of block[1].split('\n')) {
- const match = /^\s*(\w+):\s*\[([^\]]*)\]/.exec(line)
- if (match) theirs[match[1]] = match[2].split(',').map((word) => word.trim().replace(/^'|'$/g, '')).filter(Boolean)
- }
- assert.deepEqual(RESUME_ARGS, theirs, 'lib/resume.mjs has drifted from the daemon\'s LAUNCH_RESUME_FLAG')
-})
diff --git a/store/agents/harness-monitor/test/server.test.mjs b/store/agents/harness-monitor/test/server.test.mjs
index c6b57acd0..b45c0b330 100644
--- a/store/agents/harness-monitor/test/server.test.mjs
+++ b/store/agents/harness-monitor/test/server.test.mjs
@@ -101,8 +101,8 @@ test('a verb with the token acts, records a receipt, and refreshes', async (t) =
const reply = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['a1'] })
assert.equal(reply.results.length, 1)
assert.deepEqual(done, [['pause', 'a1']])
- const tickets = JSON.parse(await readFile(join(process.env.HARNESS_MONITOR_STATE, 'paused.json'), 'utf8'))
- assert.ok(tickets.a1, 'the resume ticket was written down')
+ const tickets = await readFile(join(process.env.HARNESS_MONITOR_STATE, 'paused.json'), 'utf8').catch(() => '{}')
+ assert.deepEqual(JSON.parse(tickets), {}, 'saved lifecycle belongs to the daemon, not a second ticket book')
const log = await readFile(join(process.env.HARNESS_MONITOR_STATE, 'log.jsonl'), 'utf8')
assert.match(log, /"by":"pane"/)
})
@@ -116,6 +116,27 @@ test('pinning is a state edit and needs no engine at all', async (t) => {
assert.match(rules, /\/\/ Most engines running at once/, 'and the comments are still there')
assert.deepEqual(done, [])
})
+test('cleanup rechecks the plan while explicit row stops remain explicit', async (t) => {
+ let reads = 0
+ const { viewer, base, done } = await serve(undefined, { collect: async () => ({ rows: [row({ id: 'a1', idleMs: reads++ ? 0 : 2 * DAY })], problems: [] }) })
+ t.after(() => viewer.close())
+ const refused = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['a1'] })
+ assert.equal(refused.results[0].ok, false); assert.deepEqual(done, [])
+ const explicit = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['a1'], manual: true })
+ assert.equal(explicit.results[0].ok, true); assert.deepEqual(done, [['pause', 'a1']])
+})
+test('the reviewed conversation cannot be replaced by a newly eligible conversation', async (t) => {
+ const current = row({ id: 'a1', idleMs: 2 * DAY, sessionId: 'new-conversation' })
+ const { viewer, base, done } = await serve([current])
+ t.after(() => viewer.close())
+ for (const manual of [false, true]) {
+ const reply = await post(base, viewer.token, '/api/act', { verb: 'pause', ids: ['a1'], manual,
+ expected: [{ id: 'a1', sessionId: 'reviewed-conversation', lastActivity: current.lastActivity }] })
+ assert.equal(reply.results[0].ok, false)
+ assert.match(reply.results[0].detail, /changed since you reviewed/)
+ }
+ assert.deepEqual(done, [])
+})
test('a policy is validated before it is written', async (t) => {
const { viewer, base, workspace } = await serve()
diff --git a/store/agents/harness-monitor/test/state.test.mjs b/store/agents/harness-monitor/test/state.test.mjs
index 975a78f4c..0d3727021 100644
--- a/store/agents/harness-monitor/test/state.test.mjs
+++ b/store/agents/harness-monitor/test/state.test.mjs
@@ -100,17 +100,20 @@ test('pin and the resume ticket are the only edits, and each is reversible', ()
})
test('every action leaves a receipt, newest first', async () => {
- const dir = await workspace()
- await record(dir, { action: 'pause', id: 'a1', name: 'widgets', ok: true, detail: 'engine stopped' })
- await record(dir, { action: 'resume', id: 'a1', name: 'widgets', ok: true, detail: 'resumed' })
- const log = await readLog(dir)
+ const { dir, env } = await machine()
+ await record(dir, { action: 'pause', id: 'a1', name: 'widgets', ok: true, detail: 'engine stopped' }, env)
+ await record(dir, { action: 'resume', id: 'a1', name: 'widgets', ok: true, detail: 'resumed' }, env)
+ const log = await readLog(dir, {}, env)
assert.equal(log.length, 2)
assert.equal(log[0].action, 'resume')
assert.ok(log[0].at)
})
test('a log that cannot be written does not undo the action', async () => {
- await record('/nope/not/a/place', { action: 'pause', ok: true })
+ const { dir, env } = await machine()
+ const blocked = join(dir, 'file')
+ await writeFile(blocked, 'not a directory')
+ await record(null, { action: 'pause', ok: true }, { ...env, HARNESS_MONITOR_STATE: join(blocked, 'state') })
})
test('the pane header is ready only when the fleet is inside its policy', async () => {
diff --git a/store/agents/harness-monitor/test/table.test.mjs b/store/agents/harness-monitor/test/table.test.mjs
new file mode 100644
index 000000000..ac50e67ee
--- /dev/null
+++ b/store/agents/harness-monitor/test/table.test.mjs
@@ -0,0 +1,24 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { visibleRows, memory, number, age } from '../viewer/table.js'
+const rows = [
+ { id: 'm1/a', name: 'Agent 10', cpu: 5, activity: 'working', branch: 'fix/hello', machine: 'office' },
+ { id: 'm2/a', name: 'Agent 2', cpu: 0, activity: 'idle', branch: 'main', machine: 'studio' },
+ { id: 'm1/b', name: 'Unknown', cpu: null, activity: 'offline', branch: 'main', machine: 'office' },
+]
+test('sort is stable, numeric and keeps unknown measurements last in either direction', () => {
+ assert.deepEqual(visibleRows(rows, { sort: 'cpu', direction: -1 }).map(r => r.cpu), [5, 0, null])
+ assert.deepEqual(visibleRows(rows, { sort: 'cpu', direction: 1 }).map(r => r.cpu), [0, 5, null])
+ assert.deepEqual(visibleRows(rows, { sort: 'name', direction: 1 }).map(r => r.name), ['Agent 2', 'Agent 10', 'Unknown'])
+ assert.equal(rows[0].name, 'Agent 10')
+})
+test('search matches metadata and combines with plain status filters', () => {
+ assert.equal(visibleRows(rows, { query: 'HELLO' })[0].id, 'm1/a')
+ assert.equal(visibleRows(rows, { query: 'office', filter: 'offline' })[0].id, 'm1/b')
+ assert.equal(visibleRows(rows, { query: 'office', filter: 'idle' }).length, 0)
+})
+test('formatters distinguish zero from unknown and handle future timestamps', () => {
+ assert.equal(memory(null), '—'); assert.equal(memory(0), '0 MB')
+ assert.equal(number(null), '—'); assert.equal(number(0), '0')
+ assert.equal(age(null), '—'); assert.equal(age(1100, 1000), 'now')
+})
diff --git a/store/agents/harness-monitor/toolchain/doctor.sh b/store/agents/harness-monitor/toolchain/doctor.sh
index d4a8587cf..fa2798f13 100755
--- a/store/agents/harness-monitor/toolchain/doctor.sh
+++ b/store/agents/harness-monitor/toolchain/doctor.sh
@@ -1,15 +1,16 @@
#!/usr/bin/env bash
-# exit 0 = ready. Harness Monitor is ready when it can see the fleet: a Node to run on, tmux to read, and either
-# the daemon's local bridge or its registry file.
-set -u; cd "$(dirname "$0")/.."; bad=0
+# Read-only diagnosis: the daemon is authoritative, including for linked machines.
+set -u
+cd "$(dirname "$0")/.."
+bad=0
# shellcheck source=runtimes.sh
. toolchain/runtimes.sh
if harness_node 22; then echo "ok node $(node --version)"; else bad=1; fi
-if command -v tmux >/dev/null 2>&1; then echo "ok tmux $(tmux -V | awk '{print $2}')"; else echo "miss tmux is not on PATH — pausing needs it"; bad=1; fi
-seen=$(node toolchain/hps.mjs ls --json --all 2>/dev/null | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{const j=JSON.parse(s);console.log(j.rows.length)}catch{console.log("")}})')
+seen=$(node toolchain/hps.mjs ls --json --all 2>/dev/null | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{const j=JSON.parse(s);if(j.problems?.length)process.exit(1);console.log(j.rows.length)}catch{process.exit(1)}})')
if [ -n "${seen:-}" ]; then
- echo "ok the fleet is readable ($seen harnesses in view)"
+ echo "ok daemon inventory is readable ($seen harnesses in view)"
else
- echo "miss could not read the fleet — start Harness, or check that ~/.harness/cli/data/registry.json is readable"; bad=1
+ echo "miss could not read daemon inventory — start or reconnect Harness"
+ bad=1
fi
-exit $bad
+exit "$bad"
diff --git a/store/agents/harness-monitor/toolchain/hps.mjs b/store/agents/harness-monitor/toolchain/hps.mjs
index 5f168c086..d50b4d767 100755
--- a/store/agents/harness-monitor/toolchain/hps.mjs
+++ b/store/agents/harness-monitor/toolchain/hps.mjs
@@ -13,26 +13,27 @@
import { homedir } from 'node:os'
import { resolve } from 'node:path'
import { pause, resume } from '../lib/actions.mjs'
+import { closeBridges } from '../lib/bridge.mjs'
import { collect, resolveRef, summarize } from '../lib/inventory.mjs'
-import { capture } from '../lib/panes.mjs'
+import { capture, panes } from '../lib/panes.mjs'
import { DEFAULT_POLICY, decide, humanIdle, normalizePolicy, parseDuration } from '../lib/policy.mjs'
-import { clearPaused, gb, markPaused, readState, record, writeState, writeVerdict } from '../lib/state.mjs'
+import { gb, readState, record, writeVerdict } from '../lib/state.mjs'
import { footer, planLines, receiptLine, table } from '../lib/format.mjs'
const WORKSPACE = resolve(process.env.HARNESS_WORKSPACE || process.cwd())
const TTY = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR
const COLUMNS = Number(process.env.COLUMNS) || process.stdout.columns || 120
-const USAGE = `hps — every harness on this machine, running or paused
+const USAGE = `hps — sessions on this machine, running or stopped
hps the list, freshest first (like \`docker ps\`)
hps top the same list, refreshing
hps [--all] [--state running|paused|shell|gone] [--project NAME] [--engine NAME]
[--idle 4h] [--sort idle|mem|name|project] [--limit N] [--watch [SECONDS]]
- [--machines] also list every other machine you have linked (read-only from here)
+ [--machines] include linked machines for reads and actions
hps show <ref> one harness in full, with the last thing on its pane
- hps pause <ref…> the engine exits; pane, scrollback and conversation stay
- hps resume <ref…> the engine comes back where it left off
+ hps pause <ref…> stop the process and retain history and launch settings
+ hps resume <ref…> reopen with the saved engine configuration
hps pause --policy what the rules would do to the fleet right now, and why
hps pause --policy --apply do it
hps pause --idle 8h one threshold instead of all of them
@@ -43,9 +44,9 @@ const USAGE = `hps — every harness on this machine, running or paused
Add --json to any command. --force gets past a guard; --dry-run shows what would happen.
\`park\`/\`wake\` alias pause/resume. \`prune\`, \`gc\` and \`policy\` alias \`pause --policy\`.
- The rules are a config file: ~/.config/harness/policy.jsonc. Edit it, or drag the two lines in the pane.
+ The rules are a config file: ~/.config/harness/policy.jsonc. Edit it and review Cleanup in the table.
Nothing here writes it for you — a setter subcommand was only ever a worse text editor. To exempt one
- harness, put its id in "pins" (or click the pin in the pane).
+ harness, put its composite id from --json in "pins".
`
function parseArgs(argv) {
@@ -100,8 +101,7 @@ async function world({ includeRemote = false } = {}) {
return { state, policy, rows, problems, machines, degraded, plan, summary: summarize(rows) }
}
-async function commit(state, entries) {
- await writeState(WORKSPACE, state)
+async function commit(entries) {
for (const entry of entries) await record(WORKSPACE, entry)
}
@@ -160,19 +160,19 @@ async function main() {
}
if (command === 'show') {
- const { rows } = await world()
+ const { rows } = await world({ includeRemote: Boolean(flags.machines) })
const { row, error } = resolveRef(rest[0], rows)
if (error) die(error)
const screen = row.local && row.pane ? await capture(row.pane, { lines: Number(flags.lines) || 12 }) : ''
if (flags.json) { out(JSON.stringify({ ...row, screen }, null, 2)); return }
const pairs = [
- ['name', row.name], ['title', row.title ?? '—'], ['state', row.state + (row.needsInput ? ' (looks like it is waiting on you)' : '')],
- ['idle', `${humanIdle(row.idleMs)} (last turn ${new Date(row.lastActivity).toLocaleString()})`],
+ ['name', row.name], ['title', row.title ?? '—'], ['status', row.activity],
+ ['idle', row.lastActivity == null ? 'unknown' : `${humanIdle(row.idleMs)} (last active ${new Date(row.lastActivity).toLocaleString()})`],
['engine', `${row.engine}${row.model ? ` · ${row.model}${row.effort ? ` @${row.effort}` : ''}` : ''}`],
['folder', row.home], ['branch', row.branch ?? '—'], ['project', row.project],
- ['memory', row.rssBytes ? `${gb(row.rssBytes)} across ${row.procs} ${row.procs === 1 ? 'process' : 'processes'}` : '—'],
+ ['memory', row.rssBytes == null ? '—' : `${gb(row.rssBytes)} resident across the process tree`],
['pane', row.pane ? `${row.pane}${row.paneTarget ? ` (${row.paneTarget})` : ''}${row.dead ? ' · dead, held open' : ''}` : '—'],
- ['machine', row.machine + (row.local ? '' : ' (remote — read-only from here)')],
+ ['machine', row.machine + (row.local ? '' : ' (remote)')],
['harness', row.dshName ?? row.dsh ?? '—'], ['agent id', row.id],
['pinned', row.pinned ? 'yes — the policy leaves it alone' : 'no'],
]
@@ -183,7 +183,7 @@ async function main() {
}
if (['pause', 'resume'].includes(command)) {
- const { rows, policy, state, plan, summary, problems } = await world()
+ const { rows, policy, plan, summary, problems } = await world({ includeRemote: Boolean(flags.machines) })
let targets = []
// `resume --paused` is the undo button: everything this ever paused, back in one line. A dry run first,
// like every other bulk selection.
@@ -206,7 +206,10 @@ async function main() {
// thing a config file cannot tell you — what it would do to the fleet as it is right now.
if (flags['dry-run']) {
await writeVerdict(WORKSPACE, { summary, rows, plan: plan.entries, problems })
- if (flags.json) { out(JSON.stringify({ dryRun: true, command, totals: plan.totals, plan: plan.entries.filter((e) => e.action !== 'keep') }, null, 2)); return }
+ if (flags.json) {
+ const preview = flags.policy ? plan.entries.filter(e => e.action !== 'keep') : targets.map(row => ({ id: row.id, name: row.name, action: command, activity: row.activity, idleMs: row.idleMs }))
+ out(JSON.stringify({ dryRun: true, command, ...(flags.policy ? { totals: plan.totals } : {}), plan: preview }, null, 2)); return
+ }
if (flags.policy) {
out(planLines(plan.entries, { tty: TTY }))
out('')
@@ -218,19 +221,13 @@ async function main() {
return
}
- const options = { policy, force: Boolean(flags.force), killAfterGrace: Boolean(flags.force) }
+ const options = { policy, force: Boolean(flags.force) }
const results = []
- let next = state
for (const row of targets) {
- const ticket = state.paused?.[row.id] ?? null
- const result = command === 'pause' ? await pause(row, options) : await resume(row, { ticket })
- // The ticket is written before the receipt is printed: a pause whose session id was not recorded is
- // a harness nobody can resume, which is worse than one that is still running.
- if (result.ok && result.ticket) next = markPaused(next, row, result.ticket)
- if (result.ok && command === 'resume') next = clearPaused(next, row.id)
+ const result = command === 'pause' ? await pause(row, options) : await resume(row)
results.push(result)
}
- await commit(next, results.map((result) => ({ ...result, by: flags.by ?? 'cli' })))
+ await commit(results.map((result) => ({ ...result, by: flags.by ?? 'cli' })))
if (flags.json) { out(JSON.stringify({ results }, null, 2)); return }
for (const result of results) out(receiptLine(result, { tty: TTY }))
const freed = results.filter((r) => r.ok && r.freed).reduce((sum, r) => sum + r.freed, 0)
@@ -244,7 +241,8 @@ async function main() {
const { rows } = await world({ includeRemote: false })
const { row, error } = resolveRef(rest[0], rows)
if (error) die(error)
- if (!row.paneTarget) die('That harness has no pane on this machine.')
+ row.paneTarget = (await panes()).get(row.pane)?.target
+ if (!row.local || !row.paneTarget) die('That harness has no pane on this machine. Open it in Harness Monitor.')
if (flags.json) { out(JSON.stringify({ session: row.paneTarget.split(':')[0], pane: row.pane })); return }
// Hand the terminal over, the way `docker attach` and `screen -r` do. Printing a command for someone
// to paste is the worst of both: it is neither the answer nor the action.
@@ -264,4 +262,4 @@ async function main() {
die(`No such command: ${command}\n\n${USAGE}`, 2)
}
-main().catch((error) => die(error instanceof Error ? error.message : String(error)))
+main().finally(closeBridges).catch((error) => die(error instanceof Error ? error.message : String(error)))
diff --git a/store/agents/harness-monitor/toolchain/setup.sh b/store/agents/harness-monitor/toolchain/setup.sh
index 5a5a84809..366c7e22c 100755
--- a/store/agents/harness-monitor/toolchain/setup.sh
+++ b/store/agents/harness-monitor/toolchain/setup.sh
@@ -1,13 +1,11 @@
#!/usr/bin/env bash
# Runs once at install, cwd = the install dir. Harness Monitor installs nothing: it reads the daemon Harness
-# already runs, the tmux server it already uses, and the process table. All this needs is a Node.
+# already runs. All this needs is Node and the Harness CLI.
set -euo pipefail
cd "$(dirname "$0")/.."
# shellcheck source=runtimes.sh
. toolchain/runtimes.sh
harness_node 22 || exit 1
echo "ok node $(node --version) (the hps CLI and the pane)"
-if command -v tmux >/dev/null 2>&1; then echo "ok tmux $(tmux -V | awk '{print $2}') (where every harness lives)"
-else echo "warn tmux is not on PATH — Harness Monitor can list the fleet but not pause anything"; fi
if command -v harness >/dev/null 2>&1; then echo "ok harness CLI on PATH (the local bridge to the daemon)"
-else echo "warn the harness CLI is not on PATH — Harness Monitor will read the registry file instead, without models or branches"; fi
+else echo "warn the harness CLI is not on PATH — reconnect Harness before using the monitor"; fi
diff --git a/store/agents/harness-monitor/viewer.mjs b/store/agents/harness-monitor/viewer.mjs
index 6085a0549..07479176f 100644
--- a/store/agents/harness-monitor/viewer.mjs
+++ b/store/agents/harness-monitor/viewer.mjs
@@ -1,18 +1,4 @@
-/**
- * The pane beside the terminal: the fleet, live, and the four reversible verbs.
- *
- * A loopback server and nothing else — it binds 127.0.0.1, refuses a request whose Host or Origin is not
- * its own, and serves three static files with a self-only CSP. What it adds over the other store viewers
- * is a narrow write surface, because a fleet manager you can only read is a fleet manager nobody uses:
- *
- * POST /api/act pause · resume · retire · pin · unpin — every one of them reversible
- * POST /api/policy the thresholds, validated before they are written
- *
- * Both require the token this process mints at boot and hands to its own page; a page from anywhere else
- * does not have it. What is deliberately NOT here: deleting an agent, killing a tmux session, touching a
- * transcript. Those are irreversible, they already exist in the app behind their own confirmation, and a
- * pane full of eighty rows is the last place they belong.
- */
+/** Loopback viewer. Inventory and explicit actions require no model inference. */
import { randomBytes } from 'node:crypto'
import { createServer } from 'node:http'
@@ -23,19 +9,13 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
import { pause, resume } from './lib/actions.mjs'
import { closeBridges } from './lib/bridge.mjs'
import { collect as collectFleet, summarize, tilde } from './lib/inventory.mjs'
-import { capture, looksBlocked } from './lib/panes.mjs'
import { DEFAULT_POLICY, decide, normalizePolicy } from './lib/policy.mjs'
-import { clearPaused, markPaused, pin, readLog, readState, record, savePolicyValues, writeState, writeVerdict } from './lib/state.mjs'
+import { pin, readLog, readState, record, savePolicyValues, writeState, writeVerdict } from './lib/state.mjs'
const PACKAGE = dirname(fileURLToPath(import.meta.url))
const VERBS = new Set(['pause', 'resume', 'pin', 'unpin'])
-/** Panes to read per refresh when looking for an open prompt. Bounded because each one is a tmux call
- * and a fleet of eighty must cost the same as a fleet of eight: the candidates are the rows the policy
- * is about to act on, which are the only rows where the answer changes anything. */
-const BLOCKED_SCAN_LIMIT = 24
-
-export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntervalMs = 60_000, now = () => Date.now(), collect = collectFleet, scan = capture, verbs = { pause, resume } }) {
+export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntervalMs = 15_000, now = () => Date.now(), collect = collectFleet, verbs = { pause, resume } }) {
const token = randomBytes(24).toString('base64url')
const clients = new Set()
const cache = new Map()
@@ -70,16 +50,6 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
const policy = normalizePolicy(state.policy, { home: homedir() })
const { rows, problems, degraded } = await collect({ state, now: now(), includeRemote: true, cache, remote, remoteIntervalMs: forceRemote ? 0 : remoteIntervalMs })
- // Look for an open prompt only where it would change a decision, newest candidates first.
- const candidates = rows
- .filter((row) => row.local && row.state === 'running' && row.pane && row.idleMs >= policy.pauseAfterIdleMs / 2)
- .slice(0, BLOCKED_SCAN_LIMIT)
- await Promise.all(candidates.map(async (row) => {
- const screen = await scan(row.pane, { lines: 30 })
- row.needsInput = looksBlocked(screen)
- row.screenTail = screen.split('\n').filter((line) => line.trim()).slice(-3).join('\n').slice(0, 600)
- }))
-
const plan = decide(rows, policy, { home: homedir(), now: now() })
const summary = summarize(rows)
snapshot = {
@@ -132,32 +102,54 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
/** The write surface. One verb, up to 64 rows, and a receipt per row — the same library call the CLI
* makes, so a click and a typed command cannot behave differently. */
- async function act({ verb, ids }) {
+ let writes = Promise.resolve()
+ function write(operation) {
+ const result = writes.then(operation)
+ writes = result.catch(() => {})
+ return result
+ }
+ const act = payload => write(() => actOnce(payload))
+ async function actOnce({ verb, ids, manual = false, expected }) {
if (!VERBS.has(verb)) return { error: `Not a verb Harness Monitor has: ${verb}` }
- const targets = (Array.isArray(ids) ? ids : []).filter((id) => typeof id === 'string').slice(0, 64)
+ const targets = [...new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === 'string'))].slice(0, 64)
if (!targets.length) return { error: 'Name at least one harness.' }
+ const explicit = manual === true && targets.length === 1
+ const reviewed = new Map((Array.isArray(expected) ? expected : snapshot.rows).filter(row => row && typeof row.id === 'string').map(({ id, sessionId, lastActivity }) => [id, { sessionId, lastActivity }]))
+ // Bulk actions are restricted to what is still in the reviewed cleanup plan.
+ if (verb === 'pause' && !explicit) {
+ await polling
+ await poll({ immediate: true, forceRemote: true })
+ }
const state = await readState(workspace)
const policy = normalizePolicy(state.policy, { home: homedir() })
const rows = snapshot.rows.filter((row) => targets.includes(row.id))
if (!rows.length) return { error: 'Those harnesses are not in the current view. Refresh and try again.' }
let next = state
- const results = []
+ const results = targets.filter(id => !rows.some(row => row.id === id)).map(id => ({ id, name: id, action: verb, ok: false, refused: true, detail: 'This session is no longer in the current view.' }))
+ const eligible = new Set(snapshot.plan.filter(entry => entry.action === 'pause').map(entry => entry.id))
for (const row of rows) {
+ const review = reviewed.get(row.id)
+ if (verb === 'pause' && (!review || review.sessionId !== row.sessionId || (!explicit && review.lastActivity !== row.lastActivity))) {
+ results.push({ id: row.id, name: row.name, action: verb, ok: false, refused: true, detail: 'This session changed since you reviewed it. Refresh and review it again.' })
+ continue
+ }
+ if (verb === 'pause' && !explicit && !eligible.has(row.id)) {
+ results.push({ id: row.id, name: row.name, action: verb, ok: false, refused: true, detail: 'This session is no longer eligible for cleanup. Review the new plan.' })
+ continue
+ }
if (verb === 'pin' || verb === 'unpin') {
next = pin(next, row.id, verb === 'pin')
results.push({ ok: true, action: verb, id: row.id, name: row.name, detail: verb === 'pin' ? 'never paused by the policy' : 'the policy may pause it again' })
continue
}
- const ticket = state.paused?.[row.id] ?? null
- const result = verb === 'pause' ? await verbs.pause(row, { policy }) : await verbs.resume(row, { ticket })
- if (result.ok && result.ticket) next = markPaused(next, row, result.ticket)
- if (result.ok && verb === 'resume') next = clearPaused(next, row.id)
+ const result = verb === 'pause' ? await verbs.pause(row, { policy, force: explicit }) : await verbs.resume(row)
results.push(result)
}
- await writeState(workspace, next)
+ if (verb === 'pin' || verb === 'unpin') await writeState(workspace, next)
for (const result of results) await record(workspace, { ...result, by: 'pane' })
- await poll({ immediate: true })
+ await polling
+ await poll({ immediate: true, forceRemote: true })
return { results }
}
@@ -189,8 +181,8 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
for await (const chunk of req) { body += chunk; if (body.length > 64 * 1024) { json(res, 413, { error: 'Too large.' }); return } }
let payload; try { payload = JSON.parse(body || '{}') } catch { json(res, 400, { error: 'Send JSON.' }); return }
if (url.pathname === '/api/act') { json(res, 200, await act(payload)); return }
- if (url.pathname === '/api/policy') { json(res, 200, await savePolicy(payload.policy ?? {})); return }
- if (url.pathname === '/api/refresh') { await poll({ immediate: true, forceRemote: true }); json(res, 200, { ok: true }); return }
+ if (url.pathname === '/api/policy') { json(res, 200, await write(() => savePolicy(payload.policy ?? {}))); return }
+ if (url.pathname === '/api/refresh') { await polling; await poll({ immediate: true, forceRemote: true }); json(res, 200, { ok: true }); return }
json(res, 404, { error: 'Not found' }); return
}
@@ -210,11 +202,20 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
return
}
+ const icon = /^\/icons\/([a-z0-9-]+)\.png$/.exec(url.pathname)
+ if (icon) {
+ try {
+ const content = await readFile(join(PACKAGE, 'viewer', 'icons', icon[1] + '.png'))
+ res.writeHead(200, { ...headers, 'content-type': 'image/png' }); res.end(req.method === 'HEAD' ? undefined : content)
+ } catch { json(res, 404, { error: 'Icon not found' }) }
+ return
+ }
const assets = {
'/': ['index.html', 'text/html; charset=utf-8'],
'/app.js': ['app.js', 'text/javascript; charset=utf-8'],
'/app.css': ['app.css', 'text/css; charset=utf-8'],
'/scale.js': ['scale.js', 'text/javascript; charset=utf-8'],
+ '/table.js': ['table.js', 'text/javascript; charset=utf-8'],
}
if (!assets[url.pathname]) { json(res, 404, { error: 'Not found' }); return }
const [file, contentType] = assets[url.pathname]
diff --git a/store/agents/harness-monitor/viewer/app.css b/store/agents/harness-monitor/viewer/app.css
index 17849c860..b8a482a90 100644
--- a/store/agents/harness-monitor/viewer/app.css
+++ b/store/agents/harness-monitor/viewer/app.css
@@ -1,269 +1,61 @@
-/* Harness Monitor's pane. Light is the default palette; dark only redefines the tokens in the block below it —
- the contract the app's other viewers use (store/agents/autonomous-grid/viewer/app.css) — so the page
- follows the appearance the app is in rather than always rendering dark. Every colour past this block
- is one of these tokens.
-
- The look is deliberately terminal-adjacent: hairlines instead of borders, a monospace column grid,
- one accent, and no rounded-corner-and-shadow card anywhere near the dense list. The Harness Monitor is allowed
- to breathe; the Table is not. */
-:root {
- color-scheme: light;
- --bg: #ffffff;
- --panel: #f9f9f8;
- --panel-2: #f3f3f2;
- --hover: rgba(0, 0, 0, .04);
- --selected: rgba(0, 0, 0, .07);
- --line: rgba(0, 0, 0, .09);
- --line-strong: rgba(0, 0, 0, .16);
- --ink: #1a1a18;
- --ink-2: #5b5a54;
- --ink-3: #8b8a83;
- --live: #1f8a5f; /* running */
- --live-soft: rgba(31, 138, 95, .12);
- --gold: #a3711c; /* working right now */
- --gold-soft: rgba(163, 113, 28, .12);
- --amber: #b07403; /* waiting on you */
- --amber-soft: rgba(176, 116, 3, .14);
- --red: #b8402f;
- --shadow: 0 8px 24px rgba(0, 0, 0, .10), 0 1px 3px rgba(0, 0, 0, .06);
- --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
- --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, system-ui, sans-serif;
- --lane-h: 34px;
-}
-@media (prefers-color-scheme: dark) {
- :root:not([data-theme="light"]) {
- color-scheme: dark;
- --bg: #131312; --panel: #1a1a19; --panel-2: #212120;
- --hover: rgba(255, 255, 255, .05); --selected: rgba(255, 255, 255, .09);
- --line: rgba(255, 255, 255, .10); --line-strong: rgba(255, 255, 255, .20);
- --ink: #f2f1ee; --ink-2: #a8a6a0; --ink-3: #78766f;
- --live: #4ec38a; --live-soft: rgba(78, 195, 138, .14);
- --gold: #d6a344; --gold-soft: rgba(214, 163, 68, .16);
- --amber: #e0a33a; --amber-soft: rgba(224, 163, 58, .18);
- --red: #e4705c;
- --shadow: 0 10px 30px rgba(0, 0, 0, .5), 0 1px 3px rgba(0, 0, 0, .4);
- }
-}
-:root[data-theme="dark"] {
- color-scheme: dark;
- --bg: #131312; --panel: #1a1a19; --panel-2: #212120;
- --hover: rgba(255, 255, 255, .05); --selected: rgba(255, 255, 255, .09);
- --line: rgba(255, 255, 255, .10); --line-strong: rgba(255, 255, 255, .20);
- --ink: #f2f1ee; --ink-2: #a8a6a0; --ink-3: #78766f;
- --live: #4ec38a; --live-soft: rgba(78, 195, 138, .14);
- --gold: #d6a344; --gold-soft: rgba(214, 163, 68, .16);
- --amber: #e0a33a; --amber-soft: rgba(224, 163, 58, .18);
- --red: #e4705c;
-}
-
-* { box-sizing: border-box; }
-html, body { height: 100%; }
-body {
- margin: 0; background: var(--bg); color: var(--ink);
- font: 13px/1.45 var(--sans); -webkit-font-smoothing: antialiased;
-}
-#app { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
-.mono { font-family: var(--mono); font-variant-numeric: tabular-nums; }
-button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
-button:focus-visible, [tabindex]:focus-visible, input:focus-visible { outline: 2px solid var(--gold); outline-offset: 1px; }
-
-/* ── the bar ─────────────────────────────────────────────────────────────── */
-.bar {
- display: flex; align-items: center; gap: 14px; flex-wrap: wrap;
- padding: 8px 12px; border-bottom: 1px solid var(--line); background: var(--panel);
-}
-.identity { display: flex; align-items: baseline; gap: 8px; }
-.identity h1 { margin: 0; font-size: 13px; font-weight: 650; letter-spacing: .02em; }
-.mark { width: 9px; height: 9px; border-radius: 2px; background: var(--live); box-shadow: 0 0 0 3px var(--live-soft); }
-.where { color: var(--ink-3); font-size: 11px; }
-.gauges { display: flex; gap: 6px; flex: 1 1 auto; flex-wrap: wrap; }
-.gauge {
- display: inline-flex; align-items: baseline; gap: 5px; padding: 2px 8px;
- border: 1px solid var(--line); border-radius: 999px; background: var(--bg);
- font-family: var(--mono); font-size: 11px; color: var(--ink-2); white-space: nowrap;
-}
-.gauge b { color: var(--ink); font-weight: 600; font-variant-numeric: tabular-nums; }
-.gauge.live b { color: var(--live); }
-.gauge.attention { border-color: var(--amber); background: var(--amber-soft); }
-.gauge.attention b { color: var(--amber); }
-.tools { display: flex; align-items: center; gap: 8px; }
-.segmented { display: inline-flex; padding: 2px; gap: 2px; background: var(--panel-2); border-radius: 7px; }
-.segmented button { padding: 3px 11px; border-radius: 5px; font-size: 12px; color: var(--ink-2); }
-.segmented button[aria-selected="true"] { background: var(--bg); color: var(--ink); box-shadow: 0 1px 2px rgba(0, 0, 0, .10); }
-.filter { display: flex; align-items: center; gap: 5px; padding: 2px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); }
-.filter span { color: var(--ink-3); font-family: var(--mono); }
-.filter input { width: 190px; border: 0; background: none; color: inherit; font: 12px var(--sans); }
-.filter input::-webkit-search-cancel-button { display: none; }
-.ghost { padding: 3px 7px; border-radius: 6px; color: var(--ink-2); }
-.ghost:hover { background: var(--hover); color: var(--ink); }
-.primary { padding: 4px 12px; border-radius: 6px; background: var(--ink); color: var(--bg); font-size: 12px; font-weight: 550; }
-.primary:hover { opacity: .88; }
-
-.view { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
-[hidden] { display: none !important; }
-
-/* ── Lanes: the picture ───────────────────────────────────────────────────── */
-/* One lane per project, oldest work on the left, "now" hard against the right edge. The two policy
- rules are drawn as vertical lines you can drag: the fleet's geography IS the policy, which is the
- only way to judge a threshold without running it. */
-.lanes-head { display: grid; grid-template-columns: var(--label-w, 150px) 1fr; align-items: end; gap: 10px; padding: 7px 12px 0; }
-.axis-label, .lane-label { font: 10px/1 var(--mono); letter-spacing: .08em; color: var(--ink-3); text-transform: uppercase; }
-.axis { position: relative; height: 22px; border-bottom: 1px solid var(--line); }
-.axis .tick { position: absolute; bottom: 0; transform: translateX(-50%); font: 10px var(--mono); color: var(--ink-3); white-space: nowrap; }
-.axis .tick::after { content: ""; position: absolute; left: 50%; bottom: -1px; width: 1px; height: 4px; background: var(--line-strong); }
-.rule { position: absolute; top: -2px; bottom: -8px; width: 11px; margin-left: -5px; cursor: ew-resize; z-index: 4; }
-.rule-grip { position: absolute; inset: 0 4px; background: var(--ink-3); border-radius: 1px; }
-.rule[data-rule="pause"] .rule-grip { background: var(--gold); }
-.rule[data-rule="hide"] .rule-grip { background: var(--ink-3); }
-.rule-tag {
- position: absolute; top: -4px; left: 9px; padding: 1px 5px; border-radius: 3px;
- font: 9px/1.5 var(--mono); letter-spacing: .05em; text-transform: uppercase; white-space: nowrap;
- background: var(--panel-2); color: var(--ink-2); border: 1px solid var(--line);
-}
-.rule:hover .rule-tag, .rule.dragging .rule-tag { color: var(--ink); border-color: var(--line-strong); }
-
-.lanes { position: relative; flex: 1 1 auto; overflow-y: auto; padding: 4px 12px 14px; }
-/* The rules continue down through every lane, drawn once behind them all. */
-.lanes::before, .lanes::after {
- content: ""; position: absolute; top: 0; bottom: 0; width: 1px; pointer-events: none; z-index: 1;
- left: calc(var(--label-w, 150px) + 10px + var(--x) * (100% - var(--label-w, 150px) - 10px - 24px));
-}
-.lanes::before { --x: var(--pause-x, .5); background: linear-gradient(to bottom, var(--gold), transparent 88%); opacity: .55; }
-.lanes::after { --x: var(--hide-x, .15); background: linear-gradient(to bottom, var(--red), transparent 88%); opacity: .45; }
-
-.lane { display: grid; grid-template-columns: var(--label-w, 150px) 1fr; gap: 10px; align-items: start; }
-.lane + .lane { border-top: 1px dashed var(--line); }
-.lane-label {
- padding: 11px 0 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- text-transform: none; font-size: 11px; color: var(--ink-2); letter-spacing: 0;
-}
-.lane-label b { color: var(--ink); font-weight: 550; }
-.lane-label i { color: var(--ink-3); font-style: normal; }
-.track { position: relative; min-height: var(--lane-h); padding: 5px 0; }
-
-.chip {
- position: absolute; display: inline-flex; align-items: center; gap: 6px; max-width: 220px;
- padding: 3px 8px 3px 6px; border: 1px solid var(--line-strong); border-radius: 5px;
- background: var(--bg); color: var(--ink-2); cursor: pointer; z-index: 2;
- font-size: 11px; white-space: nowrap; transition: transform .1s ease, border-color .1s ease;
-}
-.chip:hover { transform: translateY(-1px); border-color: var(--ink-3); color: var(--ink); z-index: 3; }
-.chip .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--ink-3); flex: none; }
-.chip .what { overflow: hidden; text-overflow: ellipsis; }
-.chip .mem { font-family: var(--mono); font-size: 10px; color: var(--ink-3); }
-.chip[data-state="running"] { background: var(--live-soft); border-color: var(--live); color: var(--ink); }
-.chip[data-state="running"] .dot { background: var(--live); }
-.chip[data-working="true"] { background: var(--gold-soft); border-color: var(--gold); }
-.chip[data-working="true"] .dot { background: var(--gold); animation: breathe 2.4s ease-in-out infinite; }
-.chip[data-state="paused"] { border-style: dashed; background: transparent; }
-.chip[data-state="retired"] { border-style: dotted; background: transparent; color: var(--ink-3); }
-.chip[data-state="terminal"] { border-style: solid; border-color: var(--line); background: transparent; color: var(--ink-3); }
-.chip[data-state="gone"] { border-style: dotted; opacity: .5; text-decoration: line-through; }
-.chip[data-attention="true"] { border-color: var(--amber); background: var(--amber-soft); box-shadow: 0 0 0 3px var(--amber-soft); }
-.chip[data-attention="true"] .dot { background: var(--amber); }
-.chip[data-selected="true"] { outline: 2px solid var(--ink); outline-offset: 1px; }
-.chip[data-doomed="true"] { opacity: .62; }
-.chip[data-doomed="true"] .what { text-decoration: line-through solid var(--ink-3) 1px; }
-.chip .pin { color: var(--gold); font-size: 9px; }
-@keyframes breathe { 0%, 100% { opacity: 1; } 50% { opacity: .35; } }
-@media (prefers-reduced-motion: reduce) { .chip .dot { animation: none !important; } }
-
-.lanes-empty { margin: auto; text-align: center; color: var(--ink-2); padding: 40px; }
-.lanes-empty .big { font-size: 15px; color: var(--ink); margin: 0 0 6px; }
-
-/* ── the table ───────────────────────────────────────────────────────────── */
-/* htop's density, and htop's rules: fixed columns, tabular numerals, one line per thing, no wrapping,
- colour only where it carries a state that the glyph also carries. */
-.grid { flex: 1 1 auto; overflow: auto; font-family: var(--mono); font-size: 12px; }
-.grid table { width: 100%; border-collapse: collapse; }
-.grid thead th {
- position: sticky; top: 0; z-index: 2; background: var(--panel); border-bottom: 1px solid var(--line);
- padding: 5px 8px; text-align: left; font: 10px/1.6 var(--mono); letter-spacing: .08em;
- color: var(--ink-3); text-transform: uppercase; cursor: pointer; white-space: nowrap; user-select: none;
-}
-.grid thead th:hover { color: var(--ink); }
-.grid thead th[aria-sort] { color: var(--ink); }
-.grid thead th[aria-sort]::after { content: " ↓"; }
-.grid thead th[aria-sort="ascending"]::after { content: " ↑"; }
-.grid td { padding: 3px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; }
-.grid tbody tr { cursor: pointer; }
-.grid tbody tr:hover td { background: var(--hover); }
-.grid tbody tr[data-selected="true"] td { background: var(--selected); }
-.grid tbody tr[data-cursor="true"] td { box-shadow: inset 0 0 0 1px var(--line-strong); }
-.grid tbody tr[data-doomed="true"] .c-title { color: var(--ink-3); }
-.c-num { color: var(--ink-3); text-align: right; }
-.c-state { width: 1.6em; }
-.c-idle, .c-mem { text-align: right; }
-.c-title, .c-project { max-width: 34ch; overflow: hidden; text-overflow: ellipsis; }
-.c-dim { color: var(--ink-3); }
-/* The verb sits on the row and stays out of the way until the pointer is near it. It is in the DOM at all
- times, so keyboard focus finds it even when it is not painted. */
-.c-do { width: 5.5em; text-align: right; }
-.c-do button {
- padding: 1px 7px; border: 1px solid var(--line-strong); border-radius: 4px;
- font: 10.5px var(--mono); color: var(--ink-2); opacity: 0;
-}
-.grid tbody tr:hover .c-do button, .grid tbody tr[data-cursor="true"] .c-do button,
-.c-do button:focus-visible { opacity: 1; }
-.c-do button:hover { background: var(--hover); color: var(--ink); border-color: var(--ink-3); }
-.toggle[aria-pressed="true"] { background: var(--selected); color: var(--ink); }
-.st-running { color: var(--live); }
-.st-working { color: var(--gold); }
-.st-attention { color: var(--amber); }
-.st-paused, .st-retired, .st-gone, .st-terminal { color: var(--ink-3); }
-/* Memory as a bar behind the number: the one place this table spends a pixel on drawing, because "what
- would I get back" is the question the column exists to answer. */
-.membar { position: relative; }
-.membar i { position: absolute; right: 8px; top: 3px; bottom: 3px; background: var(--gold-soft); border-radius: 1px; }
-.membar span { position: relative; }
-
-/* ── status bar, policy bar, inspector, toast ────────────────────────────── */
-.statusbar {
- display: flex; align-items: center; gap: 12px; padding: 5px 12px;
- border-top: 1px solid var(--line); background: var(--panel); font-size: 11px; color: var(--ink-2);
-}
-.statusbar .keys { margin-left: auto; color: var(--ink-3); font-size: 10.5px; }
-.statusbar code { font: 10.5px var(--mono); color: var(--ink-2); user-select: all; }
-.statusbar kbd {
- font: 10px var(--mono); padding: 1px 4px; border: 1px solid var(--line); border-radius: 3px;
- background: var(--bg); color: var(--ink-2);
-}
-.actions { display: flex; gap: 6px; align-items: center; }
-.actions button { padding: 2px 9px; border: 1px solid var(--line-strong); border-radius: 5px; font-size: 11px; }
-.actions button:hover { background: var(--hover); }
-.actions .danger { color: var(--red); border-color: var(--red); }
-.policybar {
- display: flex; align-items: center; gap: 10px; padding: 7px 12px;
- border-top: 1px solid var(--gold); background: var(--gold-soft); font-size: 12px;
-}
-.policy-preview { flex: 1 1 auto; }
-
-.inspector {
- position: absolute; right: 0; top: 0; bottom: 0; width: min(380px, 78vw); z-index: 10;
- display: flex; flex-direction: column; gap: 0; overflow: auto;
- background: var(--panel); border-left: 1px solid var(--line-strong); box-shadow: var(--shadow);
-}
-.inspector header { display: flex; align-items: flex-start; gap: 8px; padding: 12px 14px 8px; }
-.inspector h2 { margin: 0; font-size: 13px; font-weight: 600; }
-.inspector .sub { color: var(--ink-3); font-size: 11px; }
-.inspector dl { margin: 0; padding: 4px 14px 12px; display: grid; grid-template-columns: 86px 1fr; gap: 4px 10px; font-size: 11.5px; }
-.inspector dt { color: var(--ink-3); }
-.inspector dd { margin: 0; font-family: var(--mono); overflow-wrap: anywhere; }
-.inspector .screen {
- margin: 0 14px 12px; padding: 8px; border-radius: 5px; background: var(--bg); border: 1px solid var(--line);
- font: 10.5px/1.5 var(--mono); color: var(--ink-2); white-space: pre-wrap; max-height: 150px; overflow: auto;
-}
-.inspector .row-actions { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 14px 14px; }
-.inspector .why { margin: 0 14px 10px; padding: 7px 9px; border-left: 2px solid var(--gold); background: var(--gold-soft); font-size: 11.5px; }
-.toast {
- position: absolute; left: 50%; bottom: 46px; transform: translateX(-50%); z-index: 20;
- max-width: 78vw; padding: 7px 13px; border-radius: 7px; background: var(--ink); color: var(--bg);
- font-size: 12px; box-shadow: var(--shadow);
-}
-.toast.bad { background: var(--red); color: #fff; }
-
-@media (max-width: 720px) {
- :root { --label-w: 104px; }
- .filter input { width: 110px; }
- .gauges { order: 3; width: 100%; }
-}
+:root { color-scheme: light; --bg:#fafafa; --row:#fff; --alt:#f4f4f5; --text:#242428; --muted:#71717a; --line:#dedee3; --hover:#ececf2; --selection:#e6edff; --accent:#4464cb; --yellow:#926000; --red:#b84141; --green:#347848; --cyan:#187593; font:13px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
+@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { color-scheme:dark; --bg:#202124; --row:#242528; --alt:#27282c; --text:#eeeef0; --muted:#a1a1aa; --line:#393a41; --hover:#32343b; --selection:#303c58; --accent:#9fb5ff; --yellow:#eac56b; --red:#f28b82; --green:#9dce9c; --cyan:#7ec6de; } }
+:root[data-theme="dark"] { color-scheme:dark; --bg:#202124; --row:#242528; --alt:#27282c; --text:#eeeef0; --muted:#a1a1aa; --line:#393a41; --hover:#32343b; --selection:#303c58; --accent:#9fb5ff; --yellow:#eac56b; --red:#f28b82; --green:#9dce9c; --cyan:#7ec6de; }
+* { box-sizing:border-box; }
+body { margin:0; background: var(--bg); color:var(--text); height:100vh; display:flex; flex-direction:column; overflow:hidden; }
+button,input,select,summary { font:inherit; color:inherit; }
+button,select,summary { background:transparent; border:1px solid transparent; border-radius:4px; padding:6px 9px; cursor:pointer; white-space:nowrap; }
+button:hover,summary:hover { background:var(--hover); }
+button:disabled { color:var(--muted); opacity:.45; cursor:default; }
+button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,[tabindex]:focus-visible { outline:2px solid var(--accent); outline-offset:-2px; }
+header { display:flex; align-items:center; gap:20px; padding:18px 20px 10px; flex-wrap:wrap; }
+h1 { font-size:16px; font-weight:600; margin:0; white-space:nowrap; }
+input[type=search] { min-width:180px; flex:1; max-width:500px; margin-left:auto; padding:8px 10px; border:1px solid var(--line); border-radius:5px; background:var(--row); }
+input::placeholder { color:var(--muted); }
+#assistant { border-color:var(--line); }
+nav { display:flex; align-items:center; gap:6px; padding:0 14px 10px; border-bottom:1px solid var(--line); }
+nav label { display:flex; gap:5px; align-items:center; color:var(--muted); }
+select { color:var(--text); }
+.spacer { flex:1; }
+details { position:relative; }
+summary { list-style:none; } summary::-webkit-details-marker { display:none; }
+.menu { position:absolute; z-index:10; right:0; top:34px; width:200px; padding:8px; background:var(--row); border:1px solid var(--line); border-radius:6px; box-shadow:0 8px 24px #0003; }
+.menu label { color:var(--text); padding:5px; gap:10px; }
+#problems { padding:8px 20px; color:var(--yellow); border-bottom:1px solid var(--line); font-size:12px; }
+#grid { flex:1; min-height:0; overflow:auto; position:relative; }
+table { border-collapse:separate; border-spacing:0; table-layout:fixed; min-width:100%; font-variant-numeric:tabular-nums; }
+th { text-align:left; position:sticky; top:0; z-index:3; background:var(--bg); border-bottom:1px solid var(--line); height:36px; padding:0; color:var(--muted); font-weight:400; }
+th button { width:100%; text-align:left; padding:9px 12px; border-radius:0; overflow:hidden; text-overflow:ellipsis; }
+th.numeric button { text-align:right; }
+.resize { position:absolute; width:7px; right:0; top:6px; bottom:6px; cursor:col-resize; border-right:1px solid var(--line); touch-action:none; }
+td { height:36px; padding:0 12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; background:var(--row); }
+tr:nth-child(even) td { background:var(--alt); }
+tr:hover td { background:var(--hover); }
+tr[aria-selected=true] td { background:var(--selection); }
+th:first-child,td:first-child { position:sticky; left:0; z-index:2; border-right:1px solid var(--line); }
+th:last-child,td:last-child { position:sticky; right:0; z-index:2; border-left:1px solid var(--line); }
+th:first-child,th:last-child { z-index:4; }
+td:first-child { font-weight:500; }
+.numeric { text-align:right; }
+.status { display:inline-flex; align-items:center; gap:7px; }
+.mark { display:inline-block; width:12px; text-align:center; }
+.working { color:var(--cyan); } .needsInput,.starting { color:var(--yellow); } .failed { color:var(--red); } .done { color:var(--green); } .idle,.offline,.stopped { color:var(--muted); }
+.engine { display:inline-flex; gap:7px; align-items:center; }
+.engine img { width:16px; height:16px; object-fit:contain; }
+.engine img.dark-tile { background:#29322f; border-radius:3px; padding:1px; }
+.actions { padding:0 4px; text-align:center; }
+.actions button { padding:5px 7px; } .actions .stop { font-size:18px; line-height:16px; }
+.actions .stop:not(:disabled):hover { color:var(--red); }
+#empty { padding:36px 20px; color:var(--muted); text-align:center; }
+footer { min-height:32px; padding:7px 18px; display:flex; gap:20px; align-items:center; color:var(--muted); border-top:1px solid var(--line); font-size:11px; }
+#message { flex:1; color:var(--text); } #updated { white-space:nowrap; }
+dialog { background:var(--bg); color:var(--text); border:1px solid var(--line); border-radius:8px; padding:24px; max-width:600px; width:calc(100% - 40px); max-height:85vh; }
+dialog::backdrop { background:#0007; }
+h2 { font-size:16px; margin:0 0 18px; } p { line-height:1.6; }
+.muted { color:var(--muted); }
+.dialog-actions { display:flex; justify-content:flex-end; flex-wrap:wrap; gap:8px; margin-top:24px; }
+.dialog-actions button { border-color:var(--line); }
+#cleanup-plan { max-height:35vh; overflow:auto; }
+.plan-row { padding:9px 0; border-bottom:1px solid var(--line); }
+.plan-row small { display:block; color:var(--muted); margin-top:5px; }
+@media (max-width:650px) { header { gap:10px; padding:12px; } h1 { width:100%; } input[type=search] { margin:0; } nav { padding-inline:6px; } footer { gap:10px; } }
diff --git a/store/agents/harness-monitor/viewer/app.js b/store/agents/harness-monitor/viewer/app.js
index 56604a0f6..b1d7dd752 100644
--- a/store/agents/harness-monitor/viewer/app.js
+++ b/store/agents/harness-monitor/viewer/app.js
@@ -1,610 +1,248 @@
-/* Harness Monitor's pane.
- *
- * One snapshot from the server, two ways to read it, and six verbs. No build step, no dependencies, no
- * inline script — the page is served with `script-src 'self'`, so everything here is plain DOM and one
- * ES module import for the arithmetic (viewer/scale.js, tested in test/scale.test.mjs).
- *
- * The two views share ONE selection and ONE cursor on purpose: a fleet manager where the dense list and
- * the picture disagree about what is selected is a fleet manager that cannot be trusted with a verb.
- */
-import { HIDE_STEPS, PAUSE_STEPS, UNITS, bytes, humanIdle, idleOfX, parseDuration, snap, xOf } from './scale.js'
-
-const TOKEN = document.querySelector('meta[name="hps-token"]')?.content ?? ''
-
-const el = (id) => document.getElementById(id)
+import { ACTIVITY, SPINNER, COLUMNS, visibleRows, number, memory, age } from './table.js'
+const el = id => document.getElementById(id)
const dom = {
- where: el('where'), gauges: el('gauges'), filter: el('filter'), refresh: el('refresh'),
- lanes: el('lanes-view'), laneList: el('lane-list'), axis: el('axis'), lanesEmpty: el('lanes-empty'),
- table: el('table'), grid: el('grid'),
- rulePause: el('rule-pause'), ruleHide: el('rule-hide'),
- showAll: el('show-all'), policybar: el('policybar'), policyPreview: el('policy-preview'), policySave: el('policy-save'), policyReset: el('policy-reset'),
- statusLeft: el('status-left'), statusActions: el('status-actions'), statusRight: el('status-right'),
- inspector: el('inspector'), toast: el('toast'),
-}
-
+ search: el('search'), filter: el('filter'), columns: el('columns'), columnOptions: el('column-options'),
+ grid: el('grid'), table: el('table'), colgroup: el('colgroup'), head: el('head'), body: el('body'),
+ empty: el('empty'), count: el('count'), message: el('message'), updated: el('updated'), problems: el('problems'),
+ assistant: el('assistant'), choice: el('assistant-choice'), free: el('assistant-free'), other: el('assistant-other'), cancel: el('assistant-cancel'),
+ refresh: el('refresh'), cleanup: el('cleanup'), cleanupDialog: el('cleanup-dialog'), cleanupPlan: el('cleanup-plan'),
+ cleanupSummary: el('cleanup-summary'), cleanupCancel: el('cleanup-cancel'), cleanupApply: el('cleanup-apply'),
+}
+const token = document.querySelector('meta[name="hps-token"]').content
+let saved = {}
+try { saved = JSON.parse(localStorage.getItem('harness-monitor.table.v2') || '{}') } catch { /* private browsing */ }
const state = {
- snapshot: null,
- view: 'lanes',
- filter: '',
- showAll: false,
- selected: new Set(),
- cursor: null,
- inspecting: null,
- sort: { key: 'idle', dir: 'asc' },
- draft: null, // policy being dragged, before it is saved
- busy: false,
-}
-
-/* ── the fleet, filtered ──────────────────────────────────────────────────── */
-
-function policy() {
- return { ...(state.snapshot?.policy ?? {}), ...(state.draft ?? {}) }
-}
-
-function rows() {
- const all = state.snapshot?.rows ?? []
- const hideMs = parseDuration(policy().hideAfterIdle ?? '14d')
- // Below the fold unless you ask: a pane that opens on 146 rows is the junk drawer this was built to fix.
- // Filtering by hand overrides it, because someone typing a name is looking for that name anywhere.
- const needle = state.filter.trim().toLowerCase()
- const visible = state.showAll || needle
- ? all
- : all.filter((row) => row.state !== 'gone' && row.idleMs < hideMs)
- if (!needle) return visible
- return visible.filter((row) => [row.name, row.title, row.project, row.engine, row.model, row.branch, row.machine, row.state]
- .some((field) => String(field ?? '').toLowerCase().includes(needle)))
-}
-
-/** What the plan says about one row, as the server computed it — unless a line is being dragged, in
- * which case the same idle rules are applied here so the picture answers while the mouse is moving. */
-function verdictFor(row) {
- if (state.draft) {
- const pause = parseDuration(state.draft.pauseAfterIdle ?? policy().pauseAfterIdle)
-
- if (row.pinned || row.needsInput || row.working || row.attached) return null
- if (row.state === 'gone' || row.state === 'terminal') return null
- if (row.state === 'running' && row.idleMs >= pause) return 'pause'
- return null
- }
- const entry = (state.snapshot?.plan ?? []).find((candidate) => candidate.id === row.id)
- return entry && entry.action !== 'keep' ? entry.action : null
-}
-
-function planTotals(list) {
- let pause = 0, frees = 0
- for (const row of list) {
- if (verdictFor(row) !== 'pause') continue
- pause += 1
- if (row.state === 'running') frees += row.rssBytes || 0
- }
- return { pause, frees }
-}
-
-/* ── rendering ────────────────────────────────────────────────────────────── */
-
-function renderGauges() {
- const summary = state.snapshot?.summary
- if (!summary) return
- const held = summary.held >= 1024 ** 3 ? `${(summary.held / 1024 ** 3).toFixed(1)} GB` : `${Math.round(summary.held / 1024 ** 2)} MB`
- const chips = [
- ['live', summary.running, 'running'],
- ['', summary.paused, 'paused'],
- ['', held, 'held'],
- ['', summary.projects, 'projects'],
- ]
- if (summary.needsInput) chips.unshift(['attention', summary.needsInput, 'waiting on you'])
- dom.gauges.replaceChildren(...chips.map(([kind, value, label]) => {
- const node = document.createElement('span')
- node.className = `gauge ${kind}`.trim()
- node.innerHTML = `<b></b> <span></span>`
- node.querySelector('b').textContent = value
- node.querySelector('span').textContent = label
- return node
- }))
- const machines = state.snapshot.rows.filter((row) => !row.local).length
- dom.where.textContent = machines
- ? `this machine, plus ${machines} seen elsewhere`
- : state.snapshot.status === 'degraded' ? 'read from the registry — the daemon is not answering' : 'this machine'
-}
-
-function renderAxis() {
- const ticks = [['now', 0], ['1h', UNITS.h], ['6h', 6 * UNITS.h], ['1d', UNITS.d], ['3d', 3 * UNITS.d], ['1w', UNITS.w], ['2w', 2 * UNITS.w], ['4w', 4 * UNITS.w]]
- for (const node of dom.axis.querySelectorAll('.tick')) node.remove()
- for (const [label, idle] of ticks) {
- const tick = document.createElement('span')
- tick.className = 'tick'
- tick.textContent = label
- tick.style.left = `${xOf(idle) * 100}%`
- dom.axis.append(tick)
- }
- placeRules()
-}
-
-function placeRules() {
- const current = policy()
- const pauseX = xOf(parseDuration(current.pauseAfterIdle))
- const hideX = xOf(parseDuration(current.hideAfterIdle))
- dom.rulePause.style.left = `${pauseX * 100}%`
- dom.ruleHide.style.left = `${hideX * 100}%`
- dom.rulePause.setAttribute('aria-valuetext', current.pauseAfterIdle)
- dom.ruleHide.setAttribute('aria-valuetext', current.hideAfterIdle)
- dom.rulePause.querySelector('.rule-tag').textContent = `pause ${current.pauseAfterIdle}`
- dom.ruleHide.querySelector('.rule-tag').textContent = `hide ${current.hideAfterIdle}`
- dom.laneList.style.setProperty('--pause-x', pauseX)
- dom.laneList.style.setProperty('--hide-x', hideX)
-}
-
-function chipFor(row) {
- const chip = document.createElement('button')
- chip.type = 'button'
- chip.className = 'chip'
- chip.dataset.id = row.id
- chip.dataset.state = row.state
- chip.dataset.working = String(Boolean(row.working && row.state === 'running'))
- chip.dataset.attention = String(Boolean(row.needsInput))
- chip.dataset.selected = String(state.selected.has(row.id))
- const doomed = verdictFor(row)
- if (doomed) chip.dataset.doomed = 'true'
- chip.title = `${row.title || row.name}\n${row.engine}${row.model ? ` · ${row.model}` : ''} · idle ${humanIdle(row.idleMs)}${doomed ? `\nthe policy would ${doomed} this` : ''}`
- const dot = document.createElement('span'); dot.className = 'dot'
- const what = document.createElement('span'); what.className = 'what'; what.textContent = row.title || row.name
- chip.append(dot, what)
- if (row.pinned) { const pin = document.createElement('span'); pin.className = 'pin'; pin.textContent = '📌'; chip.append(pin) }
- if (row.rssBytes) { const mem = document.createElement('span'); mem.className = 'mem'; mem.textContent = bytes(row.rssBytes); chip.append(mem) }
- return chip
-}
-
-/** Lay the chips out along the lane, then push any that overlap onto a second row of the same lane.
- * Measured, not estimated: a title's width depends on the font the app is in. */
-function stack(track) {
- const chips = [...track.querySelectorAll('.chip')]
- const width = track.clientWidth || 1
- const placed = []
- let rowsUsed = 1
- for (const chip of chips) {
- const w = chip.offsetWidth
- const wanted = Number(chip.dataset.x) * width
- const left = Math.max(0, Math.min(width - w, wanted - w)) // the chip ends at its own moment in time
- let level = 0
- while (placed.some((other) => other.level === level && left < other.right + 6 && left + w > other.left - 6)) level += 1
- placed.push({ level, left, right: left + w })
- rowsUsed = Math.max(rowsUsed, level + 1)
- chip.style.left = `${left}px`
- chip.style.top = `${5 + level * 26}px`
- }
- track.style.height = `${Math.max(34, 10 + rowsUsed * 26)}px`
-}
-
-function renderLanes() {
- const list = rows().filter((row) => row.state !== 'gone' || state.filter)
- dom.lanesEmpty.hidden = list.length > 0
- const lanes = new Map()
- for (const row of list) {
- const key = row.project || 'elsewhere'
- if (!lanes.has(key)) lanes.set(key, [])
- lanes.get(key).push(row)
- }
- // Freshest project first: the top of the hps is the working set, and the sediment sinks.
- const ordered = [...lanes.entries()].sort((a, b) => Math.min(...a[1].map((r) => r.idleMs)) - Math.min(...b[1].map((r) => r.idleMs)))
- const fragment = document.createDocumentFragment()
- for (const [project, group] of ordered) {
- const lane = document.createElement('div')
- lane.className = 'lane'
- const label = document.createElement('div')
- label.className = 'lane-label'
- const branch = group.find((row) => row.branch)?.branch
- label.innerHTML = '<b></b> <i></i>'
- label.querySelector('b').textContent = project
- label.querySelector('i').textContent = group.length > 1 ? `×${group.length}` : (branch ?? '')
- label.title = group.map((row) => `${row.title || row.name} — ${humanIdle(row.idleMs)}`).join('\n')
- const track = document.createElement('div')
- track.className = 'track'
- for (const row of [...group].sort((a, b) => a.idleMs - b.idleMs)) {
- const chip = chipFor(row)
- chip.dataset.x = String(xOf(row.idleMs))
- track.append(chip)
- }
- lane.append(label, track)
- fragment.append(lane)
- }
- dom.laneList.replaceChildren(fragment)
- for (const track of dom.laneList.querySelectorAll('.track')) stack(track)
-}
-
-const COLUMNS = [
- { key: 'n', label: '#', sortable: false, cell: (row, i) => ({ text: String(i + 1), className: 'c-num' }) },
- { key: 'state', label: '', cell: (row) => {
- const glyph = row.needsInput ? '!' : row.state === 'running' ? (row.working ? '◐' : '●')
- : row.state === 'paused' ? '○' : row.state === 'terminal' ? '$' : '✕'
- const kind = row.needsInput ? 'attention' : row.working && row.state === 'running' ? 'working' : row.state
- return { text: glyph, className: `c-state st-${kind}`, title: row.needsInput ? 'looks like it is waiting on you' : row.state }
- } },
- { key: 'idle', label: 'idle', cell: (row) => ({ text: row.state === 'gone' ? '—' : humanIdle(row.idleMs), className: 'c-idle' }) },
- { key: 'engine', label: 'engine', cell: (row) => ({ text: row.engine }) },
- { key: 'model', label: 'model', cell: (row) => ({ text: row.model ?? '—', className: 'c-dim' }) },
- { key: 'mem', label: 'mem', cell: (row, i, max) => ({ text: bytes(row.rssBytes), className: 'c-mem membar', bar: max ? (row.rssBytes || 0) / max : 0 }) },
- { key: 'project', label: 'project', cell: (row) => ({ text: row.project, className: 'c-project' }) },
- { key: 'branch', label: 'branch', cell: (row) => ({ text: row.branch ?? '—', className: 'c-dim' }) },
- { key: 'title', label: 'title', cell: (row) => ({ text: row.title || row.name, className: 'c-title' }) },
- // The verb, on the row. It used to appear only after selecting something, which meant a person looking
- // for "the pause button" could not find one.
- { key: 'do', label: '', sortable: false, cell: (row) => ({ text: '', className: 'c-do', verb: row.state === 'running' ? 'pause' : row.state === 'paused' ? 'resume' : null }) },
-]
-
-const SORTS = {
- idle: (a, b) => a.idleMs - b.idleMs,
- mem: (a, b) => (b.rssBytes || 0) - (a.rssBytes || 0),
- state: (a, b) => a.state.localeCompare(b.state) || a.idleMs - b.idleMs,
- engine: (a, b) => a.engine.localeCompare(b.engine) || a.idleMs - b.idleMs,
- model: (a, b) => String(a.model ?? '').localeCompare(String(b.model ?? '')),
- project: (a, b) => a.project.localeCompare(b.project) || a.idleMs - b.idleMs,
- branch: (a, b) => String(a.branch ?? '').localeCompare(String(b.branch ?? '')),
- title: (a, b) => String(a.title || a.name).localeCompare(String(b.title || b.name)),
-}
-
-function sortedRows() {
- const list = [...rows()]
- const by = SORTS[state.sort.key] ?? SORTS.idle
- list.sort(by)
- if (state.sort.dir === 'desc') list.reverse()
- return list
-}
-
-function renderTable() {
- const list = sortedRows()
- const max = Math.max(1, ...list.map((row) => row.rssBytes || 0))
- const table = document.createElement('table')
- const thead = document.createElement('thead')
- const headRow = document.createElement('tr')
- for (const column of COLUMNS) {
- const th = document.createElement('th')
- th.textContent = column.label
- if (column.sortable !== false) {
- th.dataset.sort = column.key
- if (state.sort.key === column.key) th.setAttribute('aria-sort', state.sort.dir === 'asc' ? 'ascending' : 'descending')
+ rows: [], snapshot: null, query: typeof saved.query === 'string' ? saved.query : '',
+ filter: ['all', ...Object.keys(ACTIVITY)].includes(saved.filter) ? saved.filter : 'all',
+ sort: COLUMNS.some(c => c.key === saved.sort && c.key !== 'actions') ? saved.sort : 'lastActivity', direction: saved.direction === 1 ? 1 : -1,
+ visible: new Set(Array.isArray(saved.visible) ? saved.visible : COLUMNS.filter(c => !c.optional).map(c => c.key)),
+ widths: {}, selected: null, busy: new Set(), cleanupIds: [], cleanupRows: [], nodes: new Map(), shown: [], assistantIntroSeen: saved.assistantIntroSeen === true,
+}
+for (const col of COLUMNS) state.widths[col.key] = Math.max(64, Math.min(600, Number(saved.widths?.[col.key]) || col.width))
+const text = (node, value) => { if (node.textContent !== String(value)) node.textContent = value }
+function persist() {
+ try { localStorage.setItem('harness-monitor.table.v2', JSON.stringify({ query: state.query, filter: state.filter, sort: state.sort, direction: state.direction, visible: [...state.visible], widths: state.widths, assistantIntroSeen: state.assistantIntroSeen })) } catch { /* optional */ }
+}
+function element(tag, value, className) {
+ const node = document.createElement(tag)
+ if (value != null) node.textContent = value
+ if (className) node.className = className
+ return node
+}
+function message(value) { text(dom.message, value) }
+async function post(path, payload) {
+ const response = await fetch(path, { method: 'POST', headers: { 'content-type': 'application/json', 'x-hps-token': token }, body: JSON.stringify(payload) })
+ const result = await response.json()
+ if (!response.ok || result.error) throw new Error(result.error || 'Request failed. Refresh and try again.')
+ return result
+}
+// Both the native webview and the remote viewer renderer consume this small, bounded navigation queue.
+// No scripts, prompts, process controls or paths cross the host bridge.
+window.harnessHostQueue = []
+function host(action) {
+ if (window.HarnessHost?.postMessage) window.HarnessHost.postMessage(JSON.stringify(action))
+ else if (window.harnessEmbedded) {
+ if (window.harnessHostQueue.length < 8) window.harnessHostQueue.push(action)
+ } else { message('Open this viewer inside Harness to use this action.'); return false }
+ return true
+}
+function openRow(id) {
+ const row = state.rows.find(r => r.id === id)
+ if (!row?.canOpen || state.busy.has(id)) return
+ host({ action: 'open', machineId: row.machineId, agentId: row.agentId })
+}
+async function stopRows(ids, manual) {
+ const expected = (manual ? state.rows : state.cleanupRows).filter(row => ids.includes(row.id)).map(({ id, sessionId, lastActivity }) => ({ id, sessionId, lastActivity }))
+ ids.forEach(id => state.busy.add(id)); render()
+ try {
+ const reply = await post('/api/act', { verb: 'pause', ids, manual, expected })
+ const failures = reply.results.filter(r => !r.ok)
+ message(failures.length ? failures.map(r => r.name + ': ' + r.detail).join(' · ') : (reply.results.length === 1 ? 'Stopped. History retained.' : reply.results.length + ' sessions stopped.'))
+ } catch (error) { message(error.message) }
+ finally { ids.forEach(id => state.busy.delete(id)); render() }
+}
+const activeColumns = () => COLUMNS.filter(c => c.required || state.visible.has(c.key))
+function resizeColumns() {
+ for (const col of dom.colgroup.children) col.style.width = state.widths[col.dataset.key] + 'px'
+ for (const header of dom.head.querySelectorAll('th[data-key]')) {
+ const grip = header.querySelector('.resize')
+ if (grip) { grip.setAttribute('aria-valuemin', '64'); grip.setAttribute('aria-valuemax', '600'); grip.setAttribute('aria-valuenow', String(state.widths[header.dataset.key])) }
+ }
+ dom.table.style.width = activeColumns().reduce((sum, c) => sum + state.widths[c.key], 0) + 'px'
+}
+function buildColumns() {
+ dom.colgroup.replaceChildren(); dom.head.replaceChildren(); state.nodes.clear(); dom.body.replaceChildren()
+ const tr = element('tr')
+ for (const col of activeColumns()) {
+ const width = element('col'); width.dataset.key = col.key; dom.colgroup.append(width)
+ const th = element('th', null, col.numeric ? 'numeric' : ''); th.scope = 'col'; th.dataset.key = col.key
+ if (col.key !== 'actions') {
+ const sort = element('button', col.label); sort.type = 'button'; sort.title = col.help || 'Sort by ' + col.label
+ sort.onclick = () => { state.direction = state.sort === col.key ? -state.direction : col.numeric ? -1 : 1; state.sort = col.key; persist(); render() }
+ th.append(sort)
+ const grip = element('span', null, 'resize'); grip.tabIndex = 0; grip.role = 'separator'; grip.setAttribute('aria-orientation', 'vertical'); grip.setAttribute('aria-label', 'Resize ' + col.label)
+ const change = width => { state.widths[col.key] = Math.max(64, Math.min(600, width)); resizeColumns() }
+ grip.onpointerdown = event => {
+ event.preventDefault(); const start = event.clientX, width = state.widths[col.key]
+ grip.setPointerCapture(event.pointerId)
+ grip.onpointermove = move => change(width + move.clientX - start)
+ grip.onpointerup = () => { grip.onpointermove = null; persist() }
+ grip.onpointercancel = () => { grip.onpointermove = null; persist() }
+ }
+ grip.onkeydown = event => { if (['ArrowLeft', 'ArrowRight'].includes(event.key)) { event.preventDefault(); change(state.widths[col.key] + (event.key === 'ArrowLeft' ? -16 : 16)); persist() } }
+ th.append(grip)
}
- headRow.append(th)
- }
- thead.append(headRow)
- const tbody = document.createElement('tbody')
- list.forEach((row, index) => {
- const tr = document.createElement('tr')
- tr.dataset.id = row.id
- tr.dataset.selected = String(state.selected.has(row.id))
- tr.dataset.cursor = String(state.cursor === row.id)
- if (verdictFor(row)) tr.dataset.doomed = 'true'
- for (const column of COLUMNS) {
- const td = document.createElement('td')
- const cell = column.cell(row, index, max)
- td.className = cell.className ?? ''
- if (cell.title) td.title = cell.title
- if (cell.verb) {
- const button = document.createElement('button')
- button.type = 'button'
- button.dataset.verb = cell.verb
- button.dataset.only = row.id
- button.textContent = cell.verb === 'pause' ? 'Pause' : 'Resume'
- td.append(button)
- } else if (cell.bar) {
- const bar = document.createElement('i')
- bar.style.width = `${Math.max(2, cell.bar * 46)}px`
- const span = document.createElement('span')
- span.textContent = cell.text
- td.append(bar, span)
- } else td.textContent = cell.text
- tr.append(td)
+ tr.append(th)
+ }
+ dom.head.append(tr); resizeColumns(); render()
+}
+for (const col of COLUMNS.filter(c => !c.required)) {
+ const label = element('label'), check = element('input'); check.type = 'checkbox'; check.checked = state.visible.has(col.key)
+ check.onchange = () => { if (check.checked) state.visible.add(col.key); else state.visible.delete(col.key); persist(); buildColumns() }
+ label.append(check, document.createTextNode(col.label)); dom.columnOptions.append(label)
+}
+const iconNames = new Set(['codex', 'opencode', 'cursor', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok', 'copilot', 'agy', 'claude'])
+const engineNames = { codex: 'Codex', claude: 'Claude', opencode: 'OpenCode', cursor: 'Cursor', terminal: 'Terminal', pi: 'Pi', hermes: 'Hermes', copilot: 'Copilot', gemini: 'Gemini' }
+function createRow(row) {
+ const tr = element('tr'); tr.dataset.id = row.id
+ tr.onclick = () => { state.selected = row.id; select(); dom.grid.focus({ preventScroll: true }) }
+ tr.ondblclick = event => { if (!event.target.closest('button')) openRow(row.id) }
+ for (const col of activeColumns()) {
+ const td = element('td', null, col.numeric ? 'numeric' : ''); td.dataset.key = col.key
+ if (col.key === 'actions') {
+ td.className = 'actions'
+ const open = element('button', 'Open'), stop = element('button', '×', 'stop')
+ open.onclick = event => { event.stopPropagation(); openRow(row.id) }
+ stop.onclick = event => { event.stopPropagation(); void stopRows([row.id], true) }
+ td.append(open, stop)
+ } else if (col.key === 'activity') {
+ const status = element('span', null, 'status'); status.append(element('span', null, 'mark'), element('span')); td.append(status)
+ } else if (col.key === 'engine') {
+ const span = element('span', null, 'engine'), img = element('img'), label = element('span'); img.alt = ''; img.hidden = true
+ span.append(img, label); td.append(span)
}
- tbody.append(tr)
- })
- table.append(thead, tbody)
- dom.grid.replaceChildren(table)
-}
-
-function renderStatus() {
- const summary = state.snapshot?.summary
- const list = rows()
- const totals = planTotals(list)
- const held = totals.frees >= 1024 ** 3 ? `${(totals.frees / 1024 ** 3).toFixed(1)} GB` : `${Math.round(totals.frees / 1024 ** 2)} MB`
- const hidden = (state.snapshot?.rows ?? []).length - list.length
- const bits = [`${list.length} shown${hidden > 0 ? ` of ${(state.snapshot?.rows ?? []).length}` : ''}`]
- if (summary) bits.push(`${summary.running} running`, `${summary.paused} paused`)
- if (totals.pause) bits.push(`policy: pause ${totals.pause} (${held})`)
- for (const problem of state.snapshot?.problems ?? []) bits.push(`⚠ ${problem.machine}`)
- dom.statusLeft.textContent = bits.join(' · ')
-
- const count = state.selected.size
- dom.statusActions.hidden = count === 0
- if (count) {
- dom.statusActions.replaceChildren()
- const label = document.createElement('span')
- label.textContent = `${count} selected`
- dom.statusActions.append(label)
- for (const [verb, text] of [['pause', 'Pause'], ['resume', 'Resume'], ['pin', 'Pin'], ['unpin', 'Unpin']]) {
- const button = document.createElement('button')
- button.type = 'button'
- button.textContent = text
- button.dataset.verb = verb
- dom.statusActions.append(button)
+ tr.append(td)
+ }
+ return tr
+}
+function updateRow(tr, row) {
+ for (const td of tr.children) {
+ const key = td.dataset.key
+ if (key === 'activity') {
+ const [mark, label] = ACTIVITY[row.activity] || ['—', 'Unknown']
+ const status = td.firstChild; status.className = 'status ' + row.activity
+ text(status.children[0], mark); text(status.children[1], label)
+ td.title = row.activityKnown || ['offline', 'stopped', 'starting', 'failed'].includes(row.activity) ? label : 'Update this machine’s Harness daemon to report activity.'
+ } else if (key === 'engine') {
+ const img = td.firstChild.children[0]; const icon = iconNames.has(row.engine) ? row.engine : null
+ img.hidden = !icon
+ img.className = ['cursor', 'opencode', 'grok', 'copilot'].includes(icon) ? 'dark-tile' : ''
+ if (icon && img.getAttribute('src') !== 'icons/' + icon + '.png') img.src = 'icons/' + icon + '.png'
+ text(td.firstChild.children[1], engineNames[row.engine] || row.engine || '—')
+ } else if (key === 'actions') {
+ const [open, stop] = td.children
+ open.disabled = !row.canOpen || state.busy.has(row.id); stop.disabled = !row.canStop || state.busy.has(row.id)
+ open.title = row.canOpen ? (row.state === 'paused' ? (row.resumeMode === 'fresh' ? 'Open a new conversation with the saved settings' : 'Resume this session') : 'Open this session') : row.unavailable || 'Session unavailable'
+ stop.title = row.canStop ? 'Stop session; keep history' : row.unavailable || 'Already stopped or unavailable'
+ stop.setAttribute('aria-label', 'Stop ' + row.name)
+ open.setAttribute('aria-label', 'Open ' + row.name)
+ } else {
+ const value = key === 'cpu' ? (row.cpu == null ? '—' : row.cpu.toFixed(1)) : key === 'rssBytes' ? memory(row.rssBytes)
+ : key === 'tokens' ? number(row.tokens) : key === 'lastActivity' ? age(row.lastActivity) : row[key] ?? '—'
+ text(td, value); td.title = key === 'lastActivity' && row.lastActivity ? new Date(row.lastActivity).toLocaleString() : String(row[key] ?? '')
}
- const clear = document.createElement('button')
- clear.type = 'button'; clear.textContent = 'Clear'; clear.dataset.verb = 'clear'
- dom.statusActions.append(clear)
}
- dom.statusRight.innerHTML = state.view === 'table'
- ? '<kbd>j</kbd><kbd>k</kbd> move · <kbd>space</kbd> select · <kbd>p</kbd> pause · <kbd>r</kbd> resume · <kbd>i</kbd> pin · <kbd>/</kbd> filter'
- : `rules: <code></code> · drag a line to try a change · <kbd>/</kbd> filter`
- const code = dom.statusRight.querySelector('code')
- if (code) code.textContent = state.snapshot?.configPath ?? '~/.config/harness/policy.jsonc'
}
-
-function renderInspector() {
- const row = (state.snapshot?.rows ?? []).find((candidate) => candidate.id === state.inspecting)
- if (!row) { dom.inspector.hidden = true; return }
- dom.inspector.hidden = false
- const verdict = verdictFor(row)
- const entry = (state.snapshot?.plan ?? []).find((candidate) => candidate.id === row.id)
- dom.inspector.replaceChildren()
- const header = document.createElement('header')
- const heading = document.createElement('div')
- const h2 = document.createElement('h2'); h2.textContent = row.title || row.name
- const sub = document.createElement('div'); sub.className = 'sub'
- sub.textContent = `${row.state}${row.pinned ? ' · pinned' : ''} · ${row.engine}${row.model ? ` ${row.model}` : ''} · ${row.machine}`
- heading.append(h2, sub)
- const close = document.createElement('button'); close.type = 'button'; close.className = 'ghost'; close.textContent = '✕'
- close.addEventListener('click', () => { state.inspecting = null; renderInspector() })
- header.append(heading, close)
- dom.inspector.append(header)
-
- if (entry && entry.action !== 'keep') {
- const why = document.createElement('p'); why.className = 'why'
- why.textContent = `The policy would ${entry.action} this: ${entry.why}.`
- dom.inspector.append(why)
- } else if (entry?.protectedBy) {
- const why = document.createElement('p'); why.className = 'why'
- why.textContent = `Protected: ${entry.why}.`
- dom.inspector.append(why)
- }
-
- const dl = document.createElement('dl')
- const pairs = [
- ['idle', `${humanIdle(row.idleMs)} — last turn ${new Date(row.lastActivity).toLocaleString()}`],
- ['folder', row.home || '—'],
- ['branch', row.branch ?? '—'],
- ['memory', row.rssBytes ? `${bytes(row.rssBytes)} across ${row.procs} ${row.procs === 1 ? 'process' : 'processes'}` : '—'],
- ['pane', row.pane ? `${row.pane}${row.dead ? ' (dead, held open)' : ''}` : '—'],
- ['harness', row.dshName ?? row.dsh ?? '—'],
- ['id', row.id.slice(0, 8)],
- ]
- for (const [key, value] of pairs) {
- const dt = document.createElement('dt'); dt.textContent = key
- const dd = document.createElement('dd'); dd.textContent = value
- dl.append(dt, dd)
- }
- dom.inspector.append(dl)
-
- if (row.screenTail) {
- const screen = document.createElement('pre'); screen.className = 'screen'; screen.textContent = row.screenTail
- dom.inspector.append(screen)
- }
- const actions = document.createElement('div'); actions.className = 'row-actions'
- // A shell has no conversation to pause or resume, so it is offered neither.
- const verbs = row.state === 'terminal' ? [] : row.state === 'running' ? [['pause', 'Pause']] : [['resume', 'Resume']]
- if (row.state !== 'terminal') verbs.push(row.pinned ? ['unpin', 'Unpin'] : ['pin', 'Pin'])
- for (const [verb, text] of verbs) {
- const button = document.createElement('button')
- button.type = 'button'; button.className = 'ghost'; button.textContent = text
- button.addEventListener('click', () => act(verb, [row.id]))
- actions.append(button)
- }
- dom.inspector.append(actions)
- if (verdict) dom.inspector.dataset.verdict = verdict
+function select() {
+ for (const [id, node] of state.nodes) node.setAttribute('aria-selected', String(id === state.selected))
}
-
function render() {
- if (!state.snapshot) return
- renderGauges()
- placeRules()
- if (state.view === 'lanes') renderLanes(); else renderTable()
- renderStatus()
- renderInspector()
-}
-
-/* ── talking to the server ────────────────────────────────────────────────── */
-
-function toast(message, bad = false) {
- dom.toast.textContent = message
- dom.toast.className = `toast${bad ? ' bad' : ''}`
- dom.toast.hidden = false
- clearTimeout(toast.timer)
- toast.timer = setTimeout(() => { dom.toast.hidden = true }, 4200)
-}
-
-async function post(path, payload) {
- const response = await fetch(path, {
- method: 'POST',
- headers: { 'content-type': 'application/json', 'x-hps-token': TOKEN },
- body: JSON.stringify(payload),
- })
- return response.json()
-}
-
-async function act(verb, ids) {
- if (state.busy || !ids.length) return
- state.busy = true
- try {
- const reply = await post('/api/act', { verb, ids })
- if (reply.error) { toast(reply.error, true); return }
- const results = reply.results ?? []
- const ok = results.filter((result) => result.ok && !result.already).length
- const refused = results.filter((result) => result.refused)
- if (results.length === 1) toast(`${results[0].ok ? '' : 'not '}${verb}: ${results[0].detail}`, !results[0].ok)
- else toast(`${verb}: ${ok} done${refused.length ? `, ${refused.length} left alone (${refused[0].detail})` : ''}`, ok === 0)
- state.selected.clear()
- } catch (error) {
- toast(`Could not ${verb}: ${error.message}`, true)
- } finally {
- state.busy = false
- }
-}
-
-async function savePolicy() {
- if (!state.draft) return
- const reply = await post('/api/policy', { policy: state.draft })
- if (reply.error) { toast(reply.error, true); return }
- toast(`Saved to ${state.snapshot?.configPath ?? 'policy.jsonc'}: pause after ${reply.policy.pauseAfterIdle}, hide after ${reply.policy.hideAfterIdle}.`)
- state.draft = null
- dom.policybar.hidden = true
- render()
-}
-
-/* ── input ────────────────────────────────────────────────────────────────── */
-
-function setView(view) {
- state.view = view
- dom.lanes.hidden = view !== 'lanes'
- dom.table.hidden = view !== 'table'
- for (const button of document.querySelectorAll('.segmented button')) {
- button.setAttribute('aria-selected', String(button.dataset.view === view))
- }
- render()
-}
-
-function toggle(id, additive) {
- if (!additive) {
- const only = state.selected.size === 1 && state.selected.has(id)
- state.selected.clear()
- if (!only) state.selected.add(id)
- } else if (state.selected.has(id)) state.selected.delete(id)
- else state.selected.add(id)
- state.cursor = id
-}
-
-function targets() {
- if (state.selected.size) return [...state.selected]
- return state.cursor ? [state.cursor] : []
-}
-
-function moveCursor(delta) {
- const list = state.view === 'table' ? sortedRows() : rows()
- if (!list.length) return
- const index = list.findIndex((row) => row.id === state.cursor)
- const next = list[Math.min(list.length - 1, Math.max(0, (index < 0 ? 0 : index) + delta))]
- state.cursor = next.id
- state.inspecting = state.inspecting ? next.id : null
- render()
- const node = dom.grid.querySelector(`tr[data-id="${next.id}"]`)
- node?.scrollIntoView({ block: 'nearest' })
-}
-
-document.addEventListener('click', (event) => {
- const chip = event.target.closest('.chip')
- if (chip) { toggle(chip.dataset.id, event.metaKey || event.ctrlKey || event.shiftKey); state.inspecting = chip.dataset.id; render(); return }
- const tr = event.target.closest('#grid tbody tr')
- if (tr) { toggle(tr.dataset.id, event.metaKey || event.ctrlKey || event.shiftKey); state.inspecting = state.inspecting ? tr.dataset.id : null; render(); return }
- const th = event.target.closest('#grid th[data-sort]')
- if (th) {
- const key = th.dataset.sort
- state.sort = { key, dir: state.sort.key === key && state.sort.dir === 'asc' ? 'desc' : 'asc' }
- render(); return
- }
- const button = event.target.closest('[data-verb]')
- const verb = button?.dataset.verb
- if (verb === 'clear') { state.selected.clear(); render(); return }
- // A button on a row acts on THAT row, whatever else is selected — otherwise clicking Pause next to one
- // harness would pause five.
- if (verb) { event.stopPropagation(); act(verb, button.dataset.only ? [button.dataset.only] : targets()); return }
- const view = event.target.closest('[data-view]')?.dataset.view
- if (view) setView(view)
-})
-
-dom.refresh.addEventListener('click', () => post('/api/refresh', {}).then(() => toast('Refreshed.')))
-dom.showAll.addEventListener('click', () => {
- state.showAll = !state.showAll
- dom.showAll.setAttribute('aria-pressed', String(state.showAll))
- render()
+ const focused = dom.body.contains(document.activeElement) ? document.activeElement : null
+ const { scrollTop, scrollLeft } = dom.grid
+ state.shown = visibleRows(state.rows, state)
+ const ids = new Set(state.shown.map(r => r.id))
+ for (const [id, node] of state.nodes) if (!ids.has(id)) { node.remove(); state.nodes.delete(id) }
+ // Keyed updates preserve row buttons, focus, selection and the scroll container on every sample.
+ let at = dom.body.firstChild
+ for (const row of state.shown) {
+ let node = state.nodes.get(row.id)
+ if (!node) { node = createRow(row); state.nodes.set(row.id, node) }
+ updateRow(node, row)
+ if (at !== node) dom.body.insertBefore(node, at)
+ at = node.nextSibling
+ }
+ select()
+ if (focused?.isConnected && document.activeElement !== focused) focused.focus({ preventScroll: true })
+ dom.grid.scrollTop = scrollTop; dom.grid.scrollLeft = scrollLeft
+ for (const th of dom.head.querySelectorAll('th')) {
+ const col = COLUMNS.find(c => c.key === th.dataset.key)
+ if (!col || col.key === 'actions') continue
+ th.setAttribute('aria-sort', state.sort === col.key ? (state.direction === 1 ? 'ascending' : 'descending') : 'none')
+ text(th.firstChild, col.label + (state.sort === col.key ? (state.direction === 1 ? ' ↑' : ' ↓') : ''))
+ }
+ dom.empty.hidden = state.shown.length > 0
+ text(dom.empty, state.snapshot?.status === 'starting' ? 'Connecting to your machines…' : state.rows.length ? 'No harnesses match this search.' : 'No harnesses found on your connected machines.')
+ text(dom.count, state.shown.length + (state.shown.length === state.rows.length ? '' : ' of ' + state.rows.length) + ' harnesses')
+ text(dom.updated, state.snapshot?.observedAt ? 'Updated ' + age(state.snapshot.observedAt) : 'Connecting…')
+}
+dom.search.value = state.query; dom.filter.value = state.filter
+dom.search.oninput = () => { state.query = dom.search.value; persist(); render() }
+dom.filter.onchange = () => { state.filter = dom.filter.value; persist(); render() }
+dom.grid.onkeydown = event => {
+ if (event.target.closest('button') || event.target.classList.contains('resize')) return
+ if (['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) {
+ event.preventDefault(); const index = state.shown.findIndex(r => r.id === state.selected)
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? state.shown.length - 1 : Math.max(0, Math.min(state.shown.length - 1, index + (event.key === 'ArrowUp' ? -1 : 1)))
+ state.selected = state.shown[next]?.id ?? null; select(); state.nodes.get(state.selected)?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
+ } else if (event.key === 'Enter' && state.selected) { event.preventDefault(); openRow(state.selected) }
+}
+document.addEventListener('keydown', event => {
+ if ((event.key === '/' || ((event.metaKey || event.ctrlKey) && event.key === 'f')) && !document.querySelector('dialog[open]') && !['INPUT', 'TEXTAREA'].includes(event.target.tagName)) { event.preventDefault(); dom.search.focus() }
})
-dom.policySave.addEventListener('click', savePolicy)
-dom.policyReset.addEventListener('click', () => { state.draft = null; dom.policybar.hidden = true; render() })
-dom.filter.addEventListener('input', () => { state.filter = dom.filter.value; render() })
-
-/* Dragging a rule: the hps is the only place a threshold can be judged, because the thing you are
- judging is how many chips end up on the wrong side of it. */
-for (const rule of [dom.rulePause, dom.ruleHide]) {
- const steps = rule.dataset.rule === 'pause' ? PAUSE_STEPS : HIDE_STEPS
- const key = rule.dataset.rule === 'pause' ? 'pauseAfterIdle' : 'hideAfterIdle'
- const begin = (event) => {
- event.preventDefault()
- rule.classList.add('dragging')
- const track = dom.axis.getBoundingClientRect()
- const move = (moveEvent) => {
- const x = (moveEvent.clientX - track.left) / Math.max(1, track.width)
- state.draft = { ...(state.draft ?? {}), [key]: snap(idleOfX(x), steps) }
- dom.policybar.hidden = false
- const totals = planTotals(rows())
- const held = totals.frees >= 1024 ** 3 ? `${(totals.frees / 1024 ** 3).toFixed(1)} GB` : `${Math.round(totals.frees / 1024 ** 2)} MB`
- dom.policyPreview.textContent = `pause after ${policy().pauseAfterIdle}, hide after ${policy().hideAfterIdle} → would pause ${totals.pause}, handing back ${held}`
- render()
- }
- const end = () => {
- rule.classList.remove('dragging')
- window.removeEventListener('pointermove', move)
- window.removeEventListener('pointerup', end)
- }
- window.addEventListener('pointermove', move)
- window.addEventListener('pointerup', end)
- }
- rule.addEventListener('pointerdown', begin)
- rule.addEventListener('keydown', (event) => {
- const direction = event.key === 'ArrowLeft' ? -1 : event.key === 'ArrowRight' ? 1 : 0
- if (!direction) return
- event.preventDefault()
- const current = policy()[key]
- const index = Math.max(0, Math.min(steps.length - 1, steps.indexOf(current) - direction))
- state.draft = { ...(state.draft ?? {}), [key]: steps[index] }
- dom.policybar.hidden = false
- render()
+dom.refresh.onclick = async () => {
+ dom.refresh.disabled = true
+ try { await post('/api/refresh', {}); message('') } catch (error) { message(error.message) }
+ finally { dom.refresh.disabled = false }
+}
+function showAssistant(chooseModel = false) {
+ if (!host({ action: 'assistant', chooseModel })) return
+ state.assistantIntroSeen = true; persist(); dom.choice.close()
+}
+dom.assistant.onclick = () => state.assistantIntroSeen ? showAssistant() : dom.choice.showModal()
+dom.cancel.onclick = () => dom.choice.close()
+dom.free.onclick = () => showAssistant()
+dom.other.onclick = () => showAssistant(true)
+dom.cleanup.onclick = () => {
+ const entries = (state.snapshot?.plan ?? []).filter(e => e.action === 'pause').slice(0, 64)
+ state.cleanupIds = entries.map(e => e.id)
+ state.cleanupRows = state.rows.filter(row => state.cleanupIds.includes(row.id))
+ dom.cleanupPlan.replaceChildren()
+ for (const entry of entries) { const node = element('div', entry.name, 'plan-row'); node.append(element('small', entry.why)); dom.cleanupPlan.append(node) }
+ text(dom.cleanupSummary, entries.length ? entries.length + ' sessions are eligible under your current cleanup rules.' : 'No sessions are eligible under your current cleanup rules.')
+ dom.cleanupApply.disabled = !entries.length; dom.cleanupDialog.showModal()
+}
+dom.cleanupCancel.onclick = () => dom.cleanupDialog.close()
+dom.cleanupApply.onclick = async () => { const ids = [...state.cleanupIds]; dom.cleanupDialog.close(); await stopRows(ids, false) }
+let stream
+function connect() {
+ if (stream || document.hidden) return
+ stream = new EventSource('/events')
+ stream.addEventListener('snapshot', event => {
+ try {
+ const snapshot = JSON.parse(event.data)
+ state.snapshot = snapshot; state.rows = snapshot.rows ?? []
+ dom.problems.hidden = !snapshot.problems?.length
+ text(dom.problems, (snapshot.problems ?? []).map(p => p.machine + ': ' + p.error).join(' · ')); render()
+ } catch { message('Could not read the monitor update. Refresh and try again.') }
})
-}
-
-document.addEventListener('keydown', (event) => {
- if (event.target === dom.filter) {
- if (event.key === 'Escape') { dom.filter.value = ''; state.filter = ''; dom.filter.blur(); render() }
- return
- }
- if (event.metaKey || event.ctrlKey || event.altKey) return
- const key = event.key
- if (key === '/') { event.preventDefault(); dom.filter.focus(); return }
- if (key === '1') return setView('lanes')
- if (key === '2') return setView('table')
- if (key === 'j' || key === 'ArrowDown') { event.preventDefault(); return moveCursor(1) }
- if (key === 'k' || key === 'ArrowUp') { event.preventDefault(); return moveCursor(-1) }
- if (key === 'g') { const list = state.view === 'table' ? sortedRows() : rows(); state.cursor = list[0]?.id ?? null; return render() }
- if (key === 'G') { const list = state.view === 'table' ? sortedRows() : rows(); state.cursor = list.at(-1)?.id ?? null; return render() }
- if (key === ' ') { event.preventDefault(); if (state.cursor) { toggle(state.cursor, true); render() } return }
- if (key === 'Enter') { state.inspecting = state.cursor; return render() }
- if (key === 'Escape') { state.selected.clear(); state.inspecting = null; state.draft = null; dom.policybar.hidden = true; return render() }
- // h pause · r resume · x retire · i pin · u unpin. `p` and `w` stay bound to the same two verbs,
- // because anyone who used this before it was renamed will reach for them.
- const verbs = { p: 'pause', h: 'pause', r: 'resume', w: 'resume', i: 'pin', u: 'unpin' }
- if (verbs[key]) { event.preventDefault(); act(verbs[key], targets()) }
-})
-
-window.addEventListener('resize', () => { if (state.view === 'lanes') renderLanes() })
-
-/* ── the stream ───────────────────────────────────────────────────────────── */
-
-function listen() {
- const source = new EventSource('/events')
- source.addEventListener('snapshot', (event) => {
- try { state.snapshot = JSON.parse(event.data) } catch { return }
- render()
- })
- source.addEventListener('error', () => {
- dom.where.textContent = 'reconnecting…'
- source.close()
- setTimeout(listen, 2500)
- })
-}
-
-renderAxis()
-listen()
+ stream.onerror = () => { message('Connection interrupted. Reconnecting…') }
+ stream.onopen = () => { if (dom.message.textContent === 'Connection interrupted. Reconnecting…') message('') }
+}
+document.addEventListener('visibilitychange', () => { if (document.hidden) { stream?.close(); stream = null } else connect() })
+const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)')
+setInterval(() => {
+ if (document.hidden || reducedMotion.matches) return
+ const mark = SPINNER[Math.floor(Date.now() / 100) % SPINNER.length]
+ for (const node of dom.body.querySelectorAll('.working .mark')) text(node, mark)
+}, 100)
+buildColumns(); connect()
diff --git a/store/agents/harness-monitor/viewer/icons/MODEL-ICONS-LICENSE b/store/agents/harness-monitor/viewer/icons/MODEL-ICONS-LICENSE
new file mode 100644
index 000000000..1dd53d2a9
--- /dev/null
+++ b/store/agents/harness-monitor/viewer/icons/MODEL-ICONS-LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 LobeHub
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/harness-monitor/viewer/icons/MODEL-ICONS-NOTICE.md b/store/agents/harness-monitor/viewer/icons/MODEL-ICONS-NOTICE.md
new file mode 100644
index 000000000..539c98e46
--- /dev/null
+++ b/store/agents/harness-monitor/viewer/icons/MODEL-ICONS-NOTICE.md
@@ -0,0 +1,7 @@
+# Model artwork
+
+Logos identify their respective models and providers; they do not imply endorsement.
+
+SVG artwork from [Lobe Icons](https://github.com/lobehub/lobe-icons/tree/5c1ecb4fb06b92519a39102482d4e8273f000422/packages/static-svg/icons), revision `5c1ecb4fb06b92519a39102482d4e8273f000422` (MIT; see LICENSE). PNGs are rasterized to 128 × 128 with their aspect ratios and colors preserved. OpenAI and Z.ai use theme-aware monochrome artwork.
+
+The original SVG sources are retained beside their PNGs.
diff --git a/store/agents/harness-monitor/viewer/icons/NOTICE.txt b/store/agents/harness-monitor/viewer/icons/NOTICE.txt
new file mode 100644
index 000000000..3ed9d03e6
--- /dev/null
+++ b/store/agents/harness-monitor/viewer/icons/NOTICE.txt
@@ -0,0 +1,1680 @@
+OpenHarness: artwork notices for harness package marks
+
+Generated by desktop/tool/harness_marks.mjs; do not edit directly.
+
+Logo sources, provenance and modifications: https://github.com/autonomous-ai/openharness/tree/main/store/branding
+
+Original wrapper marks are MIT-licensed. Third-party artwork retains its own license.
+
+Upstream SVGs are rasterized with their colors, shapes and aspect ratio preserved.
+The OpenSCAD PNG is copied unchanged. Project names and marks identify the tools;
+they do not imply sponsorship or endorsement. Habitat is an original wrapper mark,
+not the Home Assistant logo or a mark of the Open Home Foundation.
+
+autonomous/web-studio
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/web-studio.svg
+
+autonomous/data-studio
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/data-studio.svg
+
+autonomous/quantum-studio
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/quantum-studio.svg
+
+autonomous/gis
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/gis.svg
+
+autonomous/openscad
+OpenSCAD contributors
+License: GPL-2.0-or-later
+Source: https://raw.githubusercontent.com/openscad/openscad/033ddb6f6aafa7f3042b6ff2b7f60c5ecf59f926/resources/icons/openscad-256.png
+
+autonomous/freecad
+FreeCAD contributors; trademark owned by the FreeCAD Project Association
+License: LGPL-2.1-or-later
+Source: https://raw.githubusercontent.com/FreeCAD/FreeCAD/9b86f258893c86016b8d7a62bddb24646b775fb3/src/Gui/Icons/freecad.svg
+
+autonomous/orca-slicer
+OrcaSlicer contributors
+License: AGPL-3.0-only
+Source: https://raw.githubusercontent.com/OrcaSlicer/OrcaSlicer/8500fcdccaa10b5099ac20d252af3a7c560046f1/resources/images/OrcaSlicer.svg
+
+autonomous/firmware-studio
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/firmware-studio.svg
+
+autonomous/godot-studio
+Godot Engine logo © 2017 Andrea Calabró
+License: CC-BY-4.0
+Source: https://godotengine.org/assets/press/icon_color.svg
+
+autonomous/home-assistant
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/home-assistant.svg
+
+autonomous/score
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/score.svg
+
+autonomous/sheet-docs
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/sheet-docs.svg
+
+autonomous/roundtable
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/roundtable.svg
+
+autonomous/jev-browser
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/jev-browser.svg
+
+autonomous/godogen
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/godogen.svg
+
+autonomous/ableton-ai
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/ableton-ai.svg
+
+autonomous/autoresearch-mlx
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/autoresearch-mlx.svg
+
+autonomous/foam-agent
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/foam-agent.svg
+
+autonomous/juce-agent-toolkit
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/juce-agent-toolkit.svg
+
+autonomous/machine-monitor
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/machine-monitor.svg
+
+autonomous/simskill
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/simskill.svg
+
+autonomous/harness-monitor
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/harness-monitor.svg
+
+autonomous/harness-builder
+© 2026 OpenHarness contributors
+License: MIT
+Source: https://github.com/autonomous-ai/openharness/blob/main/store/branding/harness-builder.svg
+
+licenses/original.txt
+
+MIT License
+
+Copyright (c) 2026 OpenHarness contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+licenses/openscad.txt
+
+*********************************************************************
+ As a special exception, you have permission to link this program
+ with the CGAL library and distribute executables, as long as you
+ follow the requirements of the GNU GPL in regard to all of the
+ software in the executable aside from CGAL.
+*********************************************************************
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
+
+licenses/freecad.txt
+
+GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
+ USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random
+ Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+licenses/orca-slicer.txt
+
+GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.
+
+licenses/godot.txt
+
+Godot Engine Logo
+Copyright (c) 2017 Andrea Calabró
+
+This work is licensed under the Creative Commons Attribution 4.0 International
+license (CC BY 4.0 International): https://creativecommons.org/licenses/by/4.0/
diff --git a/store/agents/harness-monitor/viewer/icons/agy.png b/store/agents/harness-monitor/viewer/icons/agy.png
new file mode 100644
index 000000000..c677e4f5f
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/agy.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/amp.png b/store/agents/harness-monitor/viewer/icons/amp.png
new file mode 100644
index 000000000..0c66a6965
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/amp.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/claude.png b/store/agents/harness-monitor/viewer/icons/claude.png
new file mode 100644
index 000000000..21e0b1194
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/claude.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/codex.png b/store/agents/harness-monitor/viewer/icons/codex.png
new file mode 100644
index 000000000..7ef8986eb
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/codex.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/commandcode.png b/store/agents/harness-monitor/viewer/icons/commandcode.png
new file mode 100644
index 000000000..6af0c72ef
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/commandcode.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/copilot.png b/store/agents/harness-monitor/viewer/icons/copilot.png
new file mode 100644
index 000000000..29c0b3215
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/copilot.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/cursor.png b/store/agents/harness-monitor/viewer/icons/cursor.png
new file mode 100644
index 000000000..ffc2f9b31
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/cursor.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/devin.png b/store/agents/harness-monitor/viewer/icons/devin.png
new file mode 100644
index 000000000..e5474fc06
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/devin.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/grok.png b/store/agents/harness-monitor/viewer/icons/grok.png
new file mode 100644
index 000000000..efac08364
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/grok.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/hermes.png b/store/agents/harness-monitor/viewer/icons/hermes.png
new file mode 100644
index 000000000..8db2977a5
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/hermes.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/kilo.png b/store/agents/harness-monitor/viewer/icons/kilo.png
new file mode 100644
index 000000000..03ebe10e6
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/kilo.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/muse.png b/store/agents/harness-monitor/viewer/icons/muse.png
new file mode 100644
index 000000000..d4b8c320d
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/muse.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/opencode.png b/store/agents/harness-monitor/viewer/icons/opencode.png
new file mode 100644
index 000000000..b9a5d612e
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/opencode.png differ
diff --git a/store/agents/harness-monitor/viewer/icons/pi.png b/store/agents/harness-monitor/viewer/icons/pi.png
new file mode 100644
index 000000000..437f21d0a
Binary files /dev/null and b/store/agents/harness-monitor/viewer/icons/pi.png differ
diff --git a/store/agents/harness-monitor/viewer/index.html b/store/agents/harness-monitor/viewer/index.html
index 08024500e..bd50108a5 100644
--- a/store/agents/harness-monitor/viewer/index.html
+++ b/store/agents/harness-monitor/viewer/index.html
@@ -2,68 +2,49 @@
<html lang="en">
<head>
<meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="hps-token" content="__HPS_TOKEN__">
- <title>Harness Monitor · your fleet</title>
+ <title>Harness Monitor</title>
<link rel="stylesheet" href="app.css">
- <script type="module" src="app.js"></script>
</head>
<body>
- <div id="app">
- <header class="bar">
- <div class="identity">
- <span class="mark" aria-hidden="true"></span>
- <h1>Harness Monitor</h1>
- <span class="where" id="where">reading the fleet…</span>
- </div>
- <div class="gauges" id="gauges" aria-live="polite"></div>
- <div class="tools">
- <div class="segmented" role="tablist" aria-label="View">
- <button type="button" id="view-lanes" role="tab" aria-selected="true" data-view="lanes">Lanes</button>
- <button type="button" id="view-table" role="tab" aria-selected="false" data-view="table">Table</button>
- </div>
- <div class="filter">
- <span aria-hidden="true">/</span>
- <input id="filter" type="search" placeholder="filter by name, project, engine" autocomplete="off" spellcheck="false" aria-label="Filter harnesses">
- </div>
- <button type="button" class="ghost toggle" id="show-all" aria-pressed="false" title="Also show what the policy hides: idle past the hide line, and harnesses whose pane is gone">show all</button>
- <button type="button" class="ghost" id="refresh" title="Refresh now">↻</button>
- </div>
- </header>
-
- <section class="view" id="lanes-view" aria-label="The lanes">
- <div class="lanes-head">
- <div class="axis-label">PROJECT</div>
- <div class="axis" id="axis">
- <div class="rule" id="rule-pause" data-rule="pause" tabindex="0" role="slider" aria-label="Pause after" aria-valuetext="4h"><span class="rule-grip"></span><span class="rule-tag">pause</span></div>
- <div class="rule" id="rule-hide" data-rule="hide" tabindex="0" role="slider" aria-label="Hide after" aria-valuetext="14d"><span class="rule-grip"></span><span class="rule-tag">hide</span></div>
- </div>
- </div>
- <div class="lanes" id="lane-list"></div>
- <div class="lanes-empty" id="lanes-empty" hidden>
- <p class="big">Nothing is running here yet.</p>
- <p>Ask the agent beside this pane to show your fleet, or open a harness and come back.</p>
- </div>
- </section>
-
- <section class="view" id="table" hidden aria-label="The table">
- <div class="grid" id="grid" role="grid" tabindex="0"></div>
- </section>
-
- <div class="policybar" id="policybar" hidden>
- <span class="policy-preview" id="policy-preview"></span>
- <button type="button" class="primary" id="policy-save">Save policy</button>
- <button type="button" class="ghost" id="policy-reset">Reset</button>
- </div>
-
- <footer class="statusbar" id="statusbar">
- <span id="status-left" class="mono"></span>
- <span id="status-actions" class="actions" hidden></span>
- <span id="status-right" class="keys mono"></span>
- </footer>
-
- <aside class="inspector" id="inspector" hidden aria-label="Harness details"></aside>
- <div class="toast" id="toast" role="status" hidden></div>
- </div>
+ <header>
+ <h1>Harness Monitor</h1>
+ <input id="search" type="search" placeholder="Search harnesses" aria-label="Search harnesses" autocomplete="off" spellcheck="false">
+ <button id="assistant">Ask assistant</button>
+ </header>
+ <nav aria-label="Monitor controls">
+ <label>Status <select id="filter" aria-label="Filter by status">
+ <option value="all">All</option><option value="needsInput">Needs you</option>
+ <option value="working">Working</option><option value="done">Done</option>
+ <option value="idle">Idle</option><option value="starting">Starting</option>
+ <option value="failed">Failed</option><option value="stopped">Stopped</option><option value="offline">Offline</option><option value="unknown">Unknown</option>
+ </select></label>
+ <span class="spacer"></span>
+ <details id="columns"><summary>Columns</summary><div id="column-options" class="menu"></div></details>
+ <button id="cleanup">Cleanup…</button>
+ <button id="refresh" title="Refresh all machines">Refresh</button>
+ </nav>
+ <div id="problems" role="status" hidden></div>
+ <main id="grid" tabindex="0" aria-label="Harness sessions. Arrow keys select, Enter opens.">
+ <table id="table" aria-label="Harness sessions"><colgroup id="colgroup"></colgroup><thead id="head"></thead><tbody id="body"></tbody></table>
+ <p id="empty">Connecting to your machines…</p>
+ </main>
+ <footer><span id="count"></span><span id="message" role="status" aria-live="polite"></span><span id="updated"></span></footer>
+ <dialog id="assistant-choice" aria-labelledby="assistant-title">
+ <h2 id="assistant-title">Ask assistant</h2>
+ <p>New monitors use OpenCode with <strong>Muse Spark 1.3 Contributor Free</strong>. This limited-time free model allows Meta to use prompts and responses for training. Existing sessions keep their selected engine and model.</p>
+ <p>Only what you send to the assistant, and information its tools read, enters the conversation. The table works without the assistant.</p>
+ <p class="muted">OpenCode may require a Zen login. If the free model is unavailable, choose a model yourself; Harness Monitor does not switch to a paid model automatically.</p>
+ <div class="dialog-actions"><button id="assistant-cancel">Cancel</button><button id="assistant-other">Choose another model</button><button id="assistant-free">Open assistant</button></div>
+ </dialog>
+ <dialog id="cleanup-dialog" aria-labelledby="cleanup-title">
+ <h2 id="cleanup-title">Review cleanup</h2>
+ <p id="cleanup-summary"></p>
+ <div id="cleanup-plan"></div>
+ <p class="muted">Cleanup rechecks your rules and current activity. By default, working sessions, questions and pins are protected. Unknown activity is always protected. History and launch settings are retained. Nothing runs automatically.</p>
+ <div class="dialog-actions"><button id="cleanup-cancel">Cancel</button><button id="cleanup-apply">Stop reviewed sessions</button></div>
+ </dialog>
+ <script type="module" src="app.js"></script>
</body>
</html>
diff --git a/store/agents/harness-monitor/viewer/table.js b/store/agents/harness-monitor/viewer/table.js
new file mode 100644
index 000000000..9150fadc2
--- /dev/null
+++ b/store/agents/harness-monitor/viewer/table.js
@@ -0,0 +1,43 @@
+/** UI contracts mirror desktop HarnessActivity/EngineMark; pure sorting is shared with tests. */
+export const ACTIVITY = {
+ needsInput: ['?', 'Needs you'], failed: ['✗', 'Failed'], done: ['✓', 'Done'], working: ['⠋', 'Working'],
+ starting: ['◌', 'Starting'], idle: ['', 'Idle'], stopped: ['Ⅱ', 'Stopped'], offline: ['⊘', 'Offline'], unknown: ['—', 'Unknown'],
+}
+export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
+export const COLUMNS = [
+ { key: 'name', label: 'Harness', width: 280, required: true },
+ { key: 'activity', label: 'Status', width: 116 }, { key: 'engine', label: 'Agent', width: 114 },
+ { key: 'machine', label: 'Machine', width: 104 }, { key: 'project', label: 'Project', width: 180 },
+ { key: 'branch', label: 'Branch', width: 184 },
+ { key: 'cpu', label: 'CPU %', width: 86, numeric: true, help: 'Process tree CPU, as reported by ps. Can exceed 100% across cores; averaging varies by OS.' },
+ { key: 'rssBytes', label: 'RAM', width: 92, numeric: true, help: 'Resident memory of the engine and its child processes. Shared pages may be counted more than once.' },
+ { key: 'tokens', label: 'Tokens', width: 86, numeric: true },
+ { key: 'lastActivity', label: 'Last active', width: 128, numeric: true },
+ { key: 'model', label: 'Model', width: 190, optional: true },
+ { key: 'enginePid', label: 'PID', width: 80, numeric: true, optional: true },
+ { key: 'agentId', label: 'Harness ID', width: 220, optional: true },
+ { key: 'sessionId', label: 'Conversation ID', width: 220, optional: true },
+ { key: 'home', label: 'Folder', width: 240, optional: true },
+ { key: 'actions', label: '', width: 100, required: true },
+]
+export function visibleRows(rows, { query = '', filter = 'all', sort = 'lastActivity', direction = -1 } = {}) {
+ const q = query.trim().toLocaleLowerCase()
+ const rank = Object.keys(ACTIVITY)
+ return rows.filter(row => (filter === 'all' || row.activity === filter) && (!q ||
+ [row.name, row.title, row.engine, row.machine, row.project, row.branch, row.model, row.agentId, row.sessionId, row.home].some(v => v?.toLocaleLowerCase().includes(q))))
+ .sort((a, b) => {
+ let av = a[sort], bv = b[sort]
+ if (av == null && bv != null) return 1
+ if (bv == null && av != null) return -1
+ if (sort === 'activity') { av = rank.indexOf(av); bv = rank.indexOf(bv) }
+ const compared = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av ?? '').localeCompare(String(bv ?? ''), undefined, { numeric: true })
+ return compared * direction || a.id.localeCompare(b.id)
+ })
+}
+export const number = n => n == null ? '—' : Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 }).format(n)
+export const memory = n => n == null ? '—' : n >= 1024 ** 3 ? (n / 1024 ** 3).toFixed(1) + ' GB' : Math.round(n / 1024 ** 2) + ' MB'
+export const age = (stamp, now = Date.now()) => {
+ if (stamp == null) return '—'
+ const s = Math.max(0, (now - stamp) / 1000)
+ return s < 60 ? 'now' : s < 3600 ? Math.floor(s / 60) + 'm ago' : s < 86400 ? Math.floor(s / 3600) + 'h ago' : Math.floor(s / 86400) + 'd ago'
+}