Skip to content

Commit c5766da

Browse files
radroidclaude
authored andcommitted
feat(web): closed-tab Web Push notifications (SW + PWA + server VAPID push)
Closes the accepted v1 gap from #14: notifications previously only fired while a T3 tab was open. This delivers a push when the tab is fully closed. Client (apps/web): - PWA manifest + icons + installability (required for iOS Safari Web Push). - Push-only service worker (no fetch handler, so no offline/stale-asset risk): shows a notification on push, focuses/opens the waiting thread on click, and suppresses when any T3 tab is open so the in-page NotificationCoordinator stays the single source while a tab is alive. - PushSubscriptionManager keeps the subscription in sync with the existing notifyOnNeedsInput setting + permission (reacts to a post-mount grant via the Permissions API). Pure, tested VAPID/subscription helpers. Server (apps/server/src/t3x/webPush — fork-seam clean, no upstream edits): - Reactor taps OrchestrationEngine.streamDomainEvents, recomputes the awareness phase with the shared projectThreadAwareness, edge-detects the same transitions the web client does (waiting_for_input/approval; running-> completed), and sends Web Push to registered subscriptions, pruning expired (404/410) ones. - JSON subscription store in the state dir; VAPID keypair via ServerSecretStore (T3X_VAPID_* env override supported); raw /api/t3x/push/{subscribe,unsubscribe,vapid-public-key} routes mounted through the existing T3xRoutesLive seam. Verified: apps/web + apps/server typecheck clean (0 errors); web + server unit tests pass; web-push loads at runtime; server+bin construction tests (277) pass. Browser end-to-end (grant permission, close tab, receive push) is manual QA. Closes #19 Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 3a222c2 commit c5766da

22 files changed

Lines changed: 1403 additions & 2 deletions

‎apps/server/package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"@pierre/diffs": "catalog:",
3333
"effect": "catalog:",
3434
"node-pty": "^1.1.0",
35+
"web-push": "^3.6.7",
3536
"yaml": "catalog:"
3637
},
3738
"devDependencies": {
@@ -42,6 +43,7 @@
4243
"@t3tools/web": "workspace:*",
4344
"@types/bun": "1.3.14",
4445
"@types/node": "catalog:",
46+
"@types/web-push": "^3.6.4",
4547
"effect-acp": "workspace:*",
4648
"effect-codex-app-server": "workspace:*",
4749
"vite-plus": "catalog:"

‎apps/server/src/t3x/index.ts‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,14 @@ import { ServerConfig } from "../config.ts";
2222
import { autoResumeRouteLayer } from "./autoResume/http.ts";
2323
import { AutoResumeReactorLive } from "./autoResume/Reactor.ts";
2424
import { AutoResumeStore, makeAutoResumeStore } from "./autoResume/state.ts";
25+
import { resolveConfig as resolveWebPushConfig } from "./webPush/config.ts";
26+
import { webPushRouteLayer } from "./webPush/http.ts";
27+
import { WebPushReactorLive } from "./webPush/Reactor.ts";
28+
import { makePushSubscriptionStore, PushSubscriptionStore } from "./webPush/state.ts";
29+
import { makeWebPushVapid, WebPushVapid } from "./webPush/vapid.ts";
2530

2631
const AUTO_RESUME_STATE_FILENAME = "t3x-auto-resume.json";
32+
const WEB_PUSH_STATE_FILENAME = "t3x-web-push-subscriptions.json";
2733

2834
/** Wires the durable store to the server state directory. */
2935
const AutoResumeStoreLive = Layer.effect(
@@ -35,12 +41,37 @@ const AutoResumeStoreLive = Layer.effect(
3541
}),
3642
);
3743

44+
/** Web Push subscription store, wired to the server state directory. */
45+
const PushSubscriptionStoreLive = Layer.effect(
46+
PushSubscriptionStore,
47+
Effect.gen(function* () {
48+
const config = yield* ServerConfig;
49+
const path = yield* Path.Path;
50+
return yield* makePushSubscriptionStore(path.join(config.stateDir, WEB_PUSH_STATE_FILENAME));
51+
}),
52+
);
53+
54+
/** VAPID keypair (env override, else generated + persisted in the secret store). */
55+
const WebPushVapidLive = Layer.effect(WebPushVapid, makeWebPushVapid(resolveWebPushConfig()));
56+
57+
/**
58+
* Shared fork-local deps for the Web Push reactor AND routes. Defined once at module scope so
59+
* both `T3xLayerLive` and `T3xRoutesLive` reference the SAME layer value — Effect memoises
60+
* construction by layer identity across the shared MemoMap, so the reactor and the subscribe
61+
* route mutate one store/keypair rather than racing two copies over a single file (the same
62+
* property `AutoResumeStoreLive` relies on above).
63+
*/
64+
const WebPushDepsLive = Layer.mergeAll(PushSubscriptionStoreLive, WebPushVapidLive);
65+
3866
/**
3967
* The single fork-local layer merged into the server. The auto-resume supervisor
4068
* self-starts on construction; its store is provided here so `server.ts` merges only
4169
* this one layer.
4270
*/
43-
export const T3xLayerLive = AutoResumeReactorLive.pipe(Layer.provide(AutoResumeStoreLive));
71+
export const T3xLayerLive = Layer.mergeAll(
72+
AutoResumeReactorLive.pipe(Layer.provide(AutoResumeStoreLive)),
73+
WebPushReactorLive.pipe(Layer.provide(WebPushDepsLive)),
74+
);
4475

4576
/**
4677
* All fork-local HTTP routes, fanned in here for the same reason as `T3xLayerLive`:
@@ -66,4 +97,7 @@ export const T3xLayerLive = AutoResumeReactorLive.pipe(Layer.provide(AutoResumeS
6697
* probes rather than importing these two layers, so treat it as a guard on the
6798
* assumption, not proof of this file's graph.
6899
*/
69-
export const T3xRoutesLive = autoResumeRouteLayer.pipe(Layer.provide(AutoResumeStoreLive));
100+
export const T3xRoutesLive = Layer.mergeAll(
101+
autoResumeRouteLayer.pipe(Layer.provide(AutoResumeStoreLive)),
102+
webPushRouteLayer.pipe(Layer.provide(WebPushDepsLive)),
103+
);
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/**
2+
* WebPushReactor — closed-tab notification supervisor.
3+
*
4+
* Self-starts one scoped fiber at layer construction (no external `.start()`, so the only
5+
* upstream seam stays the lines already in server.ts). It taps the hot orchestration
6+
* domain-event stream, and for each thread event recomputes the awareness phase from the
7+
* projected shell (the SAME `projectThreadAwareness` the web client uses), edge-detects, and
8+
* on a firing transition sends a Web Push to every registered subscription. Dead
9+
* subscriptions (404/410) are pruned as they surface.
10+
*
11+
* De-dup with the in-page coordinator is the service worker's job: it suppresses when a tab
12+
* is open, so this reactor always sends and the worker only shows when no tab exists.
13+
*
14+
* @module t3x/webPush/Reactor
15+
*/
16+
17+
import type { OrchestrationEvent, OrchestrationProjectShell, ThreadId } from "@t3tools/contracts";
18+
import { projectThreadAwareness } from "@t3tools/shared/agentAwareness";
19+
import * as Cause from "effect/Cause";
20+
import * as Effect from "effect/Effect";
21+
import * as Layer from "effect/Layer";
22+
import * as Option from "effect/Option";
23+
import * as Stream from "effect/Stream";
24+
25+
import { ServerEnvironment } from "../../environment/ServerEnvironment.ts";
26+
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
27+
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
28+
import { buildAttentionPayload, createAttentionEdgeTracker } from "./attention.ts";
29+
import { resolveConfig } from "./config.ts";
30+
import { sendWebPush } from "./send.ts";
31+
import { PushSubscriptionStore } from "./state.ts";
32+
import { WebPushVapid } from "./vapid.ts";
33+
34+
const SEND_CONCURRENCY = 4;
35+
36+
/** Local mirror of the relay's `eventThreadId`, kept in-seam to avoid coupling to upstream. */
37+
function eventThreadId(event: OrchestrationEvent): ThreadId | null {
38+
const payload = event.payload as { readonly threadId?: unknown };
39+
if (typeof payload.threadId === "string") {
40+
return payload.threadId as ThreadId;
41+
}
42+
if (event.aggregateKind === "thread" && typeof event.aggregateId === "string") {
43+
return event.aggregateId as ThreadId;
44+
}
45+
return null;
46+
}
47+
48+
const makeSupervisor = Effect.gen(function* () {
49+
const config = resolveConfig();
50+
if (!config.enabled) {
51+
yield* Effect.logInfo("t3x web-push: disabled via T3X_WEB_PUSH_ENABLED");
52+
return;
53+
}
54+
55+
const engine = yield* OrchestrationEngineService;
56+
const snapshotQuery = yield* ProjectionSnapshotQuery;
57+
const serverEnvironment = yield* ServerEnvironment;
58+
const store = yield* PushSubscriptionStore;
59+
const vapid = yield* WebPushVapid;
60+
const tracker = createAttentionEdgeTracker();
61+
62+
const handleThread = (threadId: ThreadId) =>
63+
Effect.gen(function* () {
64+
// No subscribers → no work. The tracker only builds history while subscribed, which is
65+
// fine: a subscription added mid-session is first-seen and so never replays a stale edge.
66+
const subscriptions = yield* store.list;
67+
if (subscriptions.length === 0) {
68+
return;
69+
}
70+
71+
const threadOpt = yield* snapshotQuery.getThreadShellById(threadId);
72+
if (Option.isNone(threadOpt)) {
73+
tracker.forget(threadId);
74+
return;
75+
}
76+
const thread = threadOpt.value;
77+
const projectOpt = yield* snapshotQuery.getProjectShellById(thread.projectId);
78+
const environmentId = yield* serverEnvironment.getEnvironmentId;
79+
80+
const projectTitle = (
81+
Option.isSome(projectOpt) ? projectOpt.value.title : "T3 Code"
82+
) as OrchestrationProjectShell["title"];
83+
84+
const state = projectThreadAwareness({
85+
environmentId,
86+
project: { title: projectTitle },
87+
thread,
88+
});
89+
const kind = tracker.observe(threadId, state?.phase ?? null);
90+
if (kind === null || state === null) {
91+
return;
92+
}
93+
94+
const payload = buildAttentionPayload(state, kind);
95+
yield* Effect.forEach(
96+
subscriptions,
97+
(subscription) =>
98+
sendWebPush(vapid, subscription, payload).pipe(
99+
Effect.flatMap((result) =>
100+
result.expired ? store.removeByEndpoint(subscription.endpoint) : Effect.void,
101+
),
102+
),
103+
{ concurrency: SEND_CONCURRENCY, discard: true },
104+
);
105+
});
106+
107+
yield* Effect.forkScoped(
108+
Stream.runForEach(engine.streamDomainEvents, (event) => {
109+
const threadId = eventThreadId(event);
110+
if (threadId === null) {
111+
return Effect.void;
112+
}
113+
return handleThread(threadId).pipe(
114+
Effect.catchCause((cause) =>
115+
Effect.logWarning("t3x web-push: notification handler failed", {
116+
eventType: event.type,
117+
cause: Cause.pretty(cause),
118+
}),
119+
),
120+
);
121+
}),
122+
);
123+
124+
yield* Effect.logInfo("t3x web-push: reactor started");
125+
});
126+
127+
export const WebPushReactorLive = Layer.effectDiscard(makeSupervisor);
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import type { AgentAwarenessState } from "@t3tools/shared/agentAwareness";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import {
5+
attentionKey,
6+
attentionKindForEdge,
7+
buildAttentionPayload,
8+
createAttentionEdgeTracker,
9+
} from "./attention.ts";
10+
11+
describe("attentionKindForEdge", () => {
12+
it("announces waiting phases on entry regardless of the previous phase", () => {
13+
expect(attentionKindForEdge("running", "waiting_for_approval")).toBe("waiting_for_approval");
14+
expect(attentionKindForEdge("completed", "waiting_for_input")).toBe("waiting_for_input");
15+
});
16+
17+
it("announces completed only out of running", () => {
18+
expect(attentionKindForEdge("running", "completed")).toBe("completed");
19+
expect(attentionKindForEdge("starting", "completed")).toBeNull();
20+
expect(attentionKindForEdge(null, "completed")).toBeNull();
21+
});
22+
23+
it("stays silent for non-attention phases", () => {
24+
expect(attentionKindForEdge("waiting_for_input", "running")).toBeNull();
25+
expect(attentionKindForEdge("running", "starting")).toBeNull();
26+
expect(attentionKindForEdge("running", "failed")).toBeNull();
27+
expect(attentionKindForEdge("running", "stale")).toBeNull();
28+
});
29+
});
30+
31+
describe("createAttentionEdgeTracker", () => {
32+
it("never fires on a thread's first observation", () => {
33+
const tracker = createAttentionEdgeTracker();
34+
expect(tracker.observe("t1", "waiting_for_input")).toBeNull();
35+
});
36+
37+
it("fires completed only on running -> completed", () => {
38+
const tracker = createAttentionEdgeTracker();
39+
expect(tracker.observe("t1", "running")).toBeNull(); // first-seen
40+
expect(tracker.observe("t1", "completed")).toBe("completed");
41+
});
42+
43+
it("does not fire completed when the thread was never seen running", () => {
44+
const tracker = createAttentionEdgeTracker();
45+
expect(tracker.observe("t1", "starting")).toBeNull(); // first-seen
46+
expect(tracker.observe("t1", "completed")).toBeNull(); // starting -> completed
47+
});
48+
49+
it("fires waiting_for_input on entry after a prior observation", () => {
50+
const tracker = createAttentionEdgeTracker();
51+
expect(tracker.observe("t1", "running")).toBeNull();
52+
expect(tracker.observe("t1", "waiting_for_input")).toBe("waiting_for_input");
53+
});
54+
55+
it("does not re-fire while the phase is unchanged", () => {
56+
const tracker = createAttentionEdgeTracker();
57+
tracker.observe("t1", "running");
58+
expect(tracker.observe("t1", "waiting_for_approval")).toBe("waiting_for_approval");
59+
expect(tracker.observe("t1", "waiting_for_approval")).toBeNull();
60+
});
61+
62+
it("treats a null phase as an observation that never fires", () => {
63+
const tracker = createAttentionEdgeTracker();
64+
tracker.observe("t1", "running");
65+
expect(tracker.observe("t1", null)).toBeNull();
66+
// Coming back to completed from a null observation is not a running->completed edge.
67+
expect(tracker.observe("t1", "completed")).toBeNull();
68+
});
69+
70+
it("tracks threads independently", () => {
71+
const tracker = createAttentionEdgeTracker();
72+
tracker.observe("t1", "running");
73+
expect(tracker.observe("t2", "completed")).toBeNull(); // t2 first-seen
74+
expect(tracker.observe("t1", "completed")).toBe("completed");
75+
});
76+
77+
it("re-arms first-seen after forget", () => {
78+
const tracker = createAttentionEdgeTracker();
79+
tracker.observe("t1", "running");
80+
tracker.forget("t1");
81+
// First observation again -> no fire even though it's a completed value.
82+
expect(tracker.observe("t1", "completed")).toBeNull();
83+
});
84+
});
85+
86+
describe("buildAttentionPayload", () => {
87+
it("maps an awareness state + edge into the service-worker payload", () => {
88+
const state = {
89+
environmentId: "env-1",
90+
threadId: "thread-1",
91+
projectTitle: "My Project",
92+
threadTitle: "Fix the bug",
93+
phase: "waiting_for_input",
94+
headline: "Waiting for input",
95+
modelTitle: "claude",
96+
updatedAt: "2026-07-27T00:00:00.000Z",
97+
deepLink: "/threads/env-1/thread-1",
98+
} as unknown as AgentAwarenessState;
99+
100+
expect(buildAttentionPayload(state, "waiting_for_input")).toEqual({
101+
title: "Waiting for input",
102+
body: "My Project · Fix the bug",
103+
key: "env-1::thread-1",
104+
environmentId: "env-1",
105+
threadId: "thread-1",
106+
kind: "waiting_for_input",
107+
});
108+
});
109+
110+
it("keys by environment + thread", () => {
111+
expect(attentionKey("env-1", "thread-1")).toBe("env-1::thread-1");
112+
});
113+
});

0 commit comments

Comments
 (0)