Skip to content

Commit 15c849b

Browse files
fix(server): stop replaying old agent alerts on restart
1 parent 894d334 commit 15c849b

2 files changed

Lines changed: 200 additions & 7 deletions

File tree

‎apps/server/src/relay/AgentAwarenessRelay.test.ts‎

Lines changed: 162 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { CommandId, ProviderInstanceId } from "@t3tools/contracts";
2020
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
2121
import { RELAY_ACTIVITY_PUBLISH_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";
2222
import { describe, expect, it } from "@effect/vitest";
23+
import * as DateTime from "effect/DateTime";
2324
import * as Deferred from "effect/Deferred";
2425
import * as Effect from "effect/Effect";
2526
import * as Layer from "effect/Layer";
@@ -325,6 +326,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
325326
const projectId = "project-1" as ProjectId;
326327
const activeThreadId = "thread-active" as ThreadId;
327328
const idleThreadId = "thread-idle" as ThreadId;
329+
const oldCompletedId = "thread-old-completed" as ThreadId;
330+
const newCompletedId = "thread-new-completed" as ThreadId;
328331

329332
const baseThread = {
330333
projectId,
@@ -351,6 +354,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
351354
expect(
352355
AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({
353356
environmentId,
357+
startedAt: Date.parse(now),
354358
projects: [
355359
{
356360
id: projectId,
@@ -374,6 +378,30 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
374378
...baseThread,
375379
id: idleThreadId,
376380
},
381+
{
382+
...baseThread,
383+
id: oldCompletedId,
384+
latestTurn: {
385+
turnId: "turn-old" as TurnId,
386+
state: "completed",
387+
requestedAt: "2026-05-24T00:00:00.000Z",
388+
startedAt: "2026-05-24T00:00:00.000Z",
389+
completedAt: "2026-05-24T00:01:00.000Z",
390+
assistantMessageId: null,
391+
},
392+
},
393+
{
394+
...baseThread,
395+
id: newCompletedId,
396+
latestTurn: {
397+
turnId: "turn-new" as TurnId,
398+
state: "completed",
399+
requestedAt: "2026-05-25T00:00:01.000Z",
400+
startedAt: "2026-05-25T00:00:01.000Z",
401+
completedAt: "2026-05-25T00:00:02.000Z",
402+
assistantMessageId: null,
403+
},
404+
},
377405
{
378406
...baseThread,
379407
id: "thread-missing-project" as ThreadId,
@@ -389,7 +417,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
389417
},
390418
],
391419
}),
392-
).toEqual([activeThreadId]);
420+
).toEqual([activeThreadId, newCompletedId]);
393421
});
394422

395423
it.effect("signs the activity publish JWT and rejects tampering", () =>
@@ -797,4 +825,137 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
797825
}),
798826
),
799827
);
828+
829+
it.effect("does not alert for historical completions after startup", () =>
830+
Effect.scoped(
831+
Effect.gen(function* () {
832+
const secrets = makeMemorySecretStore();
833+
const now = yield* DateTime.now;
834+
const old = DateTime.formatIso(DateTime.add(now, { days: -7 }));
835+
const threadId = "thread-old" as ThreadId;
836+
const projectId = "project-1" as ProjectId;
837+
const environmentId = "env-1" as EnvironmentId;
838+
const project = {
839+
id: projectId,
840+
title: "T3 Code",
841+
workspaceRoot: "/workspace",
842+
repositoryIdentity: null,
843+
defaultModelSelection: null,
844+
scripts: [],
845+
createdAt: old,
846+
updatedAt: old,
847+
} satisfies OrchestrationProjectShell;
848+
const completedTurn = {
849+
turnId: "turn-1" as TurnId,
850+
state: "completed",
851+
requestedAt: old,
852+
startedAt: old,
853+
completedAt: old,
854+
assistantMessageId: null,
855+
} as const;
856+
const completedThread = {
857+
id: threadId,
858+
projectId,
859+
title: "Old task",
860+
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
861+
runtimeMode: "full-access",
862+
interactionMode: "default",
863+
branch: null,
864+
worktreePath: null,
865+
pullRequests: [],
866+
latestTurn: completedTurn,
867+
createdAt: old,
868+
updatedAt: old,
869+
archivedAt: null,
870+
settledOverride: null,
871+
settledAt: null,
872+
session: null,
873+
latestUserMessageAt: old,
874+
hasPendingApprovals: false,
875+
hasPendingUserInput: false,
876+
hasActionableProposedPlan: false,
877+
} satisfies OrchestrationThreadShell;
878+
let currentThread: OrchestrationThreadShell | null = completedThread;
879+
let publishes = 0;
880+
const originalFetch = globalThis.fetch;
881+
globalThis.fetch = (() => {
882+
publishes += 1;
883+
return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
884+
}) as unknown as typeof fetch;
885+
yield* Effect.addFinalizer(() =>
886+
Effect.sync(() => {
887+
globalThis.fetch = originalFetch;
888+
}),
889+
);
890+
yield* secrets.setString(RELAY_URL_SECRET, "https://relay.example.test");
891+
yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
892+
yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
893+
894+
const layer = Layer.mergeAll(
895+
Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
896+
Layer.succeed(ServerEnvironment.ServerEnvironment, {
897+
getEnvironmentId: Effect.succeed(environmentId),
898+
getDescriptor: Effect.die("unused descriptor"),
899+
}),
900+
Layer.succeed(OrchestrationEngineService, {} as OrchestrationEngineShape),
901+
Layer.succeed(ProjectionSnapshotQuery, {
902+
getThreadShellById: () => Effect.sync(() => Option.fromNullishOr(currentThread)),
903+
getProjectShellById: () => Effect.succeed(Option.some(project)),
904+
} as unknown as ProjectionSnapshotQueryShape),
905+
);
906+
907+
yield* Effect.gen(function* () {
908+
const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
909+
yield* relay.publishThread(threadId);
910+
expect(publishes).toBe(0);
911+
912+
currentThread = {
913+
...completedThread,
914+
latestTurn: null,
915+
session: {
916+
threadId,
917+
status: "ready",
918+
providerName: "Codex",
919+
runtimeMode: "full-access",
920+
activeTurnId: null,
921+
lastError: null,
922+
updatedAt: old,
923+
},
924+
};
925+
expect(
926+
AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({
927+
environmentId,
928+
threadId,
929+
thread: Option.some(currentThread),
930+
project: Option.some(project),
931+
}).state?.phase,
932+
).toBe("completed");
933+
yield* relay.publishThread(threadId);
934+
expect(publishes).toBe(0);
935+
936+
currentThread = {
937+
...completedThread,
938+
session: {
939+
threadId,
940+
status: "error",
941+
providerName: "Codex",
942+
runtimeMode: "full-access",
943+
activeTurnId: null,
944+
lastError: "old failure",
945+
updatedAt: old,
946+
},
947+
};
948+
yield* relay.publishThread(threadId);
949+
expect(publishes).toBe(0);
950+
}).pipe(
951+
Effect.provide(
952+
AgentAwarenessRelay.layer.pipe(
953+
Layer.provide(layer),
954+
Layer.provideMerge(NodeServices.layer),
955+
),
956+
),
957+
);
958+
}),
959+
),
960+
);
800961
});

‎apps/server/src/relay/AgentAwarenessRelay.ts‎

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,22 @@ export function resolveAgentAwarenessRelayPublishSnapshot(input: {
267267
};
268268
}
269269

270+
function terminalWorkSinceStart(thread: OrchestrationThreadShell, startedAt: number): boolean {
271+
const workStartedAt =
272+
Date.parse(
273+
thread.latestTurn?.startedAt ??
274+
thread.latestTurn?.requestedAt ??
275+
thread.latestUserMessageAt ??
276+
"",
277+
) || 0;
278+
const turnCompletedAt = Date.parse(thread.latestTurn?.completedAt ?? "") || 0;
279+
const sessionUpdatedAt = Date.parse(thread.session?.updatedAt ?? "") || 0;
280+
return turnCompletedAt > startedAt || (workStartedAt > startedAt && sessionUpdatedAt > startedAt);
281+
}
282+
270283
export function resolveAgentAwarenessRelayActiveThreadIds(input: {
271284
readonly environmentId: EnvironmentId;
285+
readonly startedAt: number;
272286
readonly projects: ReadonlyArray<Pick<OrchestrationProjectShell, "id" | "title">>;
273287
readonly threads: ReadonlyArray<OrchestrationThreadShell>;
274288
}): ReadonlyArray<ThreadId> {
@@ -279,12 +293,16 @@ export function resolveAgentAwarenessRelayActiveThreadIds(input: {
279293
if (!project) {
280294
return false;
281295
}
296+
const state = projectThreadAwareness({
297+
environmentId: input.environmentId,
298+
project,
299+
thread,
300+
});
282301
return (
283-
projectThreadAwareness({
284-
environmentId: input.environmentId,
285-
project,
286-
thread,
287-
}) !== null
302+
state !== null &&
303+
(state.phase !== "completed" && state.phase !== "failed"
304+
? true
305+
: terminalWorkSinceStart(thread, input.startedAt))
288306
);
289307
})
290308
.map((thread) => thread.id);
@@ -298,6 +316,7 @@ export const make = Effect.gen(function* () {
298316
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
299317
const crypto = yield* Crypto.Crypto;
300318
const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
319+
const startedAt = (yield* DateTime.now).epochMilliseconds;
301320
const activeSnapshotPublishedRef = yield* Ref.make(false);
302321
const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
303322

@@ -417,6 +436,14 @@ export const make = Effect.gen(function* () {
417436
});
418437
const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);
419438
const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);
439+
if (
440+
(snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") &&
441+
!publishedStateByThread.has(threadId)
442+
) {
443+
// Startup has no publish history. Only work from this server process may
444+
// produce an initial terminal alert; historical threads remain quiet.
445+
if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return;
446+
}
420447
if (publishedStateByThread.get(threadId) === publishIdentity) {
421448
// The projection is back at (or never left) the last published state, so
422449
// any pending deferred confirmation is moot. Leaving the deadline in
@@ -495,7 +522,11 @@ export const make = Effect.gen(function* () {
495522
});
496523
yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
497524
const nextPublishedStates = new Map(publishedStates);
498-
nextPublishedStates.set(threadId, publishIdentity);
525+
if (snapshot.state === null) {
526+
nextPublishedStates.delete(threadId);
527+
} else {
528+
nextPublishedStates.set(threadId, publishIdentity);
529+
}
499530
return nextPublishedStates;
500531
});
501532
});
@@ -529,6 +560,7 @@ export const make = Effect.gen(function* () {
529560
const snapshot = yield* snapshotQuery.getShellSnapshot();
530561
const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
531562
environmentId,
563+
startedAt,
532564
projects: snapshot.projects,
533565
threads: snapshot.threads,
534566
});

0 commit comments

Comments
 (0)