@clawchatsai/connector 0.1.16 → 0.1.18

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/server/gateway.js CHANGED
@@ -1,102 +1,34 @@
1
1
  import path from 'node:path';
2
2
  import { WebSocket as WS } from 'ws';
3
3
  import { loadOrCreateDeviceIdentity, buildDeviceAuth } from './bootstrap/identity.js';
4
- import { parseSessionKey, extractContent, isSilentReplyExact, isSilentReplyPrefix, sanitizeAssistantContent, syncThreadUnreadCount, generateActivitySummary, writeActivityToDb } from './util/helpers.js';
5
4
 
6
- /**
7
- * Cumulative assistant text for a `chat` delta event.
8
- * Protocol-v4 gateways (2026.9+) send appends in `deltaText`; only the first frame of a
9
- * run (and any new baseline) carries the full `message` snapshot, which already includes
10
- * the delta. `replace: true` makes `deltaText` the entire text. Older gateways send the
11
- * full cumulative `message` on every delta, which the snapshot branch covers.
12
- */
13
- export function nextChatText(prev, params) {
14
- if (params?.message) return extractContent(params.message);
15
- if (typeof params?.deltaText !== 'string') return prev || '';
16
- return params.replace ? params.deltaText : (prev || '') + params.deltaText;
17
- }
5
+ // Per-session run/transcript events; hidden sessions' ones are dropped by the lens.
6
+ const RUN_EVENTS = new Set(['chat', 'agent', 'session.tool', 'session.operation', 'session.observer']);
18
7
 
19
8
  export class GatewayClient {
20
- constructor({ getDb, getWorkspaces, dataDir, debugLogger, gatewayWsUrl, authToken }) {
21
- this.getDb = getDb;
22
- this.getWorkspaces = getWorkspaces;
9
+ constructor({ dataDir, debugLogger, gatewayWsUrl, authToken }) {
23
10
  this.dataDir = dataDir;
24
11
  this.debugLogger = debugLogger;
25
12
  this.gatewayWsUrl = gatewayWsUrl;
26
13
  this.authToken = authToken;
27
- // Per-session buffer of attachment paths captured during a run. Drained by saveAssistantMessage.
28
- // Sources: (1) MEDIA: paths from exec tool's echo args, (2) Write/Edit tool args.path.
29
- // Lives on the stable singleton — safe from plugin re-registration that broke the old closure-based stash.
30
- this._runMediaPaths = new Map();
31
- // Per-toolCallId staging for Write/Edit: path captured at phase:start, promoted to _runMediaPaths
32
- // at phase:result if the call succeeded. Keyed by toolCallId; value: { sessionKey, path }.
33
- this._runWriteBuffers = new Map();
34
-
35
14
  this.ws = null;
36
15
  this.connected = false;
37
16
  this.reconnectAttempts = 0;
38
17
  this.maxReconnectDelay = 30000;
39
18
  this.browserClients = new Map();
40
19
  this._externalBroadcastTargets = [];
41
- this.streamState = new Map();
42
- this._utilityText = new Map(); // sessionKey → accumulated delta text for utility sessions
43
20
  this._rpc = new Map(); // request id → { resolve, reject, timer } for connector-originated RPCs
44
21
  this._rpcSeq = 0;
45
- this.activityLogs = new Map();
46
- this._pendingTitleGens = new Map();
47
- // Runs we've already synthesized a streaming-end{reason:'error'} for
48
- // (agent lifecycle:error emitted but no chat state:error ever will). Prevents
49
- // double-fires across retries and cross-path dedup with handleChatEvent.
50
- this._syntheticErrorRuns = new Set();
51
-
52
- // Runs that already delivered a reply the user can see (persisted + broadcast).
53
- // The gateway may report a run-level fault AFTER the reply is delivered — a retried
54
- // tool call, or a post_turn/gateway_draining fault (see OpenClaw's
55
- // AGENT_RUN_TERMINAL_RETRY_GRACE_MS deferral). Those describe the run, not the reply,
56
- // and must never overwrite a message the user already read. Keyed by runId because
57
- // sessionKey is stable for the whole thread — a late error from turn N must not be
58
- // confused with a live error from turn N+1. Mirrors the OCPlatform TUI's
59
- // finalizedRunsWithDisplay guard.
60
- this._runsWithDeliveredReply = new Set();
61
-
62
- // On startup: mark any pending activity log messages from previous crashed/restarted sessions
63
- // as interrupted. Without this, stale pending=true rows survive gateway restarts and cause
64
- // phantom "thinking..." indicators in the browser on reconnect.
65
- try {
66
- const workspaces = this.getWorkspaces();
67
- for (const wsName of Object.keys(workspaces.workspaces || {})) {
68
- const db = this.getDb(wsName);
69
- if (db) db.prepare(`UPDATE messages SET content = '[Response interrupted]', metadata = json_remove(metadata, '$.pending') WHERE content = '' AND json_extract(metadata, '$.pending') = 1`).run();
70
- }
71
- } catch (e) { console.log('[clawchats] startup pending cleanup skipped:', e.message); }
72
-
73
- // Periodically clean up stale activity logs (>10 min old)
74
- setInterval(() => {
75
- const cutoff = Date.now() - 10 * 60 * 1000;
76
- for (const [runId, log] of this.activityLogs) {
77
- if (log.startTime < cutoff) {
78
- if (log._messageId) {
79
- const db = this.getDb(log._parsed?.workspace);
80
- if (db) db.prepare(`UPDATE messages SET content = '[Response interrupted]', metadata = json_remove(metadata, '$.pending') WHERE id = ? AND content = ''`).run(log._messageId);
81
- }
82
- this.activityLogs.delete(runId);
83
- }
84
- }
85
- }, 5 * 60 * 1000);
86
- }
87
-
88
- /** parseSessionKey, but following threads that sync moved to another project. */
89
- _locate(sessionKey) {
90
- return this.sync ? this.sync.locate(sessionKey) : parseSessionKey(sessionKey);
91
22
  }
92
23
 
93
24
  connect() {
25
+ if (this._closed) return;
94
26
  if (this.ws && (this.ws.readyState === WS.CONNECTING || this.ws.readyState === WS.OPEN)) return;
95
27
  console.log(`Connecting to gateway at ${this.gatewayWsUrl}...`);
96
28
  this.ws = new WS(this.gatewayWsUrl);
97
29
  this.ws.on('open', () => { console.log('Gateway WebSocket connected'); this.reconnectAttempts = 0; });
98
30
  this.ws.on('message', data => this.handleGatewayMessage(data.toString()));
99
- this.ws.on('close', () => { console.log('Gateway WebSocket closed'); this.connected = false; this._failPendingRpcs('gateway disconnected'); this.broadcastGatewayStatus(false); this.scheduleReconnect(); });
31
+ this.ws.on('close', () => { console.log('Gateway WebSocket closed'); this.connected = false; this._failPendingRpcs('gateway disconnected'); this.lens?.reset(); this.broadcastGatewayStatus(false); if (!this._closed) this.scheduleReconnect(); });
100
32
  this.ws.on('error', err => console.error('Gateway WebSocket error:', err.message));
101
33
  }
102
34
 
@@ -115,153 +47,34 @@ export class GatewayClient {
115
47
  return;
116
48
  }
117
49
 
50
+ // Responses to browser session requests the lens filters (roster, search, groups).
51
+ if (msg.type === 'res' && this.lens?.ownsResponse(msg.id)) {
52
+ this.broadcastToBrowsers(JSON.stringify(this.lens.response(msg)));
53
+ return;
54
+ }
55
+
118
56
  if (msg.type === 'event' && msg.event === 'connect.challenge') {
119
57
  const identity = loadOrCreateDeviceIdentity(path.join(this.dataDir, 'device-identity.json'));
120
- const device = buildDeviceAuth(identity, { clientId: 'gateway-client', clientMode: 'backend', role: 'operator', scopes: ['operator.read', 'operator.write', 'operator.admin'], token: this.authToken, nonce: msg.payload?.nonce || '' });
121
- this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: { minProtocol: 3, maxProtocol: 4, client: { id: 'gateway-client', version: '0.1.0', platform: 'node', mode: 'backend' }, role: 'operator', scopes: ['operator.read', 'operator.write', 'operator.admin'], device, auth: { token: this.authToken }, caps: ['tool-events'] } }));
58
+ const device = buildDeviceAuth(identity, { clientId: 'gateway-client', clientMode: 'backend', role: 'operator', scopes: ['operator.read', 'operator.write', 'operator.admin', 'operator.approvals', 'operator.questions'], token: this.authToken, nonce: msg.payload?.nonce || '' });
59
+ this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: { minProtocol: 3, maxProtocol: 4, client: { id: 'gateway-client', version: '0.1.0', platform: 'node', mode: 'backend' }, role: 'operator', scopes: ['operator.read', 'operator.write', 'operator.admin', 'operator.approvals', 'operator.questions'], device, auth: { token: this.authToken }, caps: ['tool-events'] } }));
122
60
  return;
123
61
  }
124
- if (msg.type === 'res' && msg.payload?.type === 'hello-ok') { console.log('Gateway handshake complete'); this.connected = true; this.broadcastGatewayStatus(true); this.sync?.onConnected(); }
125
- // Session-list events exist for the connector's own subscription (gateway sync);
126
- // the ClawChats frontend never subscribes, so don't spend tunnel bandwidth on them.
62
+ if (msg.type === 'res' && msg.payload?.type === 'hello-ok') { console.log('Gateway handshake complete'); this.connected = true; this.broadcastGatewayStatus(true); this.sync?.onConnected(); this.request('sessions.subscribe', {}).catch(e => console.warn(`[lens] sessions.subscribe failed: ${e.message}`)); this.lens?.seed().catch(e => console.warn(`[lens] seed failed: ${e.message}`)); }
63
+ // Session events arrive through the connector's own subscription; the lens filters them
64
+ // for the browser (session.message only for chats a browser subscribed to).
127
65
  if (msg.type === 'event' && (msg.event === 'sessions.changed' || msg.event === 'session.message')) {
128
66
  if (msg.event === 'sessions.changed') this.sync?.onSessionsChanged(msg.payload);
67
+ const frame = msg.event === 'sessions.changed' ? this.lens?.sessionsChanged(msg.payload) : this.lens?.sessionMessage(msg.payload);
68
+ if (frame) this.broadcastToBrowsers(JSON.stringify(frame));
129
69
  return;
130
70
  }
131
- if (msg.type === 'event' && msg.event === 'chat' && msg.payload) {
132
- this.handleChatEvent(msg.payload, data);
133
- } else {
134
- this.broadcastToBrowsers(data);
135
- }
136
- if (msg.type === 'event' && msg.event === 'agent' && msg.payload) this.handleAgentEvent(msg.payload);
137
- }
138
-
139
- handleChatEvent(params, rawData) {
140
- const { sessionKey, state, message, seq, runId, errorMessage: gwErrorMessage } = params;
141
- const bareSessionKey = sessionKey.replace(/^agent:[^:]+:/, '');
142
-
143
- // --- Utility session routing (connector-side) ---
144
- // Emits semantic utility-response events. Also forwards rawData for dual-emit compatibility
145
- // during transition — browser handleChatEvent guards these and defers to utility-response handler.
146
- const UTILITY_SESSIONS = { '__clawchats_summarizer': 'summarizer', '__clawchats_semantic': 'semantic', '__clawchats_intelligence': 'intelligence' };
147
- const utilityName = UTILITY_SESSIONS[bareSessionKey];
148
- if (utilityName) {
149
- const content = state === 'delta' ? this._accumulateChatText(sessionKey, params) : extractContent(message);
150
- if (state !== 'delta') this._utilityText.delete(sessionKey);
151
- if (state === 'delta' && content) {
152
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'utility-response', session: utilityName, state: 'delta', content }));
153
- } else if (state === 'final' || state === 'aborted') {
154
- if (content) this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'utility-response', session: utilityName, state: state === 'final' ? 'final' : 'aborted', content }));
155
- } else if (state === 'error') {
156
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'utility-response', session: utilityName, state: 'error', errorMessage: gwErrorMessage || message?.error || message?.content || 'Unknown error' }));
157
- }
158
- this.broadcastToBrowsers(rawData); // dual-emit: browser guard skips raw handling for utility sessions
159
- return;
160
- }
161
-
162
- // --- Delta path ---
163
- if (state === 'delta') {
164
- const parsed = this._locate(sessionKey);
165
- if (parsed) {
166
- const existing = this.streamState.get(sessionKey) || { buffer: '', threadId: parsed.threadId, state: 'streaming', held: [] };
167
- const prevLen = existing.buffer.length; // capture before update — used to advance thoughtStartOffset on first post-tool delta
168
- const prevBuffer = existing.buffer;
169
- existing.buffer = nextChatText(existing.buffer, params);
170
- if (isSilentReplyPrefix(existing.buffer, 'NO_REPLY') || isSilentReplyPrefix(existing.buffer, 'HEARTBEAT_OK')) {
171
- existing.held = existing.held || [];
172
- existing.held.push(rawData);
173
- this.streamState.set(sessionKey, existing);
174
- return;
175
- }
176
- if (existing.held?.length > 0) {
177
- for (const h of existing.held) this.broadcastToBrowsers(h);
178
- existing.held = [];
179
- }
180
- this.streamState.set(sessionKey, existing);
181
- this.broadcastToBrowsers(rawData); // dual-emit: raw chat event (old protocol)
182
- // On the first delta after a tool result, advance the segment offset and signal the
183
- // frontend to clear the bubble. Both happen here — right before the new-segment delta —
184
- // so the clear and fill are atomic from the browser's perspective.
185
- if (existing.pendingReset) {
186
- // A v4 gateway may open the post-tool segment with a fresh snapshot instead of
187
- // extending the run text; only skip the old text if it's still a prefix.
188
- existing.thoughtStartOffset = existing.buffer.startsWith(prevBuffer) ? prevLen : 0;
189
- existing.pendingReset = false;
190
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'streaming-reset', threadId: parsed.threadId, workspace: parsed.workspace }));
191
- }
192
- // Broadcast only the current-segment portion (text after the last tool call offset).
193
- // thoughtStartOffset advances on first post-tool delta; 0 means no tools yet → full buffer.
194
- const visibleContent = existing.buffer.substring(existing.thoughtStartOffset || 0);
195
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'streaming-delta', threadId: parsed.threadId, workspace: parsed.workspace, content: visibleContent }));
196
- } else {
197
- this.broadcastToBrowsers(rawData); // non-clawchats session (discord, telegram, etc.)
198
- }
199
- return;
200
- }
201
-
202
- // --- End states ---
203
- const streamEntry = this.streamState.get(sessionKey);
204
- if (state === 'final' || state === 'aborted' || state === 'error') this.streamState.delete(sessionKey);
205
-
206
- // Title sessions are handled server-side — intercept and skip browser delivery
207
- if (sessionKey?.includes('__clawchats_title_')) {
208
- if (state === 'final') {
209
- const content = extractContent(message);
210
- const handled = content && this.handleTitleResponse(sessionKey, content);
211
- if (this.sync) this.sync.run(() => this.sync.deleteSession(sessionKey)).catch(e => console.warn(`[clawchats] title session cleanup: ${e.message}`));
212
- if (handled) return;
213
- }
214
- else if (state === 'error' || state === 'aborted') { for (const key of this._pendingTitleGens.keys()) { if (sessionKey === key || sessionKey.includes(key)) { this._pendingTitleGens.delete(key); break; } } return; }
71
+ // Run events of sessions ClawChats doesn't show (channels, cron, subagents) never
72
+ // leave the connector.
73
+ if (msg.type === 'event' && RUN_EVENTS.has(msg.event) && this.lens && msg.payload?.sessionKey && !this.lens.forwardsRunEvent(msg.payload.sessionKey)) {
215
74
  return;
216
75
  }
217
-
218
- if (state === 'final') {
219
- const rawContent = extractContent(message);
220
- const parsed = this._locate(sessionKey);
221
- if (isSilentReplyExact(rawContent, 'NO_REPLY') || isSilentReplyExact(rawContent, 'HEARTBEAT_OK')) {
222
- this._cleanupSilentPending(sessionKey);
223
- if (parsed) this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'streaming-end', threadId: parsed.threadId, workspace: parsed.workspace, reason: 'silent' }));
224
- return;
225
- }
226
- if (streamEntry?.held?.length > 0) for (const h of streamEntry.held) this.broadcastToBrowsers(h);
227
- const delivered = this.saveAssistantMessage(sessionKey, message, seq, streamEntry?.thoughtStartOffset); // persist + broadcast message-saved first
228
- if (delivered && runId) this._runsWithDeliveredReply.add(runId);
229
- this.broadcastToBrowsers(rawData); // dual-emit: raw final event
230
- if (parsed) {
231
- const activity = this._popActivityLogForSession(sessionKey);
232
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'streaming-end', threadId: parsed.threadId, workspace: parsed.workspace, reason: 'complete', ...(activity || {}) }));
233
- }
234
- return;
235
- }
236
- if (state === 'aborted') {
237
- const parsed = this._locate(sessionKey);
238
- // Clear pending flag from DB so a stale pending:true doesn't survive page reloads
239
- // and trigger phantom "thinking..." state on next visit to this thread.
240
- if (parsed) {
241
- const db = this.getDb(parsed.workspace);
242
- if (db) this._clearPendingFlag(db, parsed.threadId);
243
- }
244
- this.broadcastToBrowsers(rawData); // dual-emit
245
- if (parsed) {
246
- const activity = this._popActivityLogForSession(sessionKey);
247
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'streaming-end', threadId: parsed.threadId, workspace: parsed.workspace, reason: 'aborted', ...(activity || {}) }));
248
- }
249
- } else if (state === 'error') {
250
- // Late run-level fault for a run that already delivered its reply — drop it.
251
- // Emitting streaming-end{reason:'error'} here makes the browser replace the
252
- // rendered answer with an error bubble, destroying a message the user already read.
253
- if (runId && this._runsWithDeliveredReply.has(runId)) {
254
- console.log(`[clawchats] ignoring late error for run ${runId} — reply already delivered`);
255
- return;
256
- }
257
- const parsed = this._locate(sessionKey);
258
- this.saveErrorMarker(sessionKey, message);
259
- this.broadcastToBrowsers(rawData); // dual-emit
260
- if (parsed) {
261
- const activity = this._popActivityLogForSession(sessionKey);
262
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'streaming-end', threadId: parsed.threadId, workspace: parsed.workspace, reason: 'error', errorMessage: gwErrorMessage || message?.error || message?.content || 'Unknown error', ...(activity || {}) }));
263
- }
264
- }
76
+ // Raw chat/agent events pass through; the browser builds live runs (frontend/live-run.js).
77
+ this.broadcastToBrowsers(data);
265
78
  }
266
79
 
267
80
  // Gateway RPC from the connector itself; resolves with the response payload.
@@ -279,332 +92,6 @@ export class GatewayClient {
279
92
  for (const [id, p] of this._rpc) { clearTimeout(p.timer); p.reject(new Error(reason)); this._rpc.delete(id); }
280
93
  }
281
94
 
282
- // Utility sessions keep no streamState entry; accumulate their delta text separately.
283
- _accumulateChatText(sessionKey, params) {
284
- const text = nextChatText(this._utilityText.get(sessionKey) || '', params);
285
- this._utilityText.set(sessionKey, text);
286
- return text;
287
- }
288
-
289
- // Removes metadata.pending flag from any pending assistant message for a thread.
290
- // Called on abort and by _cleanupSilentPending — keeps the SQL in one place.
291
- _clearPendingFlag(db, threadId) {
292
- db.prepare(
293
- "UPDATE messages SET metadata = json_remove(metadata, '$.pending') " +
294
- "WHERE thread_id = ? AND role = 'assistant' AND json_extract(metadata, '$.pending') = 1"
295
- ).run(threadId);
296
- }
297
-
298
- _cleanupSilentPending(sessionKey) {
299
- const parsed = this._locate(sessionKey);
300
- if (!parsed) return;
301
- const ws = this.getWorkspaces();
302
- if (!ws.workspaces[parsed.workspace]) return;
303
- const db = this.getDb(parsed.workspace);
304
- if (!db) return;
305
- const result = db.prepare(`DELETE FROM messages WHERE thread_id = ? AND role = 'assistant' AND json_extract(metadata, '$.pending') = 1`).run(parsed.threadId);
306
- if (result.changes > 0) console.log(`[clawchats] silent-reply cleanup: removed ${result.changes} pending message(s) for ${parsed.threadId}`);
307
- // Caller broadcasts streaming-end { reason: 'silent' } — no event emitted here.
308
- }
309
-
310
- // Returns true when a reply was actually persisted for this run, false on every
311
- // early-out. handleChatEvent uses the result to decide whether the run counts as
312
- // having delivered a visible reply.
313
- saveAssistantMessage(sessionKey, message, seq, thoughtStartOffset = 0) {
314
- const parsed = this._locate(sessionKey);
315
- if (!parsed) return false;
316
- const ws = this.getWorkspaces();
317
- if (!ws.workspaces[parsed.workspace]) { console.log(`Ignoring response for deleted workspace: ${parsed.workspace}`); return false; }
318
- const db = this.getDb(parsed.workspace);
319
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(parsed.threadId)) { console.log(`Ignoring response for deleted thread: ${parsed.threadId}`); return false; }
320
-
321
- // Trim to final-answer portion: only text after the last tool call offset.
322
- // thoughtStartOffset is passed in from handleChatEvent (captured before streamState.delete).
323
- // Intermediate narration lives in activityLog steps; message.content is the clean final answer.
324
- const fullContent = extractContent(message);
325
- // Never let a stale segment offset blank the reply (v4 snapshots can be shorter).
326
- if (thoughtStartOffset > fullContent.length) thoughtStartOffset = 0;
327
- let content = sanitizeAssistantContent(fullContent.substring(thoughtStartOffset));
328
-
329
- // Attach media (MEDIA: paths extracted from exec tool args by handleAgentEvent).
330
- // Buffer is read before the empty-content guard — media-only responses (no text) must not be dropped.
331
- const pendingPaths = this._runMediaPaths.get(sessionKey) ?? [];
332
- this._runMediaPaths.delete(sessionKey);
333
- const IMAGE_EXTS = new Set(['png','jpg','jpeg','gif','webp','bmp','svg','ico','avif','tiff']);
334
- const AUDIO_EXTS = new Set(['mp3','wav','ogg','m4a','flac','aac','opus','wma']);
335
- const imagePaths = [], pendingAttachments = [];
336
- for (const p of pendingPaths) {
337
- const ext = (p.split('.').pop() || '').toLowerCase();
338
- if (IMAGE_EXTS.has(ext)) imagePaths.push(p);
339
- else pendingAttachments.push({ path: p, name: p.split('/').pop(), type: AUDIO_EXTS.has(ext) ? 'audio' : 'file' });
340
- }
341
- if (imagePaths.length > 0) content = (content?.trimEnd() || '') + '\n\n' + imagePaths.map(p => `![image](${p})`).join('\n');
342
- if (pendingPaths.length > 0) console.log(`[clawchats] media-attach: ${imagePaths.length} image(s), ${pendingAttachments.length} attachment(s) for ${sessionKey}`);
343
-
344
- const now = Date.now();
345
- const pendingMsg = db.prepare(`SELECT id, metadata FROM messages WHERE thread_id = ? AND role = 'assistant' AND json_extract(metadata, '$.pending') = 1 ORDER BY timestamp DESC LIMIT 1`).get(parsed.threadId);
346
-
347
- // Skip only if there is truly nothing to save AND no pending row to resolve.
348
- // If a pending row exists, always proceed to update it (even with empty content) so the
349
- // pending flag is cleared. Without this, tool-only responses (no post-tool text) leave
350
- // pending=true forever, and the startup cleanup marks them '[Response interrupted]'.
351
- if (!content?.trim() && pendingPaths.length === 0 && !pendingMsg) { console.log(`Skipping empty assistant response for thread ${parsed.threadId}`); return false; }
352
- let messageId;
353
-
354
- if (pendingMsg) {
355
- const metadata = pendingMsg.metadata ? JSON.parse(pendingMsg.metadata) : {};
356
- delete metadata.pending;
357
- if (metadata.activityLog) { const idx = metadata.activityLog.findLastIndex(s => s.type === 'assistant'); if (idx >= 0) metadata.activityLog.splice(idx, 1); metadata.activitySummary = generateActivitySummary(metadata.activityLog); }
358
- if (pendingAttachments.length > 0) metadata.attachments = [...(metadata.attachments || []), ...pendingAttachments];
359
- db.prepare('UPDATE messages SET content = ?, metadata = ?, timestamp = ? WHERE id = ?').run(content, JSON.stringify(metadata), now, pendingMsg.id);
360
- messageId = pendingMsg.id;
361
- } else {
362
- messageId = seq != null ? `gw-${parsed.threadId}-${seq}` : `gw-${parsed.threadId}-${now}`;
363
- const newMeta = pendingAttachments.length > 0 ? JSON.stringify({ attachments: pendingAttachments }) : null;
364
- db.prepare(`INSERT INTO messages (id, thread_id, role, content, status, metadata, timestamp, created_at) VALUES (?, ?, 'assistant', ?, 'sent', ?, ?, ?) ON CONFLICT(id) DO UPDATE SET content = excluded.content, metadata = COALESCE(excluded.metadata, metadata), timestamp = excluded.timestamp`).run(messageId, parsed.threadId, content, newMeta, now, now);
365
- }
366
-
367
- try {
368
- db.prepare('UPDATE threads SET updated_at = ? WHERE id = ?').run(now, parsed.threadId);
369
- db.prepare('INSERT OR IGNORE INTO unread_messages (thread_id, message_id, created_at) VALUES (?, ?, ?)').run(parsed.threadId, messageId, now);
370
- syncThreadUnreadCount(db, parsed.threadId);
371
- const threadInfo = db.prepare('SELECT title FROM threads WHERE id = ?').get(parsed.threadId);
372
- const unreadCount = db.prepare('SELECT COUNT(*) as c FROM unread_messages WHERE thread_id = ?').get(parsed.threadId).c;
373
- const preview = content.length > 120 ? content.substring(0, 120) + '...' : content;
374
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'message-saved', threadId: parsed.threadId, workspace: parsed.workspace, messageId, timestamp: now, title: threadInfo?.title, preview, unreadCount, updatedContent: imagePaths.length > 0 ? content : undefined, updatedAttachments: pendingAttachments.length > 0 ? pendingAttachments : undefined }));
375
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'unread-update', workspace: parsed.workspace, threadId: parsed.threadId, messageId, action: 'new', unreadCount, workspaceUnreadTotal: db.prepare('SELECT COALESCE(SUM(unread_count), 0) as total FROM threads').get().total, title: threadInfo?.title, preview, timestamp: now }));
376
- console.log(`Saved assistant message to ${parsed.workspace}/${parsed.threadId} (${pendingMsg ? 'merged into pending' : 'seq: ' + seq})`);
377
- const msgCount = db.prepare('SELECT COUNT(*) as c FROM messages WHERE thread_id = ?').get(parsed.threadId).c;
378
- if (msgCount === 2 || threadInfo?.title === 'New chat') this.generateThreadTitle(db, parsed.threadId, parsed.workspace, true);
379
- } catch (e) { console.error('Failed to save assistant message:', e.message); }
380
- // The message row is written above the try block, so it is persisted even if the
381
- // follow-up bookkeeping/broadcast throws — the reply was delivered either way.
382
- return true;
383
- }
384
-
385
- saveErrorMarker(sessionKey, message) {
386
- const parsed = this._locate(sessionKey);
387
- if (!parsed) return;
388
- const ws = this.getWorkspaces();
389
- if (!ws.workspaces[parsed.workspace]) return;
390
- const db = this.getDb(parsed.workspace);
391
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(parsed.threadId)) return;
392
- const now = Date.now();
393
- try {
394
- db.prepare('INSERT INTO messages (id, thread_id, role, content, status, metadata, timestamp, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(`gw-error-${parsed.threadId}-${now}`, parsed.threadId, 'system', `[error] ${message?.error || message?.content || 'Unknown error'}`, 'sent', '{"transient":true}', now, now);
395
- // Clear stale pending flag so browsers reloading the chat don't re-derive "thinking..." state.
396
- db.prepare("UPDATE messages SET metadata = json_remove(metadata, '$.pending') WHERE thread_id = ? AND role = 'assistant' AND json_extract(metadata, '$.pending') = 1").run(parsed.threadId);
397
- } catch (e) { console.error('Failed to save error marker:', e.message); }
398
- }
399
-
400
- generateThreadTitle(db, threadId, workspace, skipHeuristic = false) {
401
- if (!db.prepare('SELECT title FROM threads WHERE id = ?').get(threadId)) return;
402
- const titleKey = `__clawchats_title_${threadId}`;
403
- if (this._pendingTitleGens.has(titleKey)) return;
404
- const firstUserMsg = db.prepare("SELECT content FROM messages WHERE thread_id = ? AND role = 'user' ORDER BY created_at ASC LIMIT 1").get(threadId);
405
- if (!firstUserMsg?.content) return;
406
- if (!skipHeuristic) {
407
- const heuristic = firstUserMsg.content.replace(/\n.*/s, '').slice(0, 40).trim() + (firstUserMsg.content.length > 40 ? '...' : '');
408
- db.prepare('UPDATE threads SET title = ? WHERE id = ?').run(heuristic, threadId);
409
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'thread-title-updated', threadId, workspace, title: heuristic }));
410
- this._syncTitle(db, workspace, threadId, heuristic);
411
- }
412
- const messages = db.prepare('SELECT role, content FROM messages WHERE thread_id = ? ORDER BY created_at ASC LIMIT 6').all(threadId);
413
- if (messages.length < 2) return;
414
- const conversation = messages.map(m => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content.length > 300 ? m.content.slice(0, 300) + '...' : m.content}`).join('\n\n');
415
- const reqId = `title-${threadId}-${Date.now()}`;
416
- this._pendingTitleGens.set(titleKey, { threadId, workspace, reqId });
417
- setTimeout(() => { if (this._pendingTitleGens.has(titleKey)) { this._pendingTitleGens.delete(titleKey); console.log(`Title gen timeout for ${threadId}`); } }, 30000);
418
- this.sendToGateway(JSON.stringify({ type: 'req', id: reqId, method: 'chat.send', params: { sessionKey: titleKey, message: `Based on this conversation, generate a concise 3-5 word title. Return ONLY the title text, no quotes, no explanation:\n\n${conversation}\n\nTitle:`, deliver: false, idempotencyKey: reqId } }));
419
- }
420
-
421
- handleTitleResponse(sessionKey, content) {
422
- let matchKey = null, pending = null;
423
- for (const [key, val] of this._pendingTitleGens) {
424
- if (sessionKey === key || sessionKey.includes(key)) { matchKey = key; pending = val; break; }
425
- }
426
- if (!pending) return false;
427
- this._pendingTitleGens.delete(matchKey);
428
- let title = content.trim().replace(/^["']|["']$/g, '').replace(/^Title:\s*/i, '').replace(/\n.*/s, '').trim();
429
- if (title.length > 50) title = title.substring(0, 47) + '...';
430
- if (!title || title.length >= 100) return true;
431
- const db = this.getDb(pending.workspace);
432
- db.prepare('UPDATE threads SET title = ? WHERE id = ?').run(title, pending.threadId);
433
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'thread-title-updated', threadId: pending.threadId, workspace: pending.workspace, title }));
434
- console.log(`AI title generated for ${pending.threadId}: "${title}"`);
435
- this._syncTitle(db, pending.workspace, pending.threadId, title);
436
- return true;
437
- }
438
-
439
- // Copy a generated title to the gateway session's custom name; the throwaway
440
- // title-generation session is deleted once its answer is in.
441
- _syncTitle(db, workspace, threadId, title) {
442
- if (!this.sync) return;
443
- const row = db.prepare('SELECT session_key FROM threads WHERE id = ?').get(threadId);
444
- if (row?.session_key) this.sync.titleGenerated(workspace, threadId, row.session_key, title);
445
- }
446
-
447
- handleAgentEvent(payload) {
448
- const { runId, stream, data, sessionKey } = payload;
449
- if (!runId) return;
450
- if (!this.activityLogs.has(runId)) this.activityLogs.set(runId, { sessionKey, steps: [], startTime: Date.now() });
451
- const log = this.activityLogs.get(runId);
452
- if (!log._parsed && sessionKey) log._parsed = this._locate(sessionKey);
453
-
454
- if (stream === 'thinking') {
455
- let step = log.steps.find(s => s.type === 'thinking');
456
- if (step) step.text = data?.text || '';
457
- else log.steps.push({ type: 'thinking', timestamp: Date.now(), text: data?.text || '' });
458
- writeActivityToDb(this.getDb, this.broadcastToBrowsers.bind(this), runId, log);
459
- const now = Date.now();
460
- if (!log._lastThinkingBroadcast || now - log._lastThinkingBroadcast >= 300) { log._lastThinkingBroadcast = now; this._broadcastActivityUpdate(runId, log); }
461
- }
462
- if (stream === 'tool') {
463
- // At phase:start the gateway has already flushed the text buffer, so the buffer is
464
- // complete. Capture the full inter-tool narration now — no race, no stale snapshots.
465
- // For result/update phases, just defensively seal any still-open segment.
466
- if (data?.phase !== 'result' && data?.phase !== 'update') {
467
- const streamEntry = this.streamState.get(sessionKey);
468
- const narrationStart = log._lastNarrationStart ?? 0;
469
- const narrationText = streamEntry ? streamEntry.buffer.substring(narrationStart) : '';
470
- if (log._currentAssistantSegment && !log._currentAssistantSegment._sealed) {
471
- if (narrationText.trim()) log._currentAssistantSegment.text = narrationText;
472
- log._currentAssistantSegment._sealed = true;
473
- } else if (narrationText.trim()) {
474
- const seg = { type: 'assistant', timestamp: Date.now(), text: narrationText, _sealed: true };
475
- log._currentAssistantSegment = seg;
476
- log.steps.push(seg);
477
- }
478
- } else if (log._currentAssistantSegment && !log._currentAssistantSegment._sealed) {
479
- log._currentAssistantSegment._sealed = true;
480
- }
481
- const argsMeta = data?.args ? (data.args.command || data.args.path || data.args.query || data.args.url || Object.values(data.args).find(v => typeof v === 'string') || '') : '';
482
- // Extract MEDIA: paths from exec tool's echo command at phase:start.
483
- // The agent signals inline media with `echo "MEDIA:/absolute/path"` (see plugin's before_prompt_build hint).
484
- // Parsing the tool args here keeps state on this stable singleton instead of the plugin's re-registered closure.
485
- if (sessionKey && (data?.name === 'exec' || data?.name === 'process') && data?.phase === 'start' && typeof data?.args?.command === 'string') {
486
- const paths = [...data.args.command.matchAll(/MEDIA:([^\s"'`]+)/g)].map(m => m[1]).filter(Boolean);
487
- if (paths.length > 0) {
488
- const existing = this._runMediaPaths.get(sessionKey) ?? [];
489
- this._runMediaPaths.set(sessionKey, [...new Set([...existing, ...paths])]);
490
- }
491
- }
492
- // Capture Write/Edit tool paths. The split pane (and existing attachment chip render) handles
493
- // any text-ish or PDF file, so allow that broad set; image/audio extensions also flow through
494
- // — saveAssistantMessage routes them by ext (image → markdown, audio → audio chip).
495
- // Buffer at phase:start when args.path is present; promote to _runMediaPaths at phase:result
496
- // only if the call succeeded — failed writes shouldn't surface a chip for a file that may not exist.
497
- const VIEWABLE_EXTS = new Set([
498
- 'pdf','md','mdx','rst','txt','log',
499
- 'csv','tsv','json','xml','yaml','yml','toml','ini','env','conf',
500
- 'js','jsx','mjs','cjs','ts','tsx','py','rb','go','rs','java','c','cpp','h','hpp','cs','php',
501
- 'html','htm','css','scss','sass','less','sh','bash','zsh','sql','pl','lua','r','swift','kt','dart',
502
- 'png','jpg','jpeg','gif','webp','bmp','svg','ico','avif','tiff',
503
- 'mp3','wav','ogg','m4a','flac','aac','opus','wma'
504
- ]);
505
- if (sessionKey && data?.toolCallId && /^(write|edit|multiedit|notebookedit)$/i.test(data?.name || '') && data?.phase === 'start' && typeof data?.args?.path === 'string' && data.args.path.length > 0) {
506
- const ext = (data.args.path.split('.').pop() || '').toLowerCase();
507
- if (VIEWABLE_EXTS.has(ext)) this._runWriteBuffers.set(data.toolCallId, { sessionKey, path: data.args.path });
508
- }
509
- if (data?.toolCallId && data?.phase === 'result' && this._runWriteBuffers.has(data.toolCallId)) {
510
- const buf = this._runWriteBuffers.get(data.toolCallId);
511
- this._runWriteBuffers.delete(data.toolCallId);
512
- if (!data.isError && buf.sessionKey === sessionKey) {
513
- const existing = this._runMediaPaths.get(buf.sessionKey) ?? [];
514
- this._runMediaPaths.set(buf.sessionKey, [...new Set([...existing, buf.path])]);
515
- }
516
- }
517
- const step = { type: 'tool', timestamp: Date.now(), name: data?.name || 'unknown', phase: data?.phase || 'start', toolCallId: data?.toolCallId, meta: data?.meta || (argsMeta ? String(argsMeta) : undefined), isError: data?.isError || false };
518
- if (data?.phase === 'result') {
519
- const existing = log.steps.findLast(s => s.toolCallId === data.toolCallId && (s.phase === 'start' || s.phase === 'running'));
520
- if (existing) { existing.phase = 'done'; existing.resultMeta = data?.meta; existing.isError = data?.isError || false; existing.durationMs = Date.now() - existing.timestamp; }
521
- else { step.phase = 'done'; log.steps.push(step); }
522
- // Advance the visible content offset to the current buffer end.
523
- // Future streaming-delta broadcasts and the saved message content start from here,
524
- // so the response area always shows only the most recent thought / final answer.
525
- const streamEntry = this.streamState.get(sessionKey);
526
- if (streamEntry && log._parsed) {
527
- // Don't advance thoughtStartOffset or broadcast streaming-reset yet.
528
- // Wait for the first post-tool delta before doing either:
529
- // (a) No post-tool text: thoughtStartOffset stays at the current segment start,
530
- // bubble retains the last segment text as the final answer.
531
- // (b) Post-tool text arrives: delta handler advances the offset and broadcasts
532
- // streaming-reset immediately before the first new-segment delta, so the
533
- // bubble clears at exactly the right moment.
534
- streamEntry.pendingReset = true;
535
- log._lastNarrationStart = streamEntry.buffer.length; // align activity log segments with buffer
536
- }
537
- } else if (data?.phase === 'update') {
538
- const existing = log.steps.findLast(s => s.toolCallId === data.toolCallId);
539
- if (existing) { if (data?.meta) existing.resultMeta = data.meta; if (data?.isError) existing.isError = true; existing.phase = 'running'; }
540
- } else log.steps.push(step);
541
- writeActivityToDb(this.getDb, this.broadcastToBrowsers.bind(this), runId, log);
542
- this._broadcastActivityUpdate(runId, log);
543
- }
544
- if (stream === 'lifecycle' && (data?.phase === 'end' || data?.phase === 'error')) {
545
- if (log._currentAssistantSegment && !log._currentAssistantSegment._sealed) {
546
- log._currentAssistantSegment._sealed = true;
547
- }
548
- writeActivityToDb(this.getDb, this.broadcastToBrowsers.bind(this), runId, log);
549
- // Store finalized state — streaming-end (handleChatEvent) will pick it up and carry it
550
- // as one atomic payload. Do NOT broadcast activity-updated here anymore.
551
- const cleanSteps = log.steps.map(s => { const c = { ...s }; delete c._sealed; return c; });
552
- log.finalized = true;
553
- log.finalSteps = cleanSteps;
554
- log.finalSummary = generateActivitySummary(log.steps);
555
- // Note: activityLogs entry is kept until _popActivityLogForSession cleans it up
556
- //
557
- // Fallback: if the gateway never emitted any chat.* events for this session
558
- // (e.g. pre-reply provider error on a non-webchat surface where the chat
559
- // broadcast is gated off upstream), handleChatEvent won't fire a
560
- // streaming-end and the UI stays locked on "thinking…" forever. Synthesize
561
- // one here so the frontend's existing error path (`reason: 'error'`) runs.
562
- // `!streamState.has(sessionKey)` is also true for a run that finished cleanly (the entry
563
- // is deleted on every terminal state), so the delivered-reply check is what distinguishes
564
- // "never produced a reply" from "already delivered one".
565
- if (data?.phase === 'error' && !this.streamState.has(sessionKey) && !this._syntheticErrorRuns.has(runId) && !this._runsWithDeliveredReply.has(runId)) {
566
- this._syntheticErrorRuns.add(runId);
567
- const parsed = this._locate(sessionKey);
568
- if (parsed) {
569
- // Mirror the state:'error' path — writeActivityToDb just set metadata.pending=true,
570
- // and without this the flag survives: loadHistory re-derives has_pending on reconnect,
571
- // "thinking…" sticks, and sendMessage's isStreaming() guard queues future sends into
572
- // _pendingSend forever.
573
- this.saveErrorMarker(sessionKey, { error: data?.error || 'Agent failed before reply' });
574
- this.broadcastToBrowsers(JSON.stringify({
575
- type: 'clawchats',
576
- event: 'streaming-end',
577
- threadId: parsed.threadId,
578
- workspace: parsed.workspace,
579
- reason: 'error',
580
- errorMessage: data?.error || 'Agent failed before reply',
581
- }));
582
- }
583
- // Bound the set — auto-evict after the retry window so long-lived
584
- // processes don't leak. 5 min is far longer than any retry chain.
585
- setTimeout(() => this._syntheticErrorRuns.delete(runId), 5 * 60 * 1000);
586
- }
587
- }
588
- }
589
-
590
- // Returns and removes the finalized activity log for a given sessionKey, or null if none.
591
- // Called by handleChatEvent so streaming-end carries the final activity state atomically.
592
- _popActivityLogForSession(sessionKey) {
593
- for (const [runId, log] of this.activityLogs) {
594
- if (log.sessionKey === sessionKey && log.finalized) {
595
- this.activityLogs.delete(runId);
596
- return { activityLog: log.finalSteps, activitySummary: log.finalSummary };
597
- }
598
- }
599
- return null;
600
- }
601
-
602
- _broadcastActivityUpdate(runId, log) {
603
- if (!log._parsed || !log._messageId) return;
604
- const cleanSteps = log.steps.map(s => { const c = { ...s }; delete c._sealed; return c; });
605
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'activity-updated', workspace: log._parsed.workspace, threadId: log._parsed.threadId, messageId: log._messageId, activityLog: cleanSteps, activitySummary: generateActivitySummary(log.steps) }));
606
- }
607
-
608
95
  broadcastToBrowsers(data) {
609
96
  this.debugLogger.logFrame('SRV→BR', data);
610
97
  for (const client of this.browserClients.keys()) { if (client.readyState === WS.OPEN) client.send(data); }
@@ -615,6 +102,12 @@ export class GatewayClient {
615
102
  this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'gateway-status', connected }));
616
103
  }
617
104
 
105
+ /** A frame from a browser: the lens may rewrite it or answer it itself. */
106
+ forwardFromBrowser(data) {
107
+ const out = this.lens ? this.lens.outbound(data) : data;
108
+ if (out) this.sendToGateway(out);
109
+ }
110
+
618
111
  sendToGateway(data) {
619
112
  this.debugLogger.logFrame('SRV→GW', data);
620
113
  if (this.ws?.readyState === WS.OPEN) this.ws.send(data);
@@ -625,43 +118,42 @@ export class GatewayClient {
625
118
  const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), this.maxReconnectDelay);
626
119
  this.reconnectAttempts++;
627
120
  console.log(`Reconnecting to gateway in ${delay}ms (attempt ${this.reconnectAttempts})...`);
628
- setTimeout(() => this.connect(), delay);
121
+ clearTimeout(this._reconnectTimer);
122
+ this._reconnectTimer = setTimeout(() => { this._reconnectTimer = null; this.connect(); }, delay);
123
+ }
124
+
125
+ /**
126
+ * Permanent shutdown (plugin stop/reload): no reconnects, pending RPCs fail, socket closed.
127
+ * Without this the gateway's plugin drain waits forever on the open WebSocket.
128
+ */
129
+ close() {
130
+ this._closed = true;
131
+ clearTimeout(this._reconnectTimer);
132
+ this._reconnectTimer = null;
133
+ this._failPendingRpcs('connector stopping');
134
+ this.connected = false;
135
+ const ws = this.ws;
136
+ this.ws = null;
137
+ if (ws) {
138
+ ws.removeAllListeners('message');
139
+ ws.on('error', () => {});
140
+ try { ws.readyState === WS.CONNECTING ? ws.terminate() : ws.close(1001, 'connector stopping'); } catch { /* already closed */ }
141
+ // Don't let a half-closed socket hold the drain open.
142
+ setTimeout(() => { try { ws.terminate(); } catch { /* gone */ } }, 2000).unref?.();
143
+ }
144
+ this.browserClients.clear();
145
+ this._externalBroadcastTargets = [];
629
146
  }
630
147
 
631
148
  addBrowserClient(ws) {
632
- this.browserClients.set(ws, { activeWorkspace: null, activeThreadId: null });
149
+ this.browserClients.set(ws, {});
633
150
  if (ws.readyState === WS.OPEN) {
634
151
  ws.send(JSON.stringify({ type: 'clawchats', event: 'gateway-status', connected: this.connected }));
635
- const streams = [];
636
- for (const [sessionKey, state] of this.streamState.entries()) {
637
- if (state.state === 'streaming' && !(state.held?.length > 0)) {
638
- const parsed = this._locate(sessionKey);
639
- // Include both old shape (sessionKey/buffer) and new shape (workspace/content) for dual-emit compat
640
- streams.push({ sessionKey, threadId: state.threadId, buffer: state.buffer, ...(parsed ? { workspace: parsed.workspace, content: state.buffer.substring(state.thoughtStartOffset || 0) } : {}) });
641
- }
642
- }
643
- if (streams.length > 0) ws.send(JSON.stringify({ type: 'clawchats', event: 'stream-sync', streams }));
644
152
  }
645
153
  }
646
154
 
647
155
  removeBrowserClient(ws) { this.browserClients.delete(ws); }
648
156
 
649
- setActiveThread(ws, workspace, threadId) {
650
- const client = ws ? this.browserClients.get(ws) : null;
651
- if (client) { client.activeWorkspace = workspace; client.activeThreadId = threadId; }
652
- if (!workspace || !threadId) return;
653
- try {
654
- const wsData = this.getWorkspaces();
655
- if (!wsData.workspaces[workspace]) return;
656
- const db = this.getDb(workspace);
657
- if (!db.prepare('SELECT id FROM threads WHERE id = ?').get(threadId)) return;
658
- const deleted = db.prepare('DELETE FROM unread_messages WHERE thread_id = ?').run(threadId);
659
- if (deleted.changes > 0) {
660
- syncThreadUnreadCount(db, threadId);
661
- this.broadcastToBrowsers(JSON.stringify({ type: 'clawchats', event: 'unread-update', workspace, threadId, action: 'clear', unreadCount: 0, workspaceUnreadTotal: db.prepare('SELECT COALESCE(SUM(unread_count), 0) as total FROM threads').get().total, timestamp: Date.now() }));
662
- }
663
- } catch (e) { console.error('Failed to auto-clear unreads on active-thread:', e.message); }
664
- }
665
157
 
666
158
  addBroadcastTarget(fn) { this._externalBroadcastTargets.push(fn); }
667
159
  removeBroadcastTarget(fn) { this._externalBroadcastTargets = this._externalBroadcastTargets.filter(f => f !== fn); }