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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: enhance session handling for mobile by adding stale state management and recent reply processing
Dev jacobb0a5ec4876ea
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex ffdca6103..8f5061f54 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -1875,3 +1875,42 @@ describe('Autonomous direct isolation from existing relay/browser behavior', ()backend.detachDirectDevice('autonomous-direct:test')})})++describe('agent_recent replies', () => {+ // Three long answers — well past the dial's ~15KB frame — as a working agent's recaps are.+ const answer = (turn: number) => `Turn ${turn}: ${'the llama.cpp build is b4521 and '.repeat(250)}`+ const events = [1, 2, 3].map((turn) => ({ kind: 'summary', text: `body ${turn}`, recap: `recap ${turn}`, fullText: answer(turn) }))++ async function recentReplyFor(role: 'web' | 'device') {+ const socket = new BackendSocket('token')+ socket.recentProvider = () => events+ socket.recentAsksProvider = () => ['which llama.cpp build is this?']+ socket.connect()+ const ws = wsMock.instances.at(-1)!+ ws.open()+ vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'agent_recent', payload: { requestId: 'recent-1', agentId: 'a1', n: 3 } })+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(socket.e2ee, 'sessionRole').mockReturnValue(role)+ vi.spyOn(socket.e2ee, 'rpcReplyFrameBytes').mockImplementation((_c, _t, _r, payload) => Buffer.byteLength(JSON.stringify(payload)))+ const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ type: 'agent_recent_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },+ })+ ws.message({ t: 'down', connId: 'conn-1', frame: { type: 'agent_recent', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } } })+ await vi.waitFor(() => expect(wrapReply).toHaveBeenCalled())+ await socket.stop()+ return wrapReply.mock.calls[0][3] as { events: Array<Record<string, unknown>>; asks: string[] }+ }++ it('reaches the phone and a remote desktop whole, full answers included', async () => {+ const reply = await recentReplyFor('web')+ expect(reply.events).toHaveLength(3)+ expect(reply.events[0].fullText).toBe(answer(1))+ expect(reply.asks).toEqual(['which llama.cpp build is this?'])+ })++ it('is still fitted to the dial’s frame for a device', async () => {+ const reply = await recentReplyFor('device')+ expect(reply.events).toHaveLength(1)+ expect(reply.events[0]).not.toHaveProperty('fullText')+ })+})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex b7bdb0c12..47650b0df 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -1257,7 +1257,11 @@ export class BackendSocket {}if (connId && this.e2ee.hasSession(connId) && (ENCRYPTED_RPC_RESULT_TYPES.has(resultType) || SHARE_RESULT_TYPES.has(resultType))) {let replyPayload = payload- if (resultType === 'agent_recent_result') {+ // ⚠️ The DIAL's frame budget, so only a dial's reply is fitted to it. The phone app and a remote+ // desktop are `web` sessions and search this reply for the agent's latest answer: fitted, a reply+ // over ~15KB dropped to one event without its `fullText`, so any agent doing real work — long+ // answers — could not be found by what it had just said.+ if (resultType === 'agent_recent_result' && this.e2ee.sessionRole(connId) === 'device') {const trim = fitRecentReplyPayloadForDevice(payload,(candidate) => this.e2ee.rpcReplyFrameBytes(connId, resultType, requestId, candidate),diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 4b42e2d48..57a9f9382 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -381,6 +381,18 @@ class AppNotifier extends ChangeNotifier {machine.agents.map((agent) => previewKey(machine.machine.machineId, agent)),);+ /// Has the next warm re-read [agent]'s content when its machine says the+ /// conversation moved since [before] — a turn this phone may have slept+ /// through. Compared on the machine's own clock, so a phone whose clock+ /// disagrees cannot make every refresh look like news.+ void _staleIfMoved(MachineState machine, Agent? before, Agent agent) {+ final moved = agent.updatedAt;+ if (before == null || moved == null) return;+ final was = before.updatedAt;+ if (was != null && !moved.isAfter(was)) return;+ sessionPreviews.markStale(previewKey(machine.machine.machineId, agent));+ }+/// When this launch became signed in, and by which route — until the first/// message of that session has been reported, after which it is null.///@@ -2935,6 +2947,14 @@ class AppNotifier extends ChangeNotifier {final prev = byId[agent.id];if (prev == null ||prev.name != agent.name ||+ // What search and the Recent list read: a turn that ends moves+ // `updatedAt` and often `title`, and a sync that ignored them left+ // the phone sorting and searching by the list it had an hour ago.+ prev.title != agent.title ||+ prev.updatedAt != agent.updatedAt ||+ prev.gridModel != agent.gridModel ||+ prev.selectedModel != agent.selectedModel ||+ prev.dshName != agent.dshName ||prev.sessionId != agent.sessionId ||prev.engine != agent.engine ||prev.engineDisplayName != agent.engineDisplayName ||@@ -3594,6 +3614,7 @@ class AppNotifier extends ChangeNotifier {void _replaceAgents(MachineState machine, List<Agent> agents) {final nextIds = agents.map((agent) => agent.id).toSet();+ final previous = {for (final agent in machine.agents) agent.id: agent};for (final old in machine.agents.where((agent) => !nextIds.contains(agent.id),)) {@@ -3605,6 +3626,7 @@ class AppNotifier extends ChangeNotifier {agent.id,agent.sessionId,);+ _staleIfMoved(machine, previous[agent.id], agent);}for (final agentId in machine.processingAgentIds.difference(nextIds)) {_cancelTurnActivity(machine.machine.machineId, agentId);@@ -3648,6 +3670,7 @@ class AppNotifier extends ChangeNotifier {agent.id,agent.sessionId,);+ _staleIfMoved(machine, previous, agent);sessionPreviews.warm([previewKey(machine.machine.machineId, agent)]);machine.sessionAgentIds.removeWhere((_, id) => id == agent.id);final sessionId = agent.sessionId;diff --git a/mobile/lib/state/session_preview.dart b/mobile/lib/state/session_preview.dartindex 830704192..b6447ce21 100644--- a/mobile/lib/state/session_preview.dart+++ b/mobile/lib/state/session_preview.dart@@ -1,7 +1,8 @@/// Ported from the desktop's `lib/state/session_preview.dart`, so a phone/// search reaches the same session content the desktop's Open Agent picker-/// does. Keep the two in step; the one addition here is-/// [SessionPreview.searchParts], which the phone's result rows quote from.+/// does. Keep the two in step; the additions here are+/// [SessionPreview.searchParts], which the phone's result rows quote from, and+/// [SessionPreviewStore.markStale], for turns a sleeping phone never heard.library;import 'dart:async';@@ -118,6 +119,15 @@ class SessionPreviewStore extends ChangeNotifier {SessionPreview? read(SessionPreviewKey key) => _records[key];+ /// Lets the next [warm] read [key] again, inside [freshFor] or not — for a+ /// session its machine says has moved since this copy was taken.+ ///+ /// ⚠️ A phone needs this where the desktop does not. iOS suspends the socket+ /// in the background, so a reply that lands meanwhile never arrives as live+ /// events; without this the copy taken before it stays the one searched+ /// until [freshFor] runs out and something happens to warm it again.+ void markStale(SessionPreviewKey key) => _records[key]?._attemptedAt = null;+SessionPreview _entry(SessionPreviewKey key) {final entry = _records.remove(key) ?? SessionPreview();entry._searchText = null;diff --git a/mobile/test/phone_search_test.dart b/mobile/test/phone_search_test.dartindex 7a628cb72..50eea3a6b 100644--- a/mobile/test/phone_search_test.dart+++ b/mobile/test/phone_search_test.dart@@ -259,6 +259,45 @@ void main() {});});+ test(+ 'a turn the phone slept through is re-read once its machine says so',+ () async {+ final conn = _RecentConn({+ 'live': ['first question'],+ });+ final app = _app([+ _machine('box', [_agent('live', minutesAgo: 30)]),+ ], conn: conn);+ addTearDown(app.dispose);+ app.sessionPreviews.warm([+ app.previewKey('box', app.machineStates['box']!.agents.single),+ ]);+ await _settle();+ expect(rankPhoneSearch(phoneSearchIndex(app), 'deploy'), isEmpty);++ // The reply lands while the phone is away; on return the machine re-sends+ // the agent with a later `updatedAt`, well inside the store's freshFor.+ conn.asks['live'] = ['please deploy the llama build'];+ await app.handleEventForTest('box', {+ 'type': 'agent_synced',+ 'payload': {+ 'agent': {+ 'id': 'live',+ 'name': 'work · live',+ 'engine': 'codex',+ 'updatedAt': DateTime.now().toUtc().toIso8601String(),+ 'terminal': {'available': true},+ },+ },+ });+ await _settle();+ expect(conn.asked, ['live', 'live']);+ expect(_agentIds(rankPhoneSearch(phoneSearchIndex(app), 'deploy')), [+ 'live',+ ]);+ },+ );+group('session content', () {test('a word only in what an agent was asked finds it, after fields',diff --git a/mobile/test/session_preview_test.dart b/mobile/test/session_preview_test.dartindex a0b45bf5f..37113db6d 100644--- a/mobile/test/session_preview_test.dart+++ b/mobile/test/session_preview_test.dart@@ -223,4 +223,27 @@ void main() {store.warm([a]);expect(calls, 2);});++ test(+ 'markStale lets a moved session be read again inside freshFor',+ () async {+ var calls = 0;+ final store = SessionPreviewStore(+ canFetch: (_) => true,+ fetchRecent: (_) async => {+ 'asks': ['question ${++calls}'],+ },+ );+ addTearDown(store.dispose);+ store.warm([a]);+ await Future<void>.delayed(Duration.zero);+ store.warm([a]);+ expect(calls, 1, reason: 'fresh, so not read again');+ store.markStale(a);+ store.warm([a]);+ await Future<void>.delayed(Duration.zero);+ expect(calls, 2);+ expect(store.read(a)!.latestRequest, 'question 2');+ },+ );}