From 6c4dfc8d80866847fc60762b73a5062b89230dd1 Mon Sep 17 00:00:00 2001 From: Gabriel De Andrade <30420087+gabrielelpidio@users.noreply.github.com> Date: Tue, 28 Jul 2026 09:51:45 -0400 Subject: [PATCH] Fix desktop focus review findings --- .../presence/FocusedDesktopClients.test.ts | 18 +++ .../src/presence/FocusedDesktopClients.ts | 10 ++ .../src/relay/AgentAwarenessRelay.test.ts | 147 ++++++++++++++++++ apps/server/src/relay/AgentAwarenessRelay.ts | 77 ++++++--- apps/server/src/ws.ts | 5 +- 5 files changed, 232 insertions(+), 25 deletions(-) diff --git a/apps/server/src/presence/FocusedDesktopClients.test.ts b/apps/server/src/presence/FocusedDesktopClients.test.ts index 7a0c8163a9..4b8db2c2cc 100644 --- a/apps/server/src/presence/FocusedDesktopClients.test.ts +++ b/apps/server/src/presence/FocusedDesktopClients.test.ts @@ -52,4 +52,22 @@ describe("FocusedDesktopClients", () => { expect(observed).toEqual([false, true, false]); }).pipe(Effect.provide(FocusedDesktopClients.layer)), ); + + it.effect("holds a focus lease for the full lifetime of the RPC stream", () => + Effect.gen(function* () { + const presence = yield* FocusedDesktopClients.FocusedDesktopClients; + const stream = yield* FocusedDesktopClients.holdFocusLease(presence).pipe( + Stream.runDrain, + Effect.forkChild({ startImmediately: true }), + ); + + for (let iteration = 0; iteration < 100 && !(yield* presence.anyFocused); iteration++) { + yield* Effect.yieldNow; + } + expect(yield* presence.anyFocused).toBe(true); + + yield* Fiber.interrupt(stream); + expect(yield* presence.anyFocused).toBe(false); + }).pipe(Effect.provide(FocusedDesktopClients.layer)), + ); }); diff --git a/apps/server/src/presence/FocusedDesktopClients.ts b/apps/server/src/presence/FocusedDesktopClients.ts index 0b7c67207e..260f24611e 100644 --- a/apps/server/src/presence/FocusedDesktopClients.ts +++ b/apps/server/src/presence/FocusedDesktopClients.ts @@ -39,4 +39,14 @@ export const make = Effect.gen(function* () { }); }); +export function holdFocusLease(presence: { + readonly acquire: Effect.Effect; +}): Stream.Stream { + return Stream.fromEffect(presence.acquire).pipe( + Stream.drain, + Stream.concat(Stream.never), + Stream.scoped, + ); +} + export const layer = Layer.effect(FocusedDesktopClients, make); diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 442b54d872..5f1b72d7a6 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -28,6 +28,7 @@ import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import * as Tracer from "effect/Tracer"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; @@ -519,6 +520,137 @@ describe.sequential("signRelayAgentActivityPublishProof", () => { ), ); + it.effect("rechecks desktop focus immediately before publishing agent activity", () => + Effect.scoped( + Effect.gen(function* () { + const originalFetch = globalThis.fetch; + let fetchCount = 0; + let focusReadCount = 0; + let snapshotReadCount = 0; + const secrets = makeMemorySecretStore(); + const now = "2026-05-25T00:00:00.000Z"; + const environmentId = "env-1" as EnvironmentId; + const projectId = "project-1" as ProjectId; + const threadId = "thread-1" as ThreadId; + const project = { + id: projectId, + title: "T3 Code", + workspaceRoot: "/workspace", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + } satisfies OrchestrationProjectShell; + const thread = { + id: threadId, + projectId, + title: "Run remote agent", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurn: { + turnId: "turn-1" as TurnId, + state: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + assistantMessageId: null, + }, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + session: { + threadId, + status: "running", + providerName: "Codex", + runtimeMode: "full-access", + activeTurnId: "turn-1" as TurnId, + lastError: null, + updatedAt: now, + }, + latestUserMessageAt: now, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + } satisfies OrchestrationThreadShell; + const descriptor = { + environmentId, + label: "Test Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + } satisfies ExecutionEnvironmentDescriptor; + + globalThis.fetch = (() => { + fetchCount += 1; + return Promise.resolve(Response.json({ ok: true, deliveries: [] })); + }) as unknown as typeof fetch; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + globalThis.fetch = originalFetch; + }), + ); + yield* secrets.setString(RELAY_URL_SECRET, "https://transport.example.test"); + yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential"); + yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true"); + + const dependencies = Layer.mergeAll( + Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store), + Layer.succeed(ServerEnvironment.ServerEnvironment, { + getEnvironmentId: Effect.succeed(environmentId), + getDescriptor: Effect.succeed(descriptor), + }), + Layer.succeed(OrchestrationEngineService, { + readEvents: () => Stream.empty, + dispatch: () => Effect.succeed({ sequence: 1 }), + streamDomainEvents: Stream.empty, + latestSequence: Effect.succeed(0), + } satisfies OrchestrationEngineShape), + Layer.succeed(ProjectionSnapshotQuery, { + getThreadShellById: () => + Effect.sync(() => { + snapshotReadCount += 1; + return Option.some(thread); + }), + getProjectShellById: () => Effect.succeed(Option.some(project)), + } as unknown as ProjectionSnapshotQueryShape), + Layer.succeed( + FocusedDesktopClients.FocusedDesktopClients, + FocusedDesktopClients.FocusedDesktopClients.of({ + anyFocused: Effect.sync(() => { + focusReadCount += 1; + return focusReadCount > 1; + }), + changes: Stream.empty, + acquire: Effect.void, + }), + ), + ); + + yield* Effect.gen(function* () { + const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay; + yield* relay.publishThread(threadId); + }).pipe( + Effect.provide( + AgentAwarenessRelay.layer.pipe( + Layer.provide(dependencies), + Layer.provideMerge(NodeServices.layer), + ), + ), + ); + + expect(focusReadCount).toBe(2); + expect(snapshotReadCount).toBe(1); + expect(fetchCount).toBe(0); + }), + ), + ); + it.effect("keeps the orchestration listener armed until relay config is installed", () => Effect.scoped( Effect.gen(function* () { @@ -754,6 +886,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => { let snapshotThreads: Array = [thread]; const focusedDesktopClients = yield* FocusedDesktopClients.make; + let tombstoneAttempts = 0; globalThis.fetch = (async ( input: Parameters[0], init?: Parameters[1], @@ -770,6 +903,12 @@ describe.sequential("signRelayAgentActivityPublishProof", () => { const payload = (await request.json()) as { readonly state: RelayAgentActivityState | null; }; + if (payload.state === null) { + tombstoneAttempts += 1; + if (tombstoneAttempts === 1) { + throw new Error("transient tombstone publish failure"); + } + } runFork(Queue.offer(fetches, { url, state: payload.state })); return Response.json({ ok: true, deliveries: [] }); }) as typeof fetch; @@ -837,9 +976,17 @@ describe.sequential("signRelayAgentActivityPublishProof", () => { const desktopFocusScope = yield* Scope.make(); yield* focusedDesktopClients.acquire.pipe(Scope.provide(desktopFocusScope)); + for (let iteration = 0; iteration < 10; iteration++) { + if (tombstoneAttempts >= 2) { + break; + } + yield* TestClock.adjust("1 second"); + yield* Effect.yieldNow; + } const focusedPublish = yield* Queue.take(fetches).pipe(Effect.timeout("2 seconds")); expect(focusedPublish.url.origin).toBe("https://transport.example.test"); expect(focusedPublish.state).toBeNull(); + expect(tombstoneAttempts).toBe(2); snapshotThreads = []; yield* Scope.close(desktopFocusScope, Exit.void); diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 4e25c6f5d5..bd7cfcbfe5 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -385,6 +385,15 @@ export const make = Effect.gen(function* () { readonly reason: string; }) => Effect.gen(function* () { + if (!options?.desktopFocusTombstone && (yield* focusedDesktopClients.anyFocused)) { + yield* Effect.logDebug( + "agent activity publish skipped; desktop client focused during publish", + { + threadId, + }, + ); + return false; + } const proof = yield* makePublishProof({ privateKey: cloudLinkKeyPair.privateKey, relayIssuer: relayConfig.issuer, @@ -420,6 +429,7 @@ export const make = Effect.gen(function* () { ok: response.ok, deliveries: deliveryStats(response.deliveries), }); + return true; }); if (options?.desktopFocusTombstone) { @@ -521,11 +531,14 @@ export const make = Effect.gen(function* () { }); } - yield* publishState({ + const published = yield* publishState({ projectId: snapshot.projectId, state: snapshot.state, reason: snapshot.reason, }); + if (!published) { + return; + } yield* Ref.update(publishedStateByThreadRef, (publishedStates) => { const nextPublishedStates = new Map(publishedStates); nextPublishedStates.set(threadId, publishIdentity); @@ -576,6 +589,44 @@ export const make = Effect.gen(function* () { }); }); + let scheduleDesktopFocusTombstoneRetry: ( + threadId: ThreadId, + ) => Effect.Effect = () => Effect.void; + + const publishDesktopFocusTombstone = Effect.fn("publishDesktopFocusTombstone")(function* ( + threadId: ThreadId, + ) { + if (!(yield* focusedDesktopClients.anyFocused)) { + return; + } + const published = yield* publishSemaphore + .withPermits(1)( + publishThreadUnsafe(threadId, { + desktopFocusTombstone: true, + }), + ) + .pipe( + Effect.as(true), + Effect.catchCause((cause) => + Effect.logWarning("desktop focus agent activity tombstone failed; retrying", { + threadId, + cause: Cause.pretty(cause), + }).pipe(Effect.as(false)), + ), + withRelayClientTracing, + ); + if (!published) { + yield* scheduleDesktopFocusTombstoneRetry(threadId); + } + }); + + scheduleDesktopFocusTombstoneRetry = (threadId) => + Effect.sleep("1 second").pipe( + Effect.andThen(publishDesktopFocusTombstone(threadId)), + Effect.forkScoped, + Effect.asVoid, + ); + const suppressMobileAgentAwareness = Effect.fn("suppressMobileAgentAwareness")(function* ( snapshotThreadIds?: ReadonlyArray, ) { @@ -595,26 +646,10 @@ export const make = Effect.gen(function* () { yield* Effect.logInfo("desktop client focused; clearing mobile agent awareness", { count: threadIds.size, }); - yield* Effect.forEach( - threadIds, - (threadId) => - publishSemaphore - .withPermits(1)( - publishThreadUnsafe(threadId, { - desktopFocusTombstone: true, - }), - ) - .pipe( - Effect.catchCause((cause) => - Effect.logWarning("desktop focus agent activity tombstone failed", { - threadId, - cause: Cause.pretty(cause), - }), - ), - withRelayClientTracing, - ), - { discard: true }, - ); + yield* Effect.forEach(threadIds, publishDesktopFocusTombstone, { + concurrency: 4, + discard: true, + }); }); const resumeMobileAgentAwareness = Effect.fn("resumeMobileAgentAwareness")(function* () { diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index a0facd1895..aec1423ede 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1017,10 +1017,7 @@ const makeWsRpcLayer = ( observeRpcStream( WS_METHODS.clientReportDesktopFocus, currentSession.client.deviceType === "desktop" - ? Stream.fromEffect(focusedDesktopClients.acquire).pipe( - Stream.drain, - Stream.concat(Stream.never), - ) + ? FocusedDesktopClients.holdFocusLease(focusedDesktopClients) : Stream.empty, { "rpc.aggregate": "client-presence" }, ),