Skip to content

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

Unify desktop session recency and live status indicators (#735)

Dee5c7a8357ba90
diff --git a/cli/src/lib/sessionSearch/external.spec.ts b/cli/src/lib/sessionSearch/external.spec.ts
index 1a842106f..d6150addf 100644
--- a/cli/src/lib/sessionSearch/external.spec.ts
+++ b/cli/src/lib/sessionSearch/external.spec.ts
@@ -188,6 +188,25 @@ describe('OpenSessions', () => {
expect(sessions.known().get('me')).toBeDefined()
expect(await sessions.fresh()).toBe(await sessions.fresh())
})
+
+ it('reports confirmed working state without treating unknown or open as busy', async () => {
+ let busy: boolean | null = true
+ const { sessions } = open([
+ { engine: 'claude', scan: async () => [], owners: async () => [
+ { sessionId: 'live', pid: 1, record: '/live' },
+ { sessionId: 'guess', pid: 2, record: '/guess', fromArgs: true },
+ ], busy: async () => busy },
+ { engine: 'grok', scan: async () => [], owners: async () => [{ sessionId: 'error', pid: 3, record: '/bad' }], busy: async () => { throw new Error('unreadable') } },
+ ])
+ expect(await sessions.working('live')).toBe(true)
+ busy = false
+ expect(await sessions.working('live')).toBe(false)
+ busy = null
+ expect(await sessions.working('live')).toBeNull()
+ expect(await sessions.working('guess')).toBeNull()
+ expect(await sessions.working('error')).toBeNull()
+ expect(await sessions.working('closed')).toBe(false)
+ })
})
describe('stopSessionOwner', () => {
diff --git a/cli/src/lib/sessionSearch/external.ts b/cli/src/lib/sessionSearch/external.ts
index c1a3d3c13..af3d212d3 100644
--- a/cli/src/lib/sessionSearch/external.ts
+++ b/cli/src/lib/sessionSearch/external.ts
@@ -154,6 +154,15 @@ export class OpenSessions {
return said ?? true
}
+ /** Display state, unlike the conservative stop guard above: unknown is never called working. */
+ async working(sessionId: string): Promise<boolean | null> {
+ const owner = (await this.current()).owners.get(sessionId)
+ if (!owner) return false
+ if (owner.fromArgs) return null
+ const provider = this.opts.providers.find((candidate) => candidate.engine === owner.engine)
+ return await provider?.busy?.(owner).catch(() => null) ?? null
+ }
+
private current(): Promise<OpenAnswer> {
const now = (this.opts.now ?? Date.now)()
if (this.answer && now - this.answer.at <= (this.opts.maxAgeMs ?? 5_000)) return Promise.resolve(this.answer)
diff --git a/cli/src/lib/sessionSearch/externals/claude.ts b/cli/src/lib/sessionSearch/externals/claude.ts
index 56d87c85c..80665cbd4 100644
--- a/cli/src/lib/sessionSearch/externals/claude.ts
+++ b/cli/src/lib/sessionSearch/externals/claude.ts
@@ -98,10 +98,11 @@ export function claudeProvider(options: { projectsDir: string; home: string }):
}
return claims
},
- async busy(owner): Promise<boolean> {
+ async busy(owner): Promise<boolean | null> {
const row = record(await readJson(owner.record))
// No record: the process ended with it, so it is not mid-turn.
- return row ? row.status !== 'idle' : false
+ if (!row) return false
+ return row.status === 'busy' ? true : row.status === 'idle' ? false : null
},
}
}
diff --git a/cli/src/lib/sessionSearch/externals/codex.spec.ts b/cli/src/lib/sessionSearch/externals/codex.spec.ts
index 257fe55d7..a00a8c33f 100644
--- a/cli/src/lib/sessionSearch/externals/codex.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/codex.spec.ts
@@ -93,6 +93,7 @@ describe('the rest of a Codex home', () => {
const quoted = { type: 'event_msg', payload: { type: 'agent_message', phase: 'task_started' } }
expect(await codexTurnOpen(file('quoted', [event('task_complete'), quoted]))).toBe(false)
expect(await codexTurnOpen(join(dir, 'gone.jsonl'))).toBe(true)
+ expect(await codexTurnOpen(join(dir, 'gone.jsonl'), null)).toBeNull()
// Too far back to be read: busy, the safe answer.
expect(await codexTurnOpen(file('long', [event('task_complete'), { type: 'response_item', payload: { big: 'x'.repeat(5 * 1024 * 1024) } }]))).toBe(true)
})
diff --git a/cli/src/lib/sessionSearch/externals/codex.ts b/cli/src/lib/sessionSearch/externals/codex.ts
index e57c22508..b693f44b9 100644
--- a/cli/src/lib/sessionSearch/externals/codex.ts
+++ b/cli/src/lib/sessionSearch/externals/codex.ts
@@ -95,7 +95,7 @@ export function codexServer(row: RunningProcess | undefined): boolean {
* `turn_aborted` event near its end says. What was said can name the events; only events count.
* A file that cannot say counts as busy.
*/
-export async function codexTurnOpen(path: string): Promise<boolean> {
+export async function codexTurnOpen(path: string, unknown: boolean | null = true): Promise<boolean | null> {
for (const bytes of [256 * 1024, 4 * 1024 * 1024]) {
const lines = (await readTail(path, bytes)).split('\n')
for (let i = lines.length - 1; i > 0; i--) {
@@ -106,7 +106,7 @@ export async function codexTurnOpen(path: string): Promise<boolean> {
if (kind === 'task_complete' || kind === 'turn_aborted') return false
}
}
- return true
+ return unknown
}
export function codexProvider(options: { home: string }): ExternalProvider {
@@ -145,6 +145,6 @@ export function codexProvider(options: { home: string }): ExternalProvider {
}
return claims
},
- busy: (owner) => codexTurnOpen(owner.record),
+ busy: (owner) => codexTurnOpen(owner.record, null),
}
}
diff --git a/cli/src/lib/sessionSearch/indexer.spec.ts b/cli/src/lib/sessionSearch/indexer.spec.ts
index 1195fcb4e..756d2c32d 100644
--- a/cli/src/lib/sessionSearch/indexer.spec.ts
+++ b/cli/src/lib/sessionSearch/indexer.spec.ts
@@ -39,6 +39,40 @@ function setup(initial: string, agents?: () => string[]) {
}
describe('SessionSearchIndex', () => {
+ it('a later search discovers a new session without waiting for the idle sweep', async () => {
+ let now = Date.now()
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now)
+ cleanups.push(() => clock.mockRestore())
+ const store = SessionSearchStore.open(':memory:')!
+ let sources: SearchSource[] = []
+ let discovered: SearchSource[] = []
+ const discover = vi.fn(async () => { discovered = sources })
+ const index = new SessionSearchIndex({ store, sources: () => discovered, discover })
+ cleanups.push(() => { index.stop(); store.close() })
+ index.start(60_000)
+ expect(index.search('').ready).toBe(false)
+ await vi.waitFor(() => expect(index.search('').ready).toBe(true))
+ expect(discover).toHaveBeenCalledTimes(1)
+
+ const dir = mkdtempSync(join(tmpdir(), 'session-search-new-'))
+ dirs.push(dir)
+ const transcriptPath = join(dir, 'new-terminal.jsonl')
+ writeFileSync(transcriptPath, prompt('a new terminal conversation', 0) + answer('Ready.', 1))
+ sources = [{ agentId: '', sessionId: 'new-terminal', engine: 'claude',
+ transcriptPath, header: '', changedAt: now,
+ external: { cwd: '/repo', origin: 'terminal', title: 'New terminal conversation' },
+ }]
+ now += 5_001
+ expect(index.search('', { from: 0, to: now })).toMatchObject({ hits: [], ready: false })
+ index.search('')
+ await vi.waitFor(() => {
+ const result = index.search('', { from: 0, to: now })
+ expect(result.ready).toBe(true)
+ expect(result.hits.map((hit) => hit.sessionId)).toEqual(['new-terminal'])
+ })
+ expect(discover).toHaveBeenCalledTimes(2)
+ })
+
it('discovers on first search and distinguishes an unfinished scan from empty history', async () => {
const store = SessionSearchStore.open(':memory:')!
let finish!: () => void
@@ -199,13 +233,14 @@ describe('SessionSearchIndex', () => {
writeFileSync(untitledFile, prompt('compare retention\nby cohort please', 0) + answer('Day-7 is 35%.', 1))
const store = SessionSearchStore.open(':memory:')!
const open = new Map([['e1', 'terminal' as const]])
+ let working: boolean | null = true
let sources: SearchSource[] = [
{ agentId: '', sessionId: 'e1', engine: 'claude', transcriptPath: claudeFile, header: '', changedAt: 2, external: { cwd: '/work/dial', origin: 'terminal', title: '' } },
{ agentId: '', sessionId: 'e2', engine: 'claude', transcriptPath: untitledFile, header: '', changedAt: 1, external: { cwd: '/work/cohorts', origin: 'claude-app', title: '' } },
]
const index = new SessionSearchIndex({
store, sources: () => sources, agents: () => [],
- openSessions: { known: () => open, fresh: async () => open },
+ openSessions: { known: () => open, fresh: async () => open, working: async () => working },
})
cleanups.push(() => { index.stop(); store.close() })
const settle = async () => {
@@ -221,7 +256,11 @@ describe('SessionSearchIndex', () => {
expect(hit).toMatchObject({ sessionId: 'e1', agentId: '', external: { title: 'Dial fix', cwd: '/work/dial', origin: 'terminal', open: true, openIn: 'terminal' } })
expect(index.search('cohort').hits[0]).toMatchObject({ sessionId: 'e2', external: { origin: 'claude-app', open: false } })
const tail = await index.tail('e1')
- expect(tail?.external).toEqual({ title: 'Dial fix', cwd: '/work/dial', origin: 'terminal', open: true, openIn: 'terminal' })
+ expect(tail?.external).toEqual({ title: 'Dial fix', cwd: '/work/dial', origin: 'terminal', open: true, openIn: 'terminal', working: true })
+ working = false
+ expect((await index.tail('e1'))?.external?.working).toBe(false)
+ working = null
+ expect((await index.tail('e1'))?.external).not.toHaveProperty('working')
// Its file gone, it leaves the index at the next sweep.
sources = sources.filter((source) => source.sessionId !== 'e2')
diff --git a/cli/src/lib/sessionSearch/indexer.ts b/cli/src/lib/sessionSearch/indexer.ts
index e9b39a2fa..d72bcaa88 100644
--- a/cli/src/lib/sessionSearch/indexer.ts
+++ b/cli/src/lib/sessionSearch/indexer.ts
@@ -107,7 +107,11 @@ export interface SessionSearchIndexOptions {
* Which sessions are open in a running process right now (external.ts `OpenSessions`), so a
* conversation Harness did not start says whether a terminal still has it. `known` never waits.
*/
- openSessions?: { known(): ReadonlyMap<string, 'terminal' | 'app' | 'harness' | 'maybe'>; fresh(): Promise<ReadonlyMap<string, 'terminal' | 'app' | 'harness' | 'maybe'>> }
+ openSessions?: {
+ known(): ReadonlyMap<string, 'terminal' | 'app' | 'harness' | 'maybe'>
+ fresh(): Promise<ReadonlyMap<string, 'terminal' | 'app' | 'harness' | 'maybe'>>
+ working?(sessionId: string): Promise<boolean | null>
+ }
/** Looks again for conversations Harness did not start, before each sweep lists its sources. */
discover?: () => Promise<unknown>
/** Between full sweeps. */
@@ -143,6 +147,7 @@ export class SessionSearchIndex {
private discovering = false
private discoveryFailed = false
private discoveryStartedAt: number | undefined
+ private discoveryFinishedAt: number | undefined
/** Callers waiting for a session's next pass (`tail`). */
private readonly waiters = new Map<string, Array<() => void>>()
@@ -213,6 +218,7 @@ export class SessionSearchIndex {
}
this.initialized = true
this.discovering = false
+ this.discoveryFinishedAt = Date.now()
}
if (this.opts.discover) {
// Which of them are open, looked at now: a search reads it without waiting.
@@ -240,9 +246,10 @@ export class SessionSearchIndex {
search(query: string, options: { limit?: number; from?: number; to?: number } = {}): SessionSearchResult {
const started = performance.now()
- // Opening welcome/search is an explicit demand for history. Start the first scan now,
- // without blocking this request or waiting for the daemon's deferred boot sweep.
- if ((!this.initialized || this.discoveryFailed) && !this.discovering &&
+ // Opening welcome/search is an explicit demand for current history, including sessions
+ // started since boot. Keep a short cache across typing/retries, not the ten-minute idle sweep.
+ const stale = this.discoveryFinishedAt === undefined || Date.now() - this.discoveryFinishedAt >= 5_000
+ if ((!this.initialized || this.discoveryFailed || stale) && !this.discovering && !this.running &&
(this.discoveryStartedAt === undefined || Date.now() - this.discoveryStartedAt >= 1_000)) this.sweep()
const hits = this.opts.store.search(query, options)
// Whether a terminal still has it, as last looked: a search never waits for a process table.
@@ -290,7 +297,12 @@ export class SessionSearchIndex {
// A preview of a conversation Harness did not start says whether a terminal has it, as of now.
const open = await this.opts.openSessions?.fresh().catch(() => null)
const where = open?.get(sessionId)
- tail.external = { title: session.title ?? '', cwd: session.cwd ?? '', origin: session.origin ?? '', open: open?.has(sessionId) ?? false, ...(where ? { openIn: where } : {}) }
+ const working = open?.has(sessionId) ? await this.opts.openSessions?.working?.(sessionId).catch(() => null) : null
+ tail.external = {
+ title: session.title ?? '', cwd: session.cwd ?? '', origin: session.origin ?? '',
+ open: open?.has(sessionId) ?? false, ...(where ? { openIn: where } : {}),
+ ...(typeof working === 'boolean' ? { working } : {}),
+ }
}
return tail
}
diff --git a/cli/src/lib/sessionSearch/store.ts b/cli/src/lib/sessionSearch/store.ts
index 2a8b7c663..abc804dbe 100644
--- a/cli/src/lib/sessionSearch/store.ts
+++ b/cli/src/lib/sessionSearch/store.ts
@@ -66,6 +66,8 @@ export interface ExternalHit {
origin: string
/** Open in a running process elsewhere (a terminal, the engine's app): not to be opened twice. */
open?: boolean
+ /** Confirmed mid-turn, idle, or omitted when the engine cannot report its current work state. */
+ working?: boolean
/** Where it is open: a terminal, which Harness can take it over from; an app, which it cannot; or
* one of Harness's own panes, an agent the daemon is still binding; or `maybe` a terminal whose
* process was started on it and may have moved on. */
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index b5f55d47b..9d476daf7 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -353,18 +353,6 @@ class Agent {
/// the field.
final DateTime? lastOpenedAt;
- /// What harness lists sort by: the later of [lastActivityAt] and
- /// [lastOpenedAt], so a harness someone just looked at rises even while it
- /// is quiet. The order is global — every client and machine reads the same
- /// daemon stamps.
- DateTime? get lastUsedAt {
- final activity = lastActivityAt;
- final opened = lastOpenedAt;
- if (activity == null) return opened;
- if (opened == null) return activity;
- return opened.isAfter(activity) ? opened : activity;
- }
-
/// Cached conversation usage reported by this agent's owning machine.
final int? tokensUsed;
final DateTime? tokensUpdatedAt;
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 6566edacf..60a388a09 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -9710,23 +9710,41 @@ class AppNotifier extends ChangeNotifier {
int limit = 30,
}) async {
if (!searchableMachineIds.contains(machineId)) return null;
+ final elapsed = Stopwatch()..start();
+ const budget = Duration(seconds: 4);
+ List<SessionContentHit>? hits;
try {
- final reply = await _conn(machineId).request(
- 'session_search',
- payload: {
- 'query': query,
- 'limit': limit,
- if (when != null) ...{
- 'from': when.from.millisecondsSinceEpoch,
- 'to': when.to.millisecondsSinceEpoch,
+ // Discovery is asynchronous. An unfinished index is not a final empty
+ // answer; ask again briefly, within the same budget as one slow request.
+ for (var attempt = 0; attempt < 20; attempt++) {
+ if (_disposed || !searchableMachineIds.contains(machineId)) return hits;
+ final remaining = budget - elapsed.elapsed;
+ if (remaining <= Duration.zero) return hits;
+ final reply = await _conn(machineId).request(
+ 'session_search',
+ payload: {
+ 'query': query,
+ 'limit': limit,
+ if (when != null) ...{
+ 'from': when.from.millisecondsSinceEpoch,
+ 'to': when.to.millisecondsSinceEpoch,
+ },
},
- },
- timeout: const Duration(seconds: 4),
- );
- if (reply['error'] != null) return null;
- return SessionContentHit.listFromReply(machineId, reply);
+ timeout: remaining,
+ );
+ if (reply['error'] != null) return hits;
+ hits = SessionContentHit.listFromReply(machineId, reply);
+ // Older daemons omit ready; retain their single-request behavior.
+ if (reply['ready'] != false || reply['discoveryError'] == true)
+ return hits;
+ if (attempt == 19 ||
+ budget - elapsed.elapsed < const Duration(milliseconds: 200))
+ return hits;
+ await Future<void>.delayed(const Duration(milliseconds: 200));
+ }
+ return hits;
} catch (_) {
- return null;
+ return hits;
}
}
@@ -9738,12 +9756,17 @@ class AppNotifier extends ChangeNotifier {
String machineId,
String sessionId, {
int? beforeTurn,
+ int? maxChars,
}) async {
if (!searchableMachineIds.contains(machineId)) return null;
try {
final reply = await _conn(machineId).request(
'session_tail',
- payload: {'sessionId': sessionId, 'beforeTurn': ?beforeTurn},
+ payload: {
+ 'sessionId': sessionId,
+ 'beforeTurn': ?beforeTurn,
+ 'maxChars': ?maxChars,
+ },
timeout: const Duration(seconds: 4),
);
if (reply['error'] != null) return null;
@@ -10830,12 +10853,12 @@ class AppNotifier extends ChangeNotifier {
(String, String)? _touchedFocus;
/// Tell a harness's own daemon that a person just opened or focused it, so
- /// its `lastOpenedAt` moves and with it "last used" order in EVERY client
+ /// its `lastOpenedAt` records the visit in every client
/// (`agent_update {agentId, opened: true}`, sealed like any agent_update).
///
/// Fire-and-forget. Nothing waits on it and nothing is said when it fails:
- /// an older daemon answers MISSING_UPDATE and the list simply keeps sorting
- /// by activity; a socket that is down loses one stamp. Never dials a socket
+ /// an older daemon answers MISSING_UPDATE; a socket that is down loses one
+ /// stamp. Conversation recency is independent of this. Never dials a socket
/// for it, and never for a view-only shared harness — its owner's order is
/// not this window's to move.
void touchAgent(String machineId, String agentId) {
@@ -10875,8 +10898,7 @@ class AppNotifier extends ChangeNotifier {
timeout: const Duration(seconds: 10),
);
if (!_machineWorkCurrent(machine, revision)) return;
- // The daemon's own stamp, taken now rather than on the next push, so the
- // list this window just opened from is already in its new order. Only
+ // The daemon's own visit stamp, taken now rather than on the next push. Only
// this one field: the reply is not a frame to rebuild the agent from.
final returned = result['agent'];
final raw = returned is Map && (returned['id'] ?? agentId) == agentId
diff --git a/desktop/lib/state/harness_sessions.dart b/desktop/lib/state/harness_sessions.dart
index fb7714a86..bda15f96b 100644
--- a/desktop/lib/state/harness_sessions.dart
+++ b/desktop/lib/state/harness_sessions.dart
@@ -1,6 +1,7 @@
import 'package:collection/collection.dart' show compareNatural;
import '../core/models.dart';
+import '../core/relative_time.dart';
import 'app_state.dart';
import 'pending_question.dart';
import 'swarm_navigation.dart';
@@ -8,7 +9,7 @@ import 'swarm_navigation.dart';
enum SessionFilter { all, needsInput, running, paused }
enum SessionSort {
- recent('Recently used'),
+ recent('Recently active'),
name('Name'),
machine('Machine'),
project('Project'),
@@ -59,9 +60,8 @@ class HarnessSession {
final PendingQuestion? question;
bool get needsInput => question != null && !agent.isStopped;
- /// Activity or a person opening it in any client, whichever is later — see
- /// [Agent.lastUsedAt]. What every harness list sorts by and shows.
- DateTime? get lastUsedAt => agent.lastUsedAt;
+ /// Conversation activity, independent of opening or focusing the session.
+ DateTime? get lastActivityAt => agent.lastActivityAt;
String get machineId => machine.machine.machineId;
String get id => agentDestinationId(machineId, agent.id);
AgentProject? get project => machine.projectOf(agent);
@@ -199,7 +199,7 @@ List<HarnessSession> visibleHarnessSessions(
final ranks = {for (var i = 0; i < recent.length; i++) recent[i]: i};
result.sort((a, b) {
final comparison = switch (sort) {
- SessionSort.recent => _byLastUse(a, b, ranks, recent.length),
+ SessionSort.recent => _byActivity(a, b, ranks, recent.length),
SessionSort.name => compareNatural(
a.agent.displayName.toLowerCase(),
b.agent.displayName.toLowerCase(),
@@ -225,16 +225,16 @@ List<HarnessSession> visibleHarnessSessions(
return result;
}
-/// Most recently used first — the same global order as Open Harness — then
+/// Most recently active first — the same global order as Open Harness — then
/// this window's own visit order for ties and harnesses with no time at all.
-int _byLastUse(
+int _byActivity(
HarnessSession a,
HarnessSession b,
Map<String, int> ranks,
int fallback,
) {
- final used = (b.lastUsedAt?.millisecondsSinceEpoch ?? 0).compareTo(
- a.lastUsedAt?.millisecondsSinceEpoch ?? 0,
+ final used = (b.lastActivityAt?.millisecondsSinceEpoch ?? 0).compareTo(
+ a.lastActivityAt?.millisecondsSinceEpoch ?? 0,
);
return used != 0
? used
@@ -245,7 +245,11 @@ int _byLastUse(
String harnessActivityAge(DateTime? activity, DateTime now) {
if (activity == null) return '—';
final elapsed = now.difference(activity);
+ if (elapsed.inMinutes < 1) return 'now';
if (elapsed.inDays >= 1) return '${elapsed.inDays}d';
if (elapsed.inHours >= 1) return '${elapsed.inHours}h';
return '${elapsed.inMinutes.clamp(0, 59)}m';
}
+
+String harnessActivityTooltip(DateTime activity) =>
+ 'Last active ${fullDateTime(activity)}';
diff --git a/desktop/lib/state/session_activity.dart b/desktop/lib/state/session_activity.dart
new file mode 100644
index 000000000..351e956b7
--- /dev/null
+++ b/desktop/lib/state/session_activity.dart
@@ -0,0 +1,158 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import '../core/models.dart';
+import 'app_state.dart';
+import 'harness_activity.dart';
+import 'harness_sessions.dart';
+import 'swarm_navigation.dart';
+
+typedef SessionActivity = ({DateTime? at, HarnessActivity? status});
+
+/// Fresh display metadata for visible sessions. Ranking keeps its own snapshot;
+/// a long-running turn must not look idle just because its last message is old.
+class SessionActivityController extends ChangeNotifier {
+ SessionActivityController(this.app) {
+ app.addListener(_appChanged);
+ app.agentUnread.addListener(_appChanged);
+ }
+
+ final AppNotifier app;
+ final _external = <String, SessionActivity>{};
+ Map<String, SwarmDestination> _rows = const {};
+ Map<String, SessionActivity> _last = const {};
+ Timer? _timer;
+ bool _disposed = false;
+ bool _reading = false;
+ bool _scheduled = false;
+ int _revision = 0;
+
+ SessionActivity read(SwarmDestination row) {
+ final machine = app.stateOf(row.machineId ?? '');
+ final online =
+ machine?.nodeOnline != false &&
+ machine?.connectionStatus == ConnectionStatus.connected;
+ if (row.external case final external?) {
+ final value =
+ _external[row.id] ??
+ (
+ at: row.lastActivityAt,
+ status: external.open ? HarnessActivity.unknown : null,
+ );
+ return (
+ at: value.at,
+ status: online ? value.status : HarnessActivity.offline,
+ );
+ }
+ final agent = machine?.agents
+ .where((agent) => agent.id == row.agentId)
+ .firstOrNull;
+ return (
+ at: agent?.lastActivityAt ?? row.lastActivityAt,
+ status: row.machineId != null && row.agentId != null
+ ? harnessActivity(app, row.machineId!, row.agentId!)
+ : null,
+ );
+ }
+
+ /// Only watch the rows on screen, including after scrolling/searching. New
+ /// targets refresh after this frame; no network request changes list order.
+ void watch(Iterable<SwarmDestination> rows) {
+ if (_disposed) return;
+ final next = {for (final row in rows) row.id: row};
+ final changed = !setEquals(next.keys.toSet(), _rows.keys.toSet());
+ _rows = next;
+ _last = {for (final row in _rows.values) row.id: read(row)};
+ if (!changed) return;
+ _revision++;
+ _external.removeWhere((id, _) => !next.containsKey(id));
+ _timer?.cancel();
+ if (next.values.any((row) => row.external != null)) {
+ _timer = Timer.periodic(const Duration(seconds: 5), (_) => refresh());
+ _schedule();
+ }
+ }
+
+ void _schedule() {
+ if (_scheduled || _disposed) return;
+ _scheduled = true;
+ scheduleMicrotask(() {
+ _scheduled = false;
+ if (!_disposed) unawaited(refresh());
+ });
+ }
+
+ Future<void> refresh() async {
+ if (_reading || _disposed) return;
+ _reading = true;
+ final revision = _revision;
+ try {
+ await Future.wait([
+ for (final row in _rows.values.where((row) => row.external != null))
+ _readExternal(row, revision),
+ ]);
+ } finally {
+ _reading = false;
+ }
+ if (_disposed) return;
+ if (revision != _revision) {
+ _schedule();
+ return;
+ }
+ _appChanged();
+ }
+
+ Future<void> _readExternal(SwarmDestination row, int revision) async {
+ final reply = await app.readSessionTail(
+ row.machineId!,
+ row.external!.sessionId,
+ maxChars: 1000,
+ );
+ if (_disposed || revision != _revision) return;
+ if (reply == null) {
+ // A failed read cannot keep claiming work is still in progress.
+ _external[row.id] = (at: read(row).at, status: HarnessActivity.unknown);
+ return;
+ }
+ final at = reply['lastAt'];
+ final external = reply['external'];
+ final open = external is Map && external['open'] == true;
+ final working = external is Map ? external['working'] : null;
+ _external[row.id] = (
+ at: at is int ? DateTime.fromMillisecondsSinceEpoch(at) : read(row).at,
+ status: !open
+ ? null
+ : working == true
+ ? HarnessActivity.working
+ : working == false
+ ? HarnessActivity.idle
+ : HarnessActivity.unknown,
+ );
+ }
+
+ void _appChanged() {
+ if (_disposed) return;
+ final next = {for (final row in _rows.values) row.id: read(row)};
+ if (mapEquals(next, _last)) return;
+ _last = next;
+ notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _timer?.cancel();
+ app.removeListener(_appChanged);
+ app.agentUnread.removeListener(_appChanged);
+ super.dispose();
+ }
+}
+
+String? sessionActivityLabel(SessionActivity activity, DateTime now) =>
+ activity.at == null ? null : harnessActivityAge(activity.at, now);
+
+String sessionActivityTooltip(SessionActivity activity) => [
+ ?activity.status?.label,
+ if (activity.at case final at?) harnessActivityTooltip(at),
+].join(' · ');
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index 69f9c2bd8..c0db08ce4 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -798,8 +798,7 @@ class SwarmLocationCatalog {
}
}
-/// Open Harness sorts by last use — activity, or a person opening the harness
-/// in any client, whichever is later — the same time it shows beside each
+/// Open Harness sorts by conversation activity — the same time shown beside each
/// session, within each [SwarmMatchStrength]: typing "hn" puts the harness named
/// hn first, however many newer ones live in a folder whose path spells h…n.
/// Undated rows come last; ties retain visit recency and search relevance.
@@ -823,7 +822,7 @@ List<SwarmDestination> rankSwarmDestinationsByActivity(
final strength = a.strength.index.compareTo(b.strength.index);
if (strength != 0) return strength;
// What was said is ranked by the index, which weighs how well it matched
- // against how long ago; last use decides between equal answers.
+ // against how long ago; conversation activity decides between equal answers.
if (a.strength == SwarmMatchStrength.said ||
a.strength == SwarmMatchStrength.content) {
final said = b.said.compareTo(a.said);
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 00096195f..42b788e44 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -464,12 +464,10 @@ class SwarmSearchController extends ChangeNotifier {
/// Open Harness filters by latest activity; commands and splits keep relevance order.
final bool activityFirst;
- /// When this opening began: the list's ages are measured from it.
- final DateTime openedAt = DateTime.now();
final _activity = <String, DateTime?>{};
/// A row's last activity as it was when this opening first listed it. The
- /// list keeps the order and ages it opened with while agents work on:
+ /// list keeps its activity snapshot and order while agents work on:
/// rows moving under the cursor as someone arrowed through them was the
/// confusing part. The next opening reads activity afresh.
DateTime? activityOf(SwarmDestination row) =>
diff --git a/desktop/lib/state/welcome_sessions.dart b/desktop/lib/state/welcome_sessions.dart
index e9e6cb2ae..1b832342f 100644
--- a/desktop/lib/state/welcome_sessions.dart
+++ b/desktop/lib/state/welcome_sessions.dart
@@ -8,11 +8,11 @@ import 'swarm_search.dart' show externalSessionDestination;
/// What the welcome page offers to pick up: the harnesses you were just with,
/// and the Claude Code and Codex conversations on your machines that Harness
-/// did not start — the latest [limit] of them, whatever machine. Harnesses use
-/// recorded visits; external conversations use their conversation activity.
+/// did not start — the latest [limit] by conversation activity, whatever machine.
+/// Recorded visits determine which Harness sessions belong here, not their order.
///
-/// Read once when the page shows, like Cmd-P: the rows keep their order and
-/// numbers while the page is on screen, and the next showing reads again.
+/// Read once when the page shows, like Cmd-P: membership and order stay put.
+/// SessionActivityController keeps displayed activity and work state fresh.
/// Harnesses are in the app already; the others are asked of each machine's
/// session index (`session_search` with a time and no words).
class WelcomeSessions extends ChangeNotifier {
@@ -42,13 +42,7 @@ class WelcomeSessions extends ChangeNotifier {
final _asked = <String>{};
bool _hadAgents = false;
List<SwarmDestination> _external = const [];
- Map<String, DateTime?> _harnessVisits = const {};
-
- /// The same snapshot supplies both order and age. An older daemon can tell
- /// us a harness was opened without a visit time; leave its age unknown,
- /// rather than presenting a background hook or transcript write as a visit.
- DateTime? lastUsedAt(SwarmDestination row) =>
- row.external != null ? row.lastActivityAt : _harnessVisits[row.id];
+ Set<String> _knownHarnesses = const {};
/// The app changed. At launch the page shows before machines connect and
/// their harnesses arrive — before most of what it offers exists — so a
@@ -59,17 +53,17 @@ class WelcomeSessions extends ChangeNotifier {
final unasked = app.searchableMachineIds.any(
(machine) => !_asked.contains(machine),
);
- if (unasked || (!_hadAgents && _readHarnessVisits().isNotEmpty)) load();
+ if (unasked || (!_hadAgents && _readKnownHarnesses().isNotEmpty)) load();
}
Future<void> load() async {
readAt = _now();
- _harnessVisits = _readHarnessVisits();
+ _knownHarnesses = _readKnownHarnesses();
final harnesses = [
for (final row in SwarmSearchCatalog().read(app, projects))
- if (row.agentId != null && _harnessVisits.containsKey(row.id)) row,
+ if (row.agentId != null && _knownHarnesses.contains(row.id)) row,
];
- _hadAgents = _harnessVisits.isNotEmpty;
+ _hadAgents = _knownHarnesses.isNotEmpty;
// What the machines said last stays until they answer again.
_rows = _latest([...harnesses, ..._external]);
loading = true;
@@ -105,7 +99,7 @@ class WelcomeSessions extends ChangeNotifier {
notifyListeners();
}
- Map<String, DateTime?> _readHarnessVisits() {
+ Set<String> _readKnownHarnesses() {
final open = {
for (final pane in app.allPanes) (pane.machineId, pane.agentId),
};
@@ -116,16 +110,15 @@ class WelcomeSessions extends ChangeNotifier {
if (agent.lastOpenedAt != null ||
open.contains((machine.machine.machineId, agent.id)) ||
app.hasOpenedHarness(machine.machine.machineId, agent.id))
- agentDestinationId(machine.machine.machineId, agent.id):
- agent.lastOpenedAt,
+ agentDestinationId(machine.machine.machineId, agent.id),
};
}
List<SwarmDestination> _latest(List<SwarmDestination> all) {
final sorted = [...all]
..sort(
- (a, b) => (lastUsedAt(b) ?? DateTime(0)).compareTo(
- lastUsedAt(a) ?? DateTime(0),
+ (a, b) => (b.lastActivityAt ?? DateTime(0)).compareTo(
+ a.lastActivityAt ?? DateTime(0),
),
);
return List.unmodifiable(sorted.take(limit));
diff --git a/desktop/lib/widgets/session_activity_label.dart b/desktop/lib/widgets/session_activity_label.dart
new file mode 100644
index 000000000..1874cae19
--- /dev/null
+++ b/desktop/lib/widgets/session_activity_label.dart
@@ -0,0 +1,99 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/theme/appearance_prefs_store.dart';
+import '../state/harness_activity.dart';
+import '../state/session_activity.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
+import 'harness_activity_mark.dart';
+
+/// The same activity mark as tabs and panes, alongside conversation recency.
+class SessionActivityLabel extends StatelessWidget {
+ const SessionActivityLabel({
+ super.key,
+ required this.activity,
+ required this.age,
+ required this.style,
+ this.markColor,
+ this.reason,
+ });
+
+ final SessionActivity activity;
+ final String? age;
+ final TextStyle style;
+ final Color? markColor;
+ final String? reason;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final status = activity.status;
+ final showMark =
+ status != null &&
+ status != HarnessActivity.idle &&
+ status != HarnessActivity.unknown;
+ final textScaler = MediaQuery.textScalerOf(context);
+ if (age == null && !showMark) return const SizedBox.shrink();
+ final description = [
+ if (reason != null && reason != status?.label) reason!,
+ sessionActivityTooltip(activity),
+ ].where((part) => part.isNotEmpty).join(' · ');
+ return Tooltip(
+ message: description,
+ excludeFromSemantics: true,
+ child: Semantics(
+ label: description,
+ excludeSemantics: true,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // Keep both columns fixed as ages change (now, 1m, 12m), including
+ // rows without a confirmed status. Only the timestamp is shown
+ // when the status is unknown; its tooltip retains that detail.
+ SizedBox(
+ width: textScaler.scale(16),
+ child: showMark
+ ? Center(
+ heightFactor: 1,
+ child: ListenableBuilder(
+ listenable: Listenable.merge([
+ terminalThemeStore,
+ appearancePrefsStore,
+ ]),
+ builder: (context, _) => ActivityMark(
+ activity: status,
+ color:
+ markColor ??
+ activityColor(
+ status,
+ terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ ),
+ color: appearancePrefsStore.value.prompt.color,
+ ),
+ tooltip: false,
+ ),
+ ),
+ )
+ : null,
+ ),
+ const SizedBox(width: 6),
+ SizedBox(
+ width: textScaler.scale(40),
+ child: age == null
+ ? null
+ : Text(
+ age!,
+ maxLines: 1,
+ textAlign: TextAlign.right,
+ style: style,
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index 609d887cd..201f8320c 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -26,11 +26,14 @@ import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
import '../state/swarm_navigation.dart';
import '../state/session_content_search.dart';
+import '../state/session_activity.dart';
import '../state/swarm_search.dart';
import '../models/model_search_catalog.dart';
-import '../state/harness_sessions.dart' show SessionFilter, harnessActivityAge;
+import '../state/harness_sessions.dart'
+ show SessionFilter, harnessActivityTooltip;
import '../store/store_mark.dart';
import 'engine_identity.dart';
+import 'session_activity_label.dart';
import 'swarm_icon.dart';
import 'swarm_search_preview.dart';
import 'swarm_resource_preview.dart';
@@ -510,6 +513,7 @@ class SwarmSearchResults extends StatefulWidget {
this.header,
this.previewBuilder,
this.showPreview = true,
+ this.now = DateTime.now,
});
final SwarmSearchController search;
final ValueChanged<SwarmSearchSelection> onChoose;
@@ -524,6 +528,7 @@ class SwarmSearchResults extends StatefulWidget {
final Widget? header;
final Widget Function()? previewBuilder;
final bool showPreview;
+ final DateTime Function() now;
@override
State<SwarmSearchResults> createState() => _SwarmSearchResultsState();
}
@@ -538,6 +543,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
String? _announced;
final _scroll = ScrollController();
Timer? _activityClock;
+ late SessionActivityController _activity;
final _resultsKey = GlobalKey();
double _rowHeight = 56;
double _modelHeadingHeight = 28;
@@ -620,11 +626,15 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
@override
void initState() {
super.initState();
- if (widget.bios) {
- _activityClock = Timer.periodic(const Duration(minutes: 1), (_) {
- if (mounted) setState(() {});
- });
- }
+ _activity = SessionActivityController(search.app)
+ ..addListener(_activityChanged);
+ _scroll.addListener(_watchActivity);
+ _watchActivity();
+ _activityClock = Timer.periodic(const Duration(minutes: 1), (_) {
+ if (mounted && search.rows.any((row) => row.lastActivityAt != null)) {
+ setState(() {});
+ }
+ });
search.addListener(_changed);
terminalFontStore.addListener(_fontChanged);
_lastPage = search.resultPage.value;
@@ -635,6 +645,10 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
void didUpdateWidget(SwarmSearchResults oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.search != search) {
+ _activity.dispose();
+ _activity = SessionActivityController(search.app)
+ ..addListener(_activityChanged);
+ _watchActivity();
oldWidget.search.removeListener(_changed);
oldWidget.search.resultPage.removeListener(_pageResults);
search.addListener(_changed);
@@ -668,6 +682,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
}
void _changed() {
+ _watchActivity();
setState(() {});
_scrollToSelection();
_revealSelection();
@@ -690,6 +705,20 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
}
}
+ void _activityChanged() {
+ if (mounted) setState(() {});
+ }
+
+ void _watchActivity() {
+ final start = _scroll.hasClients
+ ? (_scroll.offset / _rowHeight).floor().clamp(0, search.rows.length)
+ : 0;
+ final count = _scroll.hasClients
+ ? (_scroll.position.viewportDimension / _rowHeight).ceil() + 2
+ : 12;
+ _activity.watch([...search.rows.skip(start).take(count), ?search.selected]);
+ }
+
void _revealSelection() {
if (_revealScheduled) return;
_revealScheduled = true;
@@ -748,6 +777,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
@override
void dispose() {
_activityClock?.cancel();
+ _activity.dispose();
+ _scroll.removeListener(_watchActivity);
search.removeListener(_changed);
terminalFontStore.removeListener(_fontChanged);
search.resultPage.removeListener(_pageResults);
@@ -851,14 +882,9 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
final canSubmit = search.canSubmit(row);
final unavailableReason = search.sessionUnavailable(row);
final alreadyHere = search.alreadyHere(row);
- // As of this opening, like the order: the list does not move while
- // it is open. Under a minute is "now", not "0m".
- final activity = widget.bios ? search.activityOf(row) : null;
- final activityAge = activity == null
- ? null
- : search.openedAt.difference(activity).inMinutes < 1
- ? 'now'
- : harnessActivityAge(activity, search.openedAt);
+ // Live display metadata is independent of the ranking snapshot.
+ final activity = _activity.read(row);
+ final activityAge = sessionActivityLabel(activity, widget.now());
final presentation = (
row,
selected,
@@ -879,6 +905,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
desktop,
stacked,
activityAge,
+ activity,
row.isModel ? search.modelRowAction(row) : null,
row.isModel ? search.canSelectModel(row) : null,
row.isModel ? search.canGetModel(row) : null,
@@ -917,6 +944,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
enabled: canSubmit,
cellSize: cell,
activityAge: activityAge,
+ activity: activity,
unavailableReason: unavailableReason,
),
),
@@ -1049,6 +1077,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
terminal: widget.terminal,
stacked: desktop || stacked,
highlighted: desktop && highlighted,
+ activityAge: activityAge,
+ activity: activity,
),
trailing: desktop
? row.shortcut == null
@@ -1578,6 +1608,7 @@ class _SearchRowContent extends StatefulWidget {
this.enabled = true,
this.cellSize,
this.activityAge,
+ this.activity = (at: null, status: null),
this.unavailableReason,
});
@@ -1591,6 +1622,7 @@ class _SearchRowContent extends StatefulWidget {
final bool enabled;
final Size? cellSize;
final String? activityAge;
+ final SessionActivity activity;
final String? unavailableReason;
@override
@@ -1715,6 +1747,7 @@ class _SearchRowContentState extends State<_SearchRowContent> {
? widget.search.modelRowStatus(row)
: null;
final status = unavailable ?? api?.hint ?? modelStatus;
+ final spokenStatus = status ?? widget.activity.status?.label;
// One line a model: a local model's size and speed sit muted before its word at the right.
final facts = row.isModel
? widget.search
@@ -1733,12 +1766,8 @@ class _SearchRowContentState extends State<_SearchRowContent> {
account: account,
)
: null;
- final activity = widget.search.activityOf(row);
- final age = activity == null
- ? null
- : widget.search.openedAt.difference(activity).inMinutes < 1
- ? 'now'
- : harnessActivityAge(activity, widget.search.openedAt);
+ final activity = widget.activity.at;
+ final age = widget.activityAge;
final detail = row.terminalDetail ?? row.detail;
Widget trailingLabel(String text) => Text(
text,
@@ -1764,8 +1793,8 @@ class _SearchRowContentState extends State<_SearchRowContent> {
);
return Semantics(
label:
- '$title\n$detail${status == null ? '' : ', $status'}'
- '${status == null && activity != null ? ', Last active ${activity.toLocal()}' : ''}'
+ '$title\n$detail${spokenStatus == null ? '' : ', $spokenStatus'}'
+ '${activity != null ? ', ${harnessActivityTooltip(activity)}' : ''}'
'${snippet == null ? '' : ', Found in conversation: ${snippet.plainSnippet}'}',
excludeSemantics: true,
child: Column(
@@ -1831,14 +1860,19 @@ class _SearchRowContentState extends State<_SearchRowContent> {
),
),
],
- if (status ?? age case final trailing?) ...[
+ if (!row.isModel &&
+ (activity != null || widget.activity.status != null)) ...[
const SizedBox(width: 12),
- if (status == null && activity != null)
- Tooltip(
- message: 'Last active ${activity.toLocal()}',
- child: trailingLabel(trailing),
- )
- else if (row.isModel && api == null)
+ SessionActivityLabel(
+ activity: widget.activity,
+ age: age,
+ style: DesktopChrome.metadata(color: muted),
+ markColor: widget.highlighted ? muted : null,
+ reason: unavailable,
+ ),
+ ] else if (status ?? age case final trailing?) ...[
+ const SizedBox(width: 12),
+ if (row.isModel && api == null)
SizedBox(
width: MediaQuery.textScalerOf(context).scale(96),
child: trailingLabel(trailing),
@@ -1919,7 +1953,7 @@ class _SearchRowContentState extends State<_SearchRowContent> {
'${modelAction == null ? '' : ', $modelAction'}'
'${widget.unavailableReason == null ? '' : ', ${widget.unavailableReason}'}'
'${row.shortcut == null ? '' : ', Shortcut ${row.shortcut}'}'
- '${widget.activityAge == null ? '' : ', Last used ${widget.activityAge} ago'}',
+ '${widget.activityAge == null ? '' : ', ${sessionActivityTooltip(widget.activity)}'}',
excludeSemantics: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -2050,16 +2084,14 @@ class _SearchRowContentState extends State<_SearchRowContent> {
style: terminalContentStyle(color: muted),
),
),
- ] else if (widget.activityAge case final age?) ...[
+ ] else if (widget.activity.at != null ||
+ widget.activity.status != null) ...[
SizedBox(width: cell.width * 2),
- Tooltip(
- message: 'Last active ${row.lastActivityAt!.toLocal()}',
- child: Text(
- age,
- maxLines: 1,
- style: terminalContentStyle(
- color: theme.foreground.withValues(alpha: .38),
- ),
+ SessionActivityLabel(
+ activity: widget.activity,
+ age: widget.activityAge,
+ style: terminalContentStyle(
+ color: theme.foreground.withValues(alpha: .38),
),
),
],
diff --git a/desktop/lib/widgets/workspace_welcome.dart b/desktop/lib/widgets/workspace_welcome.dart
index fd1ce274d..26885c4d0 100644
--- a/desktop/lib/widgets/workspace_welcome.dart
+++ b/desktop/lib/widgets/workspace_welcome.dart
@@ -6,13 +6,15 @@ import 'package:flutter/services.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
-import '../state/harness_sessions.dart';
import '../state/swarm_catalog.dart';
import '../state/swarm_navigation.dart';
import '../state/welcome_sessions.dart';
+import '../state/session_activity.dart';
import 'engine_identity.dart';
import 'desktop_chrome.dart';
+import 'session_activity_label.dart';
import '../shared/theme/appearance_prefs_store.dart';
+import '../shared/theme/prompt_style.dart';
import '../shared/theme/status_line_style.dart';
import '../shared/theme/harness_background.dart';
import 'swarm_wallpaper.dart';
@@ -38,12 +40,14 @@ class WorkspaceWelcome extends StatefulWidget {
this.projects = const [],
this.onOpen,
this.composerBuilder,
+ this.now = DateTime.now,
});
final ValueChanged<String> onCommand;
final AppNotifier? app;
final List<SavedSwarmProject> projects;
final ValueChanged<SwarmDestination>? onOpen;
+ final DateTime Function() now;
/// Embedded creation and the popup supply the exact same form. Welcome
/// only contributes its existing recent-session data beneath that form.
@@ -58,6 +62,8 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
// generated library overflows the browser debug runtime's stack here.
static const _phoneIcon = AppIcons.smartphone;
WelcomeSessions? _sessions;
+ SessionActivityController? _activity;
+ Timer? _activityClock;
int _cursor = 0;
final _focus = FocusNode(debugLabel: 'Welcome sessions');
@@ -68,9 +74,18 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
super.initState();
final app = widget.app;
if (app != null && widget.onOpen != null) {
- _sessions = WelcomeSessions(app, projects: widget.projects)
- ..addListener(_changed);
+ _activity = SessionActivityController(app)..addListener(_changed);
+ _sessions = WelcomeSessions(
+ app,
+ projects: widget.projects,
+ now: widget.now,
+ )..addListener(_changed);
_sessions!.load();
+ _activityClock = Timer.periodic(const Duration(minutes: 1), (_) {
+ if (mounted && (_sessions?.rows.isNotEmpty ?? false)) {
+ setState(() {});
+ }
+ });
app.addListener(_appChanged);
FocusManager.instance.addListener(_claimFocus);
WidgetsBinding.instance.addPostFrameCallback((_) => _claimFocus());
@@ -98,11 +113,14 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
void _appChanged() => _sessions?.appChanged();
void _changed() {
+ _activity?.watch(_sessions?.rows ?? const []);
if (mounted) setState(() {});
}
@override
void dispose() {
+ _activityClock?.cancel();
+ _activity?.dispose();
FocusManager.instance.removeListener(_claimFocus);
_focus.dispose();
if (_sessions != null) widget.app?.removeListener(_appChanged);
@@ -428,16 +446,7 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
),
),
const SizedBox(width: 16),
- if (sessions.lastUsedAt(row) case final at?)
- Text(
- sessions.readAt.difference(at).inMinutes < 1
- ? 'now'
- : harnessActivityAge(at, sessions.readAt),
- style: DesktopChrome.text(
- size: 12,
- color: DesktopChrome.muted,
- ),
- ),
+ _activityLabel(row),
],
),
),
@@ -445,8 +454,30 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
);
}
+ Widget _activityLabel(SwarmDestination row) {
+ final activity = _activity!.read(row);
+ return SessionActivityLabel(
+ activity: activity,
+ age: sessionActivityLabel(activity, widget.now()),
+ style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),
+ );
+ }
+
Widget? _recentContext(SwarmDestination row) {
- final context = row.promptContext;
+ final external = row.external;
+ final context =
+ row.promptContext ??
+ (external == null
+ ? null
+ : PromptContext(
+ machine: row.machineLabel,
+ project:
+ external.cwd
+ .split('/')
+ .where((part) => part.isNotEmpty)
+ .lastOrNull ??
+ external.cwd,
+ ));
if (context == null) {
return row.detail.isEmpty
? null
@@ -617,13 +648,8 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
final agent = row.agentId == null
? null
: machine?.agents.where((agent) => agent.id == row.agentId).firstOrNull;
- final at = _sessions!.lastUsedAt(row);
- final readAt = _sessions!.readAt;
- final age = at == null
- ? ''
- : readAt.difference(at).inMinutes < 1
- ? 'now'
- : harnessActivityAge(at, readAt);
+ final activity = _activity!.read(row);
+ final age = sessionActivityLabel(activity, widget.now()) ?? '';
final selected = index == _cursor;
return TextButton(
key: ValueKey('welcome-session-${row.id}'),
@@ -665,12 +691,12 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
textAlign: TextAlign.left,
),
),
- SizedBox(
- width: cell * 5,
- child: Text(
- age,
- textAlign: TextAlign.right,
- style: TextStyle(color: muted),
+ Padding(
+ padding: EdgeInsets.only(left: cell),
+ child: SessionActivityLabel(
+ activity: activity,
+ age: age,
+ style: style.copyWith(color: muted),
),
),
],
diff --git a/desktop/test/agent_last_used_test.dart b/desktop/test/agent_last_used_test.dart
index cdefad7ea..d5a017a39 100644
--- a/desktop/test/agent_last_used_test.dart
+++ b/desktop/test/agent_last_used_test.dart
@@ -7,7 +7,7 @@ import 'swarm_screen_test.dart' show terminal;
import 'swarm_state_test.dart' show createApp;
/// Opening a harness stamps it on its own daemon (`agent_update {opened}`), so
-/// every client's "last used" order moves with it.
+/// every client records the visit separately from conversation activity.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late RenameConnection connection;
@@ -45,7 +45,7 @@ void main() {
await pumpEventQueue();
final agent = app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0');
expect(agent.lastOpenedAt, stamp);
- expect(agent.lastUsedAt, stamp);
+ expect(agent.lastActivityAt, isNull);
expect(agent.name, 'Agent 0');
},
);
diff --git a/desktop/test/agent_model_test.dart b/desktop/test/agent_model_test.dart
index 6d8731ebd..58753e7f2 100644
--- a/desktop/test/agent_model_test.dart
+++ b/desktop/test/agent_model_test.dart
@@ -473,7 +473,7 @@ void _cloneTests() {
});
}
-/// `lastOpenedAt` and the "last used" order built on it.
+/// Recorded visits remain independent of conversation activity.
void _lastUsedTests() {
group('last used', () {
final active = DateTime.utc(2026, 9, 26, 10);
@@ -504,21 +504,21 @@ void _lastUsedTests() {
);
});
- test('lastUsedAt is the later of activity and the last open', () {
+ test('opening a session does not replace its conversation activity', () {
Agent agent({DateTime? activity, DateTime? open}) => Agent(
id: 'a',
name: 'a',
lastActivityAt: activity,
lastOpenedAt: open,
);
- expect(agent().lastUsedAt, isNull);
- expect(agent(activity: active).lastUsedAt, active);
- expect(agent(open: opened).lastUsedAt, opened);
- expect(agent(activity: active, open: opened).lastUsedAt, opened);
- expect(agent(activity: opened, open: active).lastUsedAt, opened);
+ expect(agent().lastActivityAt, isNull);
+ expect(agent(activity: active).lastActivityAt, active);
+ expect(agent(open: opened).lastActivityAt, isNull);
+ expect(agent(activity: active, open: opened).lastActivityAt, active);
+ expect(agent(activity: opened, open: active).lastActivityAt, opened);
expect(
- agent(activity: active).copyWith(lastOpenedAt: opened).lastUsedAt,
- opened,
+ agent(activity: active).copyWith(lastOpenedAt: opened).lastActivityAt,
+ active,
);
});
diff --git a/desktop/test/bios_navigation_test.dart b/desktop/test/bios_navigation_test.dart
index 02cf2c854..4576edf24 100644
--- a/desktop/test/bios_navigation_test.dart
+++ b/desktop/test/bios_navigation_test.dart
@@ -1,12 +1,75 @@
+import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/state/harness_placement.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
import 'swarm_state_test.dart' show createApp;
void main() {
+ testWidgets('Cmd-P ages update without changing order or selection', (
+ tester,
+ ) async {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ final now = tester.binding.clock.now();
+ app.machineStates['m']!.agents = [
+ Agent(
+ id: 'new',
+ name: 'New work',
+ engine: 'claude',
+ terminalAvailable: true,
+ lastActivityAt: now.subtract(const Duration(seconds: 20)),
+ ),
+ Agent(
+ id: 'viewed',
+ name: 'Old work viewed now',
+ engine: 'codex',
+ terminalAvailable: true,
+ lastActivityAt: now.subtract(const Duration(minutes: 5)),
+ lastOpenedAt: now,
+ ),
+ ];
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ activityFirst: true,
+ );
+ addTearDown(search.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: DesktopChrome(
+ child: Scaffold(
+ body: SwarmSearchResults(
+ search: search,
+ onChoose: (_) {},
+ onRefocus: () {},
+ now: tester.binding.clock.now,
+ showPreview: false,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final order = search.rows.map((row) => row.id).toList();
+ final selected = search.selected?.id;
+ final position = tester.getTopLeft(find.byKey(ValueKey(order.first)));
+ expect(find.text('now'), findsOneWidget);
+ expect(find.text('5m'), findsOneWidget);
+ await tester.pump(const Duration(minutes: 1));
+ expect(find.text('now'), findsNothing);
+ expect(find.text('1m'), findsOneWidget);
+ expect(find.text('6m'), findsOneWidget);
+ expect(search.rows.map((row) => row.id), order);
+ expect(search.selected?.id, selected);
+ expect(tester.getTopLeft(find.byKey(ValueKey(order.first))), position);
+ await tester.pumpWidget(const SizedBox());
+ });
testWidgets(
'Open Harness sorts by activity as it opened, and keeps that order while open',
(tester) async {
diff --git a/desktop/test/command_dock_interaction_test.dart b/desktop/test/command_dock_interaction_test.dart
index f91611639..679437f64 100644
--- a/desktop/test/command_dock_interaction_test.dart
+++ b/desktop/test/command_dock_interaction_test.dart
@@ -122,7 +122,7 @@ void main() {
find.descendant(of: opened, matching: find.byType(Tooltip)),
)
.message,
- startsWith('Last active '),
+ startsWith('Idle · Last active '),
);
expect(
find.descendant(
diff --git a/desktop/test/desktop_welcome_composer_test.dart b/desktop/test/desktop_welcome_composer_test.dart
index 18ff6c24e..c58fb798e 100644
--- a/desktop/test/desktop_welcome_composer_test.dart
+++ b/desktop/test/desktop_welcome_composer_test.dart
@@ -51,6 +51,7 @@ class _Connection extends WsConn {
onStatus: (_) {},
);
final starts = <Map<String, dynamic>>[];
+ final sessions = <Map<String, dynamic>>[];
Completer<Map<String, dynamic>>? pending;
@override
Future<Map<String, dynamic>> request(
@@ -65,6 +66,11 @@ class _Connection extends WsConn {
],
},
'dsh_list' => {'dsh': []},
+ 'session_search' => {
+ 'hits': sessions,
+ 'indexed': sessions.length,
+ 'pending': 0,
+ },
'fs_list_dir' => {'path': payload['path'] ?? '/work', 'entries': []},
'agent_create' => _create(payload),
_ => {},
@@ -124,7 +130,12 @@ void main() {
newHarnessOpensInBox = true;
addTearDown(() => newHarnessOpensInBox = old);
connection = _Connection('m');
- app = createApp(store: storage, connectionForTest: (_) => connection);
+ final connections = {'m': connection};
+ app = createApp(
+ store: storage,
+ connectionForTest: (id) =>
+ connections.putIfAbsent(id, () => _Connection(id)),
+ );
map = MemoryKeymap();
seedMixedAgents(app);
app.machineStates['m']!.localOnly = true;
@@ -326,6 +337,9 @@ void main() {
lastOpenedAt: DateTime.now().subtract(
Duration(minutes: index * 23),
),
+ lastActivityAt: DateTime.now().subtract(
+ Duration(minutes: index * 23),
+ ),
project: const AgentProject(
name: 'openharness',
cwd: '/work/openharness',
@@ -333,6 +347,24 @@ void main() {
),
),
];
+ connection.sessions.add({
+ 'agentId': '',
+ 'sessionId': 'claude-conversation',
+ 'engine': 'claude',
+ 'field': 'ask',
+ 'snippet': '',
+ 'score': .5,
+ 'lastAt': DateTime.now()
+ .subtract(const Duration(minutes: 10))
+ .millisecondsSinceEpoch,
+ 'external': {
+ 'title': 'Pane connection losses',
+ 'cwd': '/work/openharness',
+ 'origin': 'terminal',
+ 'open': true,
+ 'openIn': 'terminal',
+ },
+ });
tester.view.physicalSize = size;
final previous = grid.AppTheme.brightness.value;
final previousPalette = grid.AppTheme.palette.value;
@@ -381,6 +413,36 @@ void main() {
findsNothing,
);
expect(find.text('Older session seven'), findsNothing);
+ expect(find.text('Pane connection losses'), findsOneWidget);
+ final contextLines = tester
+ .widgetList<StatusLine>(
+ find.descendant(of: recent, matching: find.byType(StatusLine)),
+ )
+ .toList();
+ expect(contextLines, hasLength(6));
+ expect(contextLines[1].parts.text, 'M2 in openharness');
+ final paragraphs = find
+ .descendant(of: recent, matching: find.byType(StatusLine))
+ .evaluate()
+ .map(
+ (element) => tester.renderObject<RenderParagraph>(
+ find.descendant(
+ of: find.byWidget(element.widget),
+ matching: find.byType(RichText),
+ ),
+ ),
+ )
+ .toList();
+ expect(
+ paragraphs[1].text.style?.fontFamily,
+ paragraphs.first.text.style?.fontFamily,
+ );
+ expect(
+ paragraphs[1].text.style?.fontSize,
+ paragraphs.first.text.style?.fontSize,
+ );
+ expect(find.textContaining('not in Harness'), findsNothing);
+ expect(find.textContaining('terminal'), findsNothing);
expect(find.text('now'), findsOneWidget);
expect(find.text('0m'), findsNothing);
expect(
@@ -428,6 +490,7 @@ void main() {
);
expect(connection.starts, isEmpty);
if (scale == 1) {
+ connection.sessions.clear();
for (final machine in app.machineStates.values) {
machine.agents = [];
}
diff --git a/desktop/test/harness_session_picker_test.dart b/desktop/test/harness_session_picker_test.dart
index edf37c4ec..b29eeca57 100644
--- a/desktop/test/harness_session_picker_test.dart
+++ b/desktop/test/harness_session_picker_test.dart
@@ -398,10 +398,10 @@ void main() {
expect(harnessActivityAge(null, now), '—');
expect(
harnessActivityAge(now.add(const Duration(minutes: 4)), now),
- '0m',
+ 'now',
);
for (final sample in [
- (59, '0m'),
+ (59, 'now'),
(300, '5m'),
(3599, '59m'),
(3600, '1h'),
diff --git a/desktop/test/harness_sessions_test.dart b/desktop/test/harness_sessions_test.dart
index 3a2538c8d..235a1de20 100644
--- a/desktop/test/harness_sessions_test.dart
+++ b/desktop/test/harness_sessions_test.dart
@@ -74,10 +74,10 @@ void main() {
expect(harnessActivityAge(null, now), '—');
expect(
harnessActivityAge(now.add(const Duration(minutes: 4)), now),
- '0m',
+ 'now',
);
for (final sample in [
- (59, '0m'),
+ (59, 'now'),
(300, '5m'),
(3599, '59m'),
(3600, '1h'),
@@ -120,41 +120,38 @@ void main() {
);
});
- 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('recent activity ignores opening a quiet harness in any client', () {
+ app.machineStates['m']!.agents = [
+ Agent.fromJson({'id': 'busy', 'updatedAt': '2026-09-26T11:00:00Z'}),
+ // Opening it at noon does not change its nine o'clock activity.
+ Agent.fromJson({
+ 'id': 'opened',
+ 'updatedAt': '2026-09-26T09:00:00Z',
+ 'lastOpenedAt': '2026-09-26T12:00:00Z',
+ }),
+ // Activity counts independently of when it was opened.
+ 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 active');
+ expect(
+ visibleHarnessSessions(harnessSessions(app)).map((row) => row.agent.id),
+ ['busy', 'worked', 'opened', 'unknown'],
+ );
+ expect(
+ harnessSessions(app)
+ .singleWhere((row) => row.agent.id == 'opened')
+ .lastActivityAt,
+ DateTime.utc(2026, 9, 26, 9),
+ );
+ });
test('attention filters live questions, retains missing agents, excludes paused history', () {
app.rememberOpenedHarness('m', 'missing');
diff --git a/desktop/test/session_activity_test.dart b/desktop/test/session_activity_test.dart
new file mode 100644
index 000000000..8fcee6db8
--- /dev/null
+++ b/desktop/test/session_activity_test.dart
@@ -0,0 +1,225 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/notify/alert_sounds.dart';
+import 'package:harness/state/harness_activity.dart';
+import 'package:harness/state/session_activity.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/harness_activity_mark.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:harness/widgets/workspace_welcome.dart';
+
+import 'session_search_rendering_test.dart' show TailConnection;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ for (final picker in [false, true]) {
+ testWidgets(
+ '${picker ? 'Cmd-P' : 'Cmd-T'} updates working state in place during a long turn',
+ (tester) async {
+ final now = tester.binding.clock.now();
+ var lastAt = now.subtract(const Duration(minutes: 12));
+ bool? working = true;
+ const open = true;
+ var fail = false;
+ var reads = 0;
+ final hit = <String, dynamic>{
+ 'agentId': '',
+ 'sessionId': 'claude-session',
+ 'engine': 'claude',
+ 'field': 'name',
+ 'snippet': '',
+ 'lastAt': lastAt.millisecondsSinceEpoch,
+ 'external': {
+ 'title': 'Pane connection losses',
+ 'cwd': '/work/api',
+ 'origin': 'terminal',
+ 'open': true,
+ 'openIn': 'terminal',
+ },
+ };
+ final connection = TailConnection(
+ {
+ '': [hit],
+ 'Pane': [hit],
+ },
+ tail: (_) {
+ reads++;
+ return fail
+ ? {'error': 'OFFLINE'}
+ : {
+ 'lastAt': lastAt.millisecondsSinceEpoch,
+ 'external': {'open': open, 'working': ?working},
+ 'rows': <Object>[],
+ 'total': 0,
+ 'hasMore': false,
+ };
+ },
+ );
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ app.machineStates['m']!.agents = [
+ Agent(
+ id: 'other',
+ name: 'Other work',
+ engine: 'codex',
+ terminalAvailable: true,
+ lastOpenedAt: now,
+ lastActivityAt: now.subtract(const Duration(minutes: 3)),
+ ),
+ ];
+ addTearDown(app.dispose);
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ activityFirst: true,
+ );
+ addTearDown(search.dispose);
+ if (picker) search.setQuery('Pane');
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: true),
+ child: child!,
+ ),
+ home: DesktopChrome(
+ child: Scaffold(
+ body: picker
+ ? SwarmSearchResults(
+ search: search,
+ onChoose: (_) {},
+ onRefocus: () {},
+ showPreview: false,
+ now: tester.binding.clock.now,
+ )
+ : WorkspaceWelcome(
+ app: app,
+ onCommand: (_) {},
+ onOpen: (_) {},
+ now: tester.binding.clock.now,
+ composerBuilder: (recents) =>
+ recents ?? const SizedBox(),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpAndSettle();
+ final title = find.text('Pane connection losses');
+ final position = tester.getTopLeft(title);
+ expect(_mark(HarnessActivity.working), findsOneWidget);
+ expect(find.text('12m'), findsOneWidget);
+ expect(find.text('Working'), findsNothing);
+ final statusX = tester.getCenter(_mark(HarnessActivity.working)).dx;
+ final selected = search.selected?.id;
+
+ // A quiet tool can work for minutes without writing another message.
+ await tester.pump(const Duration(minutes: 2));
+ await tester.pumpAndSettle();
+ expect(_mark(HarnessActivity.working), findsOneWidget);
+ expect(find.text('14m'), findsOneWidget);
+ expect(tester.getTopLeft(title), position);
+
+ // A newer conversation event updates the time without moving the row.
+ lastAt = tester.binding.clock.now();
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pumpAndSettle();
+ expect(_mark(HarnessActivity.working), findsOneWidget);
+ expect(find.text('now'), findsOneWidget);
+ expect(tester.getCenter(_mark(HarnessActivity.working)).dx, statusX);
+ expect(tester.getTopLeft(title), position);
+ expect(search.selected?.id, selected);
+
+ working = false;
+ lastAt = tester.binding.clock.now();
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pumpAndSettle();
+ expect(_mark(HarnessActivity.working), findsNothing);
+ expect(find.text('now'), findsOneWidget);
+ expect(tester.getTopLeft(title), position);
+ expect(search.selected?.id, selected);
+
+ // Unknown status and read failures retain the latest known time.
+ working = null;
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pumpAndSettle();
+ expect(find.text('now'), findsOneWidget);
+ expect(find.text('Open'), findsNothing);
+ expect(_mark(HarnessActivity.working), findsNothing);
+ expect(_mark(HarnessActivity.unknown), findsNothing);
+ fail = true;
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pumpAndSettle();
+ expect(find.text('Open'), findsNothing);
+ expect(_mark(HarnessActivity.working), findsNothing);
+ expect(_mark(HarnessActivity.unknown), findsNothing);
+ expect(find.text('now'), findsOneWidget);
+
+ await tester.pumpWidget(const SizedBox());
+ final finishedReads = reads;
+ await tester.pump(const Duration(seconds: 30));
+ expect(reads, finishedReads);
+ },
+ );
+ }
+
+ test('managed sessions read current activity independently of their ranking snapshot', () async {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ final machine = app.machineStates['m']!;
+ final old = DateTime.utc(2026, 10, 4, 10);
+ final latest = old.add(const Duration(minutes: 12));
+ machine.agents = [
+ Agent(
+ id: 'a',
+ name: 'Work',
+ engine: 'codex',
+ terminalAvailable: true,
+ lastActivityAt: old,
+ ),
+ ];
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ activityFirst: true,
+ );
+ addTearDown(search.dispose);
+ final row = search.rows.singleWhere((row) => row.agentId == 'a');
+ expect(search.activityOf(row), old);
+ final activity = SessionActivityController(app);
+ addTearDown(activity.dispose);
+ activity.watch([row]);
+ machine.agents = [
+ Agent(
+ id: 'a',
+ name: 'Work',
+ engine: 'codex',
+ terminalAvailable: true,
+ lastActivityAt: latest,
+ ),
+ ];
+ machine.processingAgentIds.add('a');
+ expect(activity.read(row), (at: latest, status: HarnessActivity.working));
+ expect(search.activityOf(row), old);
+ machine.processingAgentIds.clear();
+ expect(activity.read(row), (at: latest, status: HarnessActivity.idle));
+ var notifications = 0;
+ activity.addListener(() => notifications++);
+ app.agentUnread.mark('m', 'a', AlertKind.done);
+ expect(activity.read(row), (at: latest, status: HarnessActivity.done));
+ expect(notifications, 1, reason: 'unread state shares the pane indicator');
+ app.markAgentSeen('m', 'a');
+ expect(activity.read(row), (at: latest, status: HarnessActivity.idle));
+ expect(search.activityOf(row), old);
+ });
+}
+
+Finder _mark(HarnessActivity activity) => find.byWidgetPredicate(
+ (widget) => widget is ActivityMark && widget.activity == activity,
+);
diff --git a/desktop/test/session_content_search_test.dart b/desktop/test/session_content_search_test.dart
index dfbb9edc8..a714c9b83 100644
--- a/desktop/test/session_content_search_test.dart
+++ b/desktop/test/session_content_search_test.dart
@@ -36,7 +36,7 @@ SessionContentHit hit(
/// A daemon that answers only `session_search`, from [answers] by query.
class SearchConnection extends WsConn {
- SearchConnection(this.answers)
+ SearchConnection(this.answers, {this.replies = const []})
: super(
wsBaseUrl: 'ws://fixture.invalid',
autonomousEnv: 'test',
@@ -48,6 +48,7 @@ class SearchConnection extends WsConn {
);
final Map<String, List<Map<String, dynamic>>> answers;
+ final List<Map<String, dynamic>> replies;
final asked = <String>[];
@override
@@ -59,6 +60,9 @@ class SearchConnection extends WsConn {
if (type != 'session_search') return {'error': 'UNSUPPORTED'};
final query = payload['query'] as String;
asked.add(query);
+ if (replies.isNotEmpty) {
+ return replies[(asked.length - 1).clamp(0, replies.length - 1)];
+ }
return {'hits': answers[query] ?? const [], 'indexed': 3, 'pending': 0};
}
}
diff --git a/desktop/test/session_search_rendering_test.dart b/desktop/test/session_search_rendering_test.dart
index 1e42ab371..c70ef59c2 100644
--- a/desktop/test/session_search_rendering_test.dart
+++ b/desktop/test/session_search_rendering_test.dart
@@ -201,10 +201,10 @@ void main() {
await tester.pump(const Duration(milliseconds: 50));
expect(tails, [null]);
await tester.pump(const Duration(seconds: 10));
- expect(tails, [null], reason: 'nothing refreshes while Cmd-P is open');
- expect(find.text('Working'), findsOneWidget);
- // Under a minute old reads "now", not "0m".
+ expect(tails, [null], reason: 'the managed preview is not refetched');
+ // The row keeps its activity time beside the shared status mark.
expect(find.text('now'), findsOneWidget);
+ expect(find.text('Working'), findsOneWidget);
expect(find.text('0m'), findsNothing);
final list = find.byKey(const ValueKey('session-tail:m:s7'));
diff --git a/desktop/test/swarm_search_preview_test.dart b/desktop/test/swarm_search_preview_test.dart
index 2bf3ba7f7..c89a7eb7a 100644
--- a/desktop/test/swarm_search_preview_test.dart
+++ b/desktop/test/swarm_search_preview_test.dart
@@ -9,10 +9,12 @@ import 'package:flutter/services.dart';
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_activity.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/terminal/terminal_text.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:harness/widgets/harness_activity_mark.dart';
import 'keymap_host_test.dart' show MemoryKeymap, key;
import 'keymap_runtime_test.dart' as configured;
@@ -214,7 +216,15 @@ void main() {
await tester.pump();
expect(
find.textContaining('Not connected', findRichText: true),
- findsNWidgets(2),
+ findsOneWidget,
+ );
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is ActivityMark &&
+ widget.activity == HarnessActivity.offline,
+ ),
+ findsOneWidget,
);
expect(find.text('Needs your input'), findsNothing);
expect(
diff --git a/desktop/test/unavailable_harness_picker_test.dart b/desktop/test/unavailable_harness_picker_test.dart
index 6c5ca27e3..512a64a7f 100644
--- a/desktop/test/unavailable_harness_picker_test.dart
+++ b/desktop/test/unavailable_harness_picker_test.dart
@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';
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_activity.dart';
import 'package:harness/state/harness_sessions.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/terminal/terminal_text.dart';
@@ -10,6 +11,7 @@ import 'package:harness/terminal/terminal_theme_store.dart';
import 'package:harness/widgets/search_result_text.dart';
import 'package:harness/widgets/swarm_resource_preview.dart';
import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/harness_activity_mark.dart';
import 'package:xterm/xterm.dart' show TerminalStyle;
import 'keymap_host_test.dart' show key;
@@ -180,12 +182,27 @@ void main() {
expect(controller.selected!.id, id);
expect(controller.canAccept, isFalse);
expect(
- find.descendant(of: row, matching: find.text(label)),
+ find.descendant(
+ of: row,
+ matching: find.byWidgetPredicate(
+ (widget) =>
+ widget is ActivityMark &&
+ widget.activity == HarnessActivity.offline,
+ ),
+ ),
findsOneWidget,
);
expect(
find.descendant(of: row, matching: find.text('33m')),
- findsNothing,
+ findsOneWidget,
+ );
+ expect(
+ tester
+ .widget<Tooltip>(
+ find.descendant(of: row, matching: find.byType(Tooltip)),
+ )
+ .message,
+ contains(label),
);
expect(
find.descendant(of: preview, matching: find.textContaining(label)),
diff --git a/desktop/test/welcome_sessions_test.dart b/desktop/test/welcome_sessions_test.dart
index fe9359b1f..9ccbdfb3b 100644
--- a/desktop/test/welcome_sessions_test.dart
+++ b/desktop/test/welcome_sessions_test.dart
@@ -77,6 +77,72 @@ Agent _agent(String id, String name, Duration ago) => Agent(
}
void main() {
+ test(
+ 'a fresh tab waits for a newly discovered terminal conversation',
+ () async {
+ final connection = SearchConnection(
+ {},
+ replies: [
+ {'ready': false, 'hits': []},
+ {'ready': false, 'hits': []},
+ {
+ 'ready': true,
+ 'hits': [
+ _external(
+ 'new-terminal',
+ 'New terminal conversation',
+ Duration.zero,
+ open: true,
+ openIn: 'terminal',
+ ),
+ ],
+ },
+ ],
+ );
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ addTearDown(app.dispose);
+ final sessions = WelcomeSessions(app, now: () => _now);
+ addTearDown(sessions.dispose);
+
+ await sessions.load();
+
+ expect(sessions.rows.single.external?.sessionId, 'new-terminal');
+ expect(connection.asked, ['', '', '']);
+ expect(sessions.loading, isFalse);
+ },
+ );
+
+ test(
+ 'a failed discovery retains cached conversations without retrying',
+ () async {
+ final connection = SearchConnection(
+ {},
+ replies: [
+ {
+ 'ready': false,
+ 'discoveryError': true,
+ 'hits': [_external('known', 'Known conversation', Duration.zero)],
+ },
+ ],
+ );
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ addTearDown(app.dispose);
+ final sessions = WelcomeSessions(app, now: () => _now);
+ addTearDown(sessions.dispose);
+
+ await sessions.load();
+
+ expect(sessions.rows.single.external?.sessionId, 'known');
+ expect(connection.asked, ['']);
+ },
+ );
+
test(
'discovered sessions never opened by the user stay out of recents',
() async {
@@ -107,34 +173,33 @@ void main() {
},
);
- test(
- 'a background conversation update does not count as a recent visit',
- () async {
- final (:sessions, connection: _) = _setup();
- sessions.app.machineStates['m']!.agents = [
- Agent(
- id: 'old',
- name: 'Last visited four days ago',
- engine: 'codex',
- terminalAvailable: true,
- lastOpenedAt: _now.subtract(const Duration(days: 4)),
- lastActivityAt: _now,
- ),
- _agent(
- 'recent',
- 'Last visited five minutes ago',
- const Duration(minutes: 5),
- ),
- ];
+ test('conversation activity ranks ahead of a more recent visit', () async {
+ final (:sessions, connection: _) = _setup();
+ sessions.app.machineStates['m']!.agents = [
+ Agent(
+ id: 'old',
+ name: 'Last visited four days ago',
+ engine: 'codex',
+ terminalAvailable: true,
+ lastOpenedAt: _now.subtract(const Duration(days: 4)),
+ lastActivityAt: _now,
+ ),
+ _agent(
+ 'recent',
+ 'Last visited five minutes ago',
+ const Duration(minutes: 5),
+ ),
+ ];
- await sessions.load();
+ await sessions.load();
- expect(
- sessions.rows.map((row) => row.external?.sessionId ?? row.agentId),
- ['recent', 'e-nfc', 'old', 'e-old'],
- );
- },
- );
+ expect(sessions.rows.map((row) => row.external?.sessionId ?? row.agentId), [
+ 'old',
+ 'recent',
+ 'e-nfc',
+ 'e-old',
+ ]);
+ });
test('discovery alone does not block visit history arriving later', () async {
final connection = SearchConnection({'': []});
@@ -166,7 +231,25 @@ void main() {
expect(sessions.rows.map((row) => row.agentId), ['visited']);
});
- testWidgets('the welcome age shows the visit, never background activity', (
+ test(
+ 'opening older harnesses does not crowd out a newer conversation',
+ () async {
+ final (:sessions, connection: _) = _setup();
+ sessions.app.machineStates['m']!.agents = [
+ for (var i = 0; i < 6; i++)
+ _agent(
+ 'old-$i',
+ 'Older work $i',
+ const Duration(days: 1),
+ ).copyWith(lastOpenedAt: _now),
+ ];
+ await sessions.load();
+ expect(sessions.rows.first.external?.sessionId, 'e-nfc');
+ expect(sessions.rows, hasLength(4));
+ },
+ );
+
+ testWidgets('the welcome age shows conversation activity, never the visit', (
tester,
) async {
final connection = SearchConnection({'': []});
@@ -175,7 +258,7 @@ void main() {
connectionForTest: (_) => connection,
);
addTearDown(app.dispose);
- final now = DateTime.now();
+ final now = tester.binding.clock.now();
app.machineStates['m']!.agents = [
Agent(
id: 'old',
@@ -196,15 +279,28 @@ void main() {
app.rememberOpenedHarness('m', 'legacy');
await tester.pumpWidget(
MaterialApp(
- home: WorkspaceWelcome(onCommand: (_) {}, app: app, onOpen: (_) {}),
+ home: WorkspaceWelcome(
+ onCommand: (_) {},
+ app: app,
+ onOpen: (_) {},
+ now: tester.binding.clock.now,
+ composerBuilder: (recents) => recents ?? const SizedBox(),
+ ),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
- expect(find.text('4d'), findsOneWidget);
+ expect(find.text('4d'), findsNothing);
expect(find.text('Previously opened on an older daemon'), findsOneWidget);
+ expect(find.text('now'), findsNWidgets(2));
+ final oldRow = find.text('Old conversation with new background activity');
+ final before = tester.getTopLeft(oldRow);
+ await tester.pump(const Duration(minutes: 1));
expect(find.text('now'), findsNothing);
+ expect(find.text('1m'), findsNWidgets(2));
+ expect(tester.getTopLeft(oldRow), before);
+ await tester.pumpWidget(const SizedBox());
});
test('offers harnesses and conversations Harness did not start, latest first, never one open elsewhere', () async {
@@ -476,10 +572,9 @@ void main() {
await pumpEventQueue();
expect(connection.asked, ['']);
expect(
- sessions.lastUsedAt(sessions.rows.first),
+ sessions.rows.first.lastActivityAt,
_now.subtract(const Duration(minutes: 5)),
- reason:
- 'the displayed age stays with the same visit snapshot as the order',
+ reason: 'activity changes do not reorder the open list',
);
});
}