@takboo/dsh-coopanion 0.4.4 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +31 -11
  2. package/desktop/main.cjs +18 -14
  3. package/dist/bridge.js +68 -25
  4. package/dist/bridge.js.map +2 -2
  5. package/dist/client.js +20238 -54
  6. package/dist/index.js +876 -118
  7. package/dist/index.js.map +4 -4
  8. package/dist/model.js +51 -12
  9. package/dist/model.js.map +2 -2
  10. package/docs/characters.md +18 -1
  11. package/docs/evidence/notification-n0/ci-final-summary.json +1251 -0
  12. package/docs/evidence/notification-n0/ci-summary.json +219 -0
  13. package/docs/evidence/notification-n0/macos-notification-center.png +0 -0
  14. package/docs/evidence/notification-n0/macos-single-instance-click.png +0 -0
  15. package/docs/evidence/notification-n0/single-instance-receipts.jsonl +13 -0
  16. package/docs/evidence/notification-n0/single-instance-session-header.json +10 -0
  17. package/docs/evidence/notification-n0/single-instance-session.zip +0 -0
  18. package/docs/evidence/notification-n0/single-instance-summary.json +80 -0
  19. package/docs/evidence/notification-n3/ci-final-summary.json +176 -0
  20. package/docs/evidence/notification-n3/ci-verification.json +7 -0
  21. package/docs/evidence/notification-n3/client-build-after.log +9 -0
  22. package/docs/evidence/notification-n3/client-build-before.log +1 -0
  23. package/docs/evidence/notification-n3/client-install-0.2.0-rc.2.json +23 -0
  24. package/docs/evidence/notification-n3/client-install-0.2.1-alpha.1.json +23 -0
  25. package/docs/evidence/notification-n3/completion-order-after.log +1 -0
  26. package/docs/evidence/notification-n3/completion-order-before.log +11 -0
  27. package/docs/evidence/notification-n3/desktop-after.log +5 -0
  28. package/docs/evidence/notification-n3/desktop-before.log +20 -0
  29. package/docs/evidence/notification-n3/desktop-exclusive-after.log +5 -0
  30. package/docs/evidence/notification-n3/install-rc2-redacted.log +29 -0
  31. package/docs/evidence/notification-n3/install-rc2-v2-redacted.log +24 -0
  32. package/docs/evidence/notification-n3/install-rc2-v3-redacted.log +33 -0
  33. package/docs/evidence/notification-n3/install-rc2-v4-redacted.log +32 -0
  34. package/docs/evidence/notification-n3/late-click-after.log +10 -0
  35. package/docs/evidence/notification-n3/late-click-before.log +39 -0
  36. package/docs/evidence/notification-n3/local-verification.json +7 -0
  37. package/docs/evidence/notification-n3/native-cold-after.log +8 -0
  38. package/docs/evidence/notification-n3/native-cold-before.log +22 -0
  39. package/docs/evidence/notification-n3/optional-projection-before.log +52 -0
  40. package/docs/evidence/notification-n3/ptc-restore-after.log +10 -0
  41. package/docs/evidence/notification-n3/ptc-restore-before.log +60 -0
  42. package/docs/evidence/notification-n3/request-capacity-before.log +39 -0
  43. package/docs/evidence/notification-n3/settlement-after.log +10 -0
  44. package/docs/evidence/notification-n3/settlement-before.log +47 -0
  45. package/docs/evidence/notification-n3/tool-error-after.log +10 -0
  46. package/docs/evidence/notification-n3/tool-error-before.log +57 -0
  47. package/docs/notification-contract.md +51 -0
  48. package/docs/notification-implementation.md +65 -0
  49. package/docs/notification-n0.md +59 -0
  50. package/docs/notification-n3.md +24 -0
  51. package/docs/notification-n4.md +9 -0
  52. package/docs/notification-plan.md +180 -0
  53. package/docs/release-notes.md +28 -0
  54. package/docs/releasing.md +10 -0
  55. package/npm-shrinkwrap.json +871 -79
  56. package/package.json +30 -6
  57. package/scripts/build.mjs +5 -1
  58. package/scripts/check-npm.mjs +1 -1
  59. package/scripts/prepare-notification-probe.mjs +21 -0
  60. package/scripts/release-support.mjs +20 -9
  61. package/src/bridge.ts +70 -35
  62. package/src/client/Settings.tsx +48 -3
  63. package/src/client/index.ts +29 -1
  64. package/src/client/locales.ts +24 -6
  65. package/src/client/notification-client.ts +161 -0
  66. package/src/client/notification-copy.ts +25 -0
  67. package/src/client/system-notifications.ts +76 -0
  68. package/src/controls.ts +64 -24
  69. package/src/index.ts +105 -20
  70. package/src/model.ts +57 -15
  71. package/src/notification-broker.ts +363 -0
  72. package/src/notification-contract.ts +77 -0
  73. package/tests/bridge.test.ts +16 -0
  74. package/tests/client-build.mjs +28 -0
  75. package/tests/controls.test.ts +59 -10
  76. package/tests/desktop.mjs +20 -0
  77. package/tests/fixtures/host.mjs +10 -1
  78. package/tests/fixtures/notification-probe/client.tsx +42 -0
  79. package/tests/fixtures/notification-probe/host.mjs +28 -0
  80. package/tests/helpers/installed-notifications.mjs +77 -0
  81. package/tests/helpers/installed-services.mjs +103 -0
  82. package/tests/helpers/native-pointer.mjs +47 -2
  83. package/tests/inbox-ui.mjs +120 -0
  84. package/tests/install.mjs +43 -1
  85. package/tests/model.test.ts +87 -2
  86. package/tests/notification-broker.test.ts +233 -0
  87. package/tests/notification-client.test.ts +162 -0
  88. package/tests/notification-contract.test.ts +62 -0
  89. package/tests/notification-host-contract.mjs +66 -0
  90. package/tests/notification-integration.test.ts +168 -0
  91. package/tests/notification-ui.mjs +121 -0
  92. package/tests/plugin.test.ts +23 -6
  93. package/tests/presentation.test.js +21 -0
  94. package/tests/release-checks.mjs +37 -0
  95. package/tests/session-recovery.test.ts +116 -0
  96. package/tests/ui.mjs +3 -2
  97. package/web/index.html +15 -3
  98. package/web/notification-ui.js +57 -0
  99. package/web/pet.js +172 -28
  100. package/web/session-ui.js +9 -0
  101. package/web/style.css +30 -1
package/dist/index.js CHANGED
@@ -1,6 +1,510 @@
1
+ // src/index.ts
2
+ import { randomUUID as randomUUID2 } from "node:crypto";
3
+ import { SessionId } from "@deepseek-ai/dsh-session";
4
+
5
+ // src/notification-broker.ts
6
+ import { randomUUID } from "node:crypto";
7
+
8
+ // src/notification-contract.ts
9
+ import { z } from "zod";
10
+ var NOTIFICATION_PROTOCOL = 1;
11
+ var id = z.string().min(1).max(2048);
12
+ var counter = z.number().int().nonnegative().safe();
13
+ var notificationPreferencesSchema = z.object({
14
+ notifications: z.boolean().default(true),
15
+ systemNotifications: z.boolean().default(false),
16
+ reminders: z.boolean().default(true),
17
+ reminderDelayMs: z.number().int().min(6e4).max(864e5).default(6e5)
18
+ }).strict();
19
+ var noticeSchema = z.object({
20
+ id,
21
+ sessionId: id,
22
+ turn: counter,
23
+ seq: counter,
24
+ time: counter,
25
+ category: z.enum(["completed", "approval", "question", "error", "stopped", "interrupted", "blocked", "max-tokens"]),
26
+ stage: z.enum(["initial", "reminder"]),
27
+ title: z.string().max(256),
28
+ body: z.string().max(2048),
29
+ requestIds: z.array(id).max(100).default([]),
30
+ source: z.enum(["event", "runtime"]).optional()
31
+ }).strict();
32
+ function noticeId(sessionId, turn, seq, category, stage, occurrence = 0, runtimeId) {
33
+ if (!Number.isSafeInteger(occurrence) || occurrence < 0) throw new Error("Invalid notification occurrence");
34
+ if (runtimeId !== void 0 && !runtimeId.length) throw new Error("Invalid runtime request id");
35
+ const tuple = [sessionId, turn, seq, category, stage];
36
+ if (runtimeId !== void 0) tuple.push(runtimeId);
37
+ if (occurrence > 0) tuple.push(occurrence);
38
+ return JSON.stringify(tuple);
39
+ }
40
+ function interactionId(sessionId, kind, nativeId) {
41
+ return JSON.stringify([sessionId, kind, nativeId]);
42
+ }
43
+ var interactionSchema = z.object({
44
+ id,
45
+ sessionId: id,
46
+ nativeId: id,
47
+ kind: z.enum(["approval", "question"]),
48
+ turn: counter,
49
+ seq: counter,
50
+ createdAt: counter,
51
+ preview: z.string().max(2048),
52
+ state: z.enum(["open", "continued", "settled"]),
53
+ source: z.enum(["event", "runtime"]).optional(),
54
+ dueAt: counter.nullable(),
55
+ automaticReminders: z.number().int().min(0).max(1)
56
+ }).strict();
57
+ var runtimeSchema = z.object({
58
+ phase: z.enum(["stopped", "starting", "running", "stopping", "error"]),
59
+ generation: counter,
60
+ visibilityRevision: counter,
61
+ visible: z.boolean(),
62
+ suspended: z.boolean(),
63
+ error: z.string().max(600).optional()
64
+ }).strict();
65
+ var deliveryClaimSchema = z.object({
66
+ token: id,
67
+ clientId: id,
68
+ generation: counter,
69
+ visibilityRevision: counter,
70
+ expiresAt: counter,
71
+ notice: noticeSchema
72
+ }).strict();
73
+ var deliveryReceiptSchema = z.object({
74
+ token: id,
75
+ clientId: id,
76
+ noticeId: id,
77
+ generation: counter,
78
+ state: z.enum(["requested", "shown", "clicked", "failed", "unknown"]),
79
+ time: counter,
80
+ detail: z.string().max(600).optional()
81
+ }).strict();
82
+ var notificationRequests = {
83
+ state: z.object({ locale: z.string().min(2).max(64).regex(/^[a-zA-Z0-9-]+$/).optional() }).strict(),
84
+ claim: z.object({ clientId: id, generation: counter }).strict(),
85
+ receipt: deliveryReceiptSchema,
86
+ test: z.object({ clientId: id, generation: counter }).strict(),
87
+ snooze: z.object({ interactionId: id, generation: counter }).strict()
88
+ };
89
+ var notificationEndpoints = ["notification-state", "notification-claim", "notification-receipt", "notification-snooze", "notification-test"];
90
+
91
+ // src/notification-broker.ts
92
+ var realClock = {
93
+ now: Date.now,
94
+ setTimeout: (callback, delay) => {
95
+ const timer = setTimeout(callback, delay);
96
+ timer.unref();
97
+ return timer;
98
+ },
99
+ clearTimeout: (timer) => clearTimeout(timer)
100
+ };
101
+ var title = {
102
+ completed: "\u4EFB\u52A1\u5B8C\u6210",
103
+ approval: "\u7B49\u4F60\u786E\u8BA4",
104
+ question: "\u6709\u4E2A\u95EE\u9898\u60F3\u95EE\u4F60",
105
+ error: "\u9700\u8981\u5173\u6CE8",
106
+ stopped: "\u5148\u505C\u5728\u8FD9\u91CC",
107
+ interrupted: "\u4EFB\u52A1\u4E2D\u65AD\u4E86",
108
+ blocked: "\u4EFB\u52A1\u6682\u65F6\u505C\u4E0B\u4E86",
109
+ "max-tokens": "\u8F93\u51FA\u8FBE\u5230\u4E0A\u9650"
110
+ };
111
+ var body = {
112
+ completed: "\u5DF2\u5B8C\u6210\uFF0C\u56DE\u5230\u4F1A\u8BDD\u67E5\u770B\u3002",
113
+ approval: "\u4E0B\u4E00\u6B65\u9700\u8981\u4F60\u786E\u8BA4\u3002",
114
+ question: "\u6709\u4E2A\u95EE\u9898\u60F3\u95EE\u4F60\u3002",
115
+ error: "\u4EFB\u52A1\u9047\u5230\u4E86\u95EE\u9898\uFF0C\u966A\u4F60\u56DE\u53BB\u770B\u770B\u3002",
116
+ stopped: "\u5148\u505C\u5728\u8FD9\u91CC\uFF0C\u968F\u65F6\u7EE7\u7EED\u3002",
117
+ interrupted: "\u8FD9\u6BB5\u4EFB\u52A1\u4E2D\u65AD\u4E86\uFF0C\u966A\u4F60\u56DE\u53BB\u770B\u770B\u3002",
118
+ blocked: "\u770B\u770B\u4E0B\u4E00\u6B65\u600E\u4E48\u7EE7\u7EED\u3002",
119
+ "max-tokens": "\u770B\u770B\u4E0B\u4E00\u6B65\u600E\u4E48\u7EE7\u7EED\u3002"
120
+ };
121
+ var NotificationBroker = class {
122
+ constructor(options = {}) {
123
+ this.options = options;
124
+ this.clock = options.clock ?? realClock;
125
+ }
126
+ clock;
127
+ prefs = notificationPreferencesSchema.parse({});
128
+ run = { phase: "stopped", generation: 0, visibilityRevision: 0, visible: false, suspended: false };
129
+ sources = /* @__PURE__ */ new Map();
130
+ requests = /* @__PURE__ */ new Map();
131
+ deliveries = /* @__PURE__ */ new Map();
132
+ clients = /* @__PURE__ */ new Map();
133
+ problems = [];
134
+ timer;
135
+ closed = false;
136
+ snapshot() {
137
+ return { protocol: NOTIFICATION_PROTOCOL, runtime: { ...this.run }, interactions: [...this.requests.values()].filter((r) => r.state !== "settled").map((r) => this.publicRequest(r)) };
138
+ }
139
+ /** Bounded diagnostics; a requested receipt alone never means the OS displayed a notification. */
140
+ diagnostics() {
141
+ return this.problems.map((p) => ({ ...p }));
142
+ }
143
+ history() {
144
+ return [...this.deliveries.values()].map((d) => ({ notice: structuredClone(d.notice), state: d.state, receipts: d.receipts.map((r) => ({ ...r })) }));
145
+ }
146
+ preferences(value) {
147
+ const delayChanged = value.reminderDelayMs !== void 0 && value.reminderDelayMs !== this.prefs.reminderDelayMs;
148
+ this.prefs = notificationPreferencesSchema.parse({ ...this.prefs, ...value });
149
+ if (!this.prefs.reminders) {
150
+ for (const delivery of this.deliveries.values()) if (delivery.notice.stage === "reminder") this.cancel(delivery);
151
+ }
152
+ if (!this.prefs.notifications) this.cancelDeliveries();
153
+ for (const request of this.requests.values()) {
154
+ if (request.state === "settled") continue;
155
+ if (!this.prefs.notifications || !this.prefs.reminders) request.dueAt = null;
156
+ else if ((request.dueAt === null || delayChanged) && request.automaticReminders === 0) request.dueAt = this.clock.now() + this.prefs.reminderDelayMs;
157
+ }
158
+ this.refresh();
159
+ }
160
+ runtime(value) {
161
+ const next = runtimeSchema.parse(value);
162
+ if (next.phase === "running" && this.run.phase === "running" && next.generation === this.run.generation && next.visibilityRevision === this.run.visibilityRevision && next.visible !== this.run.visible) return false;
163
+ if (this.closed || next.generation < this.run.generation || next.generation === this.run.generation && next.visibilityRevision < this.run.visibilityRevision) return false;
164
+ const generationChanged = next.generation !== this.run.generation;
165
+ const changed = next.generation !== this.run.generation || next.visibilityRevision !== this.run.visibilityRevision || next.phase !== this.run.phase || next.suspended !== this.run.suspended;
166
+ if (changed) for (const delivery of this.deliveries.values()) {
167
+ if (next.generation === this.run.generation && next.phase === "running" && !next.suspended && !delivery.claim && delivery.state === "pending") {
168
+ delivery.state = "pending";
169
+ delivery.claim = void 0;
170
+ } else this.cancel(delivery);
171
+ }
172
+ this.run = next;
173
+ if (next.phase !== "running" || generationChanged) for (const r of this.requests.values()) r.dueAt = null;
174
+ if (next.phase === "running") {
175
+ for (const r of this.requests.values()) if (r.state !== "settled" && r.automaticReminders === 0 && r.dueAt === null && this.prefs.reminders && this.prefs.notifications) r.dueAt = this.clock.now() + this.prefs.reminderDelayMs;
176
+ }
177
+ this.refresh();
178
+ return true;
179
+ }
180
+ /** Baseline history folds pending state; it never replays proactive initial or reminder notices. */
181
+ restore(session, questions) {
182
+ if (session.header.origin === "subagent" || this.sources.has(session.id)) return;
183
+ this.source(session);
184
+ for (const event of session.snapshotEvents?.() ?? []) this.event(session, event, false);
185
+ if (questions) this.questions(session, questions, false);
186
+ this.refresh();
187
+ }
188
+ consume(session, event) {
189
+ if (this.closed || session.header.origin === "subagent") return;
190
+ this.event(session, event, true);
191
+ this.refresh();
192
+ }
193
+ source(session) {
194
+ let state = this.sources.get(session.id);
195
+ if (!state) {
196
+ if (this.sources.size >= 100) this.remove(this.sources.keys().next().value);
197
+ state = { seq: -1, turn: 0, finalText: "", calls: /* @__PURE__ */ new Map(), label: session.header.cwd?.split(/[\\/]/).filter(Boolean).at(-1) ?? "\u4F1A\u8BDD" };
198
+ this.sources.set(session.id, state);
199
+ }
200
+ return state;
201
+ }
202
+ event(session, event, live) {
203
+ const source = this.source(session);
204
+ if (event.seq <= source.seq) return;
205
+ source.seq = event.seq;
206
+ if (event.type === "approval/decided") {
207
+ this.settle(interactionId(session.id, "approval", event.data.id));
208
+ return;
209
+ }
210
+ if (event.type === "user/message") {
211
+ const reply = event.data.source;
212
+ if (reply.kind === "user-question-reply" && reply.callId) {
213
+ this.settle(interactionId(session.id, "question", reply.callId));
214
+ return;
215
+ }
216
+ }
217
+ if ("turn" in event.data && event.data.turn !== void 0 && event.data.turn < source.turn) return;
218
+ switch (event.type) {
219
+ case "turn/start":
220
+ source.turn = event.data.turn;
221
+ source.finalText = "";
222
+ break;
223
+ case "tool/call":
224
+ if (event.data.name === "ask_user_question") this.origin(source, event.data.callId, event.data.turn, event.seq, event.time);
225
+ break;
226
+ case "tool/ptc-dispatch":
227
+ if (event.data.name === "ask_user_question") this.origin(source, event.data.subCallId, source.turn, event.seq, event.time);
228
+ break;
229
+ case "assistant/message":
230
+ source.finalText = event.data.message.content.some((p) => p.type === "tool-call") ? "" : event.data.message.content.filter((p) => p.type === "text").map((p) => p.text).join("\n");
231
+ break;
232
+ case "approval/asked":
233
+ this.open(session.id, "approval", event.data.id, source.turn, event.seq, event.time, `${event.data.toolName}: ${event.data.reason ?? body.approval}`, false, live);
234
+ break;
235
+ case "turn/end": {
236
+ source.turn = event.data.turn;
237
+ if (event.data.reason.kind === "forked") break;
238
+ const category = event.data.reason.kind === "aborted" ? "stopped" : event.data.reason.kind;
239
+ if (live) this.enqueue(this.notice(session.id, source.turn, event.seq, event.time, category, source.finalText && category === "completed" ? source.finalText : body[category]));
240
+ source.finalText = "";
241
+ for (const r of this.requests.values()) if (r.sessionId === session.id && r.kind === "approval" && r.turn <= source.turn) this.settle(r.id);
242
+ break;
243
+ }
244
+ }
245
+ }
246
+ /** Public projection is authoritative for timed questions, including continued questions after turn/end. */
247
+ questions(session, projection, live = true) {
248
+ if (this.closed || session.header.origin === "subagent") return;
249
+ const source = this.source(session), active = /* @__PURE__ */ new Set();
250
+ for (const question of projection.active) {
251
+ const id2 = interactionId(session.id, "question", question.callId);
252
+ active.add(id2);
253
+ let origin = source.calls.get(question.callId);
254
+ if (!origin) {
255
+ const events = session.snapshotEvents?.() ?? [];
256
+ const event = events.map((event2) => event2).findLast((event2) => event2.type === "tool/call" && event2.data.callId === question.callId && event2.data.name === "ask_user_question" || event2.type === "tool/ptc-dispatch" && event2.data.subCallId === question.callId && event2.data.name === "ask_user_question");
257
+ if (event) {
258
+ const start = events.findLast((prior) => prior.type === "turn/start" && prior.seq < event.seq);
259
+ const turn = "turn" in event.data && event.data.turn !== void 0 ? event.data.turn : start?.type === "turn/start" ? start.data.turn : 0;
260
+ origin = { turn, seq: event.seq, time: event.time };
261
+ }
262
+ }
263
+ const existing = this.requests.get(id2);
264
+ if (!origin && existing) origin = { turn: existing.turn, seq: existing.seq, time: existing.createdAt };
265
+ if (!origin) {
266
+ if (!this.problems.some((p) => p.sessionId === session.id && p.nativeId === question.callId)) this.problems.push({ code: "question-source-unavailable", sessionId: session.id, nativeId: question.callId });
267
+ if (this.problems.length > 100) this.problems.shift();
268
+ continue;
269
+ }
270
+ this.open(session.id, "question", question.callId, origin.turn, origin.seq, origin.time, question.questions.map((q) => q.question).join("\n"), true, live, question.state);
271
+ }
272
+ for (const r of this.requests.values()) if (r.sessionId === session.id && r.projected && !active.has(r.id)) this.settle(r.id);
273
+ for (const q of projection.settled ?? []) this.settle(interactionId(session.id, "question", q.callId));
274
+ this.refresh();
275
+ }
276
+ origin(source, id2, turn, seq, time) {
277
+ source.calls.set(id2, { turn, seq, time });
278
+ if (source.calls.size > 200) source.calls.delete(source.calls.keys().next().value);
279
+ }
280
+ /** Observe a runtime blocking request without claiming the answerer chain. */
281
+ question(session, question) {
282
+ if (this.closed || session.header.origin === "subagent" || question.signal?.aborted) return () => {
283
+ };
284
+ this.source(session);
285
+ const id2 = interactionId(session.id, "question", question.nativeId);
286
+ this.open(session.id, "question", question.nativeId, question.turn, question.seq, this.clock.now(), question.preview, false, true, "open", question.source);
287
+ const request = this.requests.get(id2);
288
+ if (!request) {
289
+ this.problems.push({ code: "request-capacity-exceeded", sessionId: session.id, nativeId: question.nativeId });
290
+ if (this.problems.length > 100) this.problems.shift();
291
+ return () => {
292
+ };
293
+ }
294
+ const finish = () => {
295
+ if (!request.projected) this.settle(id2);
296
+ this.refresh();
297
+ };
298
+ question.signal?.addEventListener("abort", finish, { once: true });
299
+ request.cleanup?.();
300
+ request.cleanup = () => question.signal?.removeEventListener("abort", finish);
301
+ this.refresh();
302
+ return finish;
303
+ }
304
+ open(sessionId, kind, nativeId, turn, seq, time, preview, projected, live, state = "open", sourceKind) {
305
+ const id2 = interactionId(sessionId, kind, nativeId), existing = this.requests.get(id2);
306
+ if (existing) {
307
+ if (existing.state !== "settled") {
308
+ existing.state = state;
309
+ existing.projected ||= projected;
310
+ existing.preview = preview.slice(0, 2048);
311
+ }
312
+ return;
313
+ }
314
+ if (this.requests.size >= 500) {
315
+ const old = [...this.requests.values()].find((r) => r.state === "settled");
316
+ if (old) this.requests.delete(old.id);
317
+ else return;
318
+ }
319
+ const request = { id: id2, nativeId, sessionId, kind, turn, seq, createdAt: time, preview: preview.slice(0, 2048), state, dueAt: live && this.prefs.notifications && this.run.phase === "running" && this.prefs.reminders ? this.clock.now() + this.prefs.reminderDelayMs : null, automaticReminders: live ? 0 : 1, projected, snoozes: 0, ...sourceKind ? { source: sourceKind } : {} };
320
+ this.requests.set(id2, request);
321
+ if (live) {
322
+ const notice = this.notice(sessionId, turn, seq, time, kind, request.preview, [id2]);
323
+ if (sourceKind) notice.source = sourceKind;
324
+ if (sourceKind === "runtime") notice.id = this.identity(notice, 0, nativeId);
325
+ this.enqueue(notice);
326
+ }
327
+ }
328
+ settle(id2) {
329
+ const request = this.requests.get(id2);
330
+ if (!request || request.state === "settled") return;
331
+ request.state = "settled";
332
+ request.dueAt = null;
333
+ request.cleanup?.();
334
+ request.cleanup = void 0;
335
+ for (const delivery of this.deliveries.values()) {
336
+ if (!delivery.notice.requestIds.includes(id2) || delivery.requested || ["role", "cancelled"].includes(delivery.state)) continue;
337
+ if (delivery.claim) {
338
+ this.cancel(delivery);
339
+ continue;
340
+ }
341
+ delivery.notice.requestIds = delivery.notice.requestIds.filter((key) => key !== id2 && this.requests.get(key)?.state !== "settled");
342
+ if (!delivery.notice.requestIds.length) delivery.state = "cancelled";
343
+ else this.cancel(delivery);
344
+ }
345
+ }
346
+ snooze(id2, generation) {
347
+ const request = this.requests.get(id2);
348
+ if (!this.eligible() || generation !== this.run.generation || !this.prefs.reminders || !request || request.state === "settled") return false;
349
+ for (const delivery of this.deliveries.values()) if (!delivery.requested && delivery.notice.requestIds.includes(id2) && ["pending", "claimed"].includes(delivery.state)) this.cancel(delivery);
350
+ request.dueAt = this.clock.now() + this.prefs.reminderDelayMs;
351
+ request.snoozes++;
352
+ this.refresh();
353
+ return true;
354
+ }
355
+ /** A live client poll refreshes its bounded liveness record and can own one eligible notice. */
356
+ claim(clientId, generation, noticeId2) {
357
+ if (!clientId || clientId.length > 2048 || this.closed || generation !== this.run.generation) return null;
358
+ this.clients.set(clientId, this.clock.now());
359
+ if (this.clients.size > 100) this.clients.delete(this.clients.keys().next().value);
360
+ this.tick();
361
+ if (!this.eligible() || this.run.visible || !this.prefs.systemNotifications) return null;
362
+ if ([...this.deliveries.values()].some((d) => d.claim?.clientId === clientId && ["claimed", "requested"].includes(d.state))) return null;
363
+ const delivery = [...this.deliveries.values()].find((d) => d.state === "pending" && this.valid(d.notice) && (noticeId2 === void 0 || d.notice.id === noticeId2));
364
+ if (!delivery) return null;
365
+ const claim = { token: this.options.token?.() ?? randomUUID(), clientId, generation, visibilityRevision: this.run.visibilityRevision, expiresAt: this.clock.now() + (this.options.claimDurationMs ?? 15e3), notice: structuredClone(delivery.notice) };
366
+ delivery.state = "claimed";
367
+ delivery.claim = claim;
368
+ this.refresh();
369
+ return structuredClone(claim);
370
+ }
371
+ receipt(value) {
372
+ const parsed = deliveryReceiptSchema.safeParse(value);
373
+ if (!parsed.success || this.closed) return false;
374
+ const receipt = parsed.data, delivery = this.deliveries.get(receipt.noticeId), claim = delivery?.claim;
375
+ if (!delivery || !claim || claim.token !== receipt.token || claim.clientId !== receipt.clientId || claim.generation !== receipt.generation || delivery.state === "cancelled") return false;
376
+ if (receipt.state === "requested") {
377
+ if (!["claimed", "unknown"].includes(delivery.state) || delivery.requested) return false;
378
+ delivery.requested = true;
379
+ } else if (receipt.state === "failed") {
380
+ if (!["claimed", "requested", "shown", "unknown"].includes(delivery.state)) return false;
381
+ } else {
382
+ if (!delivery.requested || delivery.state === "failed" || delivery.state === "clicked") return false;
383
+ if (receipt.state === "unknown" && delivery.state !== "requested") return false;
384
+ if (receipt.state === "shown" && !["requested", "unknown"].includes(delivery.state)) return false;
385
+ if (receipt.state === "clicked" && !["requested", "shown", "unknown"].includes(delivery.state)) return false;
386
+ }
387
+ delivery.state = receipt.state;
388
+ if (delivery.receipts.length < 5) delivery.receipts.push({ ...receipt });
389
+ this.refresh();
390
+ return true;
391
+ }
392
+ eligible() {
393
+ return !this.closed && this.prefs.notifications && this.run.phase === "running" && this.run.visibilityRevision > 0 && !this.run.suspended;
394
+ }
395
+ valid(notice) {
396
+ return !notice.requestIds.length || notice.requestIds.some((id2) => this.requests.get(id2)?.state !== "settled" && this.requests.has(id2));
397
+ }
398
+ notice(sessionId, turn, seq, time, category, preview, requestIds = [], stage = "initial") {
399
+ return noticeSchema.parse({ id: noticeId(sessionId, turn, seq, category, stage), sessionId, turn, seq, time, category, stage, title: `${this.sources.get(sessionId)?.label ?? "\u4F1A\u8BDD"} \xB7 ${title[category]}`.slice(0, 256), body: preview.slice(0, 2048), requestIds });
400
+ }
401
+ identity(notice, occurrence = 0, runtimeId) {
402
+ return noticeId(notice.sessionId, notice.turn, notice.seq, notice.category, notice.stage, occurrence, runtimeId);
403
+ }
404
+ enqueue(notice) {
405
+ if (!this.eligible() || this.deliveries.has(notice.id)) return;
406
+ this.deliveries.set(notice.id, { notice, state: "pending", requested: false, receipts: [] });
407
+ if (this.deliveries.size > 300) {
408
+ const old = [...this.deliveries.entries()].find(([, d]) => d.state !== "claimed" && d.state !== "requested");
409
+ if (old) this.deliveries.delete(old[0]);
410
+ }
411
+ }
412
+ cancel(delivery) {
413
+ if (delivery.claim && !["shown", "clicked", "failed"].includes(delivery.state)) delivery.state = "unknown";
414
+ else if (!delivery.claim && delivery.state !== "role") delivery.state = "cancelled";
415
+ }
416
+ cancelDeliveries() {
417
+ for (const d of this.deliveries.values()) this.cancel(d);
418
+ }
419
+ /** Callbacks always recompute request truth immediately before creating or dispatching a notice. */
420
+ tick() {
421
+ if (this.closed) return;
422
+ const now = this.clock.now();
423
+ for (const [id2, time] of this.clients) if (now - time >= (this.options.clientLifetimeMs ?? 3e4)) this.clients.delete(id2);
424
+ for (const delivery of this.deliveries.values()) {
425
+ if (!delivery.claim || !["claimed", "requested"].includes(delivery.state)) continue;
426
+ if (delivery.claim.expiresAt > now && this.clients.has(delivery.claim.clientId)) continue;
427
+ delivery.state = "unknown";
428
+ }
429
+ if (this.eligible() && this.prefs.reminders) {
430
+ const groups = /* @__PURE__ */ new Map();
431
+ for (const request of this.requests.values()) if (request.state !== "settled" && request.dueAt !== null && request.dueAt <= now) {
432
+ const group = groups.get(request.sessionId) ?? [];
433
+ group.push(request);
434
+ groups.set(request.sessionId, group);
435
+ }
436
+ for (const [sessionId, requests] of groups) for (let start = 0; start < requests.length; start += 100) {
437
+ const group = requests.slice(start, start + 100);
438
+ const origin = group[0], notice = this.notice(sessionId, origin.turn, origin.seq, now, origin.kind, group.length > 1 ? `\u8FD8\u6709 ${group.length} \u4EF6\u4E8B\u7B49\u4F60\u770B\u770B\u3002` : "\u521A\u624D\u90A3\u4EF6\u4E8B\uFF0C\u8FD8\u7B49\u4F60\u770B\u770B\u3002", group.map((r) => r.id), "reminder");
439
+ const occurrence = Math.max(...group.map((r) => r.snoozes));
440
+ if (origin.source === "runtime") {
441
+ notice.source = "runtime";
442
+ notice.id = this.identity(notice, occurrence, origin.nativeId);
443
+ } else if (occurrence) notice.id = this.identity(notice, occurrence);
444
+ for (const request of group) {
445
+ request.dueAt = null;
446
+ request.automaticReminders = 1;
447
+ }
448
+ this.enqueue(notice);
449
+ }
450
+ }
451
+ if (this.eligible() && this.run.visible) for (const delivery of this.deliveries.values()) {
452
+ if (delivery.state !== "pending" || !this.valid(delivery.notice)) continue;
453
+ const state = { ...this.run };
454
+ try {
455
+ if (this.options.presentRole?.(structuredClone(delivery.notice), state)) delivery.state = "role";
456
+ } catch {
457
+ delivery.state = "failed";
458
+ }
459
+ }
460
+ }
461
+ refresh() {
462
+ this.tick();
463
+ if (this.timer !== void 0) this.clock.clearTimeout(this.timer);
464
+ this.timer = void 0;
465
+ if (!this.closed) {
466
+ const due = this.eligible() ? [...this.requests.values()].flatMap((r) => r.dueAt === null ? [] : [r.dueAt]) : [];
467
+ for (const d of this.deliveries.values()) if (d.claim && ["claimed", "requested"].includes(d.state)) due.push(Math.min(d.claim.expiresAt, (this.clients.get(d.claim.clientId) ?? this.clock.now()) + (this.options.clientLifetimeMs ?? 3e4)));
468
+ if (due.length) this.timer = this.clock.setTimeout(() => {
469
+ this.timer = void 0;
470
+ this.refresh();
471
+ }, Math.max(1, Math.min(...due) - this.clock.now()));
472
+ try {
473
+ this.options.changed?.();
474
+ } catch {
475
+ }
476
+ }
477
+ }
478
+ publicRequest(r) {
479
+ const { projected: _projected, snoozes: _snoozes, cleanup: _cleanup, ...value } = r;
480
+ return { ...value };
481
+ }
482
+ remove(sessionId) {
483
+ this.sources.delete(sessionId);
484
+ for (const [id2, r] of this.requests) if (r.sessionId === sessionId) {
485
+ r.cleanup?.();
486
+ this.requests.delete(id2);
487
+ }
488
+ for (const [id2, d] of this.deliveries) if (d.notice.sessionId === sessionId) this.deliveries.delete(id2);
489
+ this.refresh();
490
+ }
491
+ dispose() {
492
+ this.closed = true;
493
+ if (this.timer !== void 0) this.clock.clearTimeout(this.timer);
494
+ this.timer = void 0;
495
+ for (const r of this.requests.values()) r.cleanup?.();
496
+ this.cancelDeliveries();
497
+ this.clients.clear();
498
+ this.sources.clear();
499
+ this.requests.clear();
500
+ this.deliveries.clear();
501
+ this.problems.length = 0;
502
+ }
503
+ };
504
+
1
505
  // src/index.ts
2
506
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
3
- import z from "@deepseek-ai/schemastery";
507
+ import z2 from "@deepseek-ai/schemastery";
4
508
 
5
509
  // src/bridge.ts
6
510
  import { spawn } from "node:child_process";
@@ -12,63 +516,86 @@ var ElectronBridge = class extends EventEmitter {
12
516
  latest;
13
517
  resultKey;
14
518
  closing = false;
15
- async start(options) {
519
+ generation = 0;
520
+ visibilityRevision = 0;
521
+ nativeVisible = false;
522
+ suspended = false;
523
+ lastNotificationState;
524
+ async start(options, lifetime) {
16
525
  if (this.child) throw new Error("Desktop pet is already running");
526
+ if (lifetime?.signal.aborted) throw new Error("\u684C\u5BA0\u542F\u52A8\u5DF2\u53D6\u6D88");
17
527
  this.closing = false;
18
- if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) throw new Error("\u684C\u5BA0\u9700\u8981\u684C\u9762\u663E\u793A\u73AF\u5883\u3002\u65E0\u684C\u9762\u7684\u4E91\u73AF\u5883\u53EF\u8FD0\u884C npm run dev \u9884\u89C8\uFF0C\u6216\u7528 Xvfb \u8FD0\u884C\u684C\u9762\u6D4B\u8BD5\u3002");
528
+ this.generation = lifetime?.generation ?? this.generation + 1;
529
+ this.visibilityRevision = 0;
530
+ this.nativeVisible = false;
531
+ this.suspended = false;
532
+ if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) throw new Error("\u684C\u5BA0\u9700\u8981\u684C\u9762\u663E\u793A\u73AF\u5883\u3002");
19
533
  const executable = options.electronPath ?? createRequire(import.meta.url)("electron");
20
- const env = { ...process.env };
534
+ const env = { ...process.env, DSH_PET_GENERATION: String(this.generation) };
21
535
  delete env.ELECTRON_RUN_AS_NODE;
22
536
  const args = [fileURLToPath(new URL("../desktop/main.cjs", import.meta.url))];
23
537
  if (env.DSH_PET_TEST_NO_SANDBOX === "1") args.unshift("--no-sandbox");
24
538
  const child = spawn(executable, args, { env, stdio: ["ignore", "pipe", "pipe", "ipc"] });
539
+ const generation = this.generation;
25
540
  this.child = child;
26
541
  let diagnostic = "";
27
542
  child.stderr?.on("data", (data) => {
28
543
  diagnostic = (diagnostic + data.toString()).slice(-4e3);
29
544
  });
30
545
  child.on("message", (message) => {
31
- if (isRecord(message) && message.type === "action") this.emit("action", message.action);
32
- if (isRecord(message) && message.type === "tray-state") this.emit("tray-state", message.state);
33
- if (isRecord(message) && message.type === "tray-icon") this.emit("tray-icon", message);
34
- if (isRecord(message) && message.type === "visibility" && typeof message.visible === "boolean") this.emit("lifecycle", { running: true, visible: message.visible });
546
+ if (this.child !== child || !isRecord(message)) return;
547
+ if (message.type === "action") this.emit("action", message.action);
548
+ if (message.type === "tray-state") this.emit("tray-state", message.state);
549
+ if (message.type === "tray-icon") this.emit("tray-icon", message);
550
+ if (message.type === "visibility" && message.generation === generation && typeof message.visible === "boolean" && Number.isSafeInteger(message.visibilityRevision) && message.visibilityRevision > this.visibilityRevision) {
551
+ this.visibilityRevision = message.visibilityRevision;
552
+ this.nativeVisible = message.visible;
553
+ this.suspended = message.suspended === true;
554
+ this.emit("lifecycle", { running: true, visible: this.nativeVisible, generation, visibilityRevision: this.visibilityRevision, suspended: this.suspended });
555
+ }
556
+ });
557
+ child.once("exit", (code, signal) => {
558
+ if (this.child !== child) return;
559
+ this.child = void 0;
560
+ this.nativeVisible = false;
561
+ const error = !this.closing && (code !== 0 || signal) ? `\u684C\u5BA0\u8FDB\u7A0B\u5DF2\u9000\u51FA (${signal ?? code})` : void 0;
562
+ this.emit("lifecycle", { running: false, visible: false, generation, visibilityRevision: ++this.visibilityRevision, suspended: false, ...error ? { error } : {} });
563
+ if (error) this.emit("failure", new Error(error));
35
564
  });
36
565
  await new Promise((resolve, reject) => {
566
+ let done = false;
37
567
  const finish = (error) => {
568
+ if (done) return;
569
+ done = true;
38
570
  clearTimeout(timer);
39
571
  child.off("message", ready2);
40
572
  child.off("error", failed);
41
573
  child.off("exit", exited);
574
+ lifetime?.signal.removeEventListener("abort", aborted);
42
575
  if (error) {
43
576
  child.kill();
44
577
  reject(error);
45
578
  } else resolve();
46
579
  };
47
580
  const ready2 = (message) => {
48
- if (isRecord(message) && message.type === "ready") {
581
+ if (isRecord(message) && message.type === "ready" && this.child === child && !lifetime?.signal.aborted) {
49
582
  this.send({ type: "init", options, snapshot: this.latest && desktopSnapshot(this.latest, true) });
583
+ if (this.lastNotificationState) this.notificationState(this.lastNotificationState);
50
584
  finish();
51
585
  }
52
586
  };
53
- const failed = (error) => {
54
- this.child = void 0;
55
- finish(error);
56
- };
57
- const exited = (code, signal) => {
58
- this.child = void 0;
59
- finish(new Error(`\u684C\u5BA0\u542F\u52A8\u5931\u8D25 (${signal ?? code}): ${diagnostic}`));
60
- };
587
+ const failed = (error) => finish(error);
588
+ const exited = (code, signal) => finish(new Error(`\u684C\u5BA0\u542F\u52A8\u5931\u8D25 (${signal ?? code}): ${diagnostic}`));
589
+ const aborted = () => finish(new Error("\u684C\u5BA0\u542F\u52A8\u5DF2\u53D6\u6D88"));
61
590
  const timer = setTimeout(() => finish(new Error(`\u684C\u5BA0\u672A\u80FD\u5728 20 \u79D2\u5185\u542F\u52A8: ${diagnostic}`)), 2e4);
62
591
  child.on("message", ready2);
63
592
  child.once("error", failed);
64
593
  child.once("exit", exited);
594
+ lifetime?.signal.addEventListener("abort", aborted, { once: true });
595
+ if (lifetime?.signal.aborted) aborted();
65
596
  });
66
- child.on("error", (error) => this.emit("failure", error));
67
- child.once("exit", (code) => {
68
- this.child = void 0;
69
- const error = !this.closing && code !== 0 ? `\u684C\u5BA0\u8FDB\u7A0B\u5DF2\u9000\u51FA (${code})` : void 0;
70
- this.emit("lifecycle", { running: false, visible: false, ...error ? { error } : {} });
71
- if (error) this.emit("failure", new Error(error));
597
+ child.on("error", (error) => {
598
+ if (this.child === child && !this.closing) this.emit("failure", error);
72
599
  });
73
600
  }
74
601
  update(snapshot) {
@@ -80,6 +607,18 @@ var ElectronBridge = class extends EventEmitter {
80
607
  notify(notice) {
81
608
  this.send({ type: "notice", notice });
82
609
  }
610
+ notificationState(snapshot) {
611
+ this.lastNotificationState = structuredClone(snapshot);
612
+ this.send({ type: "notification-state", snapshot });
613
+ }
614
+ snoozeResult(interactionId2, ok, error) {
615
+ this.send({ type: "notification-snooze-result", interactionId: interactionId2, ok, ...error ? { error: error.slice(0, 600) } : {} });
616
+ }
617
+ presentRole(notice, runtime) {
618
+ if (!this.child?.connected || this.closing || !this.nativeVisible || this.suspended || runtime.generation !== this.generation || runtime.visibilityRevision !== this.visibilityRevision || !runtime.visible) return false;
619
+ this.send({ type: "notice", notice, generation: runtime.generation, visibilityRevision: runtime.visibilityRevision });
620
+ return true;
621
+ }
83
622
  onAction(listener) {
84
623
  this.on("action", listener);
85
624
  }
@@ -110,19 +649,27 @@ var ElectronBridge = class extends EventEmitter {
110
649
  this.closing = true;
111
650
  const child = this.child;
112
651
  if (!child) return;
113
- if (child.exitCode !== null || child.signalCode !== null) {
652
+ if (child.pid === void 0 || child.exitCode !== null || child.signalCode !== null) {
114
653
  if (this.child === child) this.child = void 0;
115
654
  return;
116
655
  }
117
- await new Promise((resolve) => {
656
+ await new Promise((resolve, reject) => {
657
+ let deadline;
118
658
  const timer = setTimeout(() => {
119
659
  child.kill("SIGKILL");
660
+ deadline = setTimeout(() => {
661
+ if (child.exitCode !== null || child.signalCode !== null) resolve();
662
+ else reject(new Error("\u684C\u5BA0\u8FDB\u7A0B\u672A\u786E\u8BA4\u9000\u51FA"));
663
+ }, 1e3);
120
664
  }, 3e3);
121
665
  child.once("exit", () => {
122
666
  clearTimeout(timer);
667
+ clearTimeout(deadline);
123
668
  resolve();
124
669
  });
125
- if (child.connected) child.send({ type: "quit" });
670
+ if (child.connected) child.send({ type: "quit" }, (error) => {
671
+ if (error) child.kill();
672
+ });
126
673
  else child.kill();
127
674
  });
128
675
  if (this.child === child) this.child = void 0;
@@ -157,18 +704,23 @@ var PetModel = class {
157
704
  let item = this.sessions.get(session.id);
158
705
  if (!item) {
159
706
  if (this.sessions.size >= 100) {
160
- const old = [...this.sessions.keys()].find((id) => id !== this.selected);
707
+ const old = [...this.sessions.keys()].find((id2) => id2 !== this.selected);
161
708
  if (old) this.remove(old);
162
709
  }
163
710
  const project = session.header.cwd ? basename(session.header.cwd) : "\u672A\u6307\u5B9A\u9879\u76EE";
164
711
  item = { id: session.id, label: project, project, cwd: session.header.cwd ?? "", prompt: "", createdAt: session.header.createdAt, updatedAt: session.header.createdAt, mood: "idle", text: ready, reply: "", replyId: "", unread: 0, revision: 0, active: false, streaming: false, speechId: "" };
165
712
  this.sessions.set(session.id, item);
166
- this.tasks.set(session.id, { seq: -1, turn: 0, active: false, tools: /* @__PURE__ */ new Map(), approvals: /* @__PURE__ */ new Set(), celebrateUntil: 0 });
713
+ this.tasks.set(session.id, { seq: -1, turn: 0, active: false, tools: /* @__PURE__ */ new Map(), approvals: /* @__PURE__ */ new Set(), questions: /* @__PURE__ */ new Set(), requests: /* @__PURE__ */ new Set(), celebrateUntil: 0 });
167
714
  this.selected ??= session.id;
168
715
  for (const event of session.snapshotEvents?.() ?? []) this.describe(item, event);
169
716
  }
170
717
  return item;
171
718
  }
719
+ /** Fold history as a read baseline; callers reconcile activity with the live Agent status. */
720
+ restore(session) {
721
+ if (!this.observe(session)) return;
722
+ for (const event of session.snapshotEvents?.() ?? []) this.fold(session, event, false);
723
+ }
172
724
  describe(item, event) {
173
725
  if (event.type !== "user/message" || event.data.source.kind !== "user") return;
174
726
  const text = event.data.content.filter((p) => p.type === "text").map((p) => p.text).join(" ").replace(/\s+/g, " ").trim();
@@ -214,12 +766,12 @@ var PetModel = class {
214
766
  }
215
767
  return true;
216
768
  }
217
- detached(id) {
218
- const task = this.tasks.get(id);
769
+ detached(id2) {
770
+ const task = this.tasks.get(id2);
219
771
  if (task) task.stream = void 0;
220
772
  }
221
- idle(id) {
222
- const item = this.sessions.get(id), task = this.tasks.get(id);
773
+ idle(id2) {
774
+ const item = this.sessions.get(id2), task = this.tasks.get(id2);
223
775
  if (!item || !task?.active) return;
224
776
  task.active = false;
225
777
  task.stream = void 0;
@@ -238,8 +790,10 @@ var PetModel = class {
238
790
  running(session) {
239
791
  const item = this.observe(session);
240
792
  if (!item || this.tasks.get(item.id).active) return;
241
- this.tasks.get(item.id).active = true;
242
- this.present(item, "thinking", "\u6B63\u5728\u5904\u7406\u5F53\u524D\u4F1A\u8BDD\u2026");
793
+ const task = this.tasks.get(item.id);
794
+ task.active = true;
795
+ if (task.requests.size || task.approvals.size) this.present(item, "waiting", item.text);
796
+ else this.present(item, "thinking", "\u6B63\u5728\u5904\u7406\u5F53\u524D\u4F1A\u8BDD\u2026");
243
797
  }
244
798
  present(item, mood, text) {
245
799
  item.active = this.tasks.get(item.id).active;
@@ -251,10 +805,10 @@ var PetModel = class {
251
805
  /** Celebration has a deadline independent of UI refreshes or other sessions. */
252
806
  settle() {
253
807
  let changed = false;
254
- for (const [id, task] of this.tasks) {
808
+ for (const [id2, task] of this.tasks) {
255
809
  if (!task.celebrateUntil || this.now() < task.celebrateUntil) continue;
256
810
  task.celebrateUntil = 0;
257
- const item = this.sessions.get(id);
811
+ const item = this.sessions.get(id2);
258
812
  if (!task.active && item.mood === "happy") {
259
813
  this.present(item, "idle", ready);
260
814
  changed = true;
@@ -263,6 +817,9 @@ var PetModel = class {
263
817
  return changed;
264
818
  }
265
819
  consume(session, event) {
820
+ return this.fold(session, event, true);
821
+ }
822
+ fold(session, event, live) {
266
823
  const item = this.observe(session);
267
824
  if (!item) return;
268
825
  const task = this.tasks.get(item.id);
@@ -303,7 +860,7 @@ var PetModel = class {
303
860
  break;
304
861
  }
305
862
  if (event.data.message.isError) {
306
- this.present(item, "error", "\u8FD9\u4E00\u6B65\u9047\u5230\u4E86\u95EE\u9898\uFF0C\u6B63\u5728\u5904\u7406\u3002");
863
+ this.present(item, "thinking", "\u8FD9\u4E00\u6B65\u9047\u5230\u4E86\u95EE\u9898\uFF0C\u6B63\u5728\u5904\u7406\u3002");
307
864
  } else {
308
865
  this.present(item, "thinking", "\u8FD9\u4E00\u6B65\u5B8C\u6210\u4E86\uFF0C\u7EE7\u7EED\u60F3\u60F3\u2026");
309
866
  }
@@ -316,6 +873,13 @@ var PetModel = class {
316
873
  if (text.trim() && !task.tools.size && !task.approvals.size) this.present(item, "talking", "\u6B63\u5728\u7EC4\u7EC7\u56DE\u590D\u2026");
317
874
  break;
318
875
  }
876
+ case "approval/asked": {
877
+ const notice = this.approval(item.id, event.data.toolName, event.data.id);
878
+ return live ? notice : void 0;
879
+ }
880
+ case "approval/decided":
881
+ this.approvalSettled(item.id, event.data.id);
882
+ break;
319
883
  case "turn/end": {
320
884
  task.turn = event.data.turn;
321
885
  task.active = false;
@@ -328,11 +892,11 @@ var PetModel = class {
328
892
  case "completed": {
329
893
  const text = task.finalText?.trim() ? task.finalText : "";
330
894
  if (text) {
331
- const id = `${item.id}:${event.data.turn}:${event.seq}`;
332
- this.results.set(id, { id, sessionId: item.id, text, time: event.time, read: false });
895
+ const id2 = `${item.id}:${event.data.turn}:${event.seq}`;
896
+ this.results.set(id2, { id: id2, sessionId: item.id, text, time: event.time, read: !live });
333
897
  item.reply = text;
334
- item.replyId = id;
335
- item.unread++;
898
+ item.replyId = id2;
899
+ if (live) item.unread++;
336
900
  if (this.results.size > 200) {
337
901
  const old = [...this.results.values()].find((r) => r.read) ?? this.results.values().next().value;
338
902
  this.results.delete(old.id);
@@ -341,36 +905,42 @@ var PetModel = class {
341
905
  }
342
906
  }
343
907
  task.finalText = void 0;
344
- this.present(item, "happy", text || "\u4EFB\u52A1\u5B8C\u6210");
345
- task.celebrateUntil = this.now() + 2500;
346
- return { title: `${item.label} \xB7 \u4EFB\u52A1\u5B8C\u6210`, body: text.slice(0, 180) || "\u5DF2\u5B8C\u6210\uFF0C\u56DE\u5230\u4F1A\u8BDD\u67E5\u770B\u3002", sessionId: item.id, kind: "task" };
908
+ this.present(item, live ? "happy" : "idle", live ? text || "\u4EFB\u52A1\u5B8C\u6210" : ready);
909
+ task.celebrateUntil = live ? this.now() + 2500 : 0;
910
+ return live ? { title: `${item.label} \xB7 \u4EFB\u52A1\u5B8C\u6210`, body: text.slice(0, 180) || "\u5DF2\u5B8C\u6210\uFF0C\u56DE\u5230\u4F1A\u8BDD\u67E5\u770B\u3002", sessionId: item.id, kind: "task" } : void 0;
347
911
  }
348
912
  case "error":
349
913
  this.present(item, "error", "\u4EFB\u52A1\u9047\u5230\u4E86\u95EE\u9898\uFF0C\u8BF7\u56DE\u5230 Harness \u67E5\u770B\u8BE6\u60C5\u3002");
350
- return { title: `${item.label} \xB7 \u9700\u8981\u5173\u6CE8`, body: item.text, sessionId: item.id, kind: "task" };
914
+ return live ? { title: `${item.label} \xB7 \u9700\u8981\u5173\u6CE8`, body: item.text, sessionId: item.id, kind: "task" } : void 0;
351
915
  case "blocked":
352
916
  case "max-tokens":
353
917
  this.present(item, "waiting", "\u4EFB\u52A1\u6682\u65F6\u505C\u4E0B\u4E86\uFF0C\u8BF7\u56DE\u5230 Harness \u770B\u770B\u3002");
354
- return { title: `${item.label} \xB7 \u4EFB\u52A1\u6682\u505C`, body: item.text, sessionId: item.id, kind: "task" };
918
+ return live ? { title: `${item.label} \xB7 \u4EFB\u52A1\u6682\u505C`, body: item.text, sessionId: item.id, kind: "task" } : void 0;
919
+ case "aborted":
920
+ this.present(item, "idle", "\u5148\u505C\u5728\u8FD9\u91CC\uFF0C\u968F\u65F6\u7EE7\u7EED\u3002");
921
+ return live ? { title: `${item.label} \xB7 \u4EFB\u52A1\u5DF2\u505C\u6B62`, body: item.text, sessionId: item.id, kind: "task", category: "stopped" } : void 0;
922
+ case "interrupted":
923
+ this.present(item, "waiting", "\u8FD9\u6BB5\u4EFB\u52A1\u4E2D\u65AD\u4E86\uFF0C\u966A\u4F60\u56DE\u53BB\u770B\u770B\u3002");
924
+ return live ? { title: `${item.label} \xB7 \u4EFB\u52A1\u4E2D\u65AD`, body: item.text, sessionId: item.id, kind: "task", category: "interrupted" } : void 0;
355
925
  default:
356
- this.present(item, "idle", "\u4EFB\u52A1\u5DF2\u505C\u6B62\uFF0C\u6211\u5728\u8FD9\u91CC\u7B49\u4F60\u3002");
926
+ this.present(item, "idle", "\u51C6\u5907\u597D\u4E86\uFF0C\u968F\u65F6\u53EB\u6211\u3002");
357
927
  }
358
928
  }
359
929
  }
360
930
  }
361
- approval(id, tool, token = Symbol()) {
362
- const item = this.sessions.get(id);
931
+ approval(id2, tool, token = Symbol()) {
932
+ const item = this.sessions.get(id2);
363
933
  if (!item) return;
364
- const task = this.tasks.get(id);
934
+ const task = this.tasks.get(id2);
365
935
  task.active = true;
366
936
  task.approvals.add(token);
367
937
  task.celebrateUntil = 0;
368
938
  this.present(item, "waiting", `${toolLabel(tool)}\u524D\u9700\u8981\u4F60\u786E\u8BA4\uFF0C\u8BF7\u56DE\u5230 Harness\u3002`);
369
- return { title: `${item.label} \xB7 \u7B49\u4F60\u786E\u8BA4`, body: item.text, sessionId: id, kind: "task" };
939
+ return { title: `${item.label} \xB7 \u7B49\u4F60\u786E\u8BA4`, body: item.text, sessionId: id2, kind: "task" };
370
940
  }
371
- approvalSettled(id, token) {
372
- const item = this.sessions.get(id);
373
- const task = this.tasks.get(id);
941
+ approvalSettled(id2, token) {
942
+ const item = this.sessions.get(id2);
943
+ const task = this.tasks.get(id2);
374
944
  if (!item || !task?.active) return;
375
945
  if (token ? !task.approvals.delete(token) : !task.approvals.size) return;
376
946
  if (!token) task.approvals.clear();
@@ -378,25 +948,41 @@ var PetModel = class {
378
948
  this.present(item, task.tools.size ? "working" : "thinking", task.tools.size ? toolLabel(task.tools.values().next().value) : "\u786E\u8BA4\u5DF2\u5904\u7406\uFF0C\u7B49\u5F85\u4EFB\u52A1\u7EE7\u7EED\u2026");
379
949
  }
380
950
  }
381
- select(id) {
382
- if (!this.sessions.has(id)) return false;
383
- this.selected = id;
951
+ /** Public request state can outlive a turn; viewing or reading never removes its waiting entrance. */
952
+ interactions(values) {
953
+ for (const [id2, task] of this.tasks) {
954
+ const wasPending = task.requests.size > 0;
955
+ const pending = values.filter((value) => value.sessionId === id2 && value.state !== "settled");
956
+ task.requests = new Set(pending.map((value) => value.id));
957
+ task.questions = new Set(pending.filter((value) => value.kind === "question").map((value) => value.id));
958
+ const item = this.sessions.get(id2);
959
+ if (pending.length) {
960
+ task.celebrateUntil = 0;
961
+ this.present(item, "waiting", pending.some((value) => value.kind === "question") ? "\u6709\u4E2A\u95EE\u9898\u60F3\u95EE\u4F60\uFF0C\u8BF7\u56DE\u5230 Harness \u770B\u770B\u3002" : "\u4E0B\u4E00\u6B65\u9700\u8981\u4F60\u786E\u8BA4\uFF0C\u8BF7\u56DE\u5230 Harness\u3002");
962
+ } else if (wasPending && !task.approvals.size && item.mood === "waiting") {
963
+ this.present(item, task.active ? task.tools.size ? "working" : "thinking" : "idle", task.active ? task.tools.size ? toolLabel(task.tools.values().next().value) : "\u7B49\u5F85\u4EFB\u52A1\u7EE7\u7EED\u2026" : ready);
964
+ }
965
+ }
966
+ }
967
+ select(id2) {
968
+ if (!this.sessions.has(id2)) return false;
969
+ this.selected = id2;
384
970
  return true;
385
971
  }
386
972
  /** Acknowledging an older result cannot clear a newer completion. */
387
- read(id) {
388
- const result = this.results.get(id);
973
+ read(id2) {
974
+ const result = this.results.get(id2);
389
975
  if (!result || result.read) return false;
390
976
  result.read = true;
391
977
  const item = this.sessions.get(result.sessionId);
392
978
  if (item) item.unread = Math.max(0, item.unread - 1);
393
979
  return true;
394
980
  }
395
- remove(id) {
396
- this.sessions.delete(id);
397
- this.tasks.delete(id);
398
- for (const [key, result] of this.results) if (result.sessionId === id) this.results.delete(key);
399
- if (this.selected === id) this.selected = this.sessions.keys().next().value ?? null;
981
+ remove(id2) {
982
+ this.sessions.delete(id2);
983
+ this.tasks.delete(id2);
984
+ for (const [key, result] of this.results) if (result.sessionId === id2) this.results.delete(key);
985
+ if (this.selected === id2) this.selected = this.sessions.keys().next().value ?? null;
400
986
  }
401
987
  snapshot() {
402
988
  const item = this.selected ? this.sessions.get(this.selected) : void 0;
@@ -415,58 +1001,112 @@ function toolLabel(name2) {
415
1001
 
416
1002
  // src/controls.ts
417
1003
  var PetControls = class {
418
- constructor(bridge, options) {
1004
+ constructor(bridge, options, limits = {}) {
419
1005
  this.bridge = bridge;
420
1006
  this.options = options;
1007
+ this.limits = limits;
421
1008
  bridge.onLifecycle?.(this.changed);
422
1009
  }
423
- state = { phase: "stopped", visible: false };
1010
+ state = { phase: "stopped", visible: false, generation: 0, visibilityRevision: 0, suspended: false };
424
1011
  queue = Promise.resolve();
425
1012
  disposed = false;
1013
+ startup;
1014
+ listeners = /* @__PURE__ */ new Set();
426
1015
  changed = (event) => {
427
- if (this.state.phase === "starting" || this.state.phase === "stopping") return;
428
- this.state = { phase: event.error ? "error" : event.running ? "running" : "stopped", visible: event.visible, ...event.error ? { error: event.error } : {} };
1016
+ if (this.disposed || event.generation !== this.state.generation || !Number.isSafeInteger(event.visibilityRevision) || event.visibilityRevision < this.state.visibilityRevision) return;
1017
+ if (event.visibilityRevision === this.state.visibilityRevision && event.visible !== this.state.visible) return;
1018
+ if (this.state.phase === "stopping" || (this.state.phase === "stopped" || this.state.phase === "error") && event.running) return;
1019
+ this.set({ ...this.state, phase: event.error ? "error" : event.running ? this.state.phase === "starting" ? "starting" : "running" : "stopped", visible: event.running && event.visible, visibilityRevision: event.visibilityRevision, suspended: event.suspended ?? false, ...event.error ? { error: event.error.slice(0, 600) } : {} });
429
1020
  };
430
1021
  status() {
431
1022
  return { ...this.state };
432
1023
  }
1024
+ /** Root assembly registers this listener as a context-owned effect. */
1025
+ onState(listener) {
1026
+ this.listeners.add(listener);
1027
+ try {
1028
+ listener(this.status());
1029
+ } catch {
1030
+ }
1031
+ return () => this.listeners.delete(listener);
1032
+ }
433
1033
  configure() {
434
1034
  this.bridge.configure?.(this.options());
435
1035
  }
436
1036
  command(command) {
1037
+ if (command === "stop" || command === "restart") this.startup?.abort();
437
1038
  return this.enqueue(async () => {
438
1039
  if (this.disposed) throw new Error("\u684C\u5BA0\u63D2\u4EF6\u5DF2\u505C\u7528");
439
1040
  try {
440
1041
  if (command === "stop" || command === "restart") {
441
- this.state = { phase: "stopping", visible: false };
442
- await this.bridge.dispose();
443
- this.state = { phase: "stopped", visible: false };
1042
+ this.set({ ...this.state, phase: "stopping", visible: false, suspended: false });
1043
+ await this.cleanup();
1044
+ this.set({ ...this.state, phase: "stopped", visible: false, suspended: false });
444
1045
  }
445
1046
  if (command !== "stop" && command !== "hide" && this.state.phase !== "running") {
446
- this.state = { phase: "starting", visible: false };
447
- await this.bridge.start(this.options());
448
- this.state = { phase: "running", visible: true };
449
- }
450
- if (this.state.phase === "running") {
451
- this.bridge.control?.(command === "characters" ? "characters" : command === "hide" ? "hide" : "show");
452
- this.state.visible = command !== "hide";
1047
+ const startup = new AbortController();
1048
+ this.startup = startup;
1049
+ this.set({ phase: "starting", visible: false, generation: this.state.generation + 1, visibilityRevision: 0, suspended: false });
1050
+ await this.withDeadline(this.bridge.start(this.options(), { signal: startup.signal, generation: this.state.generation }), this.limits.startTimeoutMs ?? 25e3, "\u684C\u5BA0\u542F\u52A8\u8D85\u65F6", startup.signal);
1051
+ if (startup.signal.aborted || this.disposed) throw new Error("\u684C\u5BA0\u542F\u52A8\u5DF2\u53D6\u6D88");
1052
+ this.startup = void 0;
1053
+ this.set({ ...this.state, phase: "running" });
453
1054
  }
1055
+ if (this.state.phase === "running") this.bridge.control?.(command === "characters" ? "characters" : command === "hide" ? "hide" : "show");
454
1056
  return this.status();
455
1057
  } catch (error) {
456
- await this.bridge.dispose();
457
- this.state = { phase: "error", visible: false, error: String(error instanceof Error ? error.message : error).slice(0, 600) };
1058
+ this.startup?.abort();
1059
+ this.startup = void 0;
1060
+ const cleanup = await this.cleanup().then(() => "", (failure) => `\uFF1B\u6E05\u7406\u5931\u8D25\uFF1A${this.message(failure)}`);
1061
+ this.set({ ...this.state, phase: "error", visible: false, suspended: false, error: (this.message(error) + cleanup).slice(0, 600) });
458
1062
  return this.status();
459
1063
  }
460
1064
  });
461
1065
  }
462
1066
  async dispose() {
463
1067
  this.disposed = true;
1068
+ this.startup?.abort();
1069
+ this.set({ ...this.state, phase: "stopping", visible: false, suspended: false });
464
1070
  await this.enqueue(async () => {
465
1071
  this.bridge.removeLifecycle?.(this.changed);
466
- await this.bridge.dispose();
467
- this.state = { phase: "stopped", visible: false };
1072
+ const failure = await this.cleanup().then(() => void 0, (error) => this.message(error));
1073
+ this.set({ ...this.state, phase: failure ? "error" : "stopped", visible: false, ...failure ? { error: failure } : {} });
1074
+ this.listeners.clear();
468
1075
  });
469
1076
  }
1077
+ message(error) {
1078
+ return String(error instanceof Error ? error.message : error).slice(0, 600);
1079
+ }
1080
+ cleanup() {
1081
+ return this.withDeadline(Promise.resolve().then(() => this.bridge.dispose()), this.limits.cleanupTimeoutMs ?? 5e3, "\u684C\u5BA0\u6E05\u7406\u8D85\u65F6");
1082
+ }
1083
+ withDeadline(task, delay, message, signal) {
1084
+ return new Promise((resolve, reject) => {
1085
+ let done = false;
1086
+ const finish = (error, value) => {
1087
+ if (done) return;
1088
+ done = true;
1089
+ clearTimeout(timer);
1090
+ signal?.removeEventListener("abort", aborted);
1091
+ if (error) reject(error);
1092
+ else resolve(value);
1093
+ };
1094
+ const aborted = () => finish(new Error("\u684C\u5BA0\u542F\u52A8\u5DF2\u53D6\u6D88"));
1095
+ const timer = setTimeout(() => finish(new Error(message)), delay);
1096
+ signal?.addEventListener("abort", aborted, { once: true });
1097
+ if (signal?.aborted) aborted();
1098
+ task.then((value) => finish(void 0, value), (error) => finish(error));
1099
+ });
1100
+ }
1101
+ set(state) {
1102
+ this.state = state;
1103
+ for (const listener of this.listeners) {
1104
+ try {
1105
+ listener(this.status());
1106
+ } catch {
1107
+ }
1108
+ }
1109
+ }
470
1110
  enqueue(operation) {
471
1111
  const pending = this.queue.then(operation);
472
1112
  this.queue = pending.catch(() => void 0);
@@ -478,13 +1118,16 @@ var PetControls = class {
478
1118
  import { z as wire } from "zod";
479
1119
  var name = "dsh-coopanion";
480
1120
  var inject = ["agents"];
481
- var Config = z.object({
482
- size: z.number().min(90).max(240).default(180).volatile(),
483
- roam: z.boolean().default(true).volatile(),
484
- notifications: z.boolean().default(true).volatile(),
485
- bubbleDurationMs: z.number().min(2e3).max(6e4).default(12e3).volatile(),
486
- autoStart: z.boolean().default(true).volatile(),
487
- electronPath: z.string()
1121
+ var Config = z2.object({
1122
+ size: z2.number().min(90).max(240).default(180).volatile(),
1123
+ roam: z2.boolean().default(true).volatile(),
1124
+ notifications: z2.boolean().default(true).volatile(),
1125
+ systemNotifications: z2.boolean().default(false).volatile(),
1126
+ reminders: z2.boolean().default(true).volatile(),
1127
+ reminderDelayMs: z2.number().step(1).min(6e4).max(864e5).default(6e5).volatile(),
1128
+ bubbleDurationMs: z2.number().min(2e3).max(6e4).default(12e3).volatile(),
1129
+ autoStart: z2.boolean().default(true).volatile(),
1130
+ electronPath: z2.string()
488
1131
  });
489
1132
  async function apply(ctx, config) {
490
1133
  ctx.inject(["settings"], (child) => {
@@ -499,17 +1142,63 @@ async function mountPet(ctx, options, bridge) {
499
1142
  ctx.inject(["settings"], (child) => {
500
1143
  savePreference = (field, value) => child.settings.mutate("dsh-coopanion", [{ op: "set", path: [field], value }]);
501
1144
  });
502
- const currentOptions = () => ({ size: options.size.get(), roam: options.roam.get(), notifications: options.notifications.get(), bubbleDurationMs: options.bubbleDurationMs.get(), electronPath: options.electronPath, ...preferences });
1145
+ const currentOptions = () => ({ size: options.size.get(), roam: options.roam.get(), notifications: options.notifications.get(), bubbleDurationMs: options.bubbleDurationMs.get(), systemNotifications: options.systemNotifications.get(), reminders: options.reminders.get(), reminderDelayMs: options.reminderDelayMs.get(), electronPath: options.electronPath, locale, ...preferences });
503
1146
  const controls = new PetControls(bridge, currentOptions);
1147
+ let locale = "zh";
504
1148
  let navigation;
505
1149
  ctx.provide("coopanion", controls);
506
1150
  const update = () => {
507
1151
  const snapshot = model.snapshot(), live = new Set(ctx.agents.list().map((agent) => agent.session.id));
508
1152
  bridge.update({ ...snapshot, sessions: snapshot.sessions.map((session) => ({ ...session, chatAvailable: live.has(session.id) })) });
509
1153
  };
510
- const notice = (value) => {
511
- if (value && currentOptions().notifications) bridge.notify(value);
1154
+ let mounted = false;
1155
+ const notificationPrefs = () => notificationPreferencesSchema.parse({ notifications: currentOptions().notifications, systemNotifications: options.systemNotifications.get(), reminders: options.reminders.get(), reminderDelayMs: options.reminderDelayMs.get() });
1156
+ const syncNotifications = () => {
1157
+ if (!mounted) return;
1158
+ const snapshot = broker.snapshot();
1159
+ model.interactions(snapshot.interactions);
1160
+ bridge.notificationState?.(snapshot);
1161
+ update();
512
1162
  };
1163
+ const broker = new NotificationBroker({ changed: syncNotifications, presentRole: (value, runtime) => bridge.presentRole?.(value, runtime) ?? false });
1164
+ broker.preferences(notificationPrefs());
1165
+ ctx.effect(() => () => broker.dispose());
1166
+ ctx.effect(() => controls.onState((state) => broker.runtime(state)));
1167
+ let questions;
1168
+ ctx.inject(["sessionProjections", "userQuestions"], (child) => {
1169
+ const sync = (session, live = true) => {
1170
+ try {
1171
+ const view = child.sessionProjections.snapshot(session, ["userQuestions"]).values.userQuestions;
1172
+ if (view) broker.questions(session, view, live);
1173
+ } catch (error) {
1174
+ child.logger.warn(`Question projection unavailable: ${String(error).slice(0, 300)}`);
1175
+ }
1176
+ };
1177
+ questions = sync;
1178
+ child.effect(() => () => {
1179
+ if (questions === sync) questions = void 0;
1180
+ });
1181
+ queueMicrotask(() => {
1182
+ if (!mounted || questions !== sync) return;
1183
+ for (const session of child.get("sessions")?.list() ?? ctx.agents.list().map((agent) => agent.session)) sync(session, false);
1184
+ });
1185
+ });
1186
+ let testSource;
1187
+ ctx.inject(["sessions", "sessionController"], (child) => {
1188
+ let source;
1189
+ const create = () => source ??= child.sessionController.create({ sessionId: SessionId(`coopanion-notification-test-${randomUUID2()}`), cwd: process.cwd() }).then((value) => {
1190
+ const session = child.sessions.get(value.sessionId);
1191
+ if (!session) throw new Error("Notification test source unavailable");
1192
+ return session;
1193
+ }).catch((error) => {
1194
+ source = void 0;
1195
+ throw error;
1196
+ });
1197
+ testSource = create;
1198
+ child.effect(() => () => {
1199
+ if (testSource === create) testSource = void 0;
1200
+ });
1201
+ });
513
1202
  let streamUpdate;
514
1203
  ctx.effect(() => () => clearTimeout(streamUpdate));
515
1204
  ctx.effect(() => () => controls.dispose());
@@ -521,7 +1210,10 @@ async function mountPet(ctx, options, bridge) {
521
1210
  return () => clearInterval(timer);
522
1211
  });
523
1212
  ctx.on("settings/document-updated", (ns) => {
524
- if (ns === "dsh-coopanion") controls.configure();
1213
+ if (ns === "dsh-coopanion") {
1214
+ broker.preferences(notificationPrefs());
1215
+ controls.configure();
1216
+ }
525
1217
  });
526
1218
  ctx.inject(["connection"], (child) => {
527
1219
  const dispatch = async (endpoint, payload, signal) => {
@@ -537,6 +1229,41 @@ async function mountPet(ctx, options, bridge) {
537
1229
  navigation = void 0;
538
1230
  return { ok: true, value };
539
1231
  }
1232
+ if (endpoint === "notification-state") {
1233
+ const input = notificationRequests.state.parse(payload);
1234
+ if (input.locale && input.locale !== locale) {
1235
+ locale = input.locale;
1236
+ controls.configure();
1237
+ }
1238
+ return { ok: true, value: broker.snapshot() };
1239
+ }
1240
+ if (endpoint === "notification-claim") {
1241
+ const input = notificationRequests.claim.parse(payload);
1242
+ return { ok: true, value: broker.claim(input.clientId, input.generation) };
1243
+ }
1244
+ if (endpoint === "notification-receipt") {
1245
+ return { ok: true, value: { accepted: broker.receipt(notificationRequests.receipt.parse(payload)) } };
1246
+ }
1247
+ if (endpoint === "notification-snooze") {
1248
+ const input = notificationRequests.snooze.parse(payload);
1249
+ if (!broker.snooze(input.interactionId, input.generation)) throw new Error("\u5F85\u5904\u7406\u8BF7\u6C42\u5DF2\u53D8\u5316\u6216\u63D0\u9192\u6682\u4E0D\u53EF\u7528");
1250
+ return { ok: true, value: { accepted: true } };
1251
+ }
1252
+ if (endpoint === "notification-test") {
1253
+ const input = notificationRequests.test.parse(payload), state = broker.snapshot().runtime, prefs = notificationPrefs();
1254
+ if (!testSource || state.phase !== "running" || state.visible || state.suspended || state.visibilityRevision === 0 || input.generation !== state.generation || !prefs.notifications || !prefs.systemNotifications) throw new Error("\u8BF7\u542F\u52A8\u5E76\u9690\u85CF\u89D2\u8272\uFF0C\u5F00\u542F\u7CFB\u7EDF\u901A\u77E5\u540E\u6D4B\u8BD5");
1255
+ const session = await testSource();
1256
+ if (signal.aborted) throw new Error("\u8BF7\u6C42\u5DF2\u53D6\u6D88");
1257
+ const latest = broker.snapshot().runtime;
1258
+ if (latest.generation !== state.generation || latest.visibilityRevision !== state.visibilityRevision || latest.phase !== "running" || latest.visible || latest.suspended) throw new Error("\u684C\u5BA0\u72B6\u6001\u5DF2\u53D8\u5316");
1259
+ const turn = session.snapshotEvents().findLast((event2) => event2.type === "turn/start")?.data?.turn ?? 0;
1260
+ session.append("turn/start", { turn: turn + 1 });
1261
+ session.append("turn/end", { turn: turn + 1, reason: { kind: "completed" } });
1262
+ const event = session.snapshotEvents().at(-1);
1263
+ const claim = broker.claim(input.clientId, input.generation, noticeId(session.id, turn + 1, event.seq, "completed", "initial"));
1264
+ if (!claim) throw new Error("\u6D4B\u8BD5\u901A\u77E5\u672A\u80FD\u9886\u53D6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
1265
+ return { ok: true, value: claim };
1266
+ }
540
1267
  if (endpoint !== "control") throw new Error("\u672A\u77E5\u7684\u684C\u5BA0\u64CD\u4F5C");
541
1268
  const { command } = wire.object({ command: wire.enum(["start", "show", "hide", "restart", "stop", "characters"]) }).strict().parse(payload);
542
1269
  return { ok: true, value: await controls.command(command) };
@@ -544,7 +1271,7 @@ async function mountPet(ctx, options, bridge) {
544
1271
  return { ok: false, error: { code: "coopanion/rejected", message: String(error instanceof Error ? error.message : error).slice(0, 600), details: {} } };
545
1272
  }
546
1273
  };
547
- for (const endpoint of ["status", "control", "navigation"]) {
1274
+ for (const endpoint of ["status", "control", "navigation", ...notificationEndpoints]) {
548
1275
  child.effect(() => child.connection.fetch.register({
549
1276
  path: `/api/coopanion/${endpoint}`,
550
1277
  methods: ["POST"],
@@ -557,21 +1284,27 @@ async function mountPet(ctx, options, bridge) {
557
1284
  }));
558
1285
  }
559
1286
  });
1287
+ const restoreSession = (session, running = ctx.agents.list().some((agent) => agent.session.id === session.id && agent.status === "running")) => {
1288
+ model.restore(session);
1289
+ if (running) model.running(session);
1290
+ else model.idle(session.id);
1291
+ broker.restore(session);
1292
+ questions?.(session, false);
1293
+ };
560
1294
  ctx.inject(["sessions"], (child) => {
561
- for (const session of child.sessions.list()) model.observe(session);
1295
+ for (const session of child.sessions.list()) restoreSession(session);
1296
+ syncNotifications();
562
1297
  update();
563
1298
  });
564
- for (const agent of ctx.agents.list()) {
565
- model.observe(agent.session);
566
- if (agent.status === "running") model.running(agent.session);
567
- }
1299
+ for (const agent of ctx.agents.list()) restoreSession(agent.session, agent.status === "running");
568
1300
  ctx.on("session/created", (session) => {
569
- model.created(session);
1301
+ restoreSession(session);
1302
+ syncNotifications();
570
1303
  update();
571
1304
  });
572
1305
  ctx.on("agent/created", ({ agent }) => {
573
- model.observe(agent.session);
574
- if (agent.status === "running") model.running(agent.session);
1306
+ restoreSession(agent.session, agent.status === "running");
1307
+ syncNotifications();
575
1308
  update();
576
1309
  return void 0;
577
1310
  });
@@ -593,33 +1326,55 @@ async function mountPet(ctx, options, bridge) {
593
1326
  update();
594
1327
  });
595
1328
  ctx.on("session/event", (session, event) => {
596
- notice(model.consume(session, event));
1329
+ broker.consume(session, event);
1330
+ model.consume(session, event);
1331
+ questions?.(session);
1332
+ syncNotifications();
597
1333
  update();
598
1334
  });
599
1335
  ctx.on("session/disposed", (session) => {
1336
+ broker.remove(session.id);
600
1337
  model.remove(session.id);
601
1338
  update();
602
1339
  });
603
- ctx.on("approval/request", async (request, next) => {
604
- model.observe(request.agent.session);
605
- const token = Symbol("approval");
606
- notice(model.approval(request.agent.session.id, request.toolName, token));
607
- update();
608
- try {
609
- return await next();
610
- } finally {
611
- model.approvalSettled(request.agent.session.id, token);
612
- update();
613
- }
1340
+ ctx.inject(["userQuestions"], (child) => {
1341
+ child.on("user-questions/request", async (request, next) => {
1342
+ const session = request.agent?.session;
1343
+ if (!session || session.header.origin === "subagent") return next();
1344
+ model.observe(session);
1345
+ const events = session.snapshotEvents();
1346
+ const callId = request.wait?.callId;
1347
+ const origin = callId ? events.findLast((event) => event.type === "tool/call" && event.data.callId === callId || event.type === "tool/ptc-dispatch" && event.data.subCallId === callId) : void 0;
1348
+ const anchor = origin ?? events.at(-1);
1349
+ const turnEvent = events.findLast((event) => event.type === "turn/start");
1350
+ const finish = broker.question(session, { nativeId: origin && callId ? callId : randomUUID2(), turn: turnEvent?.type === "turn/start" ? turnEvent.data.turn : 0, seq: anchor?.seq ?? 0, preview: request.questions.map((q) => q.question).join("\n"), signal: request.signal, source: origin ? "event" : "runtime" });
1351
+ questions?.(session);
1352
+ syncNotifications();
1353
+ try {
1354
+ return await next();
1355
+ } finally {
1356
+ questions?.(session);
1357
+ finish();
1358
+ syncNotifications();
1359
+ }
1360
+ }, { prepend: true });
614
1361
  });
615
1362
  const onAction = (action) => {
616
1363
  if (!isRecord(action)) return;
1364
+ if (action.type === "notification-snooze") {
1365
+ const input = notificationRequests.snooze.safeParse({ interactionId: action.interactionId, generation: action.generation });
1366
+ const ok = input.success && broker.snooze(input.data.interactionId, input.data.generation);
1367
+ if (typeof action.interactionId === "string") bridge.snoozeResult?.(action.interactionId, ok, ok ? void 0 : "\u5F85\u5904\u7406\u8BF7\u6C42\u5DF2\u53D8\u5316\u6216\u63D0\u9192\u6682\u4E0D\u53EF\u7528");
1368
+ syncNotifications();
1369
+ return;
1370
+ }
617
1371
  if (action.type === "preference" && (action.field === "roam" || action.field === "notifications") && typeof action.value === "boolean") {
618
1372
  const field = action.field, value = action.value;
619
1373
  void (async () => {
620
1374
  try {
621
1375
  if (savePreference) await savePreference(field, value);
622
1376
  else preferences[field] = value;
1377
+ broker.preferences(notificationPrefs());
623
1378
  controls.configure();
624
1379
  } catch {
625
1380
  bridge.notify({ title: "\u8BBE\u7F6E\u672A\u80FD\u4FDD\u5B58", body: "\u8BF7\u56DE\u5230 Harness \u68C0\u67E5\u63D2\u4EF6\u8BBE\u7F6E\u3002", sessionId: model.snapshot().sessionId ?? "" });
@@ -646,8 +1401,8 @@ async function mountPet(ctx, options, bridge) {
646
1401
  if (action.type !== "chat" || typeof action.text !== "string" || typeof action.sessionId !== "string") return;
647
1402
  const text = action.text.trim();
648
1403
  if (!text || text.length > 2e3 || !model.select(action.sessionId)) return;
649
- const id = model.snapshot().sessionId;
650
- const agent = ctx.agents.list().find((agent2) => agent2.session.id === id);
1404
+ const id2 = model.snapshot().sessionId;
1405
+ const agent = ctx.agents.list().find((agent2) => agent2.session.id === id2);
651
1406
  if (!agent || agent.session.header.origin === "subagent") {
652
1407
  bridge.notify({ title: "\u4F1A\u8BDD\u5C1A\u672A\u5C31\u7EEA", body: "\u8BF7\u5148\u56DE\u5230 Harness \u6253\u5F00\u8FD9\u4E2A\u4F1A\u8BDD\uFF0C\u7136\u540E\u518D\u53D1\u9001\u6D88\u606F\u3002", sessionId: action.sessionId });
653
1408
  update();
@@ -672,10 +1427,13 @@ async function mountPet(ctx, options, bridge) {
672
1427
  return () => bridge.off("failure", onFailure);
673
1428
  });
674
1429
  }
1430
+ mounted = true;
1431
+ syncNotifications();
675
1432
  update();
676
1433
  if (options.autoStart.get()) {
677
- const status = await controls.command("start");
678
- if (status.error) ctx.logger.warn(status.error);
1434
+ void controls.command("start").then((status) => {
1435
+ if (status.error) ctx.logger.warn(status.error);
1436
+ }, (error) => ctx.logger.warn(String(error).slice(0, 600)));
679
1437
  }
680
1438
  }
681
1439
  export {