@dailephd/my-centcom 0.1.0 → 0.3.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.
Files changed (175) hide show
  1. package/README.md +10 -5
  2. package/apps/daemon/dist/artifacts/returnSnapshots.d.ts +12 -0
  3. package/apps/daemon/dist/artifacts/returnSnapshots.js +41 -0
  4. package/apps/daemon/dist/bootstrap/app.d.ts +21 -0
  5. package/apps/daemon/dist/bootstrap/app.js +27 -0
  6. package/apps/daemon/dist/bootstrap/installLayout.d.ts +81 -0
  7. package/apps/daemon/dist/bootstrap/installLayout.js +164 -0
  8. package/apps/daemon/dist/bootstrap/main.d.ts +14 -0
  9. package/apps/daemon/dist/bootstrap/main.js +141 -0
  10. package/apps/daemon/dist/bootstrap/operatorConsole.d.ts +75 -0
  11. package/apps/daemon/dist/bootstrap/operatorConsole.js +293 -0
  12. package/apps/daemon/dist/bootstrap/privateDataRoot.d.ts +38 -0
  13. package/apps/daemon/dist/bootstrap/privateDataRoot.js +204 -0
  14. package/apps/daemon/dist/bootstrap/secureMain.d.ts +118 -0
  15. package/apps/daemon/dist/bootstrap/secureMain.js +403 -0
  16. package/apps/daemon/dist/bootstrap/setup.d.ts +93 -0
  17. package/apps/daemon/dist/bootstrap/setup.js +738 -0
  18. package/apps/daemon/dist/context/changeProposal.d.ts +97 -0
  19. package/apps/daemon/dist/context/changeProposal.js +259 -0
  20. package/apps/daemon/dist/context/gitEvidence.d.ts +88 -0
  21. package/apps/daemon/dist/context/gitEvidence.js +332 -0
  22. package/apps/daemon/dist/context/gitObservation.d.ts +30 -0
  23. package/apps/daemon/dist/context/gitObservation.js +113 -0
  24. package/apps/daemon/dist/context/projectReadIssuer.d.ts +68 -0
  25. package/apps/daemon/dist/context/projectReadIssuer.js +158 -0
  26. package/apps/daemon/dist/context/projectReadService.d.ts +153 -0
  27. package/apps/daemon/dist/context/projectReadService.js +652 -0
  28. package/apps/daemon/dist/context/projectViewService.d.ts +85 -0
  29. package/apps/daemon/dist/context/projectViewService.js +332 -0
  30. package/apps/daemon/dist/context/proposalRecorder.d.ts +11 -0
  31. package/apps/daemon/dist/context/proposalRecorder.js +19 -0
  32. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.d.ts +40 -0
  33. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.js +73 -0
  34. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.d.ts +49 -0
  35. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.js +70 -0
  36. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.d.ts +16 -0
  37. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.js +115 -0
  38. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.d.ts +153 -0
  39. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.js +505 -0
  40. package/apps/daemon/dist/plugins/registry/operationCatalog.d.ts +23 -0
  41. package/apps/daemon/dist/plugins/registry/operationCatalog.js +41 -0
  42. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.d.ts +14 -0
  43. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.js +29 -0
  44. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.d.ts +151 -0
  45. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.js +579 -0
  46. package/apps/daemon/dist/projects/codingAuthority.d.ts +102 -0
  47. package/apps/daemon/dist/projects/codingAuthority.js +244 -0
  48. package/apps/daemon/dist/projects/fixtureAuthorization.d.ts +54 -0
  49. package/apps/daemon/dist/projects/fixtureAuthorization.js +172 -0
  50. package/apps/daemon/dist/projects/pairedAuthority.d.ts +158 -0
  51. package/apps/daemon/dist/projects/pairedAuthority.js +273 -0
  52. package/apps/daemon/dist/projects/trustedCliConsent.d.ts +47 -0
  53. package/apps/daemon/dist/projects/trustedCliConsent.js +84 -0
  54. package/apps/daemon/dist/runs/changeApplier.d.ts +59 -0
  55. package/apps/daemon/dist/runs/changeApplier.js +319 -0
  56. package/apps/daemon/dist/runs/codingWorkflowService.d.ts +283 -0
  57. package/apps/daemon/dist/runs/codingWorkflowService.js +785 -0
  58. package/apps/daemon/dist/runs/durableIntentCoordinator.d.ts +72 -0
  59. package/apps/daemon/dist/runs/durableIntentCoordinator.js +160 -0
  60. package/apps/daemon/dist/runs/inMemoryCoordinator.d.ts +55 -0
  61. package/apps/daemon/dist/runs/inMemoryCoordinator.js +375 -0
  62. package/apps/daemon/dist/runs/runExecutor.d.ts +154 -0
  63. package/apps/daemon/dist/runs/runExecutor.js +295 -0
  64. package/apps/daemon/dist/runs/workflowService.d.ts +185 -0
  65. package/apps/daemon/dist/runs/workflowService.js +300 -0
  66. package/apps/daemon/dist/runtime/boundedProcessHost.d.ts +111 -0
  67. package/apps/daemon/dist/runtime/boundedProcessHost.js +752 -0
  68. package/apps/daemon/dist/runtime/evidenceRedaction.d.ts +30 -0
  69. package/apps/daemon/dist/runtime/evidenceRedaction.js +79 -0
  70. package/apps/daemon/dist/runtime/executionDiagnostics.d.ts +134 -0
  71. package/apps/daemon/dist/runtime/executionDiagnostics.js +213 -0
  72. package/apps/daemon/dist/runtime/modelExecutionPolicy.d.ts +22 -0
  73. package/apps/daemon/dist/runtime/modelExecutionPolicy.js +19 -0
  74. package/apps/daemon/dist/runtime/mxcExecution.d.ts +12 -0
  75. package/apps/daemon/dist/runtime/mxcExecution.js +163 -0
  76. package/apps/daemon/dist/runtime/mxcIntegrity.d.ts +24 -0
  77. package/apps/daemon/dist/runtime/mxcIntegrity.js +81 -0
  78. package/apps/daemon/dist/runtime/mxcWorker.d.ts +2 -0
  79. package/apps/daemon/dist/runtime/mxcWorker.js +45 -0
  80. package/apps/daemon/dist/runtime/provisionedExecution.d.ts +150 -0
  81. package/apps/daemon/dist/runtime/provisionedExecution.js +653 -0
  82. package/apps/daemon/dist/runtime/testExecution.d.ts +76 -0
  83. package/apps/daemon/dist/runtime/testExecution.js +106 -0
  84. package/apps/daemon/dist/runtime/testProfiles.d.ts +10 -0
  85. package/apps/daemon/dist/runtime/testProfiles.js +4 -0
  86. package/apps/daemon/dist/runtime/trustedAgentStaging.d.ts +89 -0
  87. package/apps/daemon/dist/runtime/trustedAgentStaging.js +262 -0
  88. package/apps/daemon/dist/runtime/trustedCaBundle.d.ts +77 -0
  89. package/apps/daemon/dist/runtime/trustedCaBundle.js +125 -0
  90. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.d.ts +166 -0
  91. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.js +521 -0
  92. package/apps/daemon/dist/storage/diagnosticLog.d.ts +63 -0
  93. package/apps/daemon/dist/storage/diagnosticLog.js +136 -0
  94. package/apps/daemon/dist/storage/executionTelemetry.d.ts +63 -0
  95. package/apps/daemon/dist/storage/executionTelemetry.js +247 -0
  96. package/apps/daemon/dist/storage/protectedSecrets.d.ts +39 -0
  97. package/apps/daemon/dist/storage/protectedSecrets.js +106 -0
  98. package/apps/daemon/dist/storage/sqliteLedger.d.ts +786 -0
  99. package/apps/daemon/dist/storage/sqliteLedger.js +1303 -0
  100. package/apps/daemon/dist/transports/http/dispatch.d.ts +43 -0
  101. package/apps/daemon/dist/transports/http/dispatch.js +405 -0
  102. package/apps/daemon/dist/transports/http/secureRoutes.d.ts +40 -0
  103. package/apps/daemon/dist/transports/http/secureRoutes.js +332 -0
  104. package/apps/daemon/dist/transports/http/workflowRoutes.d.ts +41 -0
  105. package/apps/daemon/dist/transports/http/workflowRoutes.js +473 -0
  106. package/apps/daemon/dist/transports/mcp/localProjectReadServer.d.ts +182 -0
  107. package/apps/daemon/dist/transports/mcp/localProjectReadServer.js +221 -0
  108. package/apps/daemon/dist/transports/native/nativeHost.d.ts +24 -0
  109. package/apps/daemon/dist/transports/native/nativeHost.js +344 -0
  110. package/apps/daemon/package.json +24 -0
  111. package/apps/daemon/src/runtime/benign/referenceEcho.mjs +27 -0
  112. package/apps/daemon/src/runtime/windows/buildSupervisor.mjs +87 -0
  113. package/apps/daemon/src/runtime/windows/supervisorMain.cs +676 -0
  114. package/apps/extension/manifest.secure.json +25 -0
  115. package/apps/extension/scripts/build.mjs +173 -0
  116. package/apps/extension/src/background/secureWorker.ts +1595 -0
  117. package/apps/extension/src/background/serviceWorker.ts +892 -0
  118. package/apps/extension/src/content/captureSelection.ts +64 -0
  119. package/apps/extension/src/content/secureInsert.ts +207 -0
  120. package/apps/extension/src/probe/index.html +41 -0
  121. package/apps/extension/src/probe/main.ts +201 -0
  122. package/apps/extension/src/sidepanel/index.html +203 -0
  123. package/apps/extension/src/sidepanel/main.ts +903 -0
  124. package/package.json +19 -3
  125. package/packages/contracts/dist/artifacts.d.ts +66 -0
  126. package/packages/contracts/dist/artifacts.js +64 -0
  127. package/packages/contracts/dist/automation.d.ts +540 -0
  128. package/packages/contracts/dist/automation.js +191 -0
  129. package/packages/contracts/dist/browser.d.ts +251 -0
  130. package/packages/contracts/dist/browser.js +131 -0
  131. package/packages/contracts/dist/context.d.ts +71 -0
  132. package/packages/contracts/dist/context.js +73 -0
  133. package/packages/contracts/dist/diagnostics.d.ts +99 -0
  134. package/packages/contracts/dist/diagnostics.js +284 -0
  135. package/packages/contracts/dist/effects.d.ts +42 -0
  136. package/packages/contracts/dist/effects.js +42 -0
  137. package/packages/contracts/dist/errors.d.ts +75 -0
  138. package/packages/contracts/dist/errors.js +70 -0
  139. package/packages/contracts/dist/events.d.ts +50 -0
  140. package/packages/contracts/dist/events.js +34 -0
  141. package/packages/contracts/dist/executionDiagnostics.d.ts +212 -0
  142. package/packages/contracts/dist/executionDiagnostics.js +101 -0
  143. package/packages/contracts/dist/identity.d.ts +54 -0
  144. package/packages/contracts/dist/identity.js +40 -0
  145. package/packages/contracts/dist/index.d.ts +20 -0
  146. package/packages/contracts/dist/index.js +20 -0
  147. package/packages/contracts/dist/invocation.d.ts +90 -0
  148. package/packages/contracts/dist/invocation.js +77 -0
  149. package/packages/contracts/dist/lifecycle.d.ts +130 -0
  150. package/packages/contracts/dist/lifecycle.js +135 -0
  151. package/packages/contracts/dist/plugin.d.ts +214 -0
  152. package/packages/contracts/dist/plugin.js +117 -0
  153. package/packages/contracts/dist/projectRead.d.ts +205 -0
  154. package/packages/contracts/dist/projectRead.js +162 -0
  155. package/packages/contracts/dist/secure.d.ts +128 -0
  156. package/packages/contracts/dist/secure.js +99 -0
  157. package/packages/contracts/package.json +32 -0
  158. package/packages/contracts/src/artifacts.ts +83 -0
  159. package/packages/contracts/src/automation.ts +238 -0
  160. package/packages/contracts/src/browser.ts +164 -0
  161. package/packages/contracts/src/context.ts +91 -0
  162. package/packages/contracts/src/diagnostics.ts +318 -0
  163. package/packages/contracts/src/effects.ts +49 -0
  164. package/packages/contracts/src/errors.ts +83 -0
  165. package/packages/contracts/src/events.ts +46 -0
  166. package/packages/contracts/src/executionDiagnostics.ts +116 -0
  167. package/packages/contracts/src/identity.ts +68 -0
  168. package/packages/contracts/src/index.ts +20 -0
  169. package/packages/contracts/src/invocation.ts +96 -0
  170. package/packages/contracts/src/lifecycle.ts +169 -0
  171. package/packages/contracts/src/plugin.ts +174 -0
  172. package/packages/contracts/src/projectRead.ts +179 -0
  173. package/packages/contracts/src/secure.ts +136 -0
  174. package/provenance.json +179 -9
  175. package/source.zip +0 -0
@@ -0,0 +1,903 @@
1
+ /**
2
+ * Side panel (C11): untrusted presentation and user input only. It never performs HTTP, never receives
3
+ * the daemon credential and never stores anything. Every action is an explicit button press that sends one
4
+ * typed message to the secure worker; secret inputs are cleared as soon as a request is sent.
5
+ */
6
+
7
+ // Pure diagnostics vocabulary only (a dedicated subpath: no schema library is bundled into the panel).
8
+ import { describeObservedProcess, OPERATION_LABELS, describeFailure, formatDiagEvent, formatFailure, makeDiagEvent, newCorrelationId, type DiagEventV1, type FailureDetailV1 } from '@my-centcom/contracts/diagnostics';
9
+
10
+ const $ = <T extends HTMLElement>(id: string): T => {
11
+ const el = document.getElementById(id);
12
+ if (!el) throw new Error(`missing element ${id}`);
13
+ return el as T;
14
+ };
15
+
16
+ const input = (id: string): HTMLInputElement => $<HTMLInputElement>(id);
17
+
18
+ interface WorkerReply {
19
+ ok?: boolean;
20
+ type?: string;
21
+ code?: string;
22
+ /** The worker's correlated, actionable description of a failure (SW-062). */
23
+ diag?: FailureDetailV1;
24
+ text?: string;
25
+ port?: number;
26
+ runId?: string;
27
+ lifecycleState?: string;
28
+ duplicate?: boolean;
29
+ updatedAt?: string;
30
+ consent?: string;
31
+ /** RETURN_TEXT (SW-065 Copy Result) and REBOUND. */
32
+ returnId?: string; sha256?: string; bytes?: number;
33
+ receipt?: { returnId?: string; runId?: string; sha256?: string; bytes?: number; insertionMode?: string; editor?: string; readback?: string; submission?: string };
34
+ view?: {
35
+ returnId?: string; provenance?: string;
36
+ captureId?: string; text?: string; sha256?: string; bytes?: number; source?: string; state?: string; fidelity?: string;
37
+ attestation?: string; expiresAt?: string; warnings?: string[];
38
+ };
39
+ }
40
+
41
+ /** Panel-side events (memory only, bounded). They are exported together with the worker's events. */
42
+ const panelEvents: DiagEventV1[] = [];
43
+ function plog(level: DiagEventV1['level'], operation: string, event: string, correlationId?: string, meta?: unknown): void {
44
+ panelEvents.push(makeDiagEvent({ level, component: 'PANEL', operation, event, outcome: level === 'INFO' ? 'OK' : 'FAILED', ...(correlationId ? { correlationId } : {}), ...(meta ? { meta } : {}) }));
45
+ if (panelEvents.length > 100) panelEvents.splice(0, panelEvents.length - 100);
46
+ }
47
+
48
+ async function send(message: Record<string, unknown>): Promise<WorkerReply> {
49
+ const type = String(message.type ?? '');
50
+ const unavailable = (why: string): WorkerReply => {
51
+ const corr = newCorrelationId(); // the worker never saw this request, so the panel mints the id and logs it itself
52
+ plog('ERROR', type, 'WORKER_UNAVAILABLE', corr, { why });
53
+ return { ok: false, code: 'WORKER_UNAVAILABLE', diag: describeFailure({ operation: OPERATION_LABELS[type] ?? type, code: 'WORKER_UNAVAILABLE', correlationId: corr, component: 'PANEL', note: why }) };
54
+ };
55
+ try {
56
+ const reply = (await chrome.runtime.sendMessage(message)) as WorkerReply | undefined;
57
+ if (!reply || typeof reply !== 'object') return unavailable('EMPTY_REPLY');
58
+ if (!reply.ok) plog('WARN', type, String(reply.code ?? 'UNKNOWN'), reply.diag?.correlationId);
59
+ return reply;
60
+ } catch {
61
+ return unavailable('SEND_REJECTED');
62
+ }
63
+ }
64
+
65
+ /** Text is written with textContent only: nothing from the worker or daemon is ever interpreted as HTML. */
66
+ function show(id: string, text: string): void {
67
+ $(id).textContent = text;
68
+ }
69
+
70
+ const failureText = (r: WorkerReply): string =>
71
+ formatFailure(r.diag ?? describeFailure({ operation: 'The request', code: String(r.code ?? 'UNKNOWN').slice(0, 40) }));
72
+
73
+ const describe = (r: WorkerReply): string => {
74
+ if (!r.ok) return failureText(r);
75
+ switch (r.type) {
76
+ case 'PAIRED': return `PAIRED 127.0.0.1:${r.port}`;
77
+ case 'CAPTURED': return `CAPTURED ${r.view?.bytes} bytes sha256=${r.view?.sha256} ${r.view?.state}`;
78
+ case 'NO_CAPTURE_HELD': return 'NO_CAPTURE_HELD';
79
+ case 'RETURN_PREPARED': return `RETURN_PREPARED ${r.view?.bytes} bytes sha256=${r.view?.sha256} ${r.view?.state}`;
80
+ case 'NO_RETURN_HELD': return 'NO_RETURN_HELD';
81
+ case 'INSERTED': return `INSERTED ${r.receipt?.bytes} bytes sha256=${r.receipt?.sha256} readback=${r.receipt?.readback} ${r.receipt?.submission}`;
82
+ case 'PREPARED': return `${r.runId} ${r.lifecycleState}${r.duplicate ? ' (duplicate request, same run)' : ''}`;
83
+ case 'CANCEL_ACCEPTED': return `${r.runId} ${r.lifecycleState} (accepted; check status for the final state)`;
84
+ case 'STATUS': return `${r.runId} ${r.lifecycleState}`;
85
+ case 'DECISION': return `${r.runId} ${r.lifecycleState}${r.duplicate ? ' (duplicate, no new event)' : ''}`;
86
+ case 'DISCONNECTED': return 'DISCONNECTED';
87
+ case 'DIAGNOSTICS': return `DIAGNOSTICS ${r.text ? r.text.split('\n').length : 0} lines`;
88
+ // SW-065: the one-click workflow replies (SW-062) were missing here, so every successful Run, rebind, default change or Start over printed
89
+ // UNEXPECTED_REPLY in the status line although the worker had answered correctly. Every reply type the worker can send is named now.
90
+ case 'RUN_STARTED': return `RUN_STARTED ${r.runId} ${r.lifecycleState}${r.duplicate ? ' (duplicate click, same run)' : ''}`;
91
+ case 'REBOUND': return `REBOUND ${r.returnId}`;
92
+ case 'DEFAULT_SAVED': return 'DEFAULT_SAVED';
93
+ case 'DISMISSED': return 'DISMISSED';
94
+ case 'WORKFLOW': return `WORKFLOW ${(r as unknown as { view?: { phase?: string } }).view?.phase ?? ''}`;
95
+ case 'RETURN_TEXT': return `RESULT_RELEASED_FOR_COPY ${r.bytes} bytes`;
96
+ default: return `UNEXPECTED_REPLY type=${String(r.type ?? 'NONE').replace(/[^A-Z_]/g, '').slice(0, 40) || 'NONE'}`;
97
+ }
98
+ };
99
+
100
+ /** One in-flight action at a time: the buttons are disabled until the worker answers. */
101
+ const buttons = ['pair-btn', 'disconnect-btn', 'capture-btn', 'dispatch-btn', 'prepare-btn', 'status-btn', 'approve-btn', 'cancel-btn', 'prepare-return-btn', 'insert-return-btn'];
102
+ let inFlight = false;
103
+
104
+ async function act(message: Record<string, unknown>, target: string, after?: (r: WorkerReply) => void): Promise<void> {
105
+ if (inFlight) return;
106
+ inFlight = true;
107
+ for (const b of buttons) $<HTMLButtonElement>(b).disabled = true;
108
+ try {
109
+ const reply = await send(message);
110
+ show(target, describe(reply));
111
+ show('result', describe(reply));
112
+ after?.(reply);
113
+ } finally {
114
+ for (const b of buttons) $<HTMLButtonElement>(b).disabled = false;
115
+ inFlight = false;
116
+ }
117
+ }
118
+
119
+ $('pair-btn').addEventListener('click', () => {
120
+ const portText = input('port').value.trim();
121
+ if (!/^[0-9]{1,5}$/.test(portText)) {
122
+ plog('WARN', 'PAIR', 'INVALID_FIELD', undefined, { field: 'port' });
123
+ show('conn-status', formatFailure(describeFailure({ operation: OPERATION_LABELS.PAIR, code: 'INVALID_FIELD', component: 'PANEL', fields: [{ field: 'port', reason: portText.length === 0 ? 'EMPTY' : 'BAD_FORMAT' }] })));
124
+ return;
125
+ }
126
+ const message = {
127
+ type: 'PAIR',
128
+ port: Number(portText),
129
+ challengeId: input('challenge-id').value.trim(),
130
+ code: input('pair-code').value.trim(),
131
+ };
132
+ input('pair-code').value = ''; // the one-time code is never kept in the page
133
+ void act(message, 'conn-status');
134
+ });
135
+
136
+ /** Inert preview of the worker-held snapshot: textContent only, a read-only <pre>, never an input. */
137
+ function renderCapture(r: WorkerReply): void {
138
+ const v = r.view;
139
+ if (!r.ok || !v) {
140
+ show('cap-meta', r.ok ? 'Nothing captured.' : failureText(r));
141
+ show('cap-text', '');
142
+ return;
143
+ }
144
+ show('cap-text', String(v.text ?? ''));
145
+ show('cap-meta', [
146
+ `captureId=${v.captureId}`, `${v.bytes} bytes`, `sha256=${v.sha256}`, `source=${v.source}`, `state=${v.state}`, `expires=${v.expiresAt}`,
147
+ `fidelity=${v.fidelity}`, `attestation=${v.attestation}`, ...(v.warnings ?? []).map((w) => `WARNING ${w}`),
148
+ ].join('\n'));
149
+ }
150
+
151
+ $('capture-btn').addEventListener('click', () => {
152
+ // The target is whichever tab is active in the last focused window. The worker re-validates it (allowlisted origin, active, top frame).
153
+ void (async () => {
154
+ const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
155
+ const message = { type: 'CAPTURE', tabId: typeof tab?.id === 'number' ? tab.id : -1, userActivation: navigator.userActivation.isActive };
156
+ await act(message, 'run-status', renderCapture);
157
+ })();
158
+ });
159
+
160
+ /** Inert preview of the worker-held return snapshot: textContent only, a read-only <pre>. */
161
+ function renderReturn(r: WorkerReply): void {
162
+ const v = r.view;
163
+ if (!r.ok || !v) {
164
+ show('ret-meta', r.ok ? 'Nothing prepared.' : failureText(r));
165
+ show('ret-text', '');
166
+ return;
167
+ }
168
+ show('ret-text', String(v.text ?? ''));
169
+ show('ret-meta', [
170
+ `returnId=${v.returnId}`, `${v.bytes} bytes`, `sha256=${v.sha256}`, `source=${v.source}`, `state=${v.state}`, `provenance=${v.provenance}`,
171
+ ...(v.warnings ?? []).map((w) => `WARNING ${w}`),
172
+ ].join('\n'));
173
+ }
174
+
175
+ $('prepare-return-btn').addEventListener('click', () => {
176
+ void act({ type: 'PREPARE_RETURN', runId: input('run-id').value.trim() }, 'run-status', renderReturn);
177
+ });
178
+
179
+ $('insert-return-btn').addEventListener('click', () => {
180
+ // The user's own click is the only trigger; the worker re-validates everything and refuses without it.
181
+ const id = /^returnId=(\S+)/m.exec($('ret-meta').textContent ?? '')?.[1] ?? '';
182
+ const message = { type: 'INSERT_RETURN', returnId: id, userActivation: navigator.userActivation.isActive };
183
+ void act(message, 'run-status', (r) => {
184
+ if (r.ok && r.type === 'INSERTED') show('ret-meta', `${$('ret-meta').textContent ?? ''}\nINSERTED readback=${r.receipt?.readback} ${r.receipt?.submission}`);
185
+ });
186
+ });
187
+
188
+ $('dispatch-btn').addEventListener('click', () => {
189
+ const id = /^captureId=(\S+)/m.exec($('cap-meta').textContent ?? '')?.[1] ?? '';
190
+ const message = { type: 'DISPATCH', captureId: id, projectId: input('cap-project').value.trim(), pluginId: input('cap-plugin').value.trim(), operationId: input('cap-operation').value.trim() };
191
+ void act(message, 'run-status', (r) => {
192
+ if (r.ok && r.type === 'PREPARED' && typeof r.runId === 'string') input('run-id').value = r.runId;
193
+ });
194
+ });
195
+
196
+ $('prepare-btn').addEventListener('click', () => {
197
+ const textarea = $<HTMLTextAreaElement>('prep-prompt');
198
+ const message = {
199
+ type: 'PREPARE',
200
+ projectId: input('prep-project').value.trim(),
201
+ pluginId: input('prep-plugin').value.trim(),
202
+ operationId: input('prep-operation').value.trim(),
203
+ prompt: textarea.value, // exact text: no trimming, no rewriting
204
+ };
205
+ textarea.value = ''; // the prompt is not kept in the page once it has been handed to the worker
206
+ void act(message, 'run-status', (r) => {
207
+ if (r.ok && r.type === 'PREPARED' && typeof r.runId === 'string') input('run-id').value = r.runId;
208
+ });
209
+ });
210
+
211
+ $('disconnect-btn').addEventListener('click', () => {
212
+ void act({ type: 'DISCONNECT' }, 'conn-status');
213
+ });
214
+
215
+ $('status-btn').addEventListener('click', () => {
216
+ void act({ type: 'GET_STATUS', runId: input('run-id').value.trim() }, 'run-status');
217
+ });
218
+
219
+ $('approve-btn').addEventListener('click', () => {
220
+ const message = {
221
+ type: 'APPROVE',
222
+ runId: input('run-id').value.trim(),
223
+ approvalId: input('approval-id').value.trim(),
224
+ approvalCode: input('approval-code').value.trim(),
225
+ };
226
+ input('approval-code').value = ''; // one-time proof is consumed, never retained
227
+ void act(message, 'run-status');
228
+ });
229
+
230
+ $('cancel-btn').addEventListener('click', () => {
231
+ void act({ type: 'CANCEL', runId: input('run-id').value.trim(), reason: input('cancel-reason').value }, 'run-status');
232
+ });
233
+
234
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
235
+ // SW-062 one-click workflow. The panel renders what the worker reports (which in turn is the daemon's durable state) and offers ONE primary action per
236
+ // phase: Run, (local risk confirmation is shown, never clicked here), Insert Draft. Status arrives by a bounded long-poll; there is no "Check status" step.
237
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
238
+
239
+ interface WfOp { projectId: string; pluginId: string; operationId: string; effectClass: string; consent: string; projectLabel?: string; agentLabel?: string; coding?: boolean; strictReady?:boolean }
240
+ interface Activity { runId:string; cursor:string; collectedAt:string; daemonVersion:string; phase:string; startedAt:string; truncated:boolean; events: {id:string;ts:string;component:string;severity:string;status:string;kind:string;summary:string;runId:string}[] }
241
+ interface WfView {
242
+ activity?: Activity | null;
243
+ daemonHealth?:{state:string;version:string;observedAt:string|null;activityFreshness:string};
244
+ version: number; phase: string; connection: string;
245
+ operations: WfOp[]; preferred: { projectId: string; pluginId: string; operationId: string } | null;
246
+ capture: { captureId: string; text: string; sha256: string; bytes: number; source: string; state: string; expiresAt: string; fidelity?: string; lineEndingsNormalized?: number } | null;
247
+ run: { runId: string; lifecycleState: string; consent: string; failure?: { category: string; basis: string; causeDetermined: boolean; correlationId: string } | null } | null;
248
+ ret: { returnId: string; text: string; sha256: string; bytes: number; state: string; code: string | null; rebinds: number } | null;
249
+ problem: FailureDetailV1 | null;
250
+ }
251
+
252
+ let wf: WfView | undefined;
253
+ let wfVersion = -1;
254
+ let editorCapture = '';
255
+ let editorOriginal = '';
256
+ let taskDirty = false;
257
+ const editor = () => $<HTMLTextAreaElement>('task-editor');
258
+ editor().addEventListener('input', () => {
259
+ taskDirty = editor().value !== editorOriginal;
260
+ show('task-fidelity', taskDirty ? 'Edited. Exact UTF-8 text will be verified before dispatch.' : 'Captured preview. Review formatting before running.');
261
+ });
262
+ // Keep literal tabs in the editor instead of moving focus; Shift+Tab retains normal keyboard navigation.
263
+ editor().addEventListener('keydown', e => {
264
+ if (e.key === 'Tab' && !e.shiftKey) { e.preventDefault(); editor().setRangeText('\t', editor().selectionStart, editor().selectionEnd, 'end'); editor().dispatchEvent(new Event('input')); }
265
+ });
266
+
267
+ const friendly = (id:string) => id.replace(/^(project|plugin|op)\./, '').replace(/[._-]+/g, ' ');
268
+ function renderSelectors(v:WfView) {
269
+ const project = $<HTMLSelectElement>('task-project'), agent = $<HTMLSelectElement>('task-agent');
270
+ const selected = selectedTrustTarget() ?? v.operations.find(o => v.preferred && opKey(o) === opKey(v.preferred)) ?? v.operations[0];
271
+ const options = (sel:HTMLSelectElement, entries:{value:string;label:string}[], value?:string) => {
272
+ const signature = JSON.stringify(entries);
273
+ if (sel.dataset.items !== signature) { sel.textContent = ''; for (const item of entries) { const o = document.createElement('option'); o.value=item.value; o.textContent=item.label; sel.appendChild(o); } sel.dataset.items=signature; }
274
+ if (value !== undefined) sel.value=value;
275
+ };
276
+ const projects = [...new Map(v.operations.map(o=>[o.projectId,o])).values()];
277
+ options(project,projects.map(o=>({value:o.projectId,label:o.projectLabel ?? friendly(o.projectId)})),selected?.projectId);
278
+ options(agent,v.operations.filter(o=>o.projectId===project.value).map(o=>({value:opKey(o),label:o.agentLabel ?? `${friendly(o.pluginId)} (${friendly(o.operationId)})`})),selected ? opKey(selected) : undefined);
279
+ project.disabled = agent.disabled = !['NO_CAPTURE','CAPTURED'].includes(v.phase) || wfInFlight;
280
+ }
281
+ function selectTaskOperation() {
282
+ const project=$<HTMLSelectElement>('task-project'), agent=$<HTMLSelectElement>('task-agent');
283
+ const o=wf?.operations.find(o=>opKey(o)===agent.value && o.projectId===project.value) ?? wf?.operations.find(o=>o.projectId===project.value);
284
+ if (!o) return;
285
+ $<HTMLSelectElement>('wf-op').value=opKey(o);
286
+ input('wf-coding-mode').checked=o.coding === true;
287
+ $('wf-op').dispatchEvent(new Event('change'));
288
+ }
289
+ $('task-project').addEventListener('change',selectTaskOperation);
290
+ $('task-agent').addEventListener('change',selectTaskOperation);
291
+ let advancedTouched = false;
292
+ $('advanced').addEventListener('toggle', () => { advancedTouched = true; });
293
+
294
+ const opKey = (o: { projectId: string; pluginId: string; operationId: string }): string => `${o.projectId} ${o.pluginId} ${o.operationId}`;
295
+ const shortHost = (u: string): string => { try { const x = new URL(u); return `${x.origin}${x.pathname.length > 1 ? ' (conversation)' : ''}`; } catch { return 'the source tab'; } };
296
+
297
+ const PHASE_TEXT: Record<string, string> = {
298
+ CONNECTING: 'Connecting to the local daemon...',
299
+ REPAIR: 'Not connected to the local daemon.',
300
+ NO_CAPTURE: 'Select an instruction on the page, then click the my-centcom toolbar icon. Or copy it with the message\'s Copy button, click the toolbar icon on that conversation, then "Paste copied text".',
301
+ CAPTURED: 'Captured. Review the text, then click Run.',
302
+ AWAITING_RISK_APPROVAL: 'Waiting for your local confirmation.',
303
+ QUEUED: 'Queued...',
304
+ RUNNING: 'Running...',
305
+ COMPLETED: 'Completed. Preparing the result...',
306
+ RETURN_READY: 'Result ready. Review it, then click Insert Draft, or Copy Result and paste it yourself.',
307
+ INSERTED_UNSENT: 'Inserted as an UNSENT draft. Review it in the conversation and send it yourself.',
308
+ RETURN_STALE: 'The original conversation tab changed, so nothing was inserted.',
309
+ INSERT_FAILED: 'Insert Draft failed; nothing was sent and the result is kept. Click Copy Result, then paste it into the message box yourself (Ctrl+V).',
310
+ FAILED: 'The run failed. Nothing was returned.',
311
+ UNKNOWN: 'The run outcome is UNKNOWN (for example the daemon stopped during it). It is never restarted automatically.',
312
+ CANCELLED: 'The run was cancelled.',
313
+ };
314
+
315
+ /** Phases in which a finished result is held and can be copied (an insertion failure never loses it; copying never changes the phase). */
316
+ const RESULT_PHASES = ['RETURN_READY', 'INSERT_FAILED', 'RETURN_STALE', 'INSERTED_UNSENT'];
317
+ /** Phases in which a new paste may start a new task (never while a run or an un-inserted result is pending, so a result is not pushed out of view). */
318
+ const PASTE_PHASES = ['NO_CAPTURE', 'CAPTURED', 'INSERTED_UNSENT', 'FAILED', 'CANCELLED', 'UNKNOWN'];
319
+
320
+ /** The last failed action in this panel (cleared by the next successful one), so a refresh never erases the only explanation the user got. */
321
+ let actionFailure: WorkerReply | undefined;
322
+ /**
323
+ * Copy Result outcome per return id (panel memory only): the latest receipt or failure, and how many copies succeeded. A receipt describes what THIS
324
+ * panel wrote to the clipboard; nothing is claimed beyond that (not inserted, not sent).
325
+ */
326
+ const copyReceipts = new Map<string, { line: string; count: number }>();
327
+ /** What the user's last paste looked like before it was sent (panel memory only): shown next to the preview of the capture it produced. */
328
+ let pasteInfo: { text: string; crToLf: number; html: boolean; markdownHint: boolean } | undefined;
329
+ let copyInFlight = false;
330
+
331
+ function captureDescription(c: NonNullable<WfView['capture']>): string[] {
332
+ if (c.fidelity === 'EDITED_TASK_TEXT') return [`Edited task: ${c.bytes} UTF-8 bytes; durable preview verified. Original page source is not inferred.`];
333
+ if (c.fidelity === 'PASTED_PLAIN_TEXT') {
334
+ const out = [`${c.bytes} bytes you pasted (the plain-text clipboard content), for the conversation ${shortHost(c.source)}. Text copied with the assistant message's own Copy button is normally its Markdown source; that is not verified.`];
335
+ // SW-066: the normalization count is part of the stored capture (it survives a refresh and a restart), not just this panel's memory.
336
+ if ((c.lineEndingsNormalized ?? 0) > 0) out.push(`Line breaks normalized: ${c.lineEndingsNormalized} Windows CRLF/CR line break(s) became LF. Nothing else was changed.`);
337
+ else out.push('Line breaks: no CRLF/CR was converted; the text is exactly what the clipboard held.');
338
+ if (pasteInfo && pasteInfo.text === c.text) {
339
+ if (pasteInfo.html) out.push('The clipboard also held an HTML version; it was ignored (plain text only, never HTML).');
340
+ out.push(pasteInfo.markdownHint ? 'Markdown syntax detected (heuristic): it is kept exactly as typed characters.' : 'No Markdown syntax detected (heuristic).');
341
+ }
342
+ return out;
343
+ }
344
+ return [
345
+ `${c.bytes} bytes from ${shortHost(c.source)}. Rendered selection text (not the original Markdown source).`,
346
+ 'Source limitation: a selection carries only what the page displays. Markdown markers such as code fences cannot be recovered from it and are not added back. To keep them, use the message\'s own Copy button and "Paste copied text".',
347
+ ];
348
+ }
349
+
350
+ let trustState: { key: string; scopeKey: string; challenge: string; warningVersion: 'trusted-cli-proposal-v1'; enabled: boolean; expiresAt?:number } | undefined;
351
+ let trustKey = '';
352
+ const trustedMode = () => $<HTMLSelectElement>('model-mode').value === 'TRUSTED_LOCAL_CLI_PROPOSAL_ONLY';
353
+ function selectedTrustTarget() { return wf?.operations.find(x => opKey(x) === $<HTMLSelectElement>('wf-op').value); }
354
+ async function refreshTrust() {
355
+ const o = selectedTrustTarget(); const key = o ? opKey(o) : '';
356
+ trustState = undefined;
357
+ $('trusted-cli').hidden = !trustedMode();
358
+ if (!o || !trustedMode()) return;
359
+ const r = await send({ type: 'TRUSTED_CONSENT', projectId: o.projectId, pluginId: o.pluginId, operationId: o.operationId, action: 'status', userActivation: false });
360
+ if (!trustedMode() || opKey(selectedTrustTarget() ?? o) !== key) return;
361
+ const d = (r as unknown as { data?: { scopeKey: string; challenge: string; warningVersion: 'trusted-cli-proposal-v1'; enabled: boolean; expiresAt?:number; warning: string; cliSha256: string } }).data;
362
+ if (r.ok && d) { trustState = { key, scopeKey: d.scopeKey, challenge: d.challenge, warningVersion: d.warningVersion, enabled: d.enabled, expiresAt:d.expiresAt }; show('trusted-warning', d.warning); show('trusted-status', (d.enabled ? 'Enabled with scoped consent' : 'Disabled - separate consent required') + '. CLI SHA-256: ' + d.cliSha256); }
363
+ else show('trusted-status', 'Unavailable - authenticated project/operation consent could not be read.');
364
+ $<HTMLButtonElement>('trusted-accept').disabled = !trustState || !input('trusted-ack').checked;
365
+ $<HTMLButtonElement>('trusted-revoke').disabled = !trustState?.enabled;
366
+ if (wf) renderWorkflow(wf);
367
+ }
368
+ async function decideTrust(action: 'accept' | 'revoke', activation: boolean) {
369
+ const o = selectedTrustTarget(), t = trustState;
370
+ if (!o || !t || t.key !== opKey(o) || !activation || (action === 'accept' && !input('trusted-ack').checked)) return;
371
+ const fresh = await send({ type: 'TRUSTED_CONSENT', projectId: o.projectId, pluginId: o.pluginId, operationId: o.operationId, action: 'status', userActivation: false });
372
+ const d = (fresh as unknown as { data?: { scopeKey: string; challenge: string; warningVersion: string } }).data;
373
+ if (!fresh.ok || !d || d.scopeKey !== t.scopeKey || d.warningVersion !== t.warningVersion) { input('trusted-ack').checked = false; await refreshTrust(); show('trusted-status', 'Configuration changed. Review trust settings again.'); return; }
374
+ const r = await send({ type: 'TRUSTED_CONSENT', projectId: o.projectId, pluginId: o.pluginId, operationId: o.operationId, action, challenge: d.challenge, warningVersion: t.warningVersion, userActivation: activation });
375
+ input('trusted-ack').checked = false;
376
+ await refreshTrust();
377
+ if (!r.ok) show('trusted-status', 'Consent refused. Review the current project and CLI again.');
378
+ }
379
+ $('model-mode').addEventListener('change', () => { trustState = undefined; trustKey = 'changed'; input('trusted-ack').checked = false; if (wf) renderWorkflow(wf); });
380
+ $('review-trust').addEventListener('click',()=>{
381
+ $<HTMLSelectElement>('model-mode').value='TRUSTED_LOCAL_CLI_PROPOSAL_ONLY';
382
+ $('model-mode').dispatchEvent(new Event('change'));
383
+ });
384
+ $('wf-coding-mode').addEventListener('change', () => { if (wf) renderWorkflow(wf); });
385
+ $('trusted-ack').addEventListener('change', () => { $<HTMLButtonElement>('trusted-accept').disabled = !trustState || !input('trusted-ack').checked; });
386
+ $('trusted-accept').addEventListener('click', () => { void decideTrust('accept', navigator.userActivation.isActive); });
387
+ $('trusted-revoke').addEventListener('click', () => { void decideTrust('revoke', navigator.userActivation.isActive); });
388
+ function renderWorkflow(v: WfView): void {
389
+ wf = v;
390
+ // A previous proposal review must not hide this task's ordinary return controls.
391
+ $('wf-primary').hidden = false;
392
+ if (!v.run) { codingView = undefined; $('coding-review').hidden = true; $('wf-primary').hidden = false; }
393
+ const lines: string[] = [];
394
+ let text = '';
395
+ if (v.phase === 'CAPTURED' && v.capture) { text = v.capture.text; lines.push(...captureDescription(v.capture)); }
396
+ else if (v.ret && RESULT_PHASES.includes(v.phase)) { text = v.ret.text; lines.push(`${v.ret.bytes} bytes, sha256 ${v.ret.sha256.slice(0, 12)}..., reported by the operation (not verified output).`); }
397
+ else if (v.capture && v.capture.state === 'CAPTURED_NOT_STORED') { text = v.capture.text; lines.push('Captured locally; it will be stored once the connection is repaired.'); }
398
+ if (v.phase === 'AWAITING_RISK_APPROVAL') lines.push('This operation needs a separate confirmation on this computer. In a terminal run: npm run centcom -- confirm');
399
+ if (v.phase === 'RETURN_STALE') lines.push('Open the conversation where you want the draft, click the toolbar icon there, then "Use this tab for the result" (the operation is not run again). Or click Copy Result and paste it wherever you choose.');
400
+ if (v.run && v.phase !== 'CAPTURED') lines.push(`Run ${v.run.lifecycleState}${v.run.consent === 'RUN_CLICK' ? ' (started by your Run click)' : ''}.`);
401
+ // SW-068: a failed execution shows its category, whether the cause is known, and the correlation id its evidence is stored under (npm run centcom -- diagnose <id>).
402
+ if (v.run?.failure) lines.push(`Execution failure: ${v.run.failure.category} (${v.run.failure.causeDetermined ? 'cause observed' : v.run.failure.basis === 'INFERRED' ? 'cause only inferred' : 'cause NOT determined'}). Reference ${v.run.failure.correlationId}; details: npm run centcom -- diagnose ${v.run.failure.correlationId}`);
403
+ if (v.problem) lines.push('', formatFailure(v.problem));
404
+ if (actionFailure && actionFailure.diag?.correlationId !== v.problem?.correlationId) lines.push('', failureText(actionFailure));
405
+ show('wf-status', v.phase === 'CAPTURED' && v.capture?.fidelity === 'PASTED_PLAIN_TEXT' ? 'Captured from your paste. Review the text, then click Run.' : PHASE_TEXT[v.phase] ?? v.phase);
406
+ show('wf-detail', lines.join('\n'));
407
+ show('wf-next', v.problem?.action ?? (actionFailure && !actionFailure.ok ? 'Action failed. Open diagnostics for the recorded reason; task and result are retained.' : v.phase === 'CAPTURED' ? 'Review project, agent and exact task, then Run task. Execution permissions are in Advanced; strict mode is the default.' : 'Review the current activity and available action.'));
408
+ show('wf-text', text);
409
+ if (v.capture && editorCapture !== v.capture.captureId) {
410
+ editorCapture=v.capture.captureId; editorOriginal=v.capture.text; editor().value=v.capture.text; taskDirty=false;
411
+ if (editor().value !== v.capture.text) show('wf-next','Fidelity warning: the browser editor cannot represent the original line endings exactly. Review and explicitly approve the displayed text.');
412
+ show('task-fidelity', `${v.capture.fidelity === 'EDITED_TASK_TEXT' ? 'Edited' : 'Captured'} preview: ${v.capture.bytes} UTF-8 bytes. ${v.capture.fidelity === 'CAPTURED_RENDERED_TEXT' ? 'Fidelity warning: rendered selection may omit source formatting; correct here or paste Markdown source.' : 'Whitespace and literal characters retained; review before Run.'}`);
413
+ }
414
+ editor().disabled = v.phase !== 'CAPTURED' || wfInFlight;
415
+ editor().hidden = !v.capture || !['CAPTURED','REPAIR'].includes(v.phase);
416
+ renderActivity(v);
417
+ const hasResult = Boolean(v.ret) && RESULT_PHASES.includes(v.phase);
418
+ $('wf-text').hidden = !hasResult;
419
+ $('wf-copy').hidden = !hasResult;
420
+ $('wf-select').hidden = !hasResult;
421
+ const receipt = hasResult && v.ret ? copyReceipts.get(v.ret.returnId) : undefined;
422
+ if (!copyInFlight) show('wf-copy-status', receipt ? `${receipt.line}${receipt.count > 1 && receipt.line.startsWith('COPIED_TO_CLIPBOARD') ? ` (copied ${receipt.count} times; same bytes each time)` : ''}` : '');
423
+ const canPaste = PASTE_PHASES.includes(v.phase);
424
+ $('wf-paste').hidden = !canPaste;
425
+ if (!canPaste) $('wf-paste-area').hidden = true;
426
+
427
+ const sel = $<HTMLSelectElement>('wf-op');
428
+ const want = v.operations.map(opKey).join('|');
429
+ if (sel.dataset.ops !== want) {
430
+ sel.textContent = '';
431
+ for (const o of v.operations) {
432
+ const opt = document.createElement('option');
433
+ opt.value = opKey(o);
434
+ opt.textContent = `${o.pluginId} / ${o.operationId} (${o.effectClass}${o.consent === 'RUN_CLICK' ? '' : ', needs local confirmation'}) in ${o.projectId}`;
435
+ sel.appendChild(opt);
436
+ }
437
+ sel.dataset.ops = want;
438
+ if (v.preferred) sel.value = opKey(v.preferred);
439
+ input('wf-coding-mode').checked = v.operations.find(o=>opKey(o)===sel.value)?.coding === true;
440
+ }
441
+ $('wf-op-label').hidden = true;
442
+ renderSelectors(v);
443
+
444
+ const primary = $<HTMLButtonElement>('wf-primary');
445
+ const label: Record<string, string> = { CAPTURED: 'Run task', RETURN_READY: 'Insert Draft', INSERT_FAILED: 'Insert Draft', REPAIR: 'Repair connection' };
446
+ primary.textContent = label[v.phase] ?? (v.phase === 'RUNNING' || v.phase === 'QUEUED' ? 'Running...' : v.phase === 'INSERTED_UNSENT' ? 'Done' : 'Run');
447
+ primary.disabled = !(v.phase in label) || (v.phase === 'CAPTURED' && v.operations.length === 0);
448
+ $('wf-rebind').hidden = v.phase !== 'RETURN_STALE';
449
+ $('wf-dismiss').hidden = !(v.capture && v.capture.captureId && !['RUNNING', 'QUEUED'].includes(v.phase));
450
+ $('wf-repair').hidden = v.phase === 'REPAIR'; // in REPAIR it is the primary action
451
+ // Without the one-time setup the manual recovery controls are the only way in: show them (unless the user closed the section).
452
+ if (v.phase === 'REPAIR' && !advancedTouched) ($('advanced') as HTMLDetailsElement).open = true;
453
+ const key = trustedMode() ? (selectedTrustTarget() ? opKey(selectedTrustTarget()!) : '') : '';
454
+ if (key !== trustKey) { trustKey = key; input('trusted-ack').checked = false; void refreshTrust(); }
455
+ if (trustState?.enabled && trustState.expiresAt && trustState.expiresAt <= Date.now()) { trustState.enabled=false; show('trusted-status','Consent expired. Review and approve the current scoped warning again.'); }
456
+ if (trustedMode() && v.phase === 'CAPTURED') primary.disabled = !input('wf-coding-mode').checked || !trustState?.enabled || trustState.key !== key;
457
+ const strictUnavailable = selectedTrustTarget()?.strictReady === false && !trustedMode() && v.phase === 'CAPTURED';
458
+ $('strict-readiness').hidden = $('review-trust').hidden = !strictUnavailable;
459
+ if (strictUnavailable) primary.disabled = true;
460
+
461
+ }
462
+
463
+ const sleepMs = (ms: number) => new Promise((r) => setTimeout(r, ms));
464
+ let wfInFlight = false;
465
+
466
+ interface CodingProposalView {
467
+ executionMode?: string;
468
+ operations?: {path:string;contentSha256?:string}[];
469
+ testExecutionAvailable: boolean;
470
+ proposalId: string; runId: string; digest: string; status: string; summary: string; diff: string; target: string; preimagesValid: boolean;
471
+ actions: { action: string; result: { ok?: boolean; passed?: boolean; code?: string; state?: string; commit?: string; summary?: { tests: number; pass: number; fail: number }; evidence?: { match: boolean; changes?: { path: string }[] } } | null }[];
472
+ result: { text: string; sha256: string; bytes: number; kind?: string } | null;
473
+ reviewedPatch?: { projectId: string; target: string; baseHead: string; digest: string; challenge: string; expiresAt: number; state: string; eligible: boolean };
474
+ proposalResult: { text: string; sha256: string; bytes: number; kind: 'PROPOSAL_ONLY_UNVERIFIED' } | null;
475
+ }
476
+ let codingView: CodingProposalView | undefined;
477
+ let codingAction = '';
478
+ let codingBusy = false;
479
+ let codingActionFailure: { runId: string; text: string } | undefined;
480
+ async function refreshCoding(runId: string): Promise<boolean> {
481
+ const reply = await send({ type: 'CODING_STATUS', runId });
482
+ if (wf?.run?.runId !== runId) return false; // discard a late response for an older task
483
+ const data = (reply as unknown as { data?: { proposals?: CodingProposalView[]; coding?: boolean; lifecycleState?: string } }).data;
484
+ const p = data?.proposals?.[0];
485
+ if (!reply.ok || !p) {
486
+ codingView = undefined; $('coding-review').hidden = !data?.coding;
487
+ for (const id of ['reviewed-patch', 'reviewed-confirmation', 'local-commit']) $(id).hidden = true;
488
+ if (data?.coding) {
489
+ // A completed run without a proposal may still have a genuine immutable
490
+ // final-text return. Insertion does not imply a validated coding proposal.
491
+ const hasReturn = Boolean(wf?.ret) && RESULT_PHASES.includes(wf!.phase);
492
+ $('wf-primary').hidden = !hasReturn; $('wf-copy').hidden = !hasReturn;
493
+ show('coding-status', `Coding agent: ${data.lifecycleState}. No valid proposal is available.`);
494
+ show('coding-detail', 'No implementation, test or commit has been authorized. Agent output is not a verified coding result.');
495
+ show('coding-diff', ''); show('coding-result', '');
496
+ for (const id of ['coding-primary', 'coding-reject', 'coding-copy', 'coding-copy-proposal']) $(id).hidden = true;
497
+ $<HTMLButtonElement>('coding-commit').disabled = true;
498
+ }
499
+ // A stable absent coding surface is not a transient transport failure (e.g. a read-only reference operation).
500
+ // Reconsider it when run/evidence/connection changes, rather than retrying it on every quiet notification.
501
+ return reply.ok === true || reply.code === 'NOT_FOUND';
502
+ }
503
+ codingView = p; $('coding-review').hidden = false;
504
+ const agentReturn = Boolean(wf?.ret) && RESULT_PHASES.includes(wf!.phase);
505
+ $('wf-primary').hidden = !agentReturn; $('wf-copy').hidden = !agentReturn;
506
+ show('coding-status', `Coding workflow: ${p.status}`);
507
+ show('coding-diff', p.diff);
508
+ if (p.executionMode === 'TRUSTED_LOCAL_CLI_PROPOSAL_ONLY') show('coding-status', 'Trusted local CLI proposal - UNVERIFIED; tests not run. OS confidentiality isolation is not provided.');
509
+ const done = (action: string) => p.actions.find((a) => a.action === action)?.result;
510
+ codingAction = p.status === 'SUBMITTED' ? 'apply' : p.status === 'APPLIED' && !done('test') ? 'test' : done('test') && !done('git') ? 'git' : done('git') && !p.result ? 'finalize' : '';
511
+ if (p.executionMode === 'TRUSTED_LOCAL_CLI_PROPOSAL_ONLY') codingAction = '';
512
+ const effect = ({ apply: 'Copy Proposal ends with an untested proposal, without applying changes. Approve Changes separately applies the exact patch to a disposable clone; tests and commits require separate approval.', test: 'Execute the reviewed node-test-v1 profile in MXC. Synthetic engineering acceptance only; production isolation remains unverified.', git: 'Read Git status, diff and content digests to compare actual changes with the approved proposal.', finalize: 'Seal an immutable result from the recorded apply, test and Git evidence.' } as Record<string, string>)[codingAction] ?? 'Review the recorded outcome.';
513
+ const outcomes = p.actions.map((a) => {
514
+ const r = a.result; if (!r) return `${a.action}: pending or uncertain; it will not be retried automatically.`;
515
+ if (r.ok === false) return `${a.action}: refused (${r.code ?? 'unknown reason'}).`;
516
+ if (a.action === 'test') return `Tests ${r.passed ? 'passed' : 'failed'}: ${r.summary?.pass ?? 0}/${r.summary?.tests ?? 0} assertions passed; ${r.summary?.fail ?? 0} failed.`;
517
+ if (a.action === 'git') return `Git ${r.evidence?.match ? 'matches' : 'does not match'} the approved proposal. Changed files: ${r.evidence?.changes?.map((c) => c.path).join(', ') ?? 'see evidence'}.`;
518
+ return `${a.action}: ${r.commit ?? r.state ?? 'recorded'}.`;
519
+ });
520
+ const target = p.reviewedPatch ? `Registered application project: ${p.reviewedPatch.projectId}\nTarget repository: ${p.reviewedPatch.target}` : `Target disposable clone: ${p.target}`;
521
+ show('coding-detail', `${p.summary}\n${target}\nProposal SHA-256: ${p.digest}\nNext effect: ${effect}\n${outcomes.join('\n')}`);
522
+ const primary = $<HTMLButtonElement>('coding-primary');
523
+ primary.hidden = !codingAction; primary.disabled = codingBusy || (codingAction === 'apply' && !p.preimagesValid) || (codingAction === 'test' && !p.testExecutionAvailable) || p.actions.some((a) => a.result === null);
524
+ primary.textContent = ({ apply: 'Approve Changes', test: 'Authorize Tests (node-test-v1)', git: 'Authorize Git Evidence', finalize: 'Review Result' } as Record<string, string>)[codingAction] ?? '';
525
+ if (codingAction === 'test' && !p.testExecutionAvailable) show('coding-status', 'Tests blocked: production MXC security verification is incomplete (native capability review and off-host UDP). No test process will be launched.');
526
+ $('coding-reject').hidden = p.status !== 'SUBMITTED';
527
+ $<HTMLButtonElement>('coding-commit').disabled = codingBusy || done('test')?.passed !== true || done('git')?.evidence?.match !== true || !!p.result || p.status === 'COMMITTED';
528
+ $('coding-copy').hidden = !p.result; show('coding-result', p.result?.text ?? '');
529
+ $('coding-copy-proposal').hidden = p.status !== 'SUBMITTED' && !p.proposalResult;
530
+ $<HTMLButtonElement>('coding-copy-proposal').disabled = codingBusy || (!p.proposalResult && !p.preimagesValid);
531
+ if (p.proposalResult && !p.result) { show('coding-status', 'Proposal only — UNVERIFIED. No changes applied, tests run or commit created.'); show('coding-result', p.proposalResult.text); }
532
+ const review = p.reviewedPatch;
533
+ $('reviewed-patch').hidden = !review;
534
+ if (review) {
535
+ show('reviewed-scope', `Separate reviewed-patch transaction: ${review.state}\nProject: ${review.projectId}\nTarget: ${review.target}\nExpected HEAD: ${review.baseHead}\nExact proposal: ${p.proposalId}\nSHA-256: ${review.digest}\nApproval scope: APPLY + GIT_READ only. NOT TESTED. NOT COMMITTED.`);
536
+ $<HTMLButtonElement>('reviewed-apply').disabled = codingBusy || !review.eligible;
537
+ if (!review.eligible) $('reviewed-confirmation').hidden = true;
538
+ if (review.state !== 'APPROVAL_REQUIRED') show('coding-status', `Reviewed patch: ${review.state}. No tests or commit.`);
539
+ // Never parse model-controlled source using text delimiters: source comments may contain them.
540
+ // Before application the daemon supplies the exact live-preimage diff; afterward retain the full immutable proposal.
541
+ if (p.proposalResult && !p.preimagesValid) show('coding-diff', p.proposalResult.text);
542
+ }
543
+ if (p.result?.kind === 'APPLIED_UNTESTED_RESULT') show('coding-status', 'APPLIED — NOT TESTED — NOT COMMITTED. Independent Git verification matched.');
544
+ $('local-commit').hidden=p.result?.kind!=='APPLIED_UNTESTED_RESULT';
545
+ if(p.result?.kind==='COMMITTED_UNTESTED_RESULT')show('coding-status','COMMITTED — NOT TESTED — LOCAL ONLY');
546
+ const commitAction=p.actions.find(a=>a.action==='reviewed_commit');
547
+ $<HTMLButtonElement>('local-commit-review').disabled=codingBusy||!!commitAction;
548
+ if(commitAction)$('local-commit-confirm').hidden=true;
549
+ if(commitAction&&p.result?.kind!=='COMMITTED_UNTESTED_RESULT')show('coding-status',commitAction.result===null||commitAction.result.ok===true?'COMMIT_UNRESOLVED — verified committed result unavailable.':`Commit ${commitAction.result.state??'COMMIT_REFUSED'}: ${commitAction.result.code??'inspect durable evidence'}`);
550
+ if (codingActionFailure?.runId === p.runId) show('coding-status', codingActionFailure.text);
551
+ return true;
552
+ }
553
+ async function actCoding(action: string): Promise<void> {
554
+ const p = codingView; if (!p || codingBusy) return;
555
+ const activation = navigator.userActivation.isActive; codingBusy = true;
556
+ codingActionFailure = undefined;
557
+ try {
558
+ const r = await send({ type: 'CODING_ACTION', runId: p.runId, proposalId: p.proposalId, digest: p.digest, action, userActivation: activation });
559
+ if (!r.ok) codingActionFailure = { runId: p.runId, text: failureText(r) };
560
+ await refreshCoding(p.runId);
561
+ } finally { codingBusy = false; if (codingView) await refreshCoding(codingView.runId); }
562
+ }
563
+ $('coding-primary').addEventListener('click', () => { if (codingAction) void actCoding(codingAction); });
564
+ $('coding-reject').addEventListener('click', () => { void actCoding('reject'); });
565
+ $('coding-commit').addEventListener('click', () => { void actCoding('commit'); });
566
+ $('reviewed-apply').addEventListener('click', () => { $('reviewed-confirmation').hidden = false; });
567
+ async function reviewedPatchAction(action: 'apply' | 'cancel', activation: boolean): Promise<void> {
568
+ const p = codingView, r = p?.reviewedPatch; if (!p || !r || codingBusy || !activation) return;
569
+ codingBusy = true; $('reviewed-confirmation').hidden = true;
570
+ show('coding-status', action === 'apply' ? 'Application in progress — verifying approval and Git state.' : 'Cancelling application.');
571
+ $<HTMLButtonElement>('reviewed-apply').disabled = true;
572
+ try {
573
+ const response = await send({ type: 'REVIEWED_PATCH', runId: p.runId, proposalId: p.proposalId, projectId: r.projectId, digest: p.digest, baseHead: r.baseHead, challenge: r.challenge, action, userActivation: activation });
574
+ if (!response.ok) codingActionFailure = { runId: p.runId, text: failureText(response) };
575
+ else {
576
+ const data = (response as unknown as { data?: { result?: { ok: boolean; code?: string } } }).data;
577
+ if (data?.result?.ok === false) codingActionFailure = { runId: p.runId, text: `Application refused or unresolved: ${data.result.code}. No successful result is claimed.` };
578
+ }
579
+ } finally { codingBusy = false; await refreshCoding(p.runId); }
580
+ }
581
+ $('reviewed-confirm').addEventListener('click', () => { void reviewedPatchAction('apply', navigator.userActivation.isActive); });
582
+ $('reviewed-cancel').addEventListener('click', () => { void reviewedPatchAction('cancel', navigator.userActivation.isActive); });
583
+ let commitReceipt: {challenge:string;message:string;proposalId:string}|undefined;
584
+ $('local-commit-review').addEventListener('click',()=>{
585
+ const p=codingView;if(!p||codingBusy)return;const message=$<HTMLTextAreaElement>('local-commit-message').value,activation=navigator.userActivation.isActive;
586
+ commitReceipt=undefined;$('local-commit-confirm').hidden=true;
587
+ void send({type:'REVIEWED_COMMIT',runId:p.runId,proposalId:p.proposalId,message,challenge:'0'.repeat(64),review:true,userActivation:activation}).then(r=>{
588
+ const result=(r as unknown as {data?:{result?:{challenge:string;message:string;target:string;parent:string;branch:string;identity:string}}}).data?.result;
589
+ if(!r.ok||!result){show('local-commit-scope','COMMIT_REFUSED: review unavailable.');return;}
590
+ commitReceipt={challenge:result.challenge,message:result.message,proposalId:p.proposalId};show('local-commit-scope',`Target: ${result.target}\nBranch: ${result.branch}\nExpected HEAD: ${result.parent}\nApproved files: ${p.operations?.map(o=>o.path+' '+(o.contentSha256??'')).join('\n')??'see exact proposal'}\nIdentity: ${result.identity}\nMessage: ${result.message}\nSeparate COMMIT authority. NOT TESTED. LOCAL ONLY.`);$('local-commit-confirm').hidden=false;
591
+ });
592
+ });
593
+ $('local-commit-confirm').addEventListener('click',()=>{
594
+ const p=codingView,r=commitReceipt;if(!p||!r||p.proposalId!==r.proposalId||$<HTMLTextAreaElement>('local-commit-message').value.trim()!==r.message)return;
595
+ const activation=navigator.userActivation.isActive;commitReceipt=undefined;codingBusy=true;$('local-commit-confirm').hidden=true;show('coding-status','COMMIT_IN_PROGRESS — local only, not tested.');
596
+ void send({type:'REVIEWED_COMMIT',runId:p.runId,proposalId:p.proposalId,message:r.message,challenge:r.challenge,review:false,userActivation:activation}).then(async response=>{if(!response.ok)show('local-commit-scope','COMMIT_UNRESOLVED or refused; inspect durable status.');codingBusy=false;await refreshCoding(p.runId);});
597
+ });
598
+ $('coding-copy-proposal').addEventListener('click', () => {
599
+ const p = codingView; if (!p || codingBusy) return;
600
+ const activation = navigator.userActivation.isActive;
601
+ const raw = (async () => {
602
+ if (!p.proposalResult) {
603
+ const sealed = await send({ type: 'CODING_ACTION', runId: p.runId, proposalId: p.proposalId, digest: p.digest, action: 'proposal', userActivation: activation });
604
+ if (!sealed.ok) throw new Error('Proposal unavailable');
605
+ }
606
+ const r = await send({ type: 'CODING_STATUS', runId: p.runId });
607
+ const result = (r as unknown as { data?: { proposals?: CodingProposalView[] } }).data?.proposals?.find(v => v.proposalId === p.proposalId)?.proposalResult;
608
+ if (!r.ok || !result || result.kind !== 'PROPOSAL_ONLY_UNVERIFIED' || await sha256Hex(result.text) !== result.sha256 || new TextEncoder().encode(result.text).length !== result.bytes) throw new Error('Proposal integrity failed');
609
+ return new Blob([result.text], { type: 'text/plain' });
610
+ })();
611
+ void writePlainClipboard(raw).then(() => refreshCoding(p.runId).then(() => show('coding-status', 'Copied raw proposal — UNVERIFIED; no tests or commit.')), () => show('coding-status', 'Copy failed; the proposal remains available.'));
612
+ });
613
+ $('coding-copy').addEventListener('click', () => {
614
+ const p = codingView; if (!p?.result) return;
615
+ const verified = send({ type: 'CODING_STATUS', runId: p.runId }).then(async (r) => {
616
+ const data = (r as unknown as { data?: { proposals?: CodingProposalView[] } }).data;
617
+ const result = data?.proposals?.find((v) => v.proposalId === p.proposalId)?.result;
618
+ if (!r.ok || !result || await sha256Hex(result.text) !== result.sha256 || new TextEncoder().encode(result.text).length !== result.bytes) throw new Error('Immutable result unavailable or altered');
619
+ return new Blob([result.text], { type: 'text/plain' });
620
+ });
621
+ void writePlainClipboard(verified).then(() => show('coding-status', p.result?.kind === 'COMMITTED_UNTESTED_RESULT' ? 'Copied raw result - COMMITTED, NOT TESTED, LOCAL ONLY.' : p.result?.kind === 'APPLIED_UNTESTED_RESULT' ? 'Copied raw result — APPLIED, Git verified, NOT TESTED, NOT COMMITTED.' : 'Copied verified raw result.'), () => show('coding-status', 'Copy failed; the immutable result remains available.'));
622
+ });
623
+ async function writePlainClipboard(blob: Promise<Blob>): Promise<void> {
624
+ await navigator.clipboard.write([new ClipboardItem({ 'text/plain': blob })]);
625
+ }
626
+
627
+ let codingRefreshKey='';
628
+ async function workflowLoop(): Promise<void> {
629
+ for (;;) {
630
+ const r = await send({ type: 'GET_WORKFLOW', sinceVersion: wfVersion, waitMs: wfVersion < 0 ? 0 : 20000 });
631
+ const v = (r as unknown as { view?: WfView }).view;
632
+ if (r.ok && v) { wfVersion = v.version; if (!wfInFlight) { renderWorkflow(v); const key=v.run?`${v.run.runId}:${v.run.lifecycleState}:${v.activity?.cursor.split(':')[2]??''}:${v.connection}`:''; if(!v.run || v.connection==='REPAIR')codingRefreshKey=''; else if(key!==codingRefreshKey){if(await refreshCoding(v.run.runId))codingRefreshKey=key;} } }
633
+ else { show('wf-status', 'The extension service worker is not answering.'); show('wf-detail', failureText(r)); wfVersion = -1; await sleepMs(3000); }
634
+ }
635
+ }
636
+
637
+
638
+
639
+ const WF_BUTTONS = ['wf-primary', 'wf-rebind', 'wf-capture', 'wf-paste', 'wf-dismiss', 'wf-repair'];
640
+
641
+ async function wfAct(message: Record<string, unknown>): Promise<WorkerReply | undefined> {
642
+ if (wfInFlight) return undefined;
643
+ wfInFlight = true;
644
+ const approvedText = editor().value;
645
+ editor().disabled = true;
646
+ for (const b of WF_BUTTONS) $<HTMLButtonElement>(b).disabled = true;
647
+ let reply: WorkerReply | undefined;
648
+ try {
649
+ if (['RUN','RUN_CODING','RUN_TRUSTED_CODING'].includes(String(message.type))) {
650
+ const verified = await send({type:'SET_TASK',captureId:message.captureId,text:approvedText,sha256:await sha256Hex(approvedText),userActivation:message.userActivation});
651
+ if (!verified.ok || !verified.view?.captureId || editor().value !== approvedText) {
652
+ actionFailure = verified.ok ? {ok:false,code:'READBACK_MISMATCH'} : verified;
653
+ show('task-fidelity','Fidelity verification failed. Nothing dispatched. Correct or recapture the task.');
654
+ return actionFailure;
655
+ }
656
+ message = {...message,captureId:verified.view.captureId};
657
+ show('task-fidelity','Verified: exact approved UTF-8 bytes stored and read back before dispatch.');
658
+ }
659
+ reply = await send(message);
660
+ show('result', describe(reply));
661
+ // SW-065: the failure is KEPT (rendered on every refresh until the next successful action). Before, the re-render below erased it at once, so
662
+ // the code, Detail and correlation id of a failed Insert Draft survived only in the one-line status at the bottom of the panel.
663
+ actionFailure = reply.ok ? undefined : reply;
664
+ const r = await send({ type: 'GET_WORKFLOW', sinceVersion: -1, waitMs: 0 });
665
+ const v = (r as unknown as { view?: WfView }).view;
666
+ if (r.ok && v) wfVersion = v.version;
667
+ if (r.ok && v) wf = v;
668
+ } finally {
669
+ wfInFlight = false;
670
+ for (const b of WF_BUTTONS) $<HTMLButtonElement>(b).disabled = false;
671
+ if (wf) renderWorkflow(wf); // also restores the primary button's own enabled state
672
+ }
673
+ return reply;
674
+ }
675
+
676
+ $('wf-primary').addEventListener('click', () => {
677
+ const v = wf;
678
+ if (!v) return;
679
+ const activation = navigator.userActivation.isActive;
680
+ if (v.phase === 'CAPTURED' && v.capture) {
681
+ const o = v.operations.find((x) => opKey(x) === $<HTMLSelectElement>('wf-op').value);
682
+ if (!o) { show('wf-detail', formatFailure(describeFailure({ operation: OPERATION_LABELS.RUN, code: 'OPERATION_NOT_SELECTED', component: 'PANEL' }))); return; }
683
+ void wfAct({ type: input('wf-coding-mode').checked ? (trustedMode() ? 'RUN_TRUSTED_CODING' : 'RUN_CODING') : 'RUN', captureId: v.capture.captureId, projectId: o.projectId, pluginId: o.pluginId, operationId: o.operationId, userActivation: activation });
684
+ } else if ((v.phase === 'RETURN_READY' || v.phase === 'INSERT_FAILED') && v.ret) {
685
+ void wfAct({ type: 'INSERT_RETURN', returnId: v.ret.returnId, userActivation: activation });
686
+ } else if (v.phase === 'REPAIR') {
687
+ void wfAct({ type: 'REPAIR' });
688
+ }
689
+ });
690
+
691
+ $('wf-op').addEventListener('change', () => {
692
+ trustState = undefined; trustKey = 'changed'; if (wf) renderWorkflow(wf);
693
+ const o = wf?.operations.find((x) => opKey(x) === $<HTMLSelectElement>('wf-op').value);
694
+ if (o) void send({ type: 'SET_DEFAULT', projectId: o.projectId, pluginId: o.pluginId, operationId: o.operationId });
695
+ });
696
+
697
+ $('wf-rebind').addEventListener('click', () => {
698
+ const activation = navigator.userActivation.isActive;
699
+ void (async () => {
700
+ const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
701
+ if (wf?.ret) await wfAct({ type: 'REBIND_RETURN', returnId: wf.ret.returnId, tabId: typeof tab?.id === 'number' ? tab.id : -1, userActivation: activation });
702
+ })();
703
+ });
704
+
705
+ $('wf-capture').addEventListener('click', () => {
706
+ // Fallback second click: captures from the active tab (the toolbar icon must have been clicked on it, which is what grants access).
707
+ const activation = navigator.userActivation.isActive;
708
+ void (async () => {
709
+ const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
710
+ await wfAct({ type: 'CAPTURE', tabId: typeof tab?.id === 'number' ? tab.id : -1, userActivation: activation });
711
+ })();
712
+ });
713
+
714
+ $('wf-dismiss').addEventListener('click', () => { if (wf?.capture?.captureId) void wfAct({ type: 'DISMISS', captureId: wf.capture.captureId }); });
715
+ $('wf-repair').addEventListener('click', () => { void wfAct({ type: 'REPAIR' }); });
716
+
717
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
718
+ // SW-065 Copy Result. One direct click = one clipboard WRITE of the exact immutable result, which the worker re-fetches and digest-checks first. The panel
719
+ // never READS the clipboard. The write is issued synchronously inside the click (a ClipboardItem whose content is the pending verified text), so the
720
+ // click's user activation covers it even though the verification is asynchronous. Nothing is inserted into any page and nothing is sent: the receipt
721
+ // says COPIED_TO_CLIPBOARD and only that. A refusal or failure leaves the result, Insert Draft and Copy Result exactly as they were.
722
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
723
+
724
+ const sha256Hex = async (s: string): Promise<string> => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)))].map((b) => b.toString(16).padStart(2, '0')).join('');
725
+ const isWindows = (): boolean => /^Win/i.test(navigator.platform);
726
+
727
+ function copyFailed(returnId: string, code: string, operationNote?: string, workerReply?: WorkerReply): void {
728
+ const text = workerReply && !workerReply.ok ? failureText(workerReply)
729
+ : formatFailure(describeFailure({ operation: OPERATION_LABELS.COPY_RETURN, code, component: 'PANEL', ...(operationNote ? { note: operationNote } : {}) }));
730
+ plog('WARN', 'COPY_RETURN', workerReply && !workerReply.ok ? String(workerReply.code) : code, workerReply?.diag?.correlationId);
731
+ // kept like a receipt, so the next refresh does not erase it; the success count is preserved
732
+ copyReceipts.set(returnId, { line: `${text}\nThe result is unchanged: Insert Draft and Copy Result are still available, and nothing was sent.`, count: copyReceipts.get(returnId)?.count ?? 0 });
733
+ }
734
+
735
+ $('wf-copy').addEventListener('click', () => {
736
+ const v = wf;
737
+ if (!v?.ret || copyInFlight) return;
738
+ const returnId = v.ret.returnId;
739
+ const activation = navigator.userActivation.isActive;
740
+ copyInFlight = true;
741
+ $<HTMLButtonElement>('wf-copy').disabled = true;
742
+ show('wf-copy-status', 'Copying...');
743
+ let released: WorkerReply | undefined;
744
+ const verified: Promise<{ text: string; sha256: string; bytes: number }> = send({ type: 'COPY_RETURN', returnId, userActivation: activation }).then(async (r) => {
745
+ released = r;
746
+ if (!r.ok || r.type !== 'RETURN_TEXT' || r.returnId !== returnId || typeof r.text !== 'string' || typeof r.sha256 !== 'string') throw new Error('NOT_RELEASED');
747
+ if (r.text.length === 0) throw new Error('EMPTY_RESULT'); // the daemon never serves an empty return; refuse rather than clear the user's clipboard
748
+ if ((await sha256Hex(r.text)) !== r.sha256) throw new Error('DIGEST_MISMATCH'); // defence in depth: the bytes written are the bytes the daemon pinned
749
+ return { text: r.text, sha256: r.sha256, bytes: new TextEncoder().encode(r.text).length };
750
+ });
751
+ let write: Promise<void>;
752
+ try {
753
+ if (typeof ClipboardItem === 'undefined' || typeof navigator.clipboard?.write !== 'function') throw new Error('UNAVAILABLE');
754
+ const blob = verified.then((x) => new Blob([x.text], { type: 'text/plain' }));
755
+ blob.catch(() => undefined); // the outcome is reported below; a write the browser refused early must not leave an unhandled rejection
756
+ write = writePlainClipboard(blob);
757
+ } catch {
758
+ write = Promise.reject(new DOMException('no clipboard write', 'NotSupportedError'));
759
+ }
760
+ void (async () => {
761
+ let wrote = false; let writeError = '';
762
+ try { await write; wrote = true; } catch (e) { writeError = (e as { name?: string } | null)?.name ?? 'Error'; }
763
+ let x: { text: string; sha256: string; bytes: number } | undefined; let verifyError = '';
764
+ try { x = await verified; } catch (e) { verifyError = (e as Error).message; }
765
+ try {
766
+ if (wrote && x) {
767
+ const now = new Date().toLocaleTimeString();
768
+ const crlf = isWindows() && x.text.includes('\n') ? ' Windows stores the line breaks as CRLF; pasting into the browser turns them back into line breaks.' : '';
769
+ const prev = copyReceipts.get(returnId);
770
+ copyReceipts.set(returnId, {
771
+ line: `COPIED_TO_CLIPBOARD ${x.bytes} bytes sha256 ${x.sha256.slice(0, 12)}... at ${now}. Nothing was inserted or sent: click into the conversation's message box, press Ctrl+V, review it, then send it yourself.${crlf}`,
772
+ count: (prev?.count ?? 0) + 1,
773
+ });
774
+ plog('INFO', 'COPY_RETURN', 'COPIED_TO_CLIPBOARD', released?.diag?.correlationId, { bytes: x.bytes });
775
+ } else if (verifyError === 'NOT_RELEASED') copyFailed(returnId, 'COPY_REFUSED', undefined, released);
776
+ else if (verifyError === 'EMPTY_RESULT') copyFailed(returnId, 'RETURN_NOT_AVAILABLE', 'EMPTY_RESULT_NOTHING_COPIED');
777
+ else if (verifyError === 'DIGEST_MISMATCH') copyFailed(returnId, 'RETURN_CHANGED', 'PANEL_DIGEST_MISMATCH_NOTHING_COPIED');
778
+ else if (writeError === 'NotSupportedError') copyFailed(returnId, 'CLIPBOARD_UNAVAILABLE');
779
+ else copyFailed(returnId, 'CLIPBOARD_WRITE_DENIED', `BROWSER_ERROR=${writeError.replace(/[^A-Za-z]/g, '').toUpperCase().slice(0, 40) || 'UNKNOWN'}`);
780
+ } finally {
781
+ copyInFlight = false;
782
+ $<HTMLButtonElement>('wf-copy').disabled = false;
783
+ if (wf) renderWorkflow(wf); // shows the receipt or the failure just recorded
784
+ }
785
+ })();
786
+ });
787
+
788
+ /** Manual fallback that needs no permission at all: select the read-only preview so the user can press Ctrl+C themselves. */
789
+ $('wf-select').addEventListener('click', () => {
790
+ const sel = window.getSelection();
791
+ if (!sel) return;
792
+ const range = document.createRange();
793
+ range.selectNodeContents($('wf-text'));
794
+ sel.removeAllRanges();
795
+ sel.addRange(range);
796
+ // measured in Chromium (SW-065): a selection's text leaves out a FINAL line break of the <pre>, so this fallback is not byte-exact for such a result
797
+ const trailing = /\n$/.test($('wf-text').textContent ?? '') ? ' A selection leaves out the final line break; Copy Result is byte-exact.' : '';
798
+ show('wf-copy-status', `The result text is selected. Press Ctrl+C to copy it yourself.${trailing}`);
799
+ });
800
+
801
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
802
+ // SW-065 explicit paste input. The extension never reads the clipboard: the ONLY input is the paste event the user causes in this one box (Ctrl+V or
803
+ // the context menu). Typing and dropping are refused, so what is used is exactly what was pasted. The plain-text flavor is used verbatim except that
804
+ // Windows CRLF/CR line breaks become LF (the Windows clipboard adds CR to text a page wrote with LF); an HTML flavor is never parsed or used.
805
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
806
+
807
+ const PASTE_MAX_BYTES = 32768;
808
+ const pasteBox = $<HTMLTextAreaElement>('wf-paste-box');
809
+ const pasteFailed = (code: string): void => {
810
+ plog('WARN', 'CAPTURE_PASTED', code);
811
+ show('wf-paste-status', formatFailure(describeFailure({ operation: OPERATION_LABELS.CAPTURE_PASTED, code, component: 'PANEL' })));
812
+ };
813
+
814
+ $('wf-paste').addEventListener('click', () => {
815
+ $('wf-paste-area').hidden = false;
816
+ pasteBox.value = '';
817
+ show('wf-paste-status', '');
818
+ pasteBox.focus();
819
+ });
820
+ $('wf-paste-cancel').addEventListener('click', () => { $('wf-paste-area').hidden = true; pasteBox.value = ''; show('wf-paste-status', ''); });
821
+ pasteBox.addEventListener('beforeinput', (e) => { if (e.inputType !== 'insertFromPaste') e.preventDefault(); });
822
+ pasteBox.addEventListener('drop', (e) => { e.preventDefault(); });
823
+ pasteBox.addEventListener('paste', (e) => {
824
+ e.preventDefault(); // nothing lands in the box; the panel takes the plain-text flavor itself
825
+ const activation = navigator.userActivation.isActive;
826
+ const dt = e.clipboardData;
827
+ const types = dt ? Array.from(dt.types) : [];
828
+ if (!dt || types.length === 0) { pasteFailed('PASTE_EMPTY'); return; }
829
+ if (!types.includes('text/plain')) { pasteFailed('PASTE_NO_PLAIN_TEXT'); return; }
830
+ const raw = dt.getData('text/plain');
831
+ if (raw.trim().length === 0) { pasteFailed('PASTE_EMPTY'); return; }
832
+ const text = raw.replace(/\r\n?/g, '\n');
833
+ if (new TextEncoder().encode(text).length > PASTE_MAX_BYTES) { pasteFailed('PASTE_TOO_LARGE'); return; }
834
+ pasteInfo = {
835
+ text, crToLf: (raw.match(/\r\n?/g) ?? []).length, html: types.includes('text/html'),
836
+ markdownHint: /(^|\n)(#{1,6} |```|~~~|[-*+] |\d+\. |> )|\*\*[^*\n]+\*\*|`[^`\n]+`|\[[^\]\n]+\]\([^)\n]+\)/.test(text),
837
+ };
838
+ void (async () => {
839
+ // The conversation tab the user clicked the toolbar icon on (that click is what grants access); the worker re-validates it.
840
+ const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
841
+ const r = await wfAct({ type: 'CAPTURE_PASTED', tabId: typeof tab?.id === 'number' ? tab.id : -1, text, lineEndingsNormalized: pasteInfo.crToLf, userActivation: activation });
842
+ if (r?.ok) { $('wf-paste-area').hidden = true; show('wf-paste-status', ''); }
843
+ else if (r) show('wf-paste-status', failureText(r));
844
+ })();
845
+ });
846
+
847
+ try {
848
+ const mf = chrome.runtime.getManifest() as { version: string; version_name?: string };
849
+ show('wf-build', `Extension ${mf.version_name ?? mf.version}`);
850
+ } catch { /* not available */ }
851
+
852
+ void workflowLoop();
853
+
854
+ /** SW-097: diagnostics is a reversible inline view; it never owns task/run state. */
855
+ function activityLines(v: WfView): string[] {
856
+ const a=v.activity;
857
+ if (!a) return ['Backend evidence unavailable. No process activity is inferred.'];
858
+ const stale=v.daemonHealth ? v.daemonHealth.activityFreshness==='STALE' : v.connection==='REPAIR';
859
+ const needle=$<HTMLInputElement>('activity-search').value.toLowerCase();
860
+ return [a.truncated ? 'HISTORY_TRUNCATED: bounded recent events; older source records remain subject to retention.' : 'Durable event replay; process output is untrusted text, never task status.',
861
+ ...a.events.map(e=>`${e.ts} ${e.severity} ${e.component} ${stale?'STALE':e.status} ${e.runId} ${e.id} ${e.kind}: ${e.summary}`).filter(l=>l.toLowerCase().includes(needle))];
862
+ }
863
+ function renderActivity(v:WfView):void {
864
+ show('activity-health',v.daemonHealth?.state==='RECONNECTING'?'Reconnecting to the daemon; retained evidence is STALE.':v.connection==='REPAIR' ? 'Daemon disconnected / recovering. Retained evidence is STALE.' : 'Daemon connected - authenticated; health observed.');
865
+ const a=v.activity, op=selectedTrustTarget();
866
+ const elapsed=a ? Math.max(0,Math.floor((Date.parse(a.collectedAt)-Date.parse(a.startedAt))/1000)) : null;
867
+ const process=describeObservedProcess(a?.events??[],v.run?.lifecycleState);
868
+ show('activity-current',`${op?.projectLabel ?? (op ? friendly(op.projectId) : 'Select a project')} / ${op?.agentLabel ?? (op ? friendly(op.pluginId) : 'Select an agent')}\n${v.phase}${elapsed!==null ? ` - ${elapsed}s at last observation` : ''}\nProcess: ${process.text} (${v.daemonHealth?.activityFreshness==='STALE'?'STALE':process.evidence})`);
869
+ show('activity-console',activityLines(v).join('\n'));
870
+ }
871
+ $('activity-search').addEventListener('input',()=>{if(wf)renderActivity(wf);});
872
+ let diagnosticOpen=false;
873
+ let diagnosticGeneration=0;
874
+ $('diag-btn').addEventListener('click',()=>{
875
+ diagnosticOpen=!diagnosticOpen;
876
+ $('diagnostics').hidden=!diagnosticOpen;
877
+ $('diag-btn').setAttribute('aria-expanded',String(diagnosticOpen));
878
+ show('diag-btn',diagnosticOpen?'Hide diagnostics':'Show diagnostics');
879
+ const generation=++diagnosticGeneration;
880
+ if(diagnosticOpen) void send({type:'GET_DIAGNOSTICS'}).then(r=>{
881
+ if(generation!==diagnosticGeneration)return;
882
+ show('diag-out',r.ok && typeof r.text==='string' ? r.text : failureText(r));
883
+ if(wf)renderActivity(wf);
884
+ });
885
+ });
886
+ let diagCopyBusy=false;
887
+ $('copy-diagnostics').addEventListener('click',()=>{
888
+ if(diagCopyBusy)return;
889
+ diagCopyBusy=true;
890
+ $<HTMLButtonElement>('copy-diagnostics').disabled=true;
891
+ let reportFailure: string | undefined;
892
+ const report=send({type:'GET_DIAGNOSTICS'}).then(async r=>{
893
+ if(!r.ok || typeof r.text!=='string')throw new Error('DIAGNOSTICS_UNAVAILABLE');
894
+ const text=r.text;
895
+ if(new TextEncoder().encode(text).length>48000)throw new Error('DIAGNOSTICS_TOO_LARGE');
896
+ const hash=await sha256Hex(text);
897
+ const blob=new Blob([text],{type:'text/plain'});
898
+ if(await sha256Hex(await blob.text())!==hash)throw new Error('DIAGNOSTICS_READBACK_MISMATCH');
899
+ show('diag-out',text);
900
+ return blob;
901
+ }).catch((e:unknown)=>{ reportFailure=(e as {message?:string}).message; throw e; });
902
+ void writePlainClipboard(report).then(()=>show('diag-copy-status','Copied exact sanitized diagnostics. Retained offline data is labeled STALE.'),(e:unknown)=>{ const err=e as {message?:string;name?:string}; const failure=reportFailure ?? err.message; const reason=failure==='DIAGNOSTICS_TOO_LARGE'?'Diagnostic report exceeds the size limit.':failure==='DIAGNOSTICS_UNAVAILABLE'?'Diagnostic data is unavailable.':failure==='DIAGNOSTICS_READBACK_MISMATCH'?'Diagnostic report integrity failed.':err.name==='NotAllowedError'?'Clipboard permission was denied.':'Clipboard unavailable or write failed.'; show('diag-copy-status',`Copy diagnostics failed. ${reason} Nothing is claimed copied.`); }).finally(()=>{diagCopyBusy=false;$<HTMLButtonElement>('copy-diagnostics').disabled=false;});
903
+ });