@clawchatsai/connector 0.1.16 → 0.1.17
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/README.md +1 -2
- package/dist/index.js +34 -133
- package/package.json +2 -1
- package/server/bootstrap/native.js +0 -4
- package/server/config.js +9 -17
- package/server/controllers/filesystem.js +2 -2
- package/server/controllers/gateway-media.js +42 -0
- package/server/controllers/gateway-media.test.js +23 -0
- package/server/debug.js +14 -1
- package/server/debug.test.js +22 -0
- package/server/gateway.js +55 -563
- package/server/gateway.test.js +27 -0
- package/server/history-export.js +10 -1
- package/server/index.js +34 -205
- package/server/session-lens.js +280 -0
- package/server/session-lens.test.js +168 -0
- package/server/store/extras-store.js +77 -0
- package/server/util/helpers.js +2 -105
- package/server/controllers/files.js +0 -64
- package/server/controllers/memory.js +0 -86
- package/server/controllers/messages.js +0 -118
- package/server/controllers/threads.js +0 -119
- package/server/controllers/workspaces.js +0 -116
- package/server/gateway-cleanup.js +0 -31
- package/server/gateway-sync.js +0 -571
- package/server/providers/memory-config.js +0 -52
- package/server/providers/memory.js +0 -108
- package/server/thread-move.js +0 -47
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// SessionLens: the one place that decides which gateway sessions are ClawChats threads,
|
|
2
|
+
// and the filter between the gateway and the browser for session traffic.
|
|
3
|
+
//
|
|
4
|
+
// The gateway sends session-list events to every subscribed connection unfiltered, and
|
|
5
|
+
// the connector's single gateway connection carries everything (Discord, cron, subagents).
|
|
6
|
+
// The lens:
|
|
7
|
+
// - forwards `sessions.changed` only for visible sessions (plus key-less catalog events),
|
|
8
|
+
// with rows trimmed to the fields ClawChats renders;
|
|
9
|
+
// - drops `chat`/`agent` run events of sessions ClawChats doesn't show;
|
|
10
|
+
// - filters/trims the responses to browser-issued `sessions.list|subscribe|search`;
|
|
11
|
+
// - keeps the browser from tearing down the connector's own session subscription;
|
|
12
|
+
// - applies project-style side effects of browser-issued group renames/deletes.
|
|
13
|
+
//
|
|
14
|
+
// Visible = a root, direct, user chat: `agent:<id>:dashboard:<id>` (gateway-created) or
|
|
15
|
+
// `agent:<id>:<project>:chat:<id>` (legacy ClawChats). Everything else is hidden.
|
|
16
|
+
|
|
17
|
+
const DASHBOARD_KEY = /^agent:[^:]+:dashboard:[^:]+$/;
|
|
18
|
+
const LEGACY_CHAT_KEY = /^agent:[^:]+:[^:]+:chat:[^:]+$/;
|
|
19
|
+
const UTILITY_MARK = '__clawchats_';
|
|
20
|
+
const MAIN_SESSION_KEY = /^agent:[^:]+:main$/;
|
|
21
|
+
|
|
22
|
+
// Session row fields the browser needs. Anything else stays on the connector side.
|
|
23
|
+
export const ROW_FIELDS = new Set([
|
|
24
|
+
'key', 'sessionId', 'agentId', 'kind', 'chatType', 'classification', 'incognito',
|
|
25
|
+
'label', 'autoLabel', 'displayName', 'derivedTitle', 'lastMessagePreview', 'icon', 'color',
|
|
26
|
+
'category', 'pinned', 'pinnedAt', 'archived', 'archivedAt',
|
|
27
|
+
'unread', 'lastReadAt', 'markedUnreadAt',
|
|
28
|
+
'createdAt', 'updatedAt', 'lastActivityAt', 'lastInteractionAt',
|
|
29
|
+
'status', 'hasActiveRun', 'activeRunIds', 'lastRunId', 'lastRunError',
|
|
30
|
+
'model', 'modelProvider', 'thinkingLevel', 'contextTokens', 'totalTokens', 'totalTokensFresh',
|
|
31
|
+
'inputTokens', 'outputTokens', 'permissionMode', 'contextBudgetStatus', 'fastMode', 'effectiveFastMode',
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
// `sessions.changed` envelope fields (snapshot fields are spread next to these).
|
|
35
|
+
const EVENT_ENVELOPE = new Set(['sessionKey', 'agentId', 'reason', 'phase', 'ts', 'messageId', 'catalogChanged']);
|
|
36
|
+
|
|
37
|
+
const LIST_DEFAULTS = { excludeSubagents: true, excludeCron: true, excludeSystem: true };
|
|
38
|
+
|
|
39
|
+
export function isUtilityKey(key) {
|
|
40
|
+
return typeof key === 'string' && key.includes(UTILITY_MARK);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function isCandidateKey(key) {
|
|
44
|
+
return typeof key === 'string' && !isUtilityKey(key) && (DASHBOARD_KEY.test(key) || LEGACY_CHAT_KEY.test(key));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ── Visibility: port of the Control UI sidebar rule ──────────────────
|
|
48
|
+
// ui/src/components/app-sidebar-session-parent.ts resolveSidebarSessionParentKey
|
|
49
|
+
// ui/src/lib/sessions/navigation.ts sessionMatchesVisibleSessionScope
|
|
50
|
+
// src/shared/session-list-visibility.ts isSystemCreatedSessionRow
|
|
51
|
+
// plus the ClawChats scope (no group conversations, no coding sessions, see grouping.ts).
|
|
52
|
+
// The Control UI ignores `classification`; so do we.
|
|
53
|
+
|
|
54
|
+
function hasName(row) {
|
|
55
|
+
return [row.label, row.displayName, row.subject].some(v => typeof v === 'string' && v.trim());
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** isSystemCreatedSessionRow (cron keys never reach here: not candidate-shaped). */
|
|
59
|
+
function isSystemCreated(row) {
|
|
60
|
+
if (row.classification === 'hb_signal') return !hasName(row);
|
|
61
|
+
if (row.createdActor?.type === 'system') return true;
|
|
62
|
+
if (row.createdVia !== 'run' && row.createdVia !== 'internal') return false;
|
|
63
|
+
if (row.createdActor?.type === 'human') return false;
|
|
64
|
+
return !hasName(row);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* true = hidden, false = visible, null = undecided (partial event snapshot).
|
|
69
|
+
* Full rows (list rows and event snapshots, which always carry `kind`) decide everything;
|
|
70
|
+
* partial rows only decide on facts that can't be outweighed.
|
|
71
|
+
*/
|
|
72
|
+
export function rowVerdict(row) {
|
|
73
|
+
if (!row || typeof row !== 'object') return null;
|
|
74
|
+
const parent = row.parentSessionKey || row.spawnedBy;
|
|
75
|
+
// Nested children (resolveSidebarSessionParentKey keeps these under their parent).
|
|
76
|
+
// Fork markers only matter together with a parent: a fork of a top-level chat is a
|
|
77
|
+
// top-level chat. ClawChats deviation: forks of main-linked chats (ClawChats edit/regen
|
|
78
|
+
// branches via sessions.fork) stay top level instead of nesting under the main session.
|
|
79
|
+
if (row.spawnedBy) return true;
|
|
80
|
+
if (typeof row.spawnDepth === 'number' && row.spawnDepth > 0) return true;
|
|
81
|
+
// sessions.fork makes the source chat the parent (Control UI nests it there). ClawChats has
|
|
82
|
+
// no nesting and shows edit/regenerate branches as their own chats: a fork whose parent is
|
|
83
|
+
// the chat it was forked from counts as a top-level chat.
|
|
84
|
+
const forkOfChat = !!(row.parentSessionKey && row.forkSource?.sessionKey === row.parentSessionKey && isCandidateKey(row.parentSessionKey));
|
|
85
|
+
if (forkOfChat) return 'kind' in row ? (row.kind === 'global' || row.kind === 'unknown' || row.kind === 'group' || !!row.worktree || !!row.execNode) : null;
|
|
86
|
+
if (parent && !MAIN_SESSION_KEY.test(parent)) return true;
|
|
87
|
+
// Out of the visible scope, or outside ClawChats' scope (Groups / Coding zones).
|
|
88
|
+
if (row.kind === 'global' || row.kind === 'unknown' || row.kind === 'group') return true;
|
|
89
|
+
if (row.worktree || row.execNode) return true;
|
|
90
|
+
if (!('kind' in row)) return null;
|
|
91
|
+
if (isSystemCreated(row)) return true;
|
|
92
|
+
// Main-linked roots are top level only when operator-created (older rows stay nested).
|
|
93
|
+
if (parent && row.createdVia !== 'operator' && !row.forkSource) return true;
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function trimRow(row) {
|
|
98
|
+
const out = {};
|
|
99
|
+
for (const k of Object.keys(row)) if (ROW_FIELDS.has(k)) out[k] = row[k];
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function trimEvent(payload) {
|
|
104
|
+
const out = {};
|
|
105
|
+
for (const k of Object.keys(payload)) {
|
|
106
|
+
if (EVENT_ENVELOPE.has(k) || ROW_FIELDS.has(k)) out[k] = payload[k];
|
|
107
|
+
}
|
|
108
|
+
if (payload.session && typeof payload.session === 'object') out.session = trimRow(payload.session);
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export class SessionLens {
|
|
113
|
+
/**
|
|
114
|
+
* @param {object} opts
|
|
115
|
+
* @param {(data: string) => void} opts.broadcast send a frame to all browsers
|
|
116
|
+
* @param {(method: string, params: object, timeoutMs?: number) => Promise<any>} [opts.request] connector-originated gateway RPC
|
|
117
|
+
* @param {object} [opts.extras] ExtrasStore (project style side effects)
|
|
118
|
+
*/
|
|
119
|
+
constructor({ broadcast, request, extras, logger = console }) {
|
|
120
|
+
this.broadcast = broadcast;
|
|
121
|
+
this.request = request;
|
|
122
|
+
this.extras = extras;
|
|
123
|
+
this.log = logger;
|
|
124
|
+
this.hidden = new Set(); // candidate-shaped keys a row revealed as not a user chat
|
|
125
|
+
this.pending = new Map(); // browser req id -> { method, params }
|
|
126
|
+
// Chats a browser opened with sessions.messages.subscribe (Control UI: one per selected
|
|
127
|
+
// chat). session.message is forwarded only for these. subscriptionId -> session key.
|
|
128
|
+
this.watching = new Map();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ── Visibility ──────────────────────────────────────────────────────
|
|
132
|
+
|
|
133
|
+
/** Learn from a (possibly partial) row; returns whether the session is visible. */
|
|
134
|
+
observe(key, row) {
|
|
135
|
+
if (!isCandidateKey(key)) return false;
|
|
136
|
+
const verdict = rowVerdict(row);
|
|
137
|
+
if (verdict === true) this.hidden.add(key);
|
|
138
|
+
else if (verdict === false) this.hidden.delete(key);
|
|
139
|
+
return !this.hidden.has(key);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
isVisible(key) {
|
|
143
|
+
return isCandidateKey(key) && !this.hidden.has(key);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** chat/agent run events: visible chats plus the connector's own utility sessions. */
|
|
147
|
+
forwardsRunEvent(key) {
|
|
148
|
+
return isUtilityKey(key) || this.isVisible(key);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Seed `hidden` from a full roster so partial events of child sessions stay hidden. */
|
|
152
|
+
async seed() {
|
|
153
|
+
if (!this.request) return;
|
|
154
|
+
let offset = 0, rows = 0;
|
|
155
|
+
for (let page = 0; page < 50; page++) {
|
|
156
|
+
const res = await this.request('sessions.list', { archived: 'all', limit: 1000, offset }, 60000);
|
|
157
|
+
for (const row of res?.sessions || []) { this.observe(row.key, row); rows++; }
|
|
158
|
+
if (!res?.hasMore || res.nextOffset == null) break;
|
|
159
|
+
offset = res.nextOffset;
|
|
160
|
+
}
|
|
161
|
+
this.log.info?.(`[lens] seeded from ${rows} sessions (${this.hidden.size} hidden chat-shaped)`);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ── Gateway → browser ───────────────────────────────────────────────
|
|
165
|
+
|
|
166
|
+
/** `sessions.changed`. Returns the frame to broadcast, or null to drop. */
|
|
167
|
+
sessionsChanged(payload) {
|
|
168
|
+
if (!payload || typeof payload !== 'object') return null;
|
|
169
|
+
const key = payload.sessionKey;
|
|
170
|
+
if (!key) return { type: 'event', event: 'sessions.changed', payload: trimEvent(payload) }; // catalog/groups
|
|
171
|
+
if (!this.observe(key, payload.session || payload)) return null;
|
|
172
|
+
if (payload.reason === 'delete' && this.extras) this.extras.deleteThreadExtras?.(key);
|
|
173
|
+
return { type: 'event', event: 'sessions.changed', payload: trimEvent(payload) };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** `session.message` (live transcript entry). Forwarded only for watched visible chats. */
|
|
177
|
+
sessionMessage(payload) {
|
|
178
|
+
const key = payload?.sessionKey;
|
|
179
|
+
if (!key || !this.isVisible(key) || ![...this.watching.values()].includes(key)) return null;
|
|
180
|
+
const out = {};
|
|
181
|
+
for (const k of Object.keys(payload)) if (k === 'message' || k === 'messageId' || k === 'messageSeq' || k === 'runId' || EVENT_ENVELOPE.has(k) || ROW_FIELDS.has(k)) out[k] = payload[k];
|
|
182
|
+
return { type: 'event', event: 'session.message', payload: out };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ── Browser → gateway ───────────────────────────────────────────────
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Inspect a browser frame bound for the gateway. Returns the (possibly rewritten) frame
|
|
189
|
+
* to send, or null when the lens answered it itself.
|
|
190
|
+
*/
|
|
191
|
+
outbound(frame) {
|
|
192
|
+
let msg;
|
|
193
|
+
try { msg = JSON.parse(frame); } catch { return frame; }
|
|
194
|
+
if (msg?.type !== 'req' || typeof msg.method !== 'string') return frame;
|
|
195
|
+
const { id, method } = msg;
|
|
196
|
+
const params = msg.params && typeof msg.params === 'object' ? msg.params : {};
|
|
197
|
+
switch (method) {
|
|
198
|
+
case 'sessions.unsubscribe':
|
|
199
|
+
// The gateway subscription is per connection and the connector owns it.
|
|
200
|
+
this.broadcast(JSON.stringify({ type: 'res', id, ok: true, payload: { subscribed: true } }));
|
|
201
|
+
return null;
|
|
202
|
+
case 'sessions.list':
|
|
203
|
+
case 'sessions.subscribe': {
|
|
204
|
+
this.pending.set(id, { method });
|
|
205
|
+
// A bare subscribe only toggles the subscription; don't turn it into a list call.
|
|
206
|
+
if (method === 'sessions.subscribe' && Object.keys(params).length === 0) return frame;
|
|
207
|
+
return JSON.stringify({ ...msg, params: { ...LIST_DEFAULTS, ...params } });
|
|
208
|
+
}
|
|
209
|
+
case 'sessions.messages.subscribe':
|
|
210
|
+
if (params.key) this.watching.set(params.subscriptionId || `key:${params.key}`, params.key);
|
|
211
|
+
return frame;
|
|
212
|
+
case 'sessions.messages.unsubscribe':
|
|
213
|
+
if (params.subscriptionId) this.watching.delete(params.subscriptionId);
|
|
214
|
+
else for (const [id, k] of this.watching) if (k === params.key) this.watching.delete(id);
|
|
215
|
+
return frame;
|
|
216
|
+
case 'sessions.search':
|
|
217
|
+
case 'sessions.groups.rename':
|
|
218
|
+
case 'sessions.groups.delete':
|
|
219
|
+
this.pending.set(id, { method, params });
|
|
220
|
+
return frame;
|
|
221
|
+
default:
|
|
222
|
+
return frame;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
ownsResponse(id) {
|
|
227
|
+
return this.pending.has(id);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Response to a browser request the lens tracks. Returns the frame object to broadcast. */
|
|
231
|
+
response(msg) {
|
|
232
|
+
const req = this.pending.get(msg.id);
|
|
233
|
+
this.pending.delete(msg.id);
|
|
234
|
+
if (!req || !msg.ok || !msg.payload) return msg;
|
|
235
|
+
const p = msg.payload;
|
|
236
|
+
switch (req.method) {
|
|
237
|
+
case 'sessions.list':
|
|
238
|
+
return { ...msg, payload: this._filterList(p) };
|
|
239
|
+
case 'sessions.subscribe':
|
|
240
|
+
return p.list ? { ...msg, payload: { ...p, list: this._filterList(p.list) } } : msg;
|
|
241
|
+
case 'sessions.search': {
|
|
242
|
+
const results = (p.results || []).filter(r => this.isVisible(r.sessionKey));
|
|
243
|
+
const sessions = p.sessions ? this._visibleRows(p.sessions) : undefined;
|
|
244
|
+
return { ...msg, payload: { ...p, results, ...(sessions ? { sessions } : {}) } };
|
|
245
|
+
}
|
|
246
|
+
case 'sessions.groups.rename':
|
|
247
|
+
try { this.extras?.renameProjectStyle(req.params?.name, req.params?.to); }
|
|
248
|
+
catch (e) { this.log.warn?.(`[lens] style rename: ${e.message}`); }
|
|
249
|
+
return msg;
|
|
250
|
+
case 'sessions.groups.delete':
|
|
251
|
+
try { this.extras?.deleteProjectStyle(req.params?.name); }
|
|
252
|
+
catch (e) { this.log.warn?.(`[lens] style delete: ${e.message}`); }
|
|
253
|
+
return msg;
|
|
254
|
+
default:
|
|
255
|
+
return msg;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
_visibleRows(rows) {
|
|
260
|
+
const out = [];
|
|
261
|
+
for (const row of rows || []) if (row && this.observe(row.key, row)) out.push(trimRow(row));
|
|
262
|
+
return out;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
_filterList(list) {
|
|
266
|
+
if (!list || !Array.isArray(list.sessions)) return list;
|
|
267
|
+
const sessions = this._visibleRows(list.sessions);
|
|
268
|
+
// Keep paging (gateway offsets stay valid) and defaults; counts/facets described the
|
|
269
|
+
// unfiltered roster, so `count` is recomputed and totals/owners are dropped.
|
|
270
|
+
const out = { sessions, count: sessions.length };
|
|
271
|
+
for (const k of ['ts', 'hasMore', 'nextOffset', 'limitApplied', 'defaults']) if (k in list) out[k] = list[k];
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Forget request ids that never got an answer (gateway disconnect). */
|
|
276
|
+
reset() {
|
|
277
|
+
this.pending.clear();
|
|
278
|
+
this.watching.clear(); // gateway connection gone: browsers re-subscribe on reconnect
|
|
279
|
+
}
|
|
280
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { SessionLens, isCandidateKey, trimRow } from './session-lens.js';
|
|
4
|
+
|
|
5
|
+
const CHAT = 'agent:main:dashboard:abc';
|
|
6
|
+
const LEGACY = 'agent:main:proxmox:chat:1234';
|
|
7
|
+
const CHILD = 'agent:main:dashboard:child1';
|
|
8
|
+
const DISCORD = 'agent:main:discord:channel:99';
|
|
9
|
+
|
|
10
|
+
function lens(extras) {
|
|
11
|
+
const sent = [];
|
|
12
|
+
const l = new SessionLens({ broadcast: d => sent.push(JSON.parse(d)), extras, logger: { info() {}, warn() {} } });
|
|
13
|
+
return { l, sent };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
test('key shapes', () => {
|
|
17
|
+
assert.ok(isCandidateKey(CHAT));
|
|
18
|
+
assert.ok(isCandidateKey(LEGACY));
|
|
19
|
+
for (const k of [DISCORD, 'agent:main:main', 'agent:main:cron:x', 'agent:main:recovered:x', 'agent:main:__clawchats_summarizer', 'agent:main:x:chat:__clawchats_title_1', 'agent:main:node-1'])
|
|
20
|
+
assert.equal(isCandidateKey(k), false, k);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('child sessions stay hidden once a row revealed them, even for partial events', () => {
|
|
24
|
+
const { l } = lens();
|
|
25
|
+
assert.equal(l.sessionsChanged({ sessionKey: CHILD, reason: 'create', parentSessionKey: CHAT, label: 'x' }), null);
|
|
26
|
+
assert.equal(l.sessionsChanged({ sessionKey: CHILD, phase: 'message', ts: 1 }), null);
|
|
27
|
+
assert.equal(l.forwardsRunEvent(CHILD), false);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('visible change is trimmed; catalog events pass', () => {
|
|
31
|
+
const { l } = lens();
|
|
32
|
+
const f = l.sessionsChanged({ sessionKey: CHAT, reason: 'patch', ts: 5, label: 'Hi', category: 'Default', participants: [1, 2], swarm: {}, session: { key: CHAT, label: 'Hi', owner: {}, thinkingOptions: [] } });
|
|
33
|
+
assert.deepEqual(f.payload, { sessionKey: CHAT, reason: 'patch', ts: 5, label: 'Hi', category: 'Default', session: { key: CHAT, label: 'Hi' } });
|
|
34
|
+
assert.equal(l.sessionsChanged({ sessionKey: DISCORD, reason: 'send', channel: 'discord' }), null);
|
|
35
|
+
assert.deepEqual(l.sessionsChanged({ reason: 'groups', ts: 1 }).payload, { reason: 'groups', ts: 1 });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('run events: visible chats and utility sessions only', () => {
|
|
39
|
+
const { l } = lens();
|
|
40
|
+
assert.ok(l.forwardsRunEvent(CHAT));
|
|
41
|
+
assert.ok(l.forwardsRunEvent('agent:main:__clawchats_semantic'));
|
|
42
|
+
assert.ok(l.forwardsRunEvent('agent:main:__clawchats_title_42'));
|
|
43
|
+
assert.equal(l.forwardsRunEvent(DISCORD), false);
|
|
44
|
+
assert.equal(l.forwardsRunEvent('agent:main:main'), false);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('browser sessions.list gets defaults and a filtered, trimmed response', () => {
|
|
48
|
+
const { l } = lens();
|
|
49
|
+
const out = JSON.parse(l.outbound(JSON.stringify({ type: 'req', id: 'r1', method: 'sessions.list', params: { limit: 50 } })));
|
|
50
|
+
assert.deepEqual(out.params, { excludeSubagents: true, excludeCron: true, excludeSystem: true, limit: 50 });
|
|
51
|
+
assert.ok(l.ownsResponse('r1'));
|
|
52
|
+
const res = l.response({ type: 'res', id: 'r1', ok: true, payload: {
|
|
53
|
+
ts: 1, count: 4, totalCount: 4, hasMore: false, nextOffset: null, owners: [{}],
|
|
54
|
+
sessions: [
|
|
55
|
+
{ key: CHAT, label: 'a', owner: {}, classification: 'direct' },
|
|
56
|
+
{ key: LEGACY, label: 'b', classification: 'direct' },
|
|
57
|
+
{ key: CHILD, parentSessionKey: CHAT, classification: 'direct' },
|
|
58
|
+
{ key: DISCORD, classification: 'channel' },
|
|
59
|
+
] } });
|
|
60
|
+
assert.deepEqual(res.payload.sessions.map(s => s.key), [CHAT, LEGACY]);
|
|
61
|
+
assert.equal(res.payload.count, 2);
|
|
62
|
+
assert.equal('owners' in res.payload, false);
|
|
63
|
+
assert.equal('owner' in res.payload.sessions[0], false);
|
|
64
|
+
assert.equal(l.ownsResponse('r1'), false);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test('bare sessions.subscribe passes untouched; subscribe-with-list is filtered', () => {
|
|
68
|
+
const { l } = lens();
|
|
69
|
+
const bare = JSON.stringify({ type: 'req', id: 's0', method: 'sessions.subscribe', params: {} });
|
|
70
|
+
assert.equal(l.outbound(bare), bare);
|
|
71
|
+
l.outbound(JSON.stringify({ type: 'req', id: 's1', method: 'sessions.subscribe', params: { limit: 10 } }));
|
|
72
|
+
const res = l.response({ type: 'res', id: 's1', ok: true, payload: { subscribed: true, list: { sessions: [{ key: CHAT }, { key: DISCORD }] } } });
|
|
73
|
+
assert.deepEqual(res.payload.list.sessions.map(s => s.key), [CHAT]);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('sessions.unsubscribe from a browser is answered locally', () => {
|
|
77
|
+
const { l, sent } = lens();
|
|
78
|
+
assert.equal(l.outbound(JSON.stringify({ type: 'req', id: 'u1', method: 'sessions.unsubscribe' })), null);
|
|
79
|
+
assert.deepEqual(sent[0], { type: 'res', id: 'u1', ok: true, payload: { subscribed: true } });
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('search results are limited to visible sessions', () => {
|
|
83
|
+
const { l } = lens();
|
|
84
|
+
l.outbound(JSON.stringify({ type: 'req', id: 'q', method: 'sessions.search', params: { query: 'x' } }));
|
|
85
|
+
const res = l.response({ type: 'res', id: 'q', ok: true, payload: { results: [{ sessionKey: CHAT }, { sessionKey: DISCORD }], sessions: [{ key: CHAT }, { key: DISCORD }] } });
|
|
86
|
+
assert.deepEqual(res.payload.results, [{ sessionKey: CHAT }]);
|
|
87
|
+
assert.deepEqual(res.payload.sessions, [{ key: CHAT }]);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('group rename/delete move project styles only on success', () => {
|
|
91
|
+
const calls = [];
|
|
92
|
+
const extras = { renameProjectStyle: (a, b) => calls.push(['rename', a, b]), deleteProjectStyle: a => calls.push(['delete', a]), deleteThreadExtras: k => calls.push(['thread', k]) };
|
|
93
|
+
const { l } = lens(extras);
|
|
94
|
+
l.outbound(JSON.stringify({ type: 'req', id: 'g1', method: 'sessions.groups.rename', params: { name: 'A', to: 'B' } }));
|
|
95
|
+
l.outbound(JSON.stringify({ type: 'req', id: 'g2', method: 'sessions.groups.delete', params: { name: 'C' } }));
|
|
96
|
+
l.outbound(JSON.stringify({ type: 'req', id: 'g3', method: 'sessions.groups.delete', params: { name: 'D' } }));
|
|
97
|
+
l.response({ type: 'res', id: 'g1', ok: true, payload: {} });
|
|
98
|
+
l.response({ type: 'res', id: 'g2', ok: true, payload: {} });
|
|
99
|
+
l.response({ type: 'res', id: 'g3', ok: false, error: { message: 'nope' } });
|
|
100
|
+
l.sessionsChanged({ sessionKey: CHAT, reason: 'delete' });
|
|
101
|
+
assert.deepEqual(calls, [['rename', 'A', 'B'], ['delete', 'C'], ['thread', CHAT]]);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('trimRow keeps only allow-listed fields', () => {
|
|
105
|
+
assert.deepEqual(trimRow({ key: 'k', unread: true, participants: [], thinkingOptions: [] }), { key: 'k', unread: true });
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test('chat.history passes through untouched (gateway enforces maxBytes)', () => {
|
|
109
|
+
const { l } = lens();
|
|
110
|
+
const f = JSON.stringify({ type: 'req', id: 'h', method: 'chat.history', params: { sessionKey: CHAT, limit: 80, maxBytes: 262144 } });
|
|
111
|
+
assert.equal(l.outbound(f), f);
|
|
112
|
+
assert.equal(l.ownsResponse('h'), false);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('operator roots linked to the main session are visible; real children are not', () => {
|
|
116
|
+
const { l } = lens();
|
|
117
|
+
assert.ok(l.sessionsChanged({ sessionKey: CHAT, reason: 'create', parentSessionKey: 'agent:main:main', spawnDepth: 0, category: 'test' }));
|
|
118
|
+
assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:k1', reason: 'create', parentSessionKey: 'agent:main:main', spawnedBy: 'agent:main:main' }), null);
|
|
119
|
+
assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:k2', reason: 'create', parentSessionKey: CHAT }), null);
|
|
120
|
+
assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:k3', reason: 'create', parentSessionKey: 'agent:main:main', spawnDepth: 1 }), null);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('Control UI rule: classification ignored, kind/provenance decide, full rows can un-hide', () => {
|
|
124
|
+
const { l } = lens();
|
|
125
|
+
assert.ok(l.sessionsChanged({ sessionKey: CHAT, reason: 'create', classification: 'dashboard', parentSessionKey: 'agent:main:main', spawnDepth: 0 }));
|
|
126
|
+
const K = 'agent:main:dashboard:flip';
|
|
127
|
+
assert.equal(l.sessionsChanged({ sessionKey: K, reason: 'x', kind: 'group' }), null);
|
|
128
|
+
assert.ok(l.sessionsChanged({ sessionKey: K, reason: 'patch', kind: 'direct', createdVia: 'operator', parentSessionKey: 'agent:main:main', spawnDepth: 0 }));
|
|
129
|
+
// legacy main-linked row without operator provenance nests under Home
|
|
130
|
+
assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:old', reason: 'patch', kind: 'direct', parentSessionKey: 'agent:main:main' }), null);
|
|
131
|
+
// system-created probe without a name
|
|
132
|
+
assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:probe', reason: 'create', kind: 'direct', createdVia: 'internal' }), null);
|
|
133
|
+
// coding sessions
|
|
134
|
+
assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:wt', reason: 'create', kind: 'direct', worktree: { id: 'w' } }), null);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('forks of chats are chats (edit/regen branches)', () => {
|
|
138
|
+
const { l } = lens();
|
|
139
|
+
// fork of a legacy top-level chat: no parent
|
|
140
|
+
assert.ok(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:f1', reason: 'create', kind: 'direct', forkSource: { sessionKey: LEGACY, sessionId: 's' } }));
|
|
141
|
+
// fork of a dashboard chat: inherits the main link
|
|
142
|
+
assert.ok(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:f2', reason: 'create', kind: 'direct', createdVia: 'operator', parentSessionKey: 'agent:main:main', spawnDepth: 0, forkSource: { sessionKey: CHAT, sessionId: 's' } }));
|
|
143
|
+
// a fork nested under another chat is still a child
|
|
144
|
+
assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:f3', reason: 'create', kind: 'direct', parentSessionKey: CHAT, forkSource: { sessionKey: LEGACY, sessionId: 's' } }), null); // parent is not the fork source
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test('sessions.fork branches (parent = source chat) are top-level chats', () => {
|
|
148
|
+
const { l } = lens();
|
|
149
|
+
const SRC = 'agent:main:dashboard:src';
|
|
150
|
+
assert.ok(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:br', reason: 'create', kind: 'direct', createdVia: 'operator', parentSessionKey: SRC, forkedFromParent: true, forkSource: { sessionKey: SRC, sessionId: 's', entryId: 'e' } }));
|
|
151
|
+
assert.ok(l.forwardsRunEvent('agent:main:dashboard:br'));
|
|
152
|
+
// a child whose parent is a chat but that is not a fork of it stays nested
|
|
153
|
+
assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:kid', reason: 'create', kind: 'direct', parentSessionKey: SRC }), null);
|
|
154
|
+
// fork of a channel session is not a chat
|
|
155
|
+
assert.equal(l.sessionsChanged({ sessionKey: 'agent:main:dashboard:br2', reason: 'create', kind: 'direct', parentSessionKey: DISCORD, forkSource: { sessionKey: DISCORD } }), null);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test('session.message only for chats a browser subscribed to', () => {
|
|
159
|
+
const { l } = lens();
|
|
160
|
+
const msg = { sessionKey: CHAT, message: { role: 'assistant', content: [] }, messageId: 'm', participants: [1] };
|
|
161
|
+
assert.equal(l.sessionMessage(msg), null);
|
|
162
|
+
l.outbound(JSON.stringify({ type: 'req', id: 's', method: 'sessions.messages.subscribe', params: { key: CHAT, subscriptionId: 'tab1' } }));
|
|
163
|
+
const f = l.sessionMessage(msg);
|
|
164
|
+
assert.deepEqual(f.payload, { sessionKey: CHAT, message: msg.message, messageId: 'm' });
|
|
165
|
+
assert.equal(l.sessionMessage({ ...msg, sessionKey: DISCORD }), null);
|
|
166
|
+
l.outbound(JSON.stringify({ type: 'req', id: 'u', method: 'sessions.messages.unsubscribe', params: { key: CHAT, subscriptionId: 'tab1' } }));
|
|
167
|
+
assert.equal(l.sessionMessage(msg), null);
|
|
168
|
+
});
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// ExtrasStore: ClawChats-only data the gateway has no place for. Lives in the global DB.
|
|
2
|
+
// Registry of what belongs here: EXTRAS.md at the repo root.
|
|
3
|
+
//
|
|
4
|
+
// project_styles color/icon per gateway session group (groups are just {name, position})
|
|
5
|
+
// thread_extras per-session ClawChats data (Intelligence panel etc.), keyed by session key
|
|
6
|
+
|
|
7
|
+
export function createExtrasStore(getGlobalDb) {
|
|
8
|
+
let ready = false;
|
|
9
|
+
function db() {
|
|
10
|
+
const g = getGlobalDb();
|
|
11
|
+
if (!ready) {
|
|
12
|
+
g.exec(`CREATE TABLE IF NOT EXISTS project_styles (name TEXT PRIMARY KEY, color TEXT, icon TEXT, updated_at INTEGER NOT NULL)`);
|
|
13
|
+
g.exec(`CREATE TABLE IF NOT EXISTS thread_extras (session_key TEXT NOT NULL, kind TEXT NOT NULL, data TEXT NOT NULL, updated_at INTEGER NOT NULL, PRIMARY KEY (session_key, kind))`);
|
|
14
|
+
ready = true;
|
|
15
|
+
}
|
|
16
|
+
return g;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
return {
|
|
20
|
+
/** { [groupName]: { color, icon } } */
|
|
21
|
+
getProjectStyles() {
|
|
22
|
+
const out = {};
|
|
23
|
+
for (const r of db().prepare('SELECT name, color, icon FROM project_styles').all()) out[r.name] = { color: r.color, icon: r.icon };
|
|
24
|
+
return out;
|
|
25
|
+
},
|
|
26
|
+
|
|
27
|
+
/** Set color and/or icon; absent fields keep their value, null clears. */
|
|
28
|
+
setProjectStyle(name, { color, icon } = {}) {
|
|
29
|
+
if (!name) return;
|
|
30
|
+
const cur = db().prepare('SELECT color, icon FROM project_styles WHERE name = ?').get(name) || {};
|
|
31
|
+
db().prepare('INSERT INTO project_styles (name, color, icon, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(name) DO UPDATE SET color = excluded.color, icon = excluded.icon, updated_at = excluded.updated_at')
|
|
32
|
+
.run(name, color !== undefined ? color : (cur.color ?? null), icon !== undefined ? icon : (cur.icon ?? null), Date.now());
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
renameProjectStyle(from, to) {
|
|
36
|
+
if (!from || !to || from === to) return;
|
|
37
|
+
const g = db();
|
|
38
|
+
g.exec('BEGIN');
|
|
39
|
+
try {
|
|
40
|
+
g.prepare('DELETE FROM project_styles WHERE name = ?').run(to);
|
|
41
|
+
g.prepare('UPDATE project_styles SET name = ?, updated_at = ? WHERE name = ?').run(to, Date.now(), from);
|
|
42
|
+
g.exec('COMMIT');
|
|
43
|
+
} catch (e) { g.exec('ROLLBACK'); throw e; }
|
|
44
|
+
},
|
|
45
|
+
|
|
46
|
+
deleteProjectStyle(name) {
|
|
47
|
+
if (name) db().prepare('DELETE FROM project_styles WHERE name = ?').run(name);
|
|
48
|
+
},
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Copy styles of legacy projects (workspaces.json) that have none yet. Never overwrites,
|
|
52
|
+
* so a style set through the gateway-native UI wins over the legacy file.
|
|
53
|
+
*/
|
|
54
|
+
seedFromWorkspaces(workspaces) {
|
|
55
|
+
const ins = db().prepare('INSERT OR IGNORE INTO project_styles (name, color, icon, updated_at) VALUES (?, ?, ?, ?)');
|
|
56
|
+
let n = 0;
|
|
57
|
+
for (const p of Object.values(workspaces?.workspaces || {})) {
|
|
58
|
+
if (p?.label && (p.color || p.icon)) n += ins.run(p.label, p.color || null, p.icon || null, Date.now()).changes;
|
|
59
|
+
}
|
|
60
|
+
return n;
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
getThreadExtra(sessionKey, kind) {
|
|
64
|
+
const r = db().prepare('SELECT data FROM thread_extras WHERE session_key = ? AND kind = ?').get(sessionKey, kind);
|
|
65
|
+
return r ? JSON.parse(r.data) : null;
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
setThreadExtra(sessionKey, kind, data) {
|
|
69
|
+
db().prepare('INSERT INTO thread_extras (session_key, kind, data, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(session_key, kind) DO UPDATE SET data = excluded.data, updated_at = excluded.updated_at')
|
|
70
|
+
.run(sessionKey, kind, JSON.stringify(data), Date.now());
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
deleteThreadExtras(sessionKey) {
|
|
74
|
+
if (sessionKey) db().prepare('DELETE FROM thread_extras WHERE session_key = ?').run(sessionKey);
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
package/server/util/helpers.js
CHANGED
|
@@ -1,111 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
db.prepare('UPDATE threads SET unread_count = ? WHERE id = ?').run(count, threadId);
|
|
4
|
-
return count;
|
|
5
|
-
}
|
|
6
|
-
|
|
1
|
+
// Legacy ClawChats session keys: agent:<agent>:<workspace>:chat:<threadId>.
|
|
2
|
+
// Used by the history exporter.
|
|
7
3
|
export function parseSessionKey(sessionKey) {
|
|
8
4
|
if (!sessionKey) return null;
|
|
9
5
|
const match = sessionKey.match(/^agent:([^:]+):([^:]+):chat:([^:]+)$/);
|
|
10
6
|
if (!match) return null;
|
|
11
7
|
return { agent: match[1], workspace: match[2], threadId: match[3] };
|
|
12
8
|
}
|
|
13
|
-
|
|
14
|
-
export function extractContent(message) {
|
|
15
|
-
if (!message) return '';
|
|
16
|
-
if (typeof message.content === 'string') return message.content;
|
|
17
|
-
if (Array.isArray(message.content)) {
|
|
18
|
-
return message.content.filter(p => p.type === 'text').map(p => p.text).join('');
|
|
19
|
-
}
|
|
20
|
-
return '';
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export function isSilentReplyExact(text, token = 'NO_REPLY') {
|
|
24
|
-
if (!text) return false;
|
|
25
|
-
const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
26
|
-
return new RegExp(`^\\s*${escaped}\\s*$`).test(text);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export function isSilentReplyPrefix(text, token = 'NO_REPLY') {
|
|
30
|
-
if (!text) return false;
|
|
31
|
-
const trimmed = text.trimStart();
|
|
32
|
-
if (!trimmed) return false;
|
|
33
|
-
if (trimmed !== trimmed.toUpperCase()) return false;
|
|
34
|
-
const normalized = trimmed.toUpperCase();
|
|
35
|
-
if (normalized.length < 2 || /[^A-Z_]/.test(normalized)) return false;
|
|
36
|
-
const tokenUpper = token.toUpperCase();
|
|
37
|
-
if (!tokenUpper.startsWith(normalized)) return false;
|
|
38
|
-
if (normalized.includes('_')) return true;
|
|
39
|
-
return tokenUpper === 'NO_REPLY' && normalized === 'NO';
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function stripTrailingSentinel(text, token = 'NO_REPLY') {
|
|
43
|
-
if (!text) return text;
|
|
44
|
-
const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
45
|
-
return text.replace(new RegExp(`(?:^|\\s+|\\*+)${escaped}\\s*$`), '').trim();
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export function stripFinalTags(text) {
|
|
49
|
-
return text ? text.replace(/<\s*\/?\s*final\s*>/gi, '') : text;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function sanitizeAssistantContent(text) {
|
|
53
|
-
if (!text) return text;
|
|
54
|
-
let out = stripFinalTags(text);
|
|
55
|
-
out = out.replace(/^(?:[ \t]*\r?\n)+/, '');
|
|
56
|
-
if (out.includes('NO_REPLY')) out = stripTrailingSentinel(out, 'NO_REPLY');
|
|
57
|
-
if (out.includes('HEARTBEAT_OK')) out = stripTrailingSentinel(out, 'HEARTBEAT_OK');
|
|
58
|
-
return out;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export function generateActivitySummary(steps) {
|
|
62
|
-
const toolSteps = steps.filter(s => s.type === 'tool' && s.phase !== 'result' && s.phase !== 'update');
|
|
63
|
-
const hasThinking = steps.some(s => s.type === 'thinking' && s.text);
|
|
64
|
-
const hasNarration = steps.some(s => s.type === 'assistant' && s.text?.trim());
|
|
65
|
-
if (toolSteps.length === 0 && !hasThinking && !hasNarration) return null;
|
|
66
|
-
if (toolSteps.length === 0 && hasThinking) return 'Reasoned through the problem';
|
|
67
|
-
if (toolSteps.length === 0 && hasNarration) return 'Processed in multiple steps';
|
|
68
|
-
const counts = {};
|
|
69
|
-
for (const s of toolSteps) { const name = s.name || 'unknown'; counts[name] = (counts[name] || 0) + 1; }
|
|
70
|
-
const toolNames = { web_search: 'searched the web', web_fetch: 'fetched web pages', Read: 'read files', read: 'read files', Write: 'wrote files', write: 'wrote files', Edit: 'edited files', edit: 'edited files', exec: 'ran commands', Bash: 'ran commands', browser: 'browsed the web', memory_search: 'searched memory', memory_store: 'saved to memory', image: 'analyzed images', message: 'sent messages', sessions_spawn: 'spawned sub-agents', cron: 'managed cron jobs', Grep: 'searched code', grep: 'searched code', Glob: 'found files', glob: 'found files' };
|
|
71
|
-
const parts = [];
|
|
72
|
-
for (const [name, count] of Object.entries(counts)) {
|
|
73
|
-
const friendly = toolNames[name];
|
|
74
|
-
parts.push(friendly ? (count > 1 ? `${friendly} (${count}×)` : friendly) : (count > 1 ? `used ${name} (${count}×)` : `used ${name}`));
|
|
75
|
-
}
|
|
76
|
-
if (parts.length === 0) return null;
|
|
77
|
-
if (parts.length === 1) return parts[0].charAt(0).toUpperCase() + parts[0].slice(1);
|
|
78
|
-
const last = parts.pop();
|
|
79
|
-
return (parts.join(', ') + ' and ' + last).replace(/^./, c => c.toUpperCase());
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export function writeActivityToDb(getDbFn, broadcastFn, runId, log) {
|
|
83
|
-
if (!log._parsed) log._parsed = parseSessionKey(log.sessionKey);
|
|
84
|
-
const parsed = log._parsed;
|
|
85
|
-
if (!parsed) return;
|
|
86
|
-
const db = getDbFn(parsed.workspace);
|
|
87
|
-
if (!db) return;
|
|
88
|
-
const cleanSteps = log.steps.map(s => { const c = { ...s }; delete c._sealed; return c; });
|
|
89
|
-
const summary = generateActivitySummary(log.steps);
|
|
90
|
-
const now = Date.now();
|
|
91
|
-
if (!log._messageId) {
|
|
92
|
-
const thread = db.prepare('SELECT id FROM threads WHERE id = ?').get(parsed.threadId);
|
|
93
|
-
if (!thread) return;
|
|
94
|
-
const messageId = `gw-activity-${runId}`;
|
|
95
|
-
const metadata = { activityLog: cleanSteps, activitySummary: summary, pending: true };
|
|
96
|
-
try {
|
|
97
|
-
db.prepare(`INSERT OR IGNORE INTO messages (id, thread_id, role, content, status, metadata, timestamp, created_at) VALUES (?, ?, 'assistant', '', 'sent', ?, ?, ?)`).run(messageId, parsed.threadId, JSON.stringify(metadata), now, now);
|
|
98
|
-
log._messageId = messageId;
|
|
99
|
-
broadcastFn(JSON.stringify({ type: 'clawchats', event: 'message-saved', threadId: parsed.threadId, workspace: parsed.workspace, messageId, timestamp: now }));
|
|
100
|
-
} catch (err) {
|
|
101
|
-
console.error(`[activity] Failed to write activity ${messageId}:`, err.message);
|
|
102
|
-
}
|
|
103
|
-
} else {
|
|
104
|
-
const existing = db.prepare('SELECT metadata FROM messages WHERE id = ?').get(log._messageId);
|
|
105
|
-
const metadata = existing?.metadata ? JSON.parse(existing.metadata) : {};
|
|
106
|
-
metadata.activityLog = cleanSteps;
|
|
107
|
-
metadata.activitySummary = summary;
|
|
108
|
-
metadata.pending = true;
|
|
109
|
-
db.prepare('UPDATE messages SET metadata = ? WHERE id = ?').run(JSON.stringify(metadata), log._messageId);
|
|
110
|
-
}
|
|
111
|
-
}
|