dsh-desktop-enhance 0.7.2 → 0.8.0

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.
package/lib/client.js CHANGED
@@ -7,6 +7,695 @@ window.__ModuleLoader__.load({
7
7
  //#region src/client/namespace.ts
8
8
  const NS = "desktop-enhance";
9
9
  //#endregion
10
+ //#region src/shared/diagnostics.ts
11
+ const DIAGNOSTICS_ROUTE = "/api/desktop-enhance/diagnostics";
12
+ const DIAGNOSTIC_MAX_RECORDS = 65536;
13
+ function diagnosticSessionId(value) {
14
+ return typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,159}$/.test(value) ? value : void 0;
15
+ }
16
+ const DIAGNOSTIC_NUMBER_FIELDS = new Set([
17
+ "inputCount",
18
+ "count",
19
+ "prunedCount",
20
+ "charsRemoved",
21
+ "cap",
22
+ "attempt",
23
+ "candidateCount",
24
+ "keepCount",
25
+ "eventCount",
26
+ "sectionCount",
27
+ "ownerCount",
28
+ "disabledCount",
29
+ "beforeCount",
30
+ "afterCount",
31
+ "filteredCount",
32
+ "deviceCount",
33
+ "connectionCount",
34
+ "bytesIn",
35
+ "bytesOut",
36
+ "port",
37
+ "status",
38
+ "upstreamStatus",
39
+ "clientStatus",
40
+ "messageCount",
41
+ "replyChars",
42
+ "items",
43
+ "inputTokens",
44
+ "outputTokens",
45
+ "cacheReadTokens",
46
+ "cacheWriteTokens",
47
+ "maxTokens",
48
+ "index",
49
+ "generation",
50
+ "revision",
51
+ "pruneRevision",
52
+ "atSeq",
53
+ "summarySeq",
54
+ "loadSeq",
55
+ "eventSeq",
56
+ "waitMs",
57
+ "runMs",
58
+ "used",
59
+ "window",
60
+ "nativeThreshold",
61
+ "effectiveThreshold",
62
+ "queryLength",
63
+ "resultCount",
64
+ "suppressedCount"
65
+ ]);
66
+ const DIAGNOSTIC_BOOLEAN_FIELDS = new Set([
67
+ "forced",
68
+ "polling",
69
+ "partial",
70
+ "restoredDefault",
71
+ "complete",
72
+ "enabled",
73
+ "legacyDiscarded",
74
+ "created",
75
+ "handled",
76
+ "matched",
77
+ "cache",
78
+ "hadArray",
79
+ "fellBack",
80
+ "written",
81
+ "applied",
82
+ "headersSent",
83
+ "flushed",
84
+ "mutationCommitted",
85
+ "flushSucceeded",
86
+ "selfTarget",
87
+ "running",
88
+ "nativeLoopback",
89
+ "localNotDispatched"
90
+ ]);
91
+ const DIAGNOSTIC_CODES = new Set(`coalesced flush_failed prune_failed missing_service disabled disposed cancelled missing_agent maintenance_failed invalid_result agent_disposed no_progress rebuild_limit rebuild_required admitted invalid_json tool_call abnormal_finish deadline request_failed superseded compaction_failed no_candidates missing_context missing_job selection_failed unavailable empty_content read_failed not_admitted capacity live_failed cold_failed partial changed denied install_failed
92
+ response_closed untrusted_request device_claimed device_dropped upgrade_rejected peer_closed ineligible head oversized buffered
93
+ model-error missing-capabilities quiet-effort-unavailable capability-lookup-failed inserted insert-rejected insert-exception missing-input-actions user-dismiss enabled created connected connecting disconnected after-cancel stop MODEL_FAILED CATALOG_REGISTRATION_FAILED CAPABILITY_LOOKUP_FAILED RETAIN_FAILED WATCHER_SYNC_FAILED INSERT_FAILED
94
+ hidden loading offer parse-failed invalid-body invalid-session missing-services missing-session missing-route invalid-model-preference invalid-prompt model-aborted unexpected-finish missing-finish model-failed http-error invalid-json network-error client-aborted received invalid-response retain-failed non-append duplicate-turn turn-ended no-longer-watched missing-catalog catalog-ready stale-reply offered submit turnend dismiss use insertFailed max-tokens
95
+ unmounted not-allowed busy already-created navigation-suppressed missing-service invalid-input missing-scope opened requested unhandled operation-failed http-rejected invalid-response loaded read-only undeclared-field readback-unavailable readback-matched readback-mismatch set-threw observation-stopped stale-response response-received out-of-range already-queued host-failed done copied commit load setCap navigation-requested toggle-panel close-popover toggle-context toggle-skills toggle-tools search-tools search-skills back-context select-context search-context fold-context tools models efforts findBar turnPrefix compactionRow stepDuration folderStatus hideSidebarNewSession
96
+ ready started completed failed fallback skipped queued selected global live cold local remote unknown status configure addDevice copyDeviceLink reissue revoke issue GET POST HEAD PUT PATCH DELETE OPTIONS OTHER assemble guard skills catalog
97
+ valid empty parsed filtered valid_empty invalid_response all_filtered missing_session missing_route missing_llm missing_finish stream_error timeout request_error http_error json_error invalid_request duplicate replaced late dismissed evicted stopped feature_off unmount current running warm_expired user_close turn_start user_closed user_cancelled abort aborted input_unavailable insert_failed clipboard_failed clipboard_fallback clipboard_primary confirm_failed unauthorized invalid_status invalid_port invalid_url refresh_failed response_finished accepted applied edit_failed not_applied missing invalid duplicate_cookie invalid_source invalid_path forbidden_path missing_credential invalid_credential untrusted_host untrusted_origin cross_site method body_limit json_required forbidden token_on_nonclaim disallowed_upgrade upstream_error unsafe_redirect upstream_rejected gateway_closed device_revoked device_reissued store_failed not_running listen_failed local_only not_websocket authentication_failed bad_response no_cookie login_failed auth_cache_miss auth_cache_expired auth_cache_invalidated client_closed upstream_closed socket_error end eof shutdown final noop not_modified validated bypass limit_passthrough aborted error static api management claim probe other unsupported cache_hit cache_miss pending stale discarded success valid_json invalid_schema filtered_empty selected_empty not_collected before dispatch prepared committed flushed intent reconcile retry readback rollback preview fork attached navigation_suppressed workspace_attach_failed permission_denied legacy_discarded initialization storage_unavailable storage_failed routes_failed operation_failed resource_deleted no_change invalid_cap below_threshold not_frozen request_rebuild build_limit
98
+ sessionInfo toolsManager skillsManager contextManager skillRecovery suggest suggestModel suggestReasoning suggestPrompt disabledTools sessionToolOverrides disabledSkills sessionSkillOverrides sessionCompactionCaps sessionModel abnormalFork
99
+ manual-compaction abnormal-turn tool skill global-default session-override single group scope reset master-switch immediate-maintenance pre-step turn-stopping whenIdle selected fallback
100
+ ABORT_ERR ETIMEDOUT ECONNREFUSED ECONNRESET EPIPE EADDRINUSE ENOSPC EACCES STORE_FAILED ACCESS_CLOSED INVALID_STATE INVALID_METADATA ENTROPY_FAILED REMOTE_NOT_RUNNING NATIVE_NOT_LOOPBACK INVALID_ADDRESS INVALID_CONFIG CONFIG_ENTRY_UNAVAILABLE CONFIGURE_IN_PROGRESS INVALID_ACTION INVALID_DEVICE UNKNOWN_DEVICE INVALID_BODY BODY_TOO_LARGE UPSTREAM_NOT_LOOPBACK REMOTE_START_FAILED UPSTREAM_AUTH_FAILED OPERATION_FAILED STORAGE_FAILED CATALOG_FAILED REQUEST_FAILED READ_FAILED SAVE_FAILED PRUNE_FAILED SELECTION_FAILED INSTALL_FAILED`.split(/\s+/));
101
+ const DIAGNOSTIC_CODE_FIELDS = new Set([
102
+ "kind",
103
+ "outcome",
104
+ "from",
105
+ "to",
106
+ "reason",
107
+ "errorCode",
108
+ "source",
109
+ "hook",
110
+ "selection",
111
+ "method",
112
+ "action",
113
+ "management",
114
+ "cacheStatus",
115
+ "field",
116
+ "entry",
117
+ "scope",
118
+ "owner",
119
+ "effectState",
120
+ "finish",
121
+ "usage",
122
+ "routeSource",
123
+ "promptSource"
124
+ ]);
125
+ function sanitizeDiagnosticFields(value) {
126
+ if (value === void 0) return {};
127
+ if (value === null || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length > 40) return null;
128
+ const result = {};
129
+ for (const [key, item] of Object.entries(value)) {
130
+ if (item === void 0) continue;
131
+ if (DIAGNOSTIC_NUMBER_FIELDS.has(key) && typeof item === "number" && Number.isFinite(item) && item >= 0 && item <= Number.MAX_SAFE_INTEGER) result[key] = item;
132
+ else if (DIAGNOSTIC_BOOLEAN_FIELDS.has(key) && typeof item === "boolean") result[key] = item;
133
+ else if (DIAGNOSTIC_CODE_FIELDS.has(key) && typeof item === "string" && DIAGNOSTIC_CODES.has(item)) result[key] = item;
134
+ else if (key === "deviceId" && typeof item === "string" && /^[a-f0-9]{32}$/.test(item)) result[key] = item;
135
+ else if (["compactionId", "messageId"].includes(key) && typeof item === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(item)) result[key] = item;
136
+ else if (["childSessionId", "parentSessionId"].includes(key) && typeof item === "string" && /^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,159}$/.test(item)) result[key] = item;
137
+ else if ([
138
+ "provider",
139
+ "model",
140
+ "effort"
141
+ ].includes(key) && typeof item === "string" && /^[a-zA-Z0-9_.:/-]{1,100}$/.test(item) && !item.includes("://") && !item.startsWith("/") && !/token|secret|password|cookie|authorization/i.test(item)) result[key] = item;
142
+ else if (item === null && [
143
+ "usage",
144
+ "provider",
145
+ "model",
146
+ "effort"
147
+ ].includes(key)) result[key] = null;
148
+ else return null;
149
+ }
150
+ return result;
151
+ }
152
+ function diagnosticErrorCode(error, fallback = "OPERATION_FAILED") {
153
+ const code = error !== null && typeof error === "object" ? error.code : void 0;
154
+ const message = error instanceof Error ? error.message : void 0;
155
+ const known = new Set([
156
+ "ABORT_ERR",
157
+ "ETIMEDOUT",
158
+ "ECONNREFUSED",
159
+ "ECONNRESET",
160
+ "EPIPE",
161
+ "EADDRINUSE",
162
+ "ENOSPC",
163
+ "EACCES",
164
+ "STORE_FAILED",
165
+ "ACCESS_CLOSED",
166
+ "INVALID_STATE",
167
+ "INVALID_METADATA",
168
+ "ENTROPY_FAILED",
169
+ "REMOTE_NOT_RUNNING",
170
+ "NATIVE_NOT_LOOPBACK",
171
+ "INVALID_ADDRESS",
172
+ "INVALID_CONFIG",
173
+ "CONFIG_ENTRY_UNAVAILABLE",
174
+ "CONFIGURE_IN_PROGRESS",
175
+ "INVALID_ACTION",
176
+ "INVALID_DEVICE",
177
+ "UNKNOWN_DEVICE",
178
+ "INVALID_BODY",
179
+ "BODY_TOO_LARGE",
180
+ "UPSTREAM_NOT_LOOPBACK",
181
+ "REMOTE_START_FAILED",
182
+ "UPSTREAM_AUTH_FAILED"
183
+ ]);
184
+ return typeof code === "string" && known.has(code) ? code : typeof message === "string" && known.has(message) ? message : fallback;
185
+ }
186
+ //#endregion
187
+ //#region src/client/diagnostics/report.ts
188
+ let receiver;
189
+ let lost = 0;
190
+ function reportClientDiagnostic(input) {
191
+ try {
192
+ const fields = sanitizeDiagnosticFields(input.fields);
193
+ if (fields === null) {
194
+ lost++;
195
+ return;
196
+ }
197
+ if (receiver) receiver({
198
+ ...input,
199
+ fields
200
+ });
201
+ else lost++;
202
+ } catch {
203
+ lost++;
204
+ }
205
+ }
206
+ function startClientDiagnostic(area, event, context = {}, fields) {
207
+ let id;
208
+ try {
209
+ id = context.operationId ?? globalThis.crypto.randomUUID();
210
+ } catch {
211
+ lost++;
212
+ return {
213
+ id: "",
214
+ record() {},
215
+ end() {}
216
+ };
217
+ }
218
+ const scope = {
219
+ ...context,
220
+ sessionId: diagnosticSessionId(context.sessionId)
221
+ };
222
+ const started = globalThis.performance.now();
223
+ let ended = false;
224
+ const record = (phase, data) => reportClientDiagnostic({
225
+ ...scope,
226
+ operationId: id,
227
+ area,
228
+ event,
229
+ phase,
230
+ durationMs: Math.max(0, globalThis.performance.now() - started),
231
+ fields: data
232
+ });
233
+ record("started", fields);
234
+ return {
235
+ id,
236
+ record(phase, data) {
237
+ if (!ended) record(phase, data);
238
+ },
239
+ end(phase, data) {
240
+ if (ended) return;
241
+ ended = true;
242
+ record(phase, data);
243
+ }
244
+ };
245
+ }
246
+ function installClientDiagnostics(fetchImpl = globalThis.fetch) {
247
+ let pending = [];
248
+ let sending = false;
249
+ let live = true;
250
+ const controller = new globalThis.AbortController();
251
+ const send = async () => {
252
+ if (!live || sending || pending.length === 0) return;
253
+ sending = true;
254
+ const batch = pending.splice(0, 64);
255
+ const dropped = lost;
256
+ lost = 0;
257
+ try {
258
+ if (!(await fetchImpl("/api/desktop-enhance/diagnostics-report", {
259
+ method: "POST",
260
+ headers: { "content-type": "application/json" },
261
+ body: JSON.stringify({
262
+ records: batch,
263
+ dropped
264
+ }),
265
+ signal: controller.signal
266
+ })).ok) lost += batch.length + dropped;
267
+ } catch {
268
+ lost += batch.length + dropped;
269
+ } finally {
270
+ sending = false;
271
+ }
272
+ };
273
+ receiver = (input) => {
274
+ if (pending.length >= 256) lost++;
275
+ else pending.push(input);
276
+ };
277
+ const timer = globalThis.setInterval(() => {
278
+ send();
279
+ }, 500);
280
+ timer.unref?.();
281
+ return () => {
282
+ live = false;
283
+ receiver = void 0;
284
+ globalThis.clearInterval(timer);
285
+ controller.abort();
286
+ lost += pending.length;
287
+ pending = [];
288
+ };
289
+ }
290
+ //#endregion
291
+ //#region src/client/react.ts
292
+ const React = require("react");
293
+ const h = React.createElement;
294
+ //#endregion
295
+ //#region \0dsh-desktop-enhance-css:/Users/lijiechengbj/projects/AI-agents/dsh-desktop-enhance/src/client/diagnostics/style.css.mjs
296
+ var style_css_default = "\n.de-diagnostics { display:flex; flex-direction:column; gap:16px; min-width:0; color:var(--dsw-alias-label-primary); font-size:13px; }\n.de-diagnostics h3, .de-diagnostics h4, .de-diagnostics p { margin:0; }\n.de-diagnostics header { display:grid; gap:6px; }\n.de-diagnostics h3 { font-size:15px; }\n.de-diagnostics p, .de-diagnostics time { color:var(--dsw-alias-label-secondary); line-height:1.5; }\n.de-diagnostics [role=\"alert\"] { color:var(--dsw-alias-state-error-primary); }\n.de-diagnostics-filters { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; }\n.de-diagnostics label { display:grid; gap:6px; min-width:0; color:var(--dsw-alias-label-secondary); }\n.de-diagnostics input, .de-diagnostics select, .de-diagnostics button { box-sizing:border-box; min-width:0; min-height:36px; border:1px solid var(--dsw-alias-border-l1); border-radius:8px; background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); font:inherit; padding:6px 10px; }\n.de-diagnostics input, .de-diagnostics select { width:100%; }\n.de-diagnostics button { cursor:pointer; overflow-wrap:anywhere; }\n.de-diagnostics button:hover:not(:disabled) { background:var(--dsw-alias-interactive-bg-hover-solid); }\n.de-diagnostics button:disabled { opacity:.5; cursor:default; }\n.de-diagnostics :is(input,select,button):focus-visible { outline:2px solid var(--dsw-alias-label-primary-bluish); outline-offset:2px; }\n.de-diagnostics-actions { display:flex; flex-wrap:wrap; align-items:center; gap:8px; }\n.de-diagnostics-filters > .de-diagnostics-actions { grid-column:1 / -1; }\n.de-diagnostics-health { padding:12px; border:1px solid var(--dsw-alias-border-l1); border-radius:8px; background:var(--dsw-alias-bg-layer-2); }\n.de-diagnostics-health[data-diagnostics-state=\"failed\"] { border-color:var(--dsw-alias-state-error-primary); }\n.de-diagnostics dl { display:grid; grid-template-columns:repeat(auto-fit,minmax(130px,1fr)); gap:10px; margin:12px 0 0; }\n.de-diagnostics dt { color:var(--dsw-alias-label-secondary); }\n.de-diagnostics dd { margin:3px 0 0; overflow-wrap:anywhere; font-variant-numeric:tabular-nums; }\n.de-diagnostics-records { display:grid; gap:8px; }\n.de-diagnostics article { display:flex; align-items:center; gap:8px; min-width:0; border-bottom:1px solid var(--dsw-alias-border-l1); padding-bottom:8px; }\n.de-diagnostics button.de-diagnostics-summary { display:flex; flex:1; align-items:flex-start; flex-direction:column; gap:5px; text-align:start; border-color:transparent; background:transparent; }\n.de-diagnostics-summary strong { overflow-wrap:anywhere; }\n.de-diagnostics-summary span { color:var(--dsw-alias-label-secondary); }\n.de-diagnostics-detail { min-width:0; border:1px solid var(--dsw-alias-border-l1); border-radius:8px; padding:12px; }\n.de-diagnostics pre { margin:12px 0; white-space:pre-wrap; overflow-wrap:anywhere; max-height:400px; overflow:auto; font-size:12px; }\n@media (max-width:600px) {\n .de-diagnostics-filters { grid-template-columns:1fr; }\n .de-diagnostics :is(input,select,button) { min-height:44px; }\n .de-diagnostics input, .de-diagnostics select { font-size:16px; }\n .de-diagnostics article { align-items:stretch; flex-direction:column; }\n .de-diagnostics dl { grid-template-columns:repeat(2,minmax(0,1fr)); }\n}\n";
297
+ //#endregion
298
+ //#region src/client/diagnostics/panel.ts
299
+ const EMPTY_FILTERS = {
300
+ area: "",
301
+ sessionId: "",
302
+ operationId: "",
303
+ level: "",
304
+ from: "",
305
+ to: ""
306
+ };
307
+ const PAGE_SIZE = 50;
308
+ const DIAGNOSTIC_EXPORT_LIMIT = DIAGNOSTIC_MAX_RECORDS;
309
+ const EXPORT_MAX_BYTES = 268435458;
310
+ const CORE_KEYS = [
311
+ "schemaVersion",
312
+ "id",
313
+ "time",
314
+ "runId",
315
+ "source",
316
+ "area",
317
+ "event",
318
+ "phase",
319
+ "level",
320
+ "operationId",
321
+ "parentOperationId",
322
+ "sessionId",
323
+ "turn",
324
+ "step",
325
+ "durationMs"
326
+ ];
327
+ const HEALTH_COUNTS = [
328
+ "pending",
329
+ "persisted",
330
+ "dropped",
331
+ "rejected",
332
+ "expired",
333
+ "retentionDays",
334
+ "maxBytes",
335
+ "retainedBytes"
336
+ ];
337
+ function object(value) {
338
+ return typeof value === "object" && value !== null && !Array.isArray(value);
339
+ }
340
+ function natural(value) {
341
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
342
+ }
343
+ function identifier(value) {
344
+ return typeof value === "string" && /^[\w:.-]{1,160}$/.test(value);
345
+ }
346
+ function time(value) {
347
+ return natural(value) && value <= 864e13;
348
+ }
349
+ function diagnosticCore(record) {
350
+ const result = {};
351
+ for (const key of CORE_KEYS) if (record[key] !== void 0) result[key] = record[key];
352
+ const fields = sanitizeDiagnosticFields(record.fields);
353
+ if (fields && Object.keys(fields).length) result.fields = fields;
354
+ return result;
355
+ }
356
+ function parseDiagnosticPage(value) {
357
+ if (!object(value) || !Array.isArray(value.records) || value.records.length > 500 || !(value.nextCursor === null || typeof value.nextCursor === "string" && value.nextCursor.length > 0 && value.nextCursor.length <= 4096) || !object(value.health)) throw new Error("diagnostics.invalidResponse");
358
+ const health = value.health;
359
+ if (![
360
+ "starting",
361
+ "ready",
362
+ "failed",
363
+ "closed"
364
+ ].includes(String(health.state)) || !HEALTH_COUNTS.every((key) => natural(health[key])) || !(health.errorCode === null || typeof health.errorCode === "string" && /^[A-Z][A-Z0-9_]{0,79}$/.test(health.errorCode)) || !(health.oldestTime === null || time(health.oldestTime)) || !(health.latestTime === null || time(health.latestTime))) throw new Error("diagnostics.invalidResponse");
365
+ return {
366
+ records: value.records.map((row) => {
367
+ if (!object(row) || row.schemaVersion !== 1 || !identifier(row.id) || !identifier(row.runId) || !identifier(row.operationId) || !time(row.time) || !["host", "client"].includes(String(row.source)) || ![
368
+ "suggest",
369
+ "session",
370
+ "remote"
371
+ ].includes(String(row.area)) || ![
372
+ "info",
373
+ "warn",
374
+ "error"
375
+ ].includes(String(row.level)) || !identifier(row.event) || ![
376
+ "started",
377
+ "queued",
378
+ "completed",
379
+ "skipped",
380
+ "cancelled",
381
+ "failed",
382
+ "fallback"
383
+ ].includes(String(row.phase)) || !["sessionId", "parentOperationId"].every((key) => row[key] === void 0 || identifier(row[key])) || !["turn", "step"].every((key) => row[key] === void 0 || natural(row[key])) || !(row.durationMs === void 0 || typeof row.durationMs === "number" && Number.isFinite(row.durationMs) && row.durationMs >= 0)) throw new Error("diagnostics.invalidResponse");
384
+ return diagnosticCore(row);
385
+ }),
386
+ nextCursor: value.nextCursor,
387
+ health
388
+ };
389
+ }
390
+ function diagnosticQuery(filters) {
391
+ if (filters.area && ![
392
+ "suggest",
393
+ "session",
394
+ "remote"
395
+ ].includes(filters.area)) throw new Error("diagnostics.invalidQuery");
396
+ if (filters.level && ![
397
+ "info",
398
+ "warn",
399
+ "error"
400
+ ].includes(filters.level)) throw new Error("diagnostics.invalidQuery");
401
+ const sessionId = filters.sessionId.trim(), operationId = filters.operationId.trim();
402
+ if (sessionId && !identifier(sessionId) || operationId && !identifier(operationId)) throw new Error("diagnostics.invalidQuery");
403
+ const from = filters.from ? new Date(filters.from).getTime() : void 0;
404
+ const to = filters.to ? new Date(filters.to).getTime() : void 0;
405
+ if (from !== void 0 && !time(from) || to !== void 0 && !time(to) || from !== void 0 && to !== void 0 && from > to) throw new Error("diagnostics.invalidQuery");
406
+ return {
407
+ ...filters.area ? { area: filters.area } : {},
408
+ ...filters.level ? { level: filters.level } : {},
409
+ ...sessionId ? { sessionId } : {},
410
+ ...operationId ? { operationId } : {},
411
+ ...from !== void 0 ? { from } : {},
412
+ ...to !== void 0 ? { to } : {}
413
+ };
414
+ }
415
+ async function requestDiagnosticPage(query, signal) {
416
+ const search = new URLSearchParams();
417
+ for (const key of [
418
+ "area",
419
+ "sessionId",
420
+ "operationId",
421
+ "level",
422
+ "from",
423
+ "to",
424
+ "cursor",
425
+ "limit"
426
+ ]) {
427
+ const value = query[key];
428
+ if (value !== void 0) search.set(key, String(value));
429
+ }
430
+ const response = await globalThis.fetch(`${DIAGNOSTICS_ROUTE}?${search}`, {
431
+ method: "GET",
432
+ credentials: "same-origin",
433
+ cache: "no-store",
434
+ signal
435
+ });
436
+ if (response.status === 401 || response.status === 403) throw new Error("diagnostics.unauthorized");
437
+ if (response.status === 400) throw new Error(query.cursor ? "diagnostics.snapshotExpired" : "diagnostics.invalidQuery");
438
+ if (response.status === 409 || response.status === 410) throw new Error("diagnostics.snapshotExpired");
439
+ if (!response.ok) throw new Error("diagnostics.requestFailed");
440
+ return parseDiagnosticPage(await response.json());
441
+ }
442
+ async function collectDiagnosticExport(query, signal) {
443
+ let cursor;
444
+ let bytes = 2;
445
+ const chunks = [], cursors = new Set(), ids = new Set();
446
+ const encoder = new globalThis.TextEncoder();
447
+ do {
448
+ if (signal.aborted) throw new Error("diagnostics.exportCancelled");
449
+ const page = await requestDiagnosticPage({
450
+ ...query,
451
+ cursor,
452
+ limit: 500
453
+ }, signal);
454
+ if (signal.aborted) throw new Error("diagnostics.exportCancelled");
455
+ if (page.health.state !== "ready") throw new Error("diagnostics.storeUnavailable");
456
+ if (page.nextCursor && page.records.length === 0) throw new Error("diagnostics.exportIncomplete");
457
+ for (const record of page.records) {
458
+ if (ids.has(record.id)) throw new Error("diagnostics.exportIncomplete");
459
+ ids.add(record.id);
460
+ const chunk = JSON.stringify(diagnosticCore(record));
461
+ bytes += encoder.encode(chunk).byteLength + 1;
462
+ if (ids.size > DIAGNOSTIC_EXPORT_LIMIT || bytes > EXPORT_MAX_BYTES) throw new Error("diagnostics.exportLimit");
463
+ chunks.push(chunk);
464
+ }
465
+ cursor = page.nextCursor ?? void 0;
466
+ if (cursor && cursors.has(cursor)) throw new Error("diagnostics.exportIncomplete");
467
+ if (cursor) cursors.add(cursor);
468
+ } while (cursor);
469
+ return `[${chunks.join(",")}]`;
470
+ }
471
+ const ERROR_KEYS = new Set([
472
+ "invalidQuery",
473
+ "invalidResponse",
474
+ "unauthorized",
475
+ "snapshotExpired",
476
+ "requestFailed",
477
+ "exportCancelled",
478
+ "storeUnavailable",
479
+ "exportIncomplete",
480
+ "exportLimit"
481
+ ].map((key) => `diagnostics.${key}`));
482
+ function errorKey(error) {
483
+ return error instanceof Error && ERROR_KEYS.has(error.message) ? error.message : "diagnostics.requestFailed";
484
+ }
485
+ function formattedTime(value) {
486
+ return value === null ? "—" : new Date(value).toLocaleString();
487
+ }
488
+ function DiagnosticsPanel({ t, active }) {
489
+ const [filters, setFilters] = React.useState({ ...EMPTY_FILTERS });
490
+ const [request, setRequest] = React.useState({
491
+ query: {},
492
+ previous: []
493
+ });
494
+ const [page, setPage] = React.useState(null);
495
+ const [selected, setSelected] = React.useState(null);
496
+ const [busy, setBusy] = React.useState(false);
497
+ const [exporting, setExporting] = React.useState(false);
498
+ const [error, setError] = React.useState("");
499
+ const [note, setNote] = React.useState("");
500
+ const exportController = React.useRef(null);
501
+ const pageController = React.useRef(null);
502
+ const download = React.useRef(null);
503
+ const clearDownload = () => {
504
+ if (!download.current) return;
505
+ globalThis.clearTimeout(download.current.timer);
506
+ globalThis.URL.revokeObjectURL(download.current.url);
507
+ download.current = null;
508
+ };
509
+ React.useEffect(() => {
510
+ if (!active) return;
511
+ const abort = new globalThis.AbortController();
512
+ pageController.current = abort;
513
+ setBusy(true);
514
+ setExporting(false);
515
+ setError("");
516
+ setNote("");
517
+ setPage(null);
518
+ setSelected(null);
519
+ (request.cached ? Promise.resolve(request.cached) : requestDiagnosticPage({
520
+ ...request.query,
521
+ cursor: request.cursor,
522
+ limit: PAGE_SIZE
523
+ }, abort.signal)).then((result) => {
524
+ if (!abort.signal.aborted) setPage(result);
525
+ }).catch((caught) => {
526
+ if (!abort.signal.aborted) setError(errorKey(caught));
527
+ }).finally(() => {
528
+ if (!abort.signal.aborted) setBusy(false);
529
+ });
530
+ return () => {
531
+ abort.abort();
532
+ pageController.current = null;
533
+ exportController.current?.abort();
534
+ exportController.current = null;
535
+ clearDownload();
536
+ };
537
+ }, [active, request]);
538
+ const apply = (next = filters) => {
539
+ try {
540
+ const query = diagnosticQuery(next);
541
+ setFilters(next);
542
+ setRequest({
543
+ query,
544
+ previous: []
545
+ });
546
+ } catch (caught) {
547
+ setError(errorKey(caught));
548
+ }
549
+ };
550
+ const related = (operationId) => apply({
551
+ ...EMPTY_FILTERS,
552
+ operationId
553
+ });
554
+ const exportAll = async () => {
555
+ if (!active || busy || !page || page.health.state !== "ready" || exportController.current || !pageController.current || pageController.current.signal.aborted) return;
556
+ const abort = new globalThis.AbortController();
557
+ exportController.current = abort;
558
+ setExporting(true);
559
+ setError("");
560
+ setNote("");
561
+ try {
562
+ const content = await collectDiagnosticExport(request.query, abort.signal);
563
+ if (abort.signal.aborted) return;
564
+ clearDownload();
565
+ const anchor = globalThis.document.createElement("a");
566
+ const url = globalThis.URL.createObjectURL(new globalThis.Blob([content], { type: "application/json;charset=utf-8" }));
567
+ try {
568
+ anchor.href = url;
569
+ anchor.download = "desktop-enhance-diagnostics.json";
570
+ anchor.click();
571
+ download.current = {
572
+ url,
573
+ timer: globalThis.setTimeout(clearDownload, 1e3)
574
+ };
575
+ } catch (caught) {
576
+ globalThis.URL.revokeObjectURL(url);
577
+ throw caught;
578
+ } finally {
579
+ anchor.remove();
580
+ }
581
+ setNote("diagnostics.exported");
582
+ } catch (caught) {
583
+ if (!abort.signal.aborted) setError(errorKey(caught));
584
+ } finally {
585
+ if (!abort.signal.aborted) {
586
+ exportController.current = null;
587
+ setExporting(false);
588
+ }
589
+ }
590
+ };
591
+ if (!active) return null;
592
+ const field = (key, type = "text") => h("label", { key }, t(`diagnostics.${key}`), h("input", {
593
+ type,
594
+ value: filters[key],
595
+ maxLength: type === "text" ? 160 : void 0,
596
+ "data-diagnostics-filter": key,
597
+ onChange: (event) => {
598
+ const value = event.currentTarget.value;
599
+ setFilters((current) => ({
600
+ ...current,
601
+ [key]: value
602
+ }));
603
+ }
604
+ }));
605
+ const select = (key, options) => h("label", { key }, t(`diagnostics.${key}`), h("select", {
606
+ value: filters[key],
607
+ "data-diagnostics-filter": key,
608
+ onChange: (event) => {
609
+ const value = event.currentTarget.value;
610
+ setFilters((current) => ({
611
+ ...current,
612
+ [key]: value
613
+ }));
614
+ }
615
+ }, h("option", { value: "" }, t("diagnostics.all")), ...options.map((value) => h("option", {
616
+ key: value,
617
+ value
618
+ }, t(`diagnostics.${key}.${value}`)))));
619
+ const button = (action, label, onClick, disabled = false) => h("button", {
620
+ type: "button",
621
+ "data-diagnostics-action": action,
622
+ onClick,
623
+ disabled
624
+ }, t(label));
625
+ const health = page?.health;
626
+ return h("section", {
627
+ className: "de-diagnostics",
628
+ "aria-label": t("diagnostics.title"),
629
+ "aria-busy": busy || exporting
630
+ }, h("style", null, style_css_default), h("header", null, h("h3", null, t("diagnostics.title")), h("p", null, t("diagnostics.hint"))), h("form", {
631
+ className: "de-diagnostics-filters",
632
+ onSubmit: (event) => {
633
+ event.preventDefault();
634
+ apply();
635
+ }
636
+ }, select("area", [
637
+ "suggest",
638
+ "session",
639
+ "remote"
640
+ ]), select("level", [
641
+ "info",
642
+ "warn",
643
+ "error"
644
+ ]), field("sessionId"), field("operationId"), field("from", "datetime-local"), field("to", "datetime-local"), h("div", { className: "de-diagnostics-actions" }, h("button", {
645
+ type: "submit",
646
+ "data-diagnostics-action": "apply"
647
+ }, t("diagnostics.apply")), button("reset", "diagnostics.reset", () => apply({ ...EMPTY_FILTERS })), button("refresh", "diagnostics.refresh", () => setRequest({
648
+ query: request.query,
649
+ previous: []
650
+ })))), health ? h("div", {
651
+ className: "de-diagnostics-health",
652
+ "data-diagnostics-state": health.state
653
+ }, h("strong", null, `${t("diagnostics.state")}: ${t(`diagnostics.state.${health.state}`)}`), health.state !== "ready" ? h("p", { role: "status" }, t("diagnostics.storeUnavailable")) : null, h("dl", null, ...[
654
+ ...HEALTH_COUNTS,
655
+ "errorCode",
656
+ "oldestTime",
657
+ "latestTime"
658
+ ].map((key) => h("div", { key }, h("dt", null, t(`diagnostics.health.${key}`)), h("dd", null, key === "oldestTime" ? formattedTime(health.oldestTime) : key === "latestTime" ? formattedTime(health.latestTime) : String(health[key] ?? "—")))))) : null, error ? h("p", { role: "alert" }, t(error)) : null, h("div", { className: "de-diagnostics-actions" }, button("export", exporting ? "diagnostics.exporting" : "diagnostics.export", () => {
659
+ exportAll();
660
+ }, busy || exporting || !health || health.state !== "ready"), h("span", {
661
+ role: "status",
662
+ "aria-live": "polite"
663
+ }, busy ? t("diagnostics.loading") : note ? t(note) : "")), page?.records.length === 0 ? h("p", null, t("diagnostics.empty")) : null, h("div", { className: "de-diagnostics-records" }, ...(page?.records ?? []).map((record) => h("article", {
664
+ key: record.id,
665
+ "data-diagnostics-record": record.id
666
+ }, h("button", {
667
+ type: "button",
668
+ className: "de-diagnostics-summary",
669
+ "aria-expanded": selected?.id === record.id,
670
+ onClick: () => setSelected(selected?.id === record.id ? null : record)
671
+ }, h("time", { dateTime: new Date(record.time).toISOString() }, formattedTime(record.time)), h("strong", null, record.event), h("span", null, `${record.area} · ${record.level} · ${record.phase}`)), button(`related-${record.id}`, "diagnostics.related", () => related(record.operationId))))), selected ? h("section", {
672
+ className: "de-diagnostics-detail",
673
+ "aria-label": t("diagnostics.detail")
674
+ }, h("h4", null, t("diagnostics.detail")), h("pre", null, JSON.stringify(diagnosticCore(selected), null, 2)), selected.parentOperationId ? button("parent", "diagnostics.parentOperation", () => {
675
+ if (selected.parentOperationId) related(selected.parentOperationId);
676
+ }) : null) : null, h("nav", {
677
+ className: "de-diagnostics-actions",
678
+ "aria-label": t("diagnostics.pagination")
679
+ }, button("previous", "diagnostics.previous", () => {
680
+ const previous = request.previous.at(-1);
681
+ if (previous) setRequest({
682
+ query: request.query,
683
+ cursor: previous.cursor,
684
+ cached: previous.page,
685
+ previous: request.previous.slice(0, -1)
686
+ });
687
+ }, busy || request.previous.length === 0), h("span", null, `${t("diagnostics.page")} ${request.previous.length + 1}`), button("next", "diagnostics.next", () => {
688
+ if (page?.nextCursor) setRequest({
689
+ query: request.query,
690
+ cursor: page.nextCursor,
691
+ previous: [...request.previous, {
692
+ cursor: request.cursor,
693
+ page
694
+ }]
695
+ });
696
+ }, busy || !page?.nextCursor)));
697
+ }
698
+ //#endregion
10
699
  //#region src/client/mobile/strings.ts
11
700
  const mobileZh = {
12
701
  "mobile.settings.back": "‹ 设置",
@@ -115,6 +804,62 @@ window.__ModuleLoader__.load({
115
804
  //#endregion
116
805
  //#region src/client/strings.ts
117
806
  const zh = {
807
+ "settings.tab.diagnostics": "诊断",
808
+ "diagnostics.title": "诊断日志",
809
+ "diagnostics.hint": "仅按需加载,不自动轮询。详情与导出只含脱敏核心元数据和白名单结构字段,不含正文、任意扩展字段或 HTML。时间筛选使用本机时区。",
810
+ "diagnostics.area": "功能区域",
811
+ "diagnostics.area.suggest": "建议",
812
+ "diagnostics.area.session": "会话",
813
+ "diagnostics.area.remote": "远程接入",
814
+ "diagnostics.level": "级别",
815
+ "diagnostics.level.info": "信息",
816
+ "diagnostics.level.warn": "警告",
817
+ "diagnostics.level.error": "错误",
818
+ "diagnostics.sessionId": "会话 ID",
819
+ "diagnostics.operationId": "操作 ID",
820
+ "diagnostics.from": "开始时间",
821
+ "diagnostics.to": "结束时间",
822
+ "diagnostics.all": "全部",
823
+ "diagnostics.apply": "应用筛选",
824
+ "diagnostics.reset": "重置筛选",
825
+ "diagnostics.refresh": "刷新",
826
+ "diagnostics.state": "存储状态",
827
+ "diagnostics.state.starting": "正在启动",
828
+ "diagnostics.state.ready": "可用",
829
+ "diagnostics.state.failed": "失败",
830
+ "diagnostics.state.closed": "已关闭",
831
+ "diagnostics.health.pending": "待写入",
832
+ "diagnostics.health.persisted": "已持久化",
833
+ "diagnostics.health.dropped": "已丢弃",
834
+ "diagnostics.health.rejected": "已拒绝",
835
+ "diagnostics.health.expired": "已过期",
836
+ "diagnostics.health.errorCode": "错误码",
837
+ "diagnostics.health.retentionDays": "保留天数",
838
+ "diagnostics.health.maxBytes": "容量上限(字节)",
839
+ "diagnostics.health.retainedBytes": "占用容量(字节)",
840
+ "diagnostics.health.oldestTime": "最早记录时间",
841
+ "diagnostics.health.latestTime": "最新记录时间",
842
+ "diagnostics.export": "导出全部筛选结果",
843
+ "diagnostics.exporting": "正在导出…",
844
+ "diagnostics.exported": "完整筛选快照已导出。",
845
+ "diagnostics.loading": "正在加载…",
846
+ "diagnostics.empty": "当前筛选范围内没有记录。",
847
+ "diagnostics.detail": "记录详情",
848
+ "diagnostics.related": "关联操作",
849
+ "diagnostics.parentOperation": "查看上级关联操作",
850
+ "diagnostics.pagination": "诊断日志分页",
851
+ "diagnostics.previous": "上一页",
852
+ "diagnostics.next": "下一页",
853
+ "diagnostics.page": "页码",
854
+ "diagnostics.invalidQuery": "筛选条件无效,请检查 ID、时间范围和筛选值。",
855
+ "diagnostics.invalidResponse": "诊断响应格式无效,未展示或导出不可信内容。",
856
+ "diagnostics.unauthorized": "未获授权或登录已失效,请重新连接后重试。",
857
+ "diagnostics.snapshotExpired": "分页快照已失效或部分记录已过期;请刷新后重试,未导出部分结果。",
858
+ "diagnostics.requestFailed": "诊断请求失败;如正在导出,未下载任何部分结果。",
859
+ "diagnostics.exportCancelled": "导出已取消,未下载部分结果。",
860
+ "diagnostics.storeUnavailable": "诊断存储尚不可用;现有记录不代表完整结果,导出不可用。",
861
+ "diagnostics.exportIncomplete": "分页结果不完整或游标异常,已停止导出,未下载部分结果。",
862
+ "diagnostics.exportLimit": "筛选结果超出安全导出上限,请缩小时间范围后重试;未下载部分结果。",
118
863
  "sessionModel.oneShotTitle": "一次性子智能体记录",
119
864
  "sessionModel.readOnlyTitle": "此子智能体暂时只读",
120
865
  "sessionModel.oneShotBody": "一次性任务不支持后续消息,可在这里查看完整执行记录。",
@@ -277,6 +1022,62 @@ window.__ModuleLoader__.load({
277
1022
  "settings.writeFailed": "设置没写进去,开关已退回原状态;请重试。"
278
1023
  };
279
1024
  const en = {
1025
+ "settings.tab.diagnostics": "Diagnostics",
1026
+ "diagnostics.title": "Diagnostic logs",
1027
+ "diagnostics.hint": "Loaded on demand, with no polling. Details and exports contain only redacted core metadata and allowlisted structured fields, never message bodies, arbitrary fields or HTML. Time filters use your local time zone.",
1028
+ "diagnostics.area": "Area",
1029
+ "diagnostics.area.suggest": "Suggestions",
1030
+ "diagnostics.area.session": "Session",
1031
+ "diagnostics.area.remote": "Remote access",
1032
+ "diagnostics.level": "Level",
1033
+ "diagnostics.level.info": "Info",
1034
+ "diagnostics.level.warn": "Warning",
1035
+ "diagnostics.level.error": "Error",
1036
+ "diagnostics.sessionId": "Session ID",
1037
+ "diagnostics.operationId": "Operation ID",
1038
+ "diagnostics.from": "From",
1039
+ "diagnostics.to": "To",
1040
+ "diagnostics.all": "All",
1041
+ "diagnostics.apply": "Apply filters",
1042
+ "diagnostics.reset": "Reset filters",
1043
+ "diagnostics.refresh": "Refresh",
1044
+ "diagnostics.state": "Storage state",
1045
+ "diagnostics.state.starting": "Starting",
1046
+ "diagnostics.state.ready": "Ready",
1047
+ "diagnostics.state.failed": "Failed",
1048
+ "diagnostics.state.closed": "Closed",
1049
+ "diagnostics.health.pending": "Pending",
1050
+ "diagnostics.health.persisted": "Persisted",
1051
+ "diagnostics.health.dropped": "Dropped",
1052
+ "diagnostics.health.rejected": "Rejected",
1053
+ "diagnostics.health.expired": "Expired",
1054
+ "diagnostics.health.errorCode": "Error code",
1055
+ "diagnostics.health.retentionDays": "Retention days",
1056
+ "diagnostics.health.maxBytes": "Capacity limit (bytes)",
1057
+ "diagnostics.health.retainedBytes": "Retained bytes",
1058
+ "diagnostics.health.oldestTime": "Oldest record",
1059
+ "diagnostics.health.latestTime": "Latest record",
1060
+ "diagnostics.export": "Export all filtered results",
1061
+ "diagnostics.exporting": "Exporting…",
1062
+ "diagnostics.exported": "The complete filtered snapshot has been exported.",
1063
+ "diagnostics.loading": "Loading…",
1064
+ "diagnostics.empty": "No records match these filters.",
1065
+ "diagnostics.detail": "Record details",
1066
+ "diagnostics.related": "Related operation",
1067
+ "diagnostics.parentOperation": "View parent operation",
1068
+ "diagnostics.pagination": "Diagnostic log pagination",
1069
+ "diagnostics.previous": "Previous",
1070
+ "diagnostics.next": "Next",
1071
+ "diagnostics.page": "Page",
1072
+ "diagnostics.invalidQuery": "Invalid filters. Check the IDs, time range and selected values.",
1073
+ "diagnostics.invalidResponse": "Invalid diagnostic response. Untrusted content was not displayed or exported.",
1074
+ "diagnostics.unauthorized": "Not authorized or your login expired. Reconnect and try again.",
1075
+ "diagnostics.snapshotExpired": "The snapshot expired or some records are no longer retained. Refresh and retry; no partial export was downloaded.",
1076
+ "diagnostics.requestFailed": "The diagnostic request failed. No partial export was downloaded.",
1077
+ "diagnostics.exportCancelled": "Export cancelled. No partial export was downloaded.",
1078
+ "diagnostics.storeUnavailable": "Diagnostic storage is not ready. Existing records may be incomplete; export is unavailable.",
1079
+ "diagnostics.exportIncomplete": "Incomplete results or an invalid cursor. Export stopped without downloading partial results.",
1080
+ "diagnostics.exportLimit": "Results exceed the safe export limit. Narrow the time range and retry; no partial export was downloaded.",
280
1081
  "sessionModel.oneShotTitle": "One-shot subagent record",
281
1082
  "sessionModel.readOnlyTitle": "This subagent is read-only for now",
282
1083
  "sessionModel.oneShotBody": "One-shot tasks do not accept follow-ups; review the full execution record here.",
@@ -580,10 +1381,6 @@ window.__ModuleLoader__.load({
580
1381
  });
581
1382
  }
582
1383
  //#endregion
583
- //#region src/client/react.ts
584
- const React = require("react");
585
- const h = React.createElement;
586
- //#endregion
587
1384
  //#region src/client/find/bar.ts
588
1385
  const NO_MATCHES = [];
589
1386
  function FindBar({ store, t }) {
@@ -824,6 +1621,7 @@ window.__ModuleLoader__.load({
824
1621
  //#region src/shared/route.ts
825
1622
  const SUGGEST_ROUTE = "/api/desktop-enhance/suggest";
826
1623
  const SUGGEST_MODELS_ROUTE = "/api/desktop-enhance/suggest-models";
1624
+ const SUGGEST_EFFORTS_ROUTE = "/api/desktop-enhance/suggest-efforts";
827
1625
  const SESSION_INFO_ROUTE = "/api/desktop-enhance/session-info";
828
1626
  const TOOLS_ROUTE = "/api/desktop-enhance/tools";
829
1627
  const SKILLS_ROUTE = "/api/desktop-enhance/skills";
@@ -884,6 +1682,7 @@ window.__ModuleLoader__.load({
884
1682
  const catalogCache = createCatalogCache();
885
1683
  const CACHE_MS = 3e4;
886
1684
  const SUGGEST_MODELS_URL = SUGGEST_MODELS_ROUTE;
1685
+ const SUGGEST_EFFORTS_URL = SUGGEST_EFFORTS_ROUTE;
887
1686
  const TOOLS_URL = TOOLS_ROUTE;
888
1687
  const SKILLS_URL = SKILLS_ROUTE;
889
1688
  function createCatalogCache(now = () => Date.now()) {
@@ -899,17 +1698,27 @@ window.__ModuleLoader__.load({
899
1698
  if (hit !== void 0 && now() - hit.at < 3e4) return hit.value;
900
1699
  const running = pending.get(url);
901
1700
  if (running !== void 0) return running;
1701
+ const route = url.split("?")[0];
1702
+ const diagnostic = startClientDiagnostic("session", "session.client.catalog-load", {}, { kind: route === TOOLS_URL ? "tools" : route === SKILLS_URL ? "skills" : route === SUGGEST_MODELS_URL ? "models" : route === SUGGEST_EFFORTS_URL ? "efforts" : "unknown" });
902
1703
  const task = (async () => {
903
1704
  try {
904
1705
  const response = await fetchImpl(url, { method: "GET" });
905
- if (!response.ok) return void 0;
1706
+ if (!response.ok) {
1707
+ diagnostic.end("failed", { reason: "http-rejected" });
1708
+ return;
1709
+ }
906
1710
  const value = await response.json();
907
1711
  hits.set(url, {
908
1712
  at: now(),
909
1713
  value
910
1714
  });
1715
+ diagnostic.end("completed", { reason: "loaded" });
911
1716
  return value;
912
- } catch {
1717
+ } catch (error) {
1718
+ diagnostic.end("failed", {
1719
+ reason: "operation-failed",
1720
+ errorCode: diagnosticErrorCode(error)
1721
+ });
913
1722
  return;
914
1723
  } finally {
915
1724
  pending.delete(url);
@@ -953,17 +1762,30 @@ window.__ModuleLoader__.load({
953
1762
  return items;
954
1763
  }
955
1764
  function parseSuggestions(reply, known) {
1765
+ return parseSuggestionResult(reply, known).items;
1766
+ }
1767
+ function parseSuggestionResult(reply, known) {
956
1768
  const start = reply.indexOf("[");
957
1769
  const end = reply.lastIndexOf("]");
958
- if (start === -1 || end <= start) return [];
1770
+ const failed = {
1771
+ items: [],
1772
+ reason: "parse-failed",
1773
+ inputCount: 0
1774
+ };
1775
+ if (start === -1 || end <= start) return failed;
959
1776
  let parsed;
960
1777
  try {
961
1778
  parsed = JSON.parse(reply.slice(start, end + 1));
962
1779
  } catch {
963
- return [];
1780
+ return failed;
964
1781
  }
965
- if (!Array.isArray(parsed)) return [];
966
- return normalizeEntries(parsed, known);
1782
+ if (!Array.isArray(parsed)) return failed;
1783
+ const items = normalizeEntries(parsed, known);
1784
+ return {
1785
+ items,
1786
+ reason: parsed.length === 0 ? "empty" : items.length === 0 ? "filtered" : "parsed",
1787
+ inputCount: parsed.length
1788
+ };
967
1789
  }
968
1790
  const PROMPT_PLACEHOLDERS = ["MAX_SUGGESTIONS", "LABEL_MAX"];
969
1791
  const PLACEHOLDER_VALUES = {
@@ -2198,11 +3020,14 @@ window.__ModuleLoader__.load({
2198
3020
  const timers = React.useRef(new Set());
2199
3021
  const gen = React.useRef(0);
2200
3022
  const owner = React.useRef(new Map());
3023
+ const writeDiagnostics = React.useRef(new Map());
2201
3024
  React.useEffect(() => {
2202
3025
  const unsubscribe = store.subscribe(() => forceRender((n) => n + 1));
2203
3026
  return () => {
2204
3027
  unsubscribe();
2205
3028
  owner.current.clear();
3029
+ for (const diagnostic of writeDiagnostics.current.values()) diagnostic.end("cancelled", { reason: "unmounted" });
3030
+ writeDiagnostics.current.clear();
2206
3031
  for (const id of timers.current) globalThis.clearTimeout(id);
2207
3032
  timers.current.clear();
2208
3033
  };
@@ -2214,8 +3039,17 @@ window.__ModuleLoader__.load({
2214
3039
  const readOnly = form === null || form === void 0 || !ready || snapshot.writable !== true || typeof form.set !== "function";
2215
3040
  const isUndeclared = (field) => ready && !readOnly && (value === null || value === void 0 || typeof value !== "object" || !(field in value));
2216
3041
  const write = (field, wanted) => {
2217
- if (readOnly) return;
2218
- if (isUndeclared(field)) return;
3042
+ const diagnostic = startClientDiagnostic("session", "session.client.settings-write", {}, { field });
3043
+ if (readOnly) {
3044
+ diagnostic.end("skipped", { reason: "read-only" });
3045
+ return;
3046
+ }
3047
+ if (isUndeclared(field)) {
3048
+ diagnostic.end("skipped", { reason: "undeclared-field" });
3049
+ return;
3050
+ }
3051
+ writeDiagnostics.current.get(field)?.end("cancelled", { reason: "superseded" });
3052
+ writeDiagnostics.current.set(field, diagnostic);
2219
3053
  const mine = gen.current + 1;
2220
3054
  gen.current = mine;
2221
3055
  owner.current.set(field, mine);
@@ -2227,6 +3061,10 @@ window.__ModuleLoader__.load({
2227
3061
  if (live === null || live === void 0) return void 0;
2228
3062
  return readField(live.value, field);
2229
3063
  } catch (error) {
3064
+ diagnostic.record("fallback", {
3065
+ reason: "readback-unavailable",
3066
+ errorCode: diagnosticErrorCode(error)
3067
+ });
2230
3068
  return;
2231
3069
  }
2232
3070
  };
@@ -2240,6 +3078,13 @@ window.__ModuleLoader__.load({
2240
3078
  }
2241
3079
  };
2242
3080
  const finish = (matched) => {
3081
+ diagnostic.end(matched ? "completed" : "failed", {
3082
+ reason: matched ? "readback-matched" : "readback-mismatch",
3083
+ field,
3084
+ generation: mine,
3085
+ matched
3086
+ });
3087
+ if (writeDiagnostics.current.get(field) === diagnostic) writeDiagnostics.current.delete(field);
2243
3088
  cancel();
2244
3089
  setBusy((current) => withoutField(current, field));
2245
3090
  setFailed((current) => matched ? withoutField(current, field) : withField(current, field));
@@ -2252,10 +3097,20 @@ window.__ModuleLoader__.load({
2252
3097
  if (attempt <= attempted) return;
2253
3098
  attempted = attempt;
2254
3099
  const matched = hostValue() === wanted;
3100
+ diagnostic.record("queued", {
3101
+ reason: "reconcile",
3102
+ attempt,
3103
+ generation: mine,
3104
+ matched
3105
+ });
2255
3106
  if (matched || attempt > 0) {
2256
3107
  finish(matched);
2257
3108
  return;
2258
3109
  }
3110
+ diagnostic.record("fallback", {
3111
+ reason: "retry",
3112
+ attempt: 1
3113
+ });
2259
3114
  send(1);
2260
3115
  };
2261
3116
  const arm = (attempt) => {
@@ -2269,10 +3124,19 @@ window.__ModuleLoader__.load({
2269
3124
  timers.current.add(id);
2270
3125
  };
2271
3126
  const send = (attempt) => {
3127
+ diagnostic.record("queued", {
3128
+ reason: "requested",
3129
+ attempt
3130
+ });
2272
3131
  let written;
2273
3132
  try {
2274
3133
  written = form.set?.(field, wanted);
2275
3134
  } catch (error) {
3135
+ diagnostic.record("fallback", {
3136
+ reason: "set-threw",
3137
+ attempt,
3138
+ errorCode: diagnosticErrorCode(error)
3139
+ });
2276
3140
  judge(attempt);
2277
3141
  return;
2278
3142
  }
@@ -2342,7 +3206,11 @@ window.__ModuleLoader__.load({
2342
3206
  className: "de-subpanel"
2343
3207
  }, subpanel) : null);
2344
3208
  };
2345
- const tabs = [...SETTINGS_GROUPS.map((group) => group.id), "remote"];
3209
+ const tabs = [
3210
+ ...SETTINGS_GROUPS.map((group) => group.id),
3211
+ "remote",
3212
+ "diagnostics"
3213
+ ];
2346
3214
  const panel = (id, content) => h("div", {
2347
3215
  key: id,
2348
3216
  id: `desktop-enhance-panel-${id}`,
@@ -2397,7 +3265,10 @@ window.__ModuleLoader__.load({
2397
3265
  target?.focus();
2398
3266
  target?.click();
2399
3267
  }
2400
- }, t("settings.tab." + id)))), ...sectionCards, panel("remote", remoteContent), note);
3268
+ }, t("settings.tab." + id)))), ...sectionCards, panel("remote", remoteContent), panel("diagnostics", h(DiagnosticsPanel, {
3269
+ t,
3270
+ active: activeTab === "diagnostics"
3271
+ })), note);
2401
3272
  }
2402
3273
  function SuggestSettings({ t, value, busy, readOnly, write, drifted }) {
2403
3274
  const model = textOf(value, "suggestModel");
@@ -2507,7 +3378,7 @@ window.__ModuleLoader__.load({
2507
3378
  React.useEffect(() => {
2508
3379
  if (model === "") return void 0;
2509
3380
  let live = true;
2510
- catalogCache.get("/api/desktop-enhance/suggest-efforts?model=" + globalThis.encodeURIComponent(model), globalThis.fetch).then((body) => {
3381
+ catalogCache.get(SUGGEST_EFFORTS_URL + "?model=" + globalThis.encodeURIComponent(model), globalThis.fetch).then((body) => {
2511
3382
  if (!live) return;
2512
3383
  setState({
2513
3384
  model,
@@ -3654,11 +4525,37 @@ window.__ModuleLoader__.load({
3654
4525
  return {
3655
4526
  get: () => viewOf(session),
3656
4527
  dispatch(sessionId, input) {
3657
- put(sessionId, suggestView(viewOf(sessionId), input));
4528
+ const before = viewOf(sessionId);
4529
+ const next = suggestView(before, input);
4530
+ if (next !== before) reportClientDiagnostic({
4531
+ area: "suggest",
4532
+ event: "suggest.client.view",
4533
+ phase: "completed",
4534
+ sessionId,
4535
+ fields: {
4536
+ from: before.kind,
4537
+ to: next.kind,
4538
+ reason: input.kind === "reply" ? "received" : input.kind
4539
+ }
4540
+ });
4541
+ put(sessionId, next);
3658
4542
  },
3659
4543
  offer(sessionId, turn, raw) {
3660
4544
  const items = normalizeEntries(Array.isArray(raw) ? raw : [], null);
3661
- put(sessionId, suggestView(viewOf(sessionId), {
4545
+ const before = viewOf(sessionId);
4546
+ const stale = before.kind !== "loading" || before.turn !== turn;
4547
+ reportClientDiagnostic({
4548
+ area: "suggest",
4549
+ event: "suggest.client.offer",
4550
+ phase: stale ? "skipped" : "completed",
4551
+ sessionId,
4552
+ turn,
4553
+ fields: {
4554
+ reason: stale ? "stale-reply" : !Array.isArray(raw) ? "invalid-response" : raw.length === 0 ? "empty" : items.length === 0 ? "filtered" : "offered",
4555
+ count: items.length
4556
+ }
4557
+ });
4558
+ put(sessionId, suggestView(before, {
3662
4559
  kind: "reply",
3663
4560
  turn,
3664
4561
  items
@@ -3763,48 +4660,135 @@ window.__ModuleLoader__.load({
3763
4660
  }
3764
4661
  return turn;
3765
4662
  }
3766
- async function requestSuggestions(sessionId, fetchImpl, signal, preference = NO_PREFERENCE) {
4663
+ async function requestSuggestions(sessionId, fetchImpl, signal, preference = NO_PREFERENCE, context = {}) {
4664
+ const operation = startClientDiagnostic("suggest", "suggest.client.request", {
4665
+ ...context,
4666
+ sessionId
4667
+ });
4668
+ const cancelled = () => operation.end("cancelled", { reason: "client-aborted" });
4669
+ if (signal?.aborted) cancelled();
4670
+ signal?.addEventListener("abort", cancelled, { once: true });
4671
+ let readingJson = false;
3767
4672
  try {
3768
4673
  const response = await fetchImpl(SUGGEST_URL, {
3769
4674
  method: "POST",
3770
4675
  headers: { "content-type": "application/json" },
3771
4676
  body: JSON.stringify({
3772
4677
  sessionId,
4678
+ operationId: operation.id,
4679
+ ...context.turn === void 0 ? {} : { turn: context.turn },
3773
4680
  model: preference.model,
3774
4681
  reasoning: preference.reasoning,
3775
4682
  prompt: preference.prompt
3776
4683
  }),
3777
4684
  ...signal === void 0 ? {} : { signal }
3778
4685
  });
3779
- if (!response.ok) return [];
4686
+ if (!response.ok) {
4687
+ operation.end("failed", {
4688
+ reason: "http-error",
4689
+ status: response.status
4690
+ });
4691
+ return [];
4692
+ }
4693
+ readingJson = true;
3780
4694
  const body = await response.json();
3781
- if (body.diag !== void 0 && body.diag !== null) globalThis.console?.info?.("[desktop-enhance] suggest", body.diag);
3782
- return Array.isArray(body.items) ? body.items : [];
3783
- } catch {
4695
+ const items = body !== null && Array.isArray(body.items) ? body.items : [];
4696
+ if (signal?.aborted) reportClientDiagnostic({
4697
+ ...context,
4698
+ operationId: operation.id,
4699
+ area: "suggest",
4700
+ event: "suggest.client.response",
4701
+ phase: "completed",
4702
+ sessionId,
4703
+ fields: {
4704
+ reason: "after-cancel",
4705
+ count: items.length
4706
+ }
4707
+ });
4708
+ operation.end(body !== null && Array.isArray(body.items) ? "completed" : "failed", {
4709
+ reason: body !== null && Array.isArray(body.items) ? items.length === 0 ? "empty" : "received" : "invalid-response",
4710
+ count: items.length
4711
+ });
4712
+ return items;
4713
+ } catch (error) {
4714
+ if (signal?.aborted) cancelled();
4715
+ else operation.end("failed", {
4716
+ reason: readingJson ? "invalid-json" : "network-error",
4717
+ errorCode: diagnosticErrorCode(error, "REQUEST_FAILED")
4718
+ });
3784
4719
  return [];
4720
+ } finally {
4721
+ signal?.removeEventListener("abort", cancelled);
3785
4722
  }
3786
4723
  }
3787
4724
  function watchSession(getSessions, sessionId, store, fetchImpl = globalThis.fetch, getPreference = () => NO_PREFERENCE, onActivity) {
3788
4725
  const sessions = getSessions();
3789
- if (sessions === null || sessions === void 0 || typeof sessions.retain !== "function") return null;
4726
+ if (sessions === null || sessions === void 0 || typeof sessions.retain !== "function") {
4727
+ reportClientDiagnostic({
4728
+ area: "suggest",
4729
+ event: "suggest.client.watch",
4730
+ phase: "skipped",
4731
+ sessionId,
4732
+ fields: { reason: "missing-services" }
4733
+ });
4734
+ return null;
4735
+ }
3790
4736
  let reference;
3791
4737
  try {
3792
4738
  reference = sessions.retain(sessionId, { source: NS });
3793
- } catch {
4739
+ } catch (error) {
4740
+ reportClientDiagnostic({
4741
+ area: "suggest",
4742
+ event: "suggest.client.watch",
4743
+ phase: "skipped",
4744
+ sessionId,
4745
+ fields: {
4746
+ reason: "retain-failed",
4747
+ errorCode: diagnosticErrorCode(error, "RETAIN_FAILED")
4748
+ }
4749
+ });
3794
4750
  return null;
3795
4751
  }
4752
+ const watchOperation = startClientDiagnostic("suggest", "suggest.client.watch", { sessionId });
3796
4753
  const source = reference.binding.eventSource;
3797
4754
  let inFlight = null;
3798
4755
  const asked = new Set();
3799
4756
  const unsubscribe = source.subscribe(() => {
3800
4757
  onActivity?.();
3801
4758
  const snapshot = source.getSnapshot();
3802
- if (snapshot.change?.kind !== "append") return;
4759
+ if (snapshot.change?.kind !== "append") {
4760
+ if (turnEnded(snapshot.change?.entries ?? []) !== null) reportClientDiagnostic({
4761
+ area: "suggest",
4762
+ event: "suggest.client.trigger",
4763
+ phase: "skipped",
4764
+ sessionId,
4765
+ fields: { reason: "non-append" }
4766
+ });
4767
+ return;
4768
+ }
3803
4769
  const entries = snapshot.change.entries ?? [];
3804
4770
  if (turnStarted(entries) !== null) store.dispatch(sessionId, { kind: "submit" });
3805
4771
  const turn = turnEnded(entries);
3806
4772
  if (turn === null) return;
3807
- if (asked.has(turn)) return;
4773
+ if (asked.has(turn)) {
4774
+ reportClientDiagnostic({
4775
+ area: "suggest",
4776
+ event: "suggest.client.trigger",
4777
+ phase: "skipped",
4778
+ sessionId,
4779
+ turn,
4780
+ fields: { reason: "duplicate-turn" }
4781
+ });
4782
+ return;
4783
+ }
4784
+ reportClientDiagnostic({
4785
+ area: "suggest",
4786
+ event: "suggest.client.trigger",
4787
+ phase: "completed",
4788
+ sessionId,
4789
+ turn,
4790
+ fields: { reason: "turn-ended" }
4791
+ });
3808
4792
  asked.add(turn);
3809
4793
  store.dispatch(sessionId, {
3810
4794
  kind: "turnend",
@@ -3814,11 +4798,15 @@ window.__ModuleLoader__.load({
3814
4798
  const controller = new globalThis.AbortController();
3815
4799
  inFlight = controller;
3816
4800
  (async () => {
3817
- const items = await requestSuggestions(sessionId, fetchImpl, controller.signal, getPreference());
4801
+ const items = await requestSuggestions(sessionId, fetchImpl, controller.signal, getPreference(), {
4802
+ turn,
4803
+ parentOperationId: watchOperation.id
4804
+ });
3818
4805
  store.offer(sessionId, turn, items);
3819
4806
  })();
3820
4807
  });
3821
- return () => {
4808
+ return (reason = "stopped") => {
4809
+ watchOperation.end("completed", { reason });
3822
4810
  inFlight?.abort();
3823
4811
  unsubscribe();
3824
4812
  reference.release();
@@ -3832,6 +4820,9 @@ window.__ModuleLoader__.load({
3832
4820
  function createSuggestWatcher(getSessions, store, options = {}) {
3833
4821
  const { fetchImpl = globalThis.fetch, getPreference = () => NO_PREFERENCE, isOn = () => true, now = () => Date.now(), schedule = defaultSchedule } = options;
3834
4822
  const refs = new Map();
4823
+ const operation = startClientDiagnostic("suggest", "suggest.client.watcher");
4824
+ let enabled;
4825
+ let catalogAvailable;
3835
4826
  let current;
3836
4827
  const warmth = createWarmth();
3837
4828
  let stopped = false;
@@ -3848,7 +4839,14 @@ window.__ModuleLoader__.load({
3848
4839
  syncing = true;
3849
4840
  try {
3850
4841
  align();
3851
- } catch {} finally {
4842
+ } catch (error) {
4843
+ reportClientDiagnostic({
4844
+ area: "suggest",
4845
+ event: "suggest.client.watcher.sync",
4846
+ phase: "failed",
4847
+ fields: { errorCode: diagnosticErrorCode(error, "WATCHER_SYNC_FAILED") }
4848
+ });
4849
+ } finally {
3852
4850
  syncing = false;
3853
4851
  }
3854
4852
  if (redoSync) {
@@ -3857,8 +4855,22 @@ window.__ModuleLoader__.load({
3857
4855
  }
3858
4856
  };
3859
4857
  const align = () => {
3860
- if (!isOn()) {
3861
- for (const stop of refs.values()) stop();
4858
+ const on = isOn();
4859
+ if (on !== enabled) {
4860
+ enabled = on;
4861
+ reportClientDiagnostic({
4862
+ area: "suggest",
4863
+ event: "suggest.client.watcher.state",
4864
+ phase: "completed",
4865
+ fields: {
4866
+ reason: on ? "enabled" : "disabled",
4867
+ enabled: on,
4868
+ count: refs.size
4869
+ }
4870
+ });
4871
+ }
4872
+ if (!on) {
4873
+ for (const stop of refs.values()) stop("disabled");
3862
4874
  refs.clear();
3863
4875
  warmth.clear();
3864
4876
  store.forgetCurrent();
@@ -3866,6 +4878,15 @@ window.__ModuleLoader__.load({
3866
4878
  }
3867
4879
  const catalog = getSessions()?.list;
3868
4880
  const snapshot = catalog === null || catalog === void 0 ? null : catalog.getSnapshot();
4881
+ if (catalogAvailable !== (snapshot !== null)) {
4882
+ catalogAvailable = snapshot !== null;
4883
+ reportClientDiagnostic({
4884
+ area: "suggest",
4885
+ event: "suggest.client.watcher.catalog",
4886
+ phase: snapshot === null ? "fallback" : "completed",
4887
+ fields: { reason: snapshot === null ? "missing-catalog" : "catalog-ready" }
4888
+ });
4889
+ }
3869
4890
  if (catalogStop === void 0 && typeof catalog?.subscribe === "function") catalogStop = catalog.subscribe(() => {
3870
4891
  onCatalogChange();
3871
4892
  });
@@ -3876,7 +4897,7 @@ window.__ModuleLoader__.load({
3876
4897
  const wanted = new Set(want);
3877
4898
  for (const [id, stop] of refs) {
3878
4899
  if (wanted.has(id)) continue;
3879
- stop();
4900
+ stop("no-longer-watched");
3880
4901
  refs.delete(id);
3881
4902
  }
3882
4903
  for (const id of want) {
@@ -3911,6 +4932,10 @@ window.__ModuleLoader__.load({
3911
4932
  watching: () => [...refs.keys()],
3912
4933
  held: () => warmth.held(),
3913
4934
  stop() {
4935
+ operation.end("completed", {
4936
+ reason: "stopped",
4937
+ count: refs.size
4938
+ });
3914
4939
  stopped = true;
3915
4940
  for (const stop of refs.values()) stop();
3916
4941
  refs.clear();
@@ -3935,13 +4960,30 @@ window.__ModuleLoader__.load({
3935
4960
  setCurrent?.(sessionId);
3936
4961
  }, [sessionId, setCurrent]);
3937
4962
  const take = React.useCallback((index, prompt) => {
4963
+ const operation = startClientDiagnostic("suggest", "suggest.client.insert", { sessionId }, { index });
4964
+ let reason = inputActions === void 0 ? "missing-input-actions" : "insert-rejected";
4965
+ let errorCode;
3938
4966
  let written = inputActions === void 0;
3939
4967
  if (inputActions !== void 0) try {
3940
4968
  written = inputActions.insertText(prompt, inputActions.captureInsertion());
3941
- } catch {
4969
+ reason = written ? "inserted" : "insert-rejected";
4970
+ } catch (error) {
4971
+ reason = "insert-exception";
4972
+ errorCode = diagnosticErrorCode(error, "INSERT_FAILED");
3942
4973
  written = false;
3943
4974
  }
3944
- if (sessionId === void 0) return;
4975
+ if (sessionId === void 0) {
4976
+ operation.end("skipped", {
4977
+ reason: "missing-session",
4978
+ index
4979
+ });
4980
+ return;
4981
+ }
4982
+ operation.end(inputActions === void 0 ? "skipped" : written ? "completed" : "failed", {
4983
+ reason,
4984
+ index,
4985
+ errorCode
4986
+ });
3945
4987
  store.dispatch(sessionId, written ? {
3946
4988
  kind: "use",
3947
4989
  index
@@ -3965,6 +5007,13 @@ window.__ModuleLoader__.load({
3965
5007
  "aria-label": t("suggest.dismiss"),
3966
5008
  title: t("suggest.dismiss"),
3967
5009
  onClick: () => {
5010
+ reportClientDiagnostic({
5011
+ area: "suggest",
5012
+ event: "suggest.client.dismiss",
5013
+ phase: sessionId === void 0 ? "skipped" : "completed",
5014
+ sessionId,
5015
+ fields: { reason: sessionId === void 0 ? "missing-session" : "user-dismiss" }
5016
+ });
3968
5017
  if (sessionId !== void 0) store.dispatch(sessionId, { kind: "dismiss" });
3969
5018
  }
3970
5019
  }, "✕")]);
@@ -5765,9 +6814,24 @@ window.__ModuleLoader__.load({
5765
6814
  copyBtn.setAttribute("data-context-reader-copy", "");
5766
6815
  copyBtn.textContent = t("sessionInfo.context.copy");
5767
6816
  copyBtn.addEventListener("click", () => {
6817
+ const diagnostic = startClientDiagnostic("session", "session.client.context-copy");
5768
6818
  try {
5769
- globalThis.navigator?.clipboard?.writeText?.(selectedEntry.text);
5770
- } catch {}
6819
+ const clipboard = globalThis.navigator?.clipboard;
6820
+ if (typeof clipboard?.writeText !== "function") diagnostic.end("skipped", { reason: "missing-service" });
6821
+ else {
6822
+ const result = clipboard.writeText(selectedEntry.text);
6823
+ if (result && typeof result.then === "function") result.then(() => diagnostic.end("completed", { reason: "copied" }), (error) => diagnostic.end("failed", {
6824
+ reason: "operation-failed",
6825
+ errorCode: diagnosticErrorCode(error)
6826
+ }));
6827
+ else diagnostic.end("skipped", { reason: "requested" });
6828
+ }
6829
+ } catch (error) {
6830
+ diagnostic.end("failed", {
6831
+ reason: "operation-failed",
6832
+ errorCode: diagnosticErrorCode(error)
6833
+ });
6834
+ }
5771
6835
  copyBtn.textContent = t("sessionInfo.context.copied");
5772
6836
  });
5773
6837
  rightBar.appendChild(copyBtn);
@@ -5829,36 +6893,61 @@ window.__ModuleLoader__.load({
5829
6893
  return typeof width === "number" && width > 0 && width <= 768;
5830
6894
  }
5831
6895
  function openSkillInHost(ctx, sessionId, name) {
5832
- if (sessionId === "" || name === "") return false;
6896
+ const diagnostic = startClientDiagnostic("session", "session.client.skill-preview", { sessionId });
6897
+ const skip = (reason) => {
6898
+ diagnostic.end("skipped", { reason });
6899
+ return false;
6900
+ };
6901
+ if (sessionId === "" || name === "") return skip("invalid-input");
5833
6902
  const sessions = ctx.get("sessions");
5834
- if (sessions === null || sessions === void 0 || typeof sessions.scope !== "function") return false;
6903
+ if (sessions === null || sessions === void 0 || typeof sessions.scope !== "function") return skip("missing-service");
5835
6904
  let scope;
5836
6905
  try {
5837
6906
  scope = sessions.scope(sessionId);
5838
- } catch {
6907
+ } catch (error) {
6908
+ diagnostic.end("failed", {
6909
+ reason: "operation-failed",
6910
+ errorCode: diagnosticErrorCode(error)
6911
+ });
5839
6912
  return false;
5840
6913
  }
5841
- if (scope === void 0 || scope === null) return false;
6914
+ if (scope === void 0 || scope === null) return skip("missing-scope");
5842
6915
  const triggers = ctx.get("inputTriggers");
5843
- if (triggers === null || triggers === void 0 || typeof triggers.sessionOf !== "function") return false;
6916
+ if (triggers === null || triggers === void 0 || typeof triggers.sessionOf !== "function") return skip("missing-service");
5844
6917
  try {
5845
6918
  const controller = triggers.sessionOf(scope);
5846
- if (controller === void 0 || typeof controller.openReference !== "function") return false;
5847
- return Boolean(controller.openReference("skill", { ref: `/${name}` }));
5848
- } catch {
6919
+ if (controller === void 0 || typeof controller.openReference !== "function") return skip("missing-service");
6920
+ const handled = controller.openReference("skill", { ref: `/${name}` });
6921
+ diagnostic.end(handled === true ? "completed" : "skipped", { reason: handled === true ? "opened" : handled === void 0 ? "requested" : "unhandled" });
6922
+ return Boolean(handled);
6923
+ } catch (error) {
6924
+ diagnostic.end("failed", {
6925
+ reason: "operation-failed",
6926
+ errorCode: diagnosticErrorCode(error)
6927
+ });
5849
6928
  return false;
5850
6929
  }
5851
6930
  }
5852
6931
  async function requestSessionInfo(fetchImpl, sessionId) {
6932
+ const diagnostic = startClientDiagnostic("session", "session.client.projection-load", { sessionId });
5853
6933
  try {
5854
6934
  const response = await fetchImpl(SESSION_INFO_URL, {
5855
6935
  method: "POST",
5856
6936
  headers: { "content-type": "application/json" },
5857
6937
  body: JSON.stringify({ sessionId })
5858
6938
  });
5859
- if (!response.ok) return null;
5860
- return normalizeSkillProjection(await response.json());
5861
- } catch {
6939
+ if (!response.ok) {
6940
+ diagnostic.end("failed", { reason: "http-rejected" });
6941
+ return null;
6942
+ }
6943
+ const result = normalizeSkillProjection(await response.json());
6944
+ diagnostic.end(result === null ? "failed" : "completed", { reason: result === null ? "invalid-response" : "loaded" });
6945
+ return result;
6946
+ } catch (error) {
6947
+ diagnostic.end("failed", {
6948
+ reason: "operation-failed",
6949
+ errorCode: diagnosticErrorCode(error)
6950
+ });
5862
6951
  return null;
5863
6952
  }
5864
6953
  }
@@ -5902,7 +6991,8 @@ window.__ModuleLoader__.load({
5902
6991
  contextReaderSearchQuery: state.contextReaderSearchQuery
5903
6992
  });
5904
6993
  }
5905
- function createPolicyChannel(bridge) {
6994
+ function createPolicyChannel(bridge, kind) {
6995
+ let diagnostic = null;
5906
6996
  let optimisticRaw = null;
5907
6997
  let lastObservedRaw = "";
5908
6998
  let reconcileTimer = null;
@@ -5933,6 +7023,11 @@ window.__ModuleLoader__.load({
5933
7023
  if (hostRaw !== lastObservedRaw) {
5934
7024
  lastObservedRaw = hostRaw;
5935
7025
  if (optimisticRaw === hostRaw) {
7026
+ diagnostic?.end("completed", {
7027
+ reason: "readback-matched",
7028
+ matched: true
7029
+ });
7030
+ diagnostic = null;
5936
7031
  optimisticRaw = null;
5937
7032
  clearTimer();
5938
7033
  }
@@ -5953,6 +7048,12 @@ window.__ModuleLoader__.load({
5953
7048
  reconcileTimer = globalThis.setTimeout(() => {
5954
7049
  reconcileTimer = null;
5955
7050
  const currentHost = readHostRaw();
7051
+ const matched = optimisticRaw === null || optimisticRaw === currentHost;
7052
+ diagnostic?.end(matched ? "completed" : "failed", {
7053
+ reason: matched ? "readback-matched" : "readback-mismatch",
7054
+ matched
7055
+ });
7056
+ diagnostic = null;
5956
7057
  lastObservedRaw = currentHost;
5957
7058
  if (optimisticRaw !== null && optimisticRaw !== currentHost) {
5958
7059
  optimisticRaw = null;
@@ -5961,18 +7062,54 @@ window.__ModuleLoader__.load({
5961
7062
  }, RECONCILE_MS);
5962
7063
  };
5963
7064
  const commitSet = (nextSet, sessionId, onUpdated, onReconcileRollback) => {
5964
- if (!isWritable()) return;
7065
+ const nextDiagnostic = startClientDiagnostic("session", "session.client.policy-write", { sessionId }, {
7066
+ kind,
7067
+ action: "commit"
7068
+ });
7069
+ if (!isWritable()) {
7070
+ nextDiagnostic.end("skipped", { reason: "read-only" });
7071
+ return;
7072
+ }
7073
+ diagnostic?.end("cancelled", { reason: "superseded" });
7074
+ diagnostic = nextDiagnostic;
5965
7075
  const nextCanonical = hasSessionScope() ? updateSessionOverride(bridge?.getDisabledRaw() ?? "", currentRaw(), sessionId, nextSet) : formatDisabledTools(nextSet);
5966
7076
  optimisticRaw = nextCanonical;
5967
- writeHostRaw(nextCanonical);
7077
+ diagnostic.record("queued", { reason: "requested" });
7078
+ try {
7079
+ writeHostRaw(nextCanonical);
7080
+ } catch (error) {
7081
+ diagnostic.end("failed", {
7082
+ reason: "operation-failed",
7083
+ errorCode: diagnosticErrorCode(error)
7084
+ });
7085
+ throw error;
7086
+ }
5968
7087
  scheduleReconcile(onReconcileRollback);
5969
7088
  onUpdated();
5970
7089
  };
5971
7090
  const resetSession = (sessionId, onUpdated, onReconcileRollback) => {
5972
- if (!isWritable() || !hasSessionScope()) return;
7091
+ const nextDiagnostic = startClientDiagnostic("session", "session.client.policy-write", { sessionId }, {
7092
+ kind,
7093
+ action: "reset"
7094
+ });
7095
+ if (!isWritable() || !hasSessionScope()) {
7096
+ nextDiagnostic.end("skipped", { reason: !isWritable() ? "read-only" : "missing-service" });
7097
+ return;
7098
+ }
7099
+ diagnostic?.end("cancelled", { reason: "superseded" });
7100
+ diagnostic = nextDiagnostic;
5973
7101
  const nextCanonical = clearSessionOverride(currentRaw(), sessionId);
5974
7102
  optimisticRaw = nextCanonical;
5975
- writeHostRaw(nextCanonical);
7103
+ diagnostic.record("queued", { reason: "requested" });
7104
+ try {
7105
+ writeHostRaw(nextCanonical);
7106
+ } catch (error) {
7107
+ diagnostic.end("failed", {
7108
+ reason: "operation-failed",
7109
+ errorCode: diagnosticErrorCode(error)
7110
+ });
7111
+ throw error;
7112
+ }
5976
7113
  scheduleReconcile(onReconcileRollback);
5977
7114
  onUpdated();
5978
7115
  };
@@ -5983,7 +7120,11 @@ window.__ModuleLoader__.load({
5983
7120
  isCustomized,
5984
7121
  commitSet,
5985
7122
  resetSession,
5986
- clearTimer
7123
+ stopObservation() {
7124
+ clearTimer();
7125
+ diagnostic?.end("skipped", { reason: "observation-stopped" });
7126
+ diagnostic = null;
7127
+ }
5987
7128
  };
5988
7129
  }
5989
7130
  function installSessionInfo(ctx, isOn, getSessions, t, fetchImpl = globalThis.fetch, toolsBridge, skillsBridge) {
@@ -6001,15 +7142,22 @@ window.__ModuleLoader__.load({
6001
7142
  let mountedSkillsPopover = null;
6002
7143
  let mountedContextPopover = null;
6003
7144
  let lastSignature = "";
7145
+ const recordUi = (action) => reportClientDiagnostic({
7146
+ area: "session",
7147
+ event: "session.client.view-action",
7148
+ phase: "completed",
7149
+ ...activeSessionId === null ? {} : { sessionId: activeSessionId },
7150
+ fields: { action }
7151
+ });
6004
7152
  let activePopover = null;
6005
7153
  let contextFoldPreCompact = true;
6006
7154
  let contextSelectedEntryId = null;
6007
7155
  let contextReaderSearchQuery = "";
6008
- const toolsChannel = createPolicyChannel(toolsBridge);
7156
+ const toolsChannel = createPolicyChannel(toolsBridge, "tools");
6009
7157
  let toolsSearchQuery = "";
6010
7158
  const expandedToolNodes = new Set(TOOL_SCOPE_ORDER.map((s) => `scope:${s}`));
6011
7159
  let defaultExpandedToolsSeeded = false;
6012
- const skillsChannel = createPolicyChannel(skillsBridge);
7160
+ const skillsChannel = createPolicyChannel(skillsBridge, "skills");
6013
7161
  let skillsSearchQuery = "";
6014
7162
  const collapsedSkillNodes = new Set();
6015
7163
  function repaintCurrent(fallbackRoot, sessionId) {
@@ -6041,21 +7189,39 @@ window.__ModuleLoader__.load({
6041
7189
  if (typeof fetchImpl !== "function") return;
6042
7190
  const url = `${options.baseUrl}?sessionId=${globalThis.encodeURIComponent(sessionId)}`;
6043
7191
  if (force) catalogCache.invalidate?.(url);
7192
+ const diagnostic = startClientDiagnostic("session", "session.client.catalog-view", { sessionId }, {
7193
+ kind: options.kind,
7194
+ forced: force
7195
+ });
6044
7196
  const mySeq = ++seq;
6045
7197
  attemptedFor = sessionId;
6046
7198
  loadingFor = sessionId;
6047
7199
  catalogCache.get(url, fetchImpl).then((body) => {
6048
- if (mySeq !== seq) return;
7200
+ if (mySeq !== seq) {
7201
+ diagnostic.end("skipped", { reason: "stale-response" });
7202
+ return;
7203
+ }
6049
7204
  loadingFor = null;
6050
- if (activeSessionId !== null && activeSessionId !== sessionId) return;
7205
+ if (activeSessionId !== null && activeSessionId !== sessionId) {
7206
+ diagnostic.end("skipped", { reason: "stale-response" });
7207
+ return;
7208
+ }
6051
7209
  const parsed = options.parse(body);
7210
+ diagnostic.end(parsed.available ? "completed" : "skipped", {
7211
+ reason: parsed.available ? "loaded" : "invalid-response",
7212
+ count: parsed.items.length
7213
+ });
6052
7214
  if (parsed.available) {
6053
7215
  items = parsed.items;
6054
7216
  loadedFor = sessionId;
6055
7217
  options.onLoaded?.(items, sessionId);
6056
7218
  repaintCurrent(root, sessionId);
6057
7219
  }
6058
- }).catch(() => {
7220
+ }).catch((error) => {
7221
+ diagnostic.end("failed", {
7222
+ reason: "operation-failed",
7223
+ errorCode: diagnosticErrorCode(error)
7224
+ });
6059
7225
  if (mySeq === seq) loadingFor = null;
6060
7226
  });
6061
7227
  }
@@ -6063,6 +7229,7 @@ window.__ModuleLoader__.load({
6063
7229
  }
6064
7230
  const toolsCatalogLoader = createSessionCatalogLoader({
6065
7231
  baseUrl: TOOLS_URL,
7232
+ kind: "tools",
6066
7233
  isOn: () => toolsChannel.isOn(),
6067
7234
  parse: (body) => {
6068
7235
  const res = parseToolCatalog(body);
@@ -6084,6 +7251,7 @@ window.__ModuleLoader__.load({
6084
7251
  });
6085
7252
  const skillsCatalogLoader = createSessionCatalogLoader({
6086
7253
  baseUrl: SKILLS_URL,
7254
+ kind: "skills",
6087
7255
  isOn: () => skillsChannel.isOn(),
6088
7256
  parse: (body) => {
6089
7257
  const res = parseSkillCatalog(body, { includeProject: true });
@@ -6126,8 +7294,8 @@ window.__ModuleLoader__.load({
6126
7294
  }
6127
7295
  function detach() {
6128
7296
  fetchToken += 1;
6129
- toolsChannel.clearTimer();
6130
- skillsChannel.clearTimer();
7297
+ toolsChannel.stopObservation();
7298
+ skillsChannel.stopObservation();
6131
7299
  toolsCatalogLoader.reset();
6132
7300
  skillsCatalogLoader.reset();
6133
7301
  if (unsubscribeSource !== null) {
@@ -6247,12 +7415,15 @@ window.__ModuleLoader__.load({
6247
7415
  toggleIcon.textContent = minimized ? "▾" : "−";
6248
7416
  header.appendChild(toggleIcon);
6249
7417
  header.addEventListener("click", () => {
6250
- userMinimized = !(userMinimized ?? isCompactViewport());
7418
+ const currentMinimized = userMinimized ?? isCompactViewport();
7419
+ recordUi("toggle-panel");
7420
+ userMinimized = !currentMinimized;
6251
7421
  if (userMinimized) activePopover = null;
6252
7422
  paint(root, sessionId);
6253
7423
  });
6254
7424
  const children = [header];
6255
7425
  const closePopover = () => {
7426
+ recordUi("close-popover");
6256
7427
  activePopover = null;
6257
7428
  lastSignature = "";
6258
7429
  paint(root, sessionId);
@@ -6269,6 +7440,7 @@ window.__ModuleLoader__.load({
6269
7440
  t,
6270
7441
  popoverOpen: activePopover === "context",
6271
7442
  onTogglePopover: () => {
7443
+ recordUi("toggle-context");
6272
7444
  activePopover = activePopover === "context" ? null : "context";
6273
7445
  if (activePopover !== "context") {
6274
7446
  contextSelectedEntryId = null;
@@ -6292,6 +7464,7 @@ window.__ModuleLoader__.load({
6292
7464
  customized: skillsCustomized,
6293
7465
  popoverOpen: activePopover === "skills",
6294
7466
  onTogglePopover: () => {
7467
+ recordUi("toggle-skills");
6295
7468
  activePopover = activePopover === "skills" ? null : "skills";
6296
7469
  if (activePopover === "skills" && !skillsCatalogLoader.isLoadedFor(sessionId)) skillsCatalogLoader.ensure(root, sessionId, true);
6297
7470
  paint(root, sessionId);
@@ -6371,6 +7544,7 @@ window.__ModuleLoader__.load({
6371
7544
  customized: toolsCustomized,
6372
7545
  popoverOpen: activePopover === "tools",
6373
7546
  onTogglePopover: () => {
7547
+ recordUi("toggle-tools");
6374
7548
  activePopover = activePopover === "tools" ? null : "tools";
6375
7549
  if (activePopover === "tools" && !toolsCatalogLoader.isLoadedFor(sessionId)) toolsCatalogLoader.ensure(root, sessionId, true);
6376
7550
  paint(root, sessionId);
@@ -6393,6 +7567,7 @@ window.__ModuleLoader__.load({
6393
7567
  writable: toolsWritable,
6394
7568
  compact,
6395
7569
  onSearchChange: (nextQuery) => {
7570
+ recordUi("search-tools");
6396
7571
  toolsSearchQuery = nextQuery;
6397
7572
  lastSignature = "";
6398
7573
  paint(root, sessionId);
@@ -6436,6 +7611,7 @@ window.__ModuleLoader__.load({
6436
7611
  writable: skillsWritable,
6437
7612
  compact,
6438
7613
  onSearchChange: (nextQuery) => {
7614
+ recordUi("search-skills");
6439
7615
  skillsSearchQuery = nextQuery;
6440
7616
  lastSignature = "";
6441
7617
  paint(root, sessionId);
@@ -6476,17 +7652,20 @@ window.__ModuleLoader__.load({
6476
7652
  readerSearchQuery: contextReaderSearchQuery,
6477
7653
  compact,
6478
7654
  onToggleFoldPreCompact: () => {
7655
+ recordUi("fold-context");
6479
7656
  contextFoldPreCompact = !contextFoldPreCompact;
6480
7657
  lastSignature = "";
6481
7658
  paint(root, sessionId);
6482
7659
  },
6483
7660
  onSelectEntry: (nextId) => {
7661
+ recordUi(nextId === null ? "back-context" : "select-context");
6484
7662
  contextSelectedEntryId = nextId;
6485
7663
  if (nextId === null) contextReaderSearchQuery = "";
6486
7664
  lastSignature = "";
6487
7665
  paint(root, sessionId);
6488
7666
  },
6489
7667
  onReaderSearchChange: (nextQuery) => {
7668
+ recordUi("search-context");
6490
7669
  contextReaderSearchQuery = nextQuery;
6491
7670
  lastSignature = "";
6492
7671
  paint(root, sessionId);
@@ -6836,10 +8015,10 @@ window.__ModuleLoader__.load({
6836
8015
  try {
6837
8016
  if (globalThis.navigator?.clipboard?.writeText) {
6838
8017
  await globalThis.navigator.clipboard.writeText(url);
6839
- return;
8018
+ return "clipboard_primary";
6840
8019
  }
6841
8020
  } catch {}
6842
- if (signal.aborted) return;
8021
+ if (signal.aborted) return "aborted";
6843
8022
  const field = globalThis.document.createElement("textarea");
6844
8023
  const focused = globalThis.document.activeElement;
6845
8024
  try {
@@ -6849,6 +8028,7 @@ window.__ModuleLoader__.load({
6849
8028
  globalThis.document.body.appendChild(field);
6850
8029
  field.select();
6851
8030
  if (!globalThis.document.execCommand("copy")) throw new Error("remote.copyFailed");
8031
+ return "clipboard_fallback";
6852
8032
  } finally {
6853
8033
  field.value = "";
6854
8034
  field.remove();
@@ -6888,9 +8068,21 @@ window.__ModuleLoader__.load({
6888
8068
  setError(["remote.unauthorized", "remote.copyFailed"].includes(key) ? key : "remote.requestFailed");
6889
8069
  };
6890
8070
  React.useEffect(() => {
8071
+ const lifecycle = startClientDiagnostic("remote", "remote.client.lifecycle");
8072
+ const initial = startClientDiagnostic("remote", "remote.client.action", { parentOperationId: lifecycle.id }, { action: "status" });
6891
8073
  const abort = new globalThis.AbortController();
6892
8074
  controller.current = abort;
6893
- refresh(abort.signal).catch((caught) => {
8075
+ refresh(abort.signal).then(() => {
8076
+ initial.end(abort.signal.aborted ? "cancelled" : "completed", {
8077
+ action: "status",
8078
+ ...abort.signal.aborted ? { reason: "aborted" } : {}
8079
+ });
8080
+ }, (caught) => {
8081
+ initial.end(abort.signal.aborted ? "cancelled" : "failed", {
8082
+ action: "status",
8083
+ reason: abort.signal.aborted ? "aborted" : "refresh_failed",
8084
+ errorCode: diagnosticErrorCode(caught)
8085
+ });
6894
8086
  if (!abort.signal.aborted) fail(caught);
6895
8087
  }).finally(() => {
6896
8088
  if (!abort.signal.aborted) {
@@ -6901,12 +8093,27 @@ window.__ModuleLoader__.load({
6901
8093
  return () => {
6902
8094
  abort.abort();
6903
8095
  controller.current = null;
8096
+ initial.end("cancelled", {
8097
+ action: "status",
8098
+ reason: "unmount"
8099
+ });
8100
+ lifecycle.end("cancelled", { reason: "unmount" });
6904
8101
  };
6905
8102
  }, []);
6906
- const askConfirm = (key, source) => {
8103
+ const askConfirm = (key, source, action = "configure") => {
8104
+ const span = startClientDiagnostic("remote", "remote.client.confirm", {}, { action });
6907
8105
  try {
6908
- return globalThis.confirm(t(key));
8106
+ const confirmed = globalThis.confirm(t(key));
8107
+ span.end(confirmed ? "completed" : "cancelled", {
8108
+ action,
8109
+ reason: confirmed ? "accepted" : "user_cancelled"
8110
+ });
8111
+ return confirmed;
6909
8112
  } catch {
8113
+ span.end("failed", {
8114
+ action,
8115
+ reason: "confirm_failed"
8116
+ });
6910
8117
  setError("remote.confirmUnavailable");
6911
8118
  return false;
6912
8119
  } finally {
@@ -6917,6 +8124,17 @@ window.__ModuleLoader__.load({
6917
8124
  const abort = controller.current;
6918
8125
  if (!abort || abort.signal.aborted || inFlight.current) return;
6919
8126
  inFlight.current = true;
8127
+ const fields = {
8128
+ action: body?.action ?? "status",
8129
+ deviceId: body && "id" in body && /^[a-f0-9]{32}$/u.test(body.id) ? body.id : void 0
8130
+ };
8131
+ const span = startClientDiagnostic("remote", "remote.client.action", {}, { ...fields });
8132
+ const cancelled = () => span.end("cancelled", {
8133
+ ...fields,
8134
+ reason: "aborted"
8135
+ });
8136
+ abort.signal.addEventListener("abort", cancelled, { once: true });
8137
+ let failed = false;
6920
8138
  setBusy(true);
6921
8139
  setError("");
6922
8140
  setNote("");
@@ -6924,9 +8142,11 @@ window.__ModuleLoader__.load({
6924
8142
  try {
6925
8143
  if (body) {
6926
8144
  const { code, data } = await request(abort.signal, body);
8145
+ fields.status = code;
6927
8146
  if (abort.signal.aborted) return;
6928
8147
  if (body.action === "configure" && code === 202) {
6929
8148
  if (!data || typeof data !== "object" || !("accepted" in data) || data.accepted !== true || !("enabled" in data) || data.enabled !== body.enabled || !("port" in data) || data.port !== body.port) throw new Error("remote.requestFailed");
8149
+ fields.reason = "accepted";
6930
8150
  setStatus(null);
6931
8151
  setNote(body.enabled ? "remote.configurationAccepted" : "remote.shutdownAccepted");
6932
8152
  if (body.enabled && "reconnectUrl" in data) setEntry(reconnectUrl(data.reconnectUrl, body.port));
@@ -6935,7 +8155,7 @@ window.__ModuleLoader__.load({
6935
8155
  if (body.action === "addDevice" || body.action === "copyDeviceLink" || body.action === "reissue") {
6936
8156
  const url = deviceUrl(data);
6937
8157
  try {
6938
- await copyToClipboard(url, abort.signal);
8158
+ fields.reason = await copyToClipboard(url, abort.signal);
6939
8159
  } catch {
6940
8160
  throw new Error("remote.copyFailed");
6941
8161
  }
@@ -6958,8 +8178,16 @@ window.__ModuleLoader__.load({
6958
8178
  }
6959
8179
  await refresh(abort.signal);
6960
8180
  } catch (caught) {
8181
+ failed = true;
8182
+ fields.errorCode = diagnosticErrorCode(caught);
8183
+ fields.reason = caught instanceof Error && caught.message === "remote.unauthorized" ? "unauthorized" : caught instanceof Error && caught.message === "remote.copyFailed" ? "clipboard_failed" : "request_failed";
6961
8184
  if (!abort.signal.aborted) fail(caught);
6962
8185
  } finally {
8186
+ abort.signal.removeEventListener("abort", cancelled);
8187
+ span.end(abort.signal.aborted ? "cancelled" : failed ? "failed" : "completed", {
8188
+ ...fields,
8189
+ ...abort.signal.aborted ? { reason: "aborted" } : {}
8190
+ });
6963
8191
  if (!abort.signal.aborted) {
6964
8192
  inFlight.current = false;
6965
8193
  setBusy(false);
@@ -6985,7 +8213,7 @@ window.__ModuleLoader__.load({
6985
8213
  if (action === "revoke") {
6986
8214
  const row = id === void 0 ? void 0 : status.devices.find((item) => item.id === id);
6987
8215
  if (!row || row.revokedAt !== void 0) return;
6988
- if (!askConfirm(row.id === status.currentDeviceId ? "remote.confirmRevokeSelf" : "remote.confirmRevoke", source)) return;
8216
+ if (!askConfirm(row.id === status.currentDeviceId ? "remote.confirmRevokeSelf" : "remote.confirmRevoke", source, "revoke")) return;
6989
8217
  run({
6990
8218
  action: "revoke",
6991
8219
  id: row.id
@@ -7006,7 +8234,7 @@ window.__ModuleLoader__.load({
7006
8234
  });
7007
8235
  return;
7008
8236
  }
7009
- if (!askConfirm("remote.confirmReissue", source)) return;
8237
+ if (!askConfirm("remote.confirmReissue", source, "reissue")) return;
7010
8238
  run({
7011
8239
  action: "reissue",
7012
8240
  id: row.id
@@ -8139,9 +9367,18 @@ window.__ModuleLoader__.load({
8139
9367
  };
8140
9368
  return {
8141
9369
  async run() {
8142
- if (!live || !allowed() || state.busy || state.created) return;
9370
+ const diagnostic = startClientDiagnostic("session", "session.client.fork", { sessionId }, {
9371
+ source: "abnormal-turn",
9372
+ atSeq
9373
+ });
9374
+ const canRun = live && allowed();
9375
+ if (!canRun || state.busy || state.created) {
9376
+ diagnostic.end("skipped", { reason: !live ? "unmounted" : !canRun ? "not-allowed" : state.busy ? "busy" : "already-created" });
9377
+ return;
9378
+ }
8143
9379
  state = { busy: true };
8144
9380
  emit();
9381
+ let creationObserved = false;
8145
9382
  try {
8146
9383
  const id = await services.fork({
8147
9384
  sessionId,
@@ -8152,13 +9389,29 @@ window.__ModuleLoader__.load({
8152
9389
  ...state,
8153
9390
  created: id
8154
9391
  };
9392
+ creationObserved = typeof id === "string" && id !== "";
9393
+ diagnostic.record("queued", {
9394
+ reason: creationObserved ? "created" : "requested",
9395
+ created: creationObserved
9396
+ });
8155
9397
  }
8156
9398
  });
8157
9399
  state = {
8158
9400
  busy: false,
8159
9401
  created: id
8160
9402
  };
8161
- if (live && allowed()) services.openSession(id);
9403
+ creationObserved ||= typeof id === "string" && id !== "";
9404
+ if (live && allowed()) {
9405
+ services.openSession(id);
9406
+ diagnostic.end(creationObserved ? "completed" : "skipped", {
9407
+ reason: creationObserved ? "created" : "requested",
9408
+ created: creationObserved,
9409
+ action: "navigation-requested"
9410
+ });
9411
+ } else diagnostic.end(creationObserved ? "completed" : "skipped", {
9412
+ reason: "navigation-suppressed",
9413
+ created: creationObserved
9414
+ });
8162
9415
  } catch (error) {
8163
9416
  const rpcError = error !== null && typeof error === "object" && "rpcError" in error ? error.rpcError : null;
8164
9417
  const created = rpcError?.code === "session/workspace-attach-failed" ? rpcError.details?.sessionId : void 0;
@@ -8168,6 +9421,12 @@ window.__ModuleLoader__.load({
8168
9421
  busy: false,
8169
9422
  error: error instanceof Error ? error.message : String(error)
8170
9423
  };
9424
+ const missing = error !== null && typeof error === "object" && error.code === "SERVICE_UNAVAILABLE";
9425
+ diagnostic.end(missing && !state.created ? "skipped" : "failed", {
9426
+ reason: state.created ? "partial" : missing ? "missing-service" : "operation-failed",
9427
+ created: !!state.created,
9428
+ errorCode: diagnosticErrorCode(error)
9429
+ });
8171
9430
  }
8172
9431
  emit();
8173
9432
  },
@@ -8279,12 +9538,12 @@ window.__ModuleLoader__.load({
8279
9538
  const next = createForkAction({
8280
9539
  fork: (options) => {
8281
9540
  const sessions = ctx.get("sessions");
8282
- if (!sessions) throw new Error("sessions service unavailable");
9541
+ if (!sessions) throw Object.assign(new Error("sessions service unavailable"), { code: "SERVICE_UNAVAILABLE" });
8283
9542
  return sessions.fork(options);
8284
9543
  },
8285
9544
  openSession: (id) => {
8286
9545
  const workspace = ctx.get("uiWorkspace");
8287
- if (!workspace) throw new Error("uiWorkspace service unavailable");
9546
+ if (!workspace) throw Object.assign(new Error("uiWorkspace service unavailable"), { code: "SERVICE_UNAVAILABLE" });
8288
9547
  workspace.openSession(id);
8289
9548
  }
8290
9549
  }, sessionId, boundary, () => current.current.allowed && settings.get().value?.abnormalFork !== false, setState);
@@ -8421,7 +9680,8 @@ window.__ModuleLoader__.load({
8421
9680
  };
8422
9681
  }
8423
9682
  function createContextBridge(fetchImpl) {
8424
- const request = async (sessionId, body) => {
9683
+ const request = async (sessionId, body, action = "load") => {
9684
+ const diagnostic = startClientDiagnostic("session", "session.client.context-request", { sessionId }, { action });
8425
9685
  try {
8426
9686
  const url = `${CONTEXT_ROUTE}?sessionId=${encodeURIComponent(sessionId)}`;
8427
9687
  const response = body === void 0 ? await fetchImpl(url, { method: "GET" }) : await fetchImpl(url, {
@@ -8429,10 +9689,19 @@ window.__ModuleLoader__.load({
8429
9689
  headers: { "content-type": "application/json" },
8430
9690
  body: JSON.stringify(body)
8431
9691
  });
8432
- if (!response.ok) return null;
9692
+ if (!response.ok) {
9693
+ diagnostic.end("failed", { reason: "http-rejected" });
9694
+ return null;
9695
+ }
8433
9696
  const parsed = await response.json();
8434
- return parsed !== null && typeof parsed === "object" ? parsed : null;
8435
- } catch {
9697
+ const valid = parsed !== null && typeof parsed === "object";
9698
+ diagnostic.end(valid ? "completed" : "failed", { reason: valid ? "response-received" : "invalid-response" });
9699
+ return valid ? parsed : null;
9700
+ } catch (error) {
9701
+ diagnostic.end("failed", {
9702
+ reason: "operation-failed",
9703
+ errorCode: diagnosticErrorCode(error)
9704
+ });
8436
9705
  return null;
8437
9706
  }
8438
9707
  };
@@ -8446,14 +9715,14 @@ window.__ModuleLoader__.load({
8446
9715
  action: "setCap",
8447
9716
  sessionId,
8448
9717
  cap
8449
- });
9718
+ }, "setCap");
8450
9719
  return body === null ? null : readSnapshot(body.snapshot);
8451
9720
  },
8452
9721
  async prune(sessionId) {
8453
9722
  const body = await request(sessionId, {
8454
9723
  action: "prune",
8455
9724
  sessionId
8456
- });
9725
+ }, "prune");
8457
9726
  if (body === null) return null;
8458
9727
  const outcome = readOutcome(body.outcome);
8459
9728
  if (outcome === null) return null;
@@ -8507,6 +9776,21 @@ window.__ModuleLoader__.load({
8507
9776
  let generation = 0;
8508
9777
  let pruneRevision = -1;
8509
9778
  let pollTimer;
9779
+ let pruneDiagnostic = null;
9780
+ const finishPrune = (outcome) => {
9781
+ if (outcome.state === "queued") return;
9782
+ pruneDiagnostic?.end(outcome.state === "failed" ? "failed" : outcome.state === "noop" ? "skipped" : "completed", {
9783
+ reason: outcome.state === "failed" ? "host-failed" : outcome.state === "noop" ? "noop" : "done",
9784
+ outcome: outcome.state,
9785
+ prunedCount: outcome.prunedCount,
9786
+ charsRemoved: outcome.charsRemoved
9787
+ });
9788
+ pruneDiagnostic = null;
9789
+ };
9790
+ const stopPruneObservation = () => {
9791
+ pruneDiagnostic?.end("skipped", { reason: "observation-stopped" });
9792
+ pruneDiagnostic = null;
9793
+ };
8510
9794
  const cancelPoll = () => {
8511
9795
  globalThis.clearTimeout(pollTimer);
8512
9796
  pollTimer = void 0;
@@ -8537,6 +9821,7 @@ window.__ModuleLoader__.load({
8537
9821
  if (snapshot.pruneOutcome && snapshot.pruneRevision !== void 0 && snapshot.pruneRevision > pruneRevision) {
8538
9822
  pruneRevision = snapshot.pruneRevision;
8539
9823
  state.outcome = snapshot.pruneOutcome;
9824
+ finishPrune(snapshot.pruneOutcome);
8540
9825
  }
8541
9826
  }
8542
9827
  snapshot = cachedSnapshot;
@@ -8588,6 +9873,7 @@ window.__ModuleLoader__.load({
8588
9873
  save.addEventListener("click", () => {
8589
9874
  const parsed = parseCapInput(state.draft);
8590
9875
  if (!parsed.ok) {
9876
+ startClientDiagnostic("session", "session.client.threshold-write", { sessionId: state.sessionId }).end("skipped", { reason: parsed.reason === "range" ? "out-of-range" : "invalid-input" });
8591
9877
  state.note = parsed.reason === "range" ? "超出允许范围" : "请输入数字";
8592
9878
  render(null);
8593
9879
  return;
@@ -8678,19 +9964,36 @@ window.__ModuleLoader__.load({
8678
9964
  const reload = async () => {
8679
9965
  const id = state.sessionId;
8680
9966
  const mine = generation;
9967
+ const diagnostic = startClientDiagnostic("session", "session.client.context-load", { sessionId: id }, { polling: state.outcome?.state === "queued" });
8681
9968
  const snapshot = await bridge.load(id);
8682
- if (!isCurrent(mine, id)) return;
9969
+ if (!isCurrent(mine, id)) {
9970
+ diagnostic.end("skipped", { reason: "stale-response" });
9971
+ return;
9972
+ }
9973
+ diagnostic.end(snapshot === null ? "failed" : "completed", { reason: snapshot === null ? "invalid-response" : "loaded" });
8683
9974
  render(snapshot);
8684
9975
  };
8685
9976
  const commit = async (cap) => {
8686
9977
  const id = state.sessionId;
8687
- if (!isCurrent(generation, id) || state.busy) return;
9978
+ const diagnostic = startClientDiagnostic("session", "session.client.threshold-write", { sessionId: id }, { action: cap === null ? "reset" : "commit" });
9979
+ if (!isCurrent(generation, id) || state.busy) {
9980
+ diagnostic.end("skipped", { reason: state.busy ? "busy" : "stale-response" });
9981
+ return;
9982
+ }
8688
9983
  const mine = ++generation;
8689
9984
  cancelPoll();
8690
9985
  state.busy = true;
8691
9986
  render(null);
8692
9987
  const snapshot = await bridge.saveCap(id, cap);
8693
- if (!isCurrent(mine, id)) return;
9988
+ if (!isCurrent(mine, id)) {
9989
+ diagnostic.end("skipped", { reason: "stale-response" });
9990
+ return;
9991
+ }
9992
+ const matched = snapshot !== null && snapshot.cap === cap;
9993
+ diagnostic.end(matched ? "completed" : "failed", {
9994
+ reason: snapshot === null ? "invalid-response" : matched ? "readback-matched" : "readback-mismatch",
9995
+ matched
9996
+ });
8694
9997
  state.busy = false;
8695
9998
  if (snapshot === null) {
8696
9999
  state.note = "保存失败,阈值未生效";
@@ -8703,15 +10006,25 @@ window.__ModuleLoader__.load({
8703
10006
  };
8704
10007
  const runPrune = async () => {
8705
10008
  const id = state.sessionId;
8706
- if (!isCurrent(generation, id) || state.busy || state.outcome?.state === "queued") return;
10009
+ const diagnostic = startClientDiagnostic("session", "session.client.prune", { sessionId: id });
10010
+ if (!isCurrent(generation, id) || state.busy || state.outcome?.state === "queued") {
10011
+ diagnostic.end("skipped", { reason: state.busy ? "busy" : state.outcome?.state === "queued" ? "already-queued" : "stale-response" });
10012
+ return;
10013
+ }
10014
+ pruneDiagnostic = diagnostic;
8707
10015
  const mine = ++generation;
8708
10016
  cancelPoll();
8709
10017
  state.busy = true;
8710
10018
  render(null);
8711
10019
  const result = await bridge.prune(id);
8712
- if (!isCurrent(mine, id)) return;
10020
+ if (!isCurrent(mine, id)) {
10021
+ diagnostic.end("skipped", { reason: "stale-response" });
10022
+ return;
10023
+ }
8713
10024
  state.busy = false;
8714
10025
  if (result === null) {
10026
+ diagnostic.end("failed", { reason: "invalid-response" });
10027
+ pruneDiagnostic = null;
8715
10028
  state.outcome = {
8716
10029
  state: "failed",
8717
10030
  prunedCount: 0,
@@ -8722,6 +10035,11 @@ window.__ModuleLoader__.load({
8722
10035
  return;
8723
10036
  }
8724
10037
  state.outcome = result.outcome;
10038
+ if (result.outcome.state === "queued") diagnostic.record("queued", {
10039
+ reason: "queued",
10040
+ outcome: "queued"
10041
+ });
10042
+ else finishPrune(result.outcome);
8725
10043
  state.note = "";
8726
10044
  render(result.snapshot);
8727
10045
  };
@@ -8735,11 +10053,13 @@ window.__ModuleLoader__.load({
8735
10053
  activePanel = null;
8736
10054
  cachedSnapshot = null;
8737
10055
  cancelPoll();
10056
+ stopPruneObservation();
8738
10057
  remove();
8739
10058
  }
8740
10059
  return;
8741
10060
  }
8742
10061
  if (activePanel !== found.panel || state?.sessionId !== id) {
10062
+ stopPruneObservation();
8743
10063
  generation++;
8744
10064
  cancelPoll();
8745
10065
  pruneRevision = -1;
@@ -8772,6 +10092,7 @@ window.__ModuleLoader__.load({
8772
10092
  refresh();
8773
10093
  return () => {
8774
10094
  disposed = true;
10095
+ stopPruneObservation();
8775
10096
  generation++;
8776
10097
  cancelPoll();
8777
10098
  observer.disconnect();
@@ -8841,9 +10162,17 @@ window.__ModuleLoader__.load({
8841
10162
  let created;
8842
10163
  button.addEventListener("click", () => {
8843
10164
  (async () => {
8844
- if (!active || busy || created !== void 0 || !allowed()) return;
10165
+ const diagnostic = startClientDiagnostic("session", "session.client.fork", { sessionId }, {
10166
+ source: "manual-compaction",
10167
+ atSeq: boundary
10168
+ });
10169
+ if (!active || busy || created !== void 0 || !allowed()) {
10170
+ diagnostic.end("skipped", { reason: !active ? "unmounted" : busy ? "busy" : created !== void 0 ? "already-created" : "not-allowed" });
10171
+ return;
10172
+ }
8845
10173
  busy = true;
8846
10174
  button.disabled = true;
10175
+ let creationObserved = false;
8847
10176
  try {
8848
10177
  const id = await services.fork({
8849
10178
  sessionId,
@@ -8851,13 +10180,34 @@ window.__ModuleLoader__.load({
8851
10180
  increaseTitle: true,
8852
10181
  onCreated(childId) {
8853
10182
  created = childId;
10183
+ creationObserved = typeof childId === "string" && childId !== "";
10184
+ diagnostic.record("queued", {
10185
+ reason: creationObserved ? "created" : "requested",
10186
+ created: creationObserved
10187
+ });
8854
10188
  }
8855
10189
  });
8856
10190
  created = id;
8857
- if (active && allowed()) services.openSession(id);
10191
+ creationObserved ||= typeof id === "string" && id !== "";
10192
+ if (active && allowed()) {
10193
+ services.openSession(id);
10194
+ diagnostic.end(creationObserved ? "completed" : "skipped", {
10195
+ reason: creationObserved ? "created" : "requested",
10196
+ created: creationObserved,
10197
+ action: "navigation-requested"
10198
+ });
10199
+ } else diagnostic.end(creationObserved ? "completed" : "skipped", {
10200
+ reason: "navigation-suppressed",
10201
+ created: creationObserved
10202
+ });
8858
10203
  } catch (error) {
8859
10204
  const rpc = error !== null && typeof error === "object" && "rpcError" in error ? error.rpcError : null;
8860
10205
  if (rpc?.code === "session/workspace-attach-failed" && typeof rpc.details?.sessionId === "string") created = rpc.details.sessionId;
10206
+ diagnostic.end("failed", {
10207
+ reason: created !== void 0 ? "partial" : "operation-failed",
10208
+ created: created !== void 0,
10209
+ errorCode: diagnosticErrorCode(error)
10210
+ });
8861
10211
  button.title = error instanceof Error ? error.message : String(error);
8862
10212
  } finally {
8863
10213
  busy = false;
@@ -8879,6 +10229,7 @@ window.__ModuleLoader__.load({
8879
10229
  "shortcuts"
8880
10230
  ];
8881
10231
  function apply(ctx) {
10232
+ ctx.effect(() => installClientDiagnostics(), "desktop-enhance: client diagnostics");
8882
10233
  ctx.effect(() => {
8883
10234
  const tag = globalThis.document.createElement("style");
8884
10235
  tag.dataset.pluginCss = "dsh-desktop-enhance";
@@ -8901,7 +10252,20 @@ window.__ModuleLoader__.load({
8901
10252
  });
8902
10253
  const connectionScope = ctx.inject(["connection"], (connectionCtx) => {
8903
10254
  const connection = connectionCtx.get("connection");
8904
- connectionCtx.effect(() => watchMobileConnection(connection, (status) => runtime.setConnectionStatus(status)), "desktop-enhance: mobile connection");
10255
+ connectionCtx.effect(() => {
10256
+ let previous;
10257
+ return watchMobileConnection(connection, (status) => {
10258
+ runtime.setConnectionStatus(status);
10259
+ if (status === previous) return;
10260
+ previous = status;
10261
+ reportClientDiagnostic({
10262
+ area: "remote",
10263
+ event: "remote.client.connection",
10264
+ phase: "completed",
10265
+ fields: { reason: status }
10266
+ });
10267
+ });
10268
+ }, "desktop-enhance: mobile connection");
8905
10269
  });
8906
10270
  return () => {
8907
10271
  runtime.dispose();
@@ -8998,6 +10362,15 @@ window.__ModuleLoader__.load({
8998
10362
  installTurnPrefix(ctx);
8999
10363
  const folderStatus = installFolderStatus(ctx, () => flagOn(settings.get().value, "folderStatus"), t);
9000
10364
  const timings = installTimings(ctx, () => flagOn(settings.get().value, "stepDuration"), () => ctx.get("sessions"));
10365
+ const policyWriteFailed = (field) => reportClientDiagnostic({
10366
+ area: "session",
10367
+ event: "session.client.policy-submit",
10368
+ phase: "failed",
10369
+ fields: {
10370
+ field,
10371
+ reason: "set-threw"
10372
+ }
10373
+ });
9001
10374
  const makePolicyBridge = (featureField, globalField, overridesField) => ({
9002
10375
  isOn: () => flagOn(settings.get().value, featureField),
9003
10376
  canWrite: () => {
@@ -9010,8 +10383,10 @@ window.__ModuleLoader__.load({
9010
10383
  },
9011
10384
  setDisabledRaw: (nextCanonical) => {
9012
10385
  try {
9013
- Promise.resolve(form?.set?.(globalField, nextCanonical)).catch(() => {});
9014
- } catch {}
10386
+ Promise.resolve(form?.set?.(globalField, nextCanonical)).catch(() => policyWriteFailed(globalField));
10387
+ } catch {
10388
+ policyWriteFailed(globalField);
10389
+ }
9015
10390
  },
9016
10391
  getSessionOverridesRaw: () => {
9017
10392
  const raw = settings.get().value?.[overridesField];
@@ -9019,8 +10394,10 @@ window.__ModuleLoader__.load({
9019
10394
  },
9020
10395
  setSessionOverridesRaw: (nextCanonical) => {
9021
10396
  try {
9022
- Promise.resolve(form?.set?.(overridesField, nextCanonical)).catch(() => {});
9023
- } catch {}
10397
+ Promise.resolve(form?.set?.(overridesField, nextCanonical)).catch(() => policyWriteFailed(overridesField));
10398
+ } catch {
10399
+ policyWriteFailed(overridesField);
10400
+ }
9024
10401
  }
9025
10402
  });
9026
10403
  const sessionInfo = installSessionInfo(ctx, () => flagOn(settings.get().value, "sessionInfo"), () => ctx.get("sessions"), t, globalThis.fetch, makePolicyBridge("toolsManager", "disabledTools", "sessionToolOverrides"), makePolicyBridge("skillsManager", "disabledSkills", "sessionSkillOverrides"));
@@ -9257,6 +10634,13 @@ window.__ModuleLoader__.load({
9257
10634
  }
9258
10635
  //#endregion
9259
10636
  exports.__test = {
10637
+ installClientDiagnostics,
10638
+ reportClientDiagnostic,
10639
+ startClientDiagnostic,
10640
+ DiagnosticsPanel,
10641
+ parseDiagnosticPage,
10642
+ diagnosticQuery,
10643
+ collectDiagnosticExport,
9260
10644
  SessionModelLabel,
9261
10645
  ReadOnlyModelComposer,
9262
10646
  selectReadOnlyModel,