@clawchatsai/connector 0.1.24 → 0.1.26
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/dist/auth-handler.d.ts +1 -1
- package/dist/auth-handler.js +52 -12
- package/dist/index.js +3 -5
- package/package.json +1 -1
- package/server/controllers/filesystem.js +110 -5
- package/server/controllers/filesystem.test.js +82 -1
- package/server/index.js +33 -1
- package/server/store/extras-store.js +42 -1
- package/server/store/extras-store.test.js +24 -0
package/dist/auth-handler.d.ts
CHANGED
|
@@ -53,6 +53,6 @@ export declare function handleAuthMessage(dc: DataChannelSend, connectionId: str
|
|
|
53
53
|
*/
|
|
54
54
|
export declare function cleanupAuth(connectionId: string): void;
|
|
55
55
|
/**
|
|
56
|
-
* Check if a connection
|
|
56
|
+
* Check if a connection completed auth.
|
|
57
57
|
*/
|
|
58
58
|
export declare function isAuthenticated(connectionId: string): boolean;
|
package/dist/auth-handler.js
CHANGED
|
@@ -19,15 +19,31 @@ import { issueSessionToken, verifySessionToken } from './session-token.js';
|
|
|
19
19
|
// ---------------------------------------------------------------------------
|
|
20
20
|
/** Tracks per-connection auth state */
|
|
21
21
|
const authSessions = new Map();
|
|
22
|
+
/**
|
|
23
|
+
* Connections that completed auth. This is the only thing that grants access:
|
|
24
|
+
* a connection whose auth session was dropped (timeout, rate limit, eviction)
|
|
25
|
+
* is NOT authenticated, it is blocked until it reconnects.
|
|
26
|
+
*/
|
|
27
|
+
const authenticatedConnections = new Set();
|
|
22
28
|
/** Rate limiting: connectionIds blocked after too many failures */
|
|
23
29
|
const blockedConnections = new Map(); // connectionId → unblock timestamp
|
|
24
30
|
/** TOTP replay prevention */
|
|
25
31
|
let lastUsedTotpStep = 0;
|
|
32
|
+
/**
|
|
33
|
+
* Gateway-wide auth-full lockout. Per-connection limits alone reset on every
|
|
34
|
+
* reconnect, so failures are also counted across all connections.
|
|
35
|
+
*/
|
|
36
|
+
let globalFailCount = 0;
|
|
37
|
+
let globalLockoutCount = 0;
|
|
38
|
+
let globalLockedUntil = 0;
|
|
26
39
|
/** Max nonces to prevent memory leaks from connection storms */
|
|
27
40
|
const MAX_PENDING_NONCES = 10;
|
|
28
41
|
const AUTH_TIMEOUT_MS = 60_000; // 60s — enough time to open authenticator app and enter code
|
|
29
42
|
const MAX_FAILURES = 5;
|
|
30
43
|
const BLOCK_DURATION_MS = 60_000;
|
|
44
|
+
const GLOBAL_MAX_FAILURES = 5;
|
|
45
|
+
const GLOBAL_LOCKOUT_BASE_MS = 60_000; // doubles per consecutive lockout
|
|
46
|
+
const GLOBAL_LOCKOUT_MAX_MS = 60 * 60_000;
|
|
31
47
|
// ---------------------------------------------------------------------------
|
|
32
48
|
// Public API
|
|
33
49
|
// ---------------------------------------------------------------------------
|
|
@@ -63,6 +79,8 @@ export function initAuth(dc, connectionId) {
|
|
|
63
79
|
const old = authSessions.get(oldestKey);
|
|
64
80
|
clearTimeout(old.timeoutHandle);
|
|
65
81
|
authSessions.delete(oldestKey);
|
|
82
|
+
// Tell the evicted client so it reconnects instead of hanging
|
|
83
|
+
old.dc.send(JSON.stringify({ type: 'auth-failed', reason: 'auth_timeout' }));
|
|
66
84
|
}
|
|
67
85
|
}
|
|
68
86
|
const nonce = crypto.randomBytes(32).toString('hex');
|
|
@@ -83,6 +101,7 @@ export function initAuth(dc, connectionId) {
|
|
|
83
101
|
failCount: 0,
|
|
84
102
|
createdAt: Date.now(),
|
|
85
103
|
timeoutHandle,
|
|
104
|
+
dc,
|
|
86
105
|
});
|
|
87
106
|
dc.send(JSON.stringify({
|
|
88
107
|
type: 'auth-required',
|
|
@@ -99,16 +118,14 @@ export function initAuth(dc, connectionId) {
|
|
|
99
118
|
* 'blocked' if the message was dropped (pre-auth non-auth message)
|
|
100
119
|
*/
|
|
101
120
|
export async function handleAuthMessage(dc, connectionId, msg, config) {
|
|
102
|
-
|
|
103
|
-
// No auth session = already authenticated or unknown connection
|
|
104
|
-
if (!session) {
|
|
121
|
+
if (authenticatedConnections.has(connectionId)) {
|
|
105
122
|
return 'pass';
|
|
106
123
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
return '
|
|
124
|
+
const session = authSessions.get(connectionId);
|
|
125
|
+
// No auth session and never authenticated: the session was dropped (timeout,
|
|
126
|
+
// rate limit, eviction) or never started. Block; the client must reconnect.
|
|
127
|
+
if (!session || session.state !== 'awaiting-auth') {
|
|
128
|
+
return 'blocked';
|
|
112
129
|
}
|
|
113
130
|
// Only accept auth messages pre-auth
|
|
114
131
|
const msgType = msg['type'];
|
|
@@ -141,16 +158,23 @@ export async function handleAuthMessage(dc, connectionId, msg, config) {
|
|
|
141
158
|
const totp = msg['totp'];
|
|
142
159
|
const sessionDays = msg['sessionDays'] || 7;
|
|
143
160
|
const msgNonce = msg['nonce'];
|
|
161
|
+
// Gateway-wide lockout: refuse without checking anything, so no guess is tested
|
|
162
|
+
if (Date.now() < globalLockedUntil) {
|
|
163
|
+
dc.send(JSON.stringify({ type: 'auth-failed', reason: 'rate_limited' }));
|
|
164
|
+
return 'pending';
|
|
165
|
+
}
|
|
144
166
|
// Verify nonce
|
|
145
167
|
if (msgNonce !== session.nonce) {
|
|
146
168
|
return sendFailure(dc, connectionId, 'nonce_mismatch');
|
|
147
169
|
}
|
|
148
|
-
//
|
|
170
|
+
// Google ID token check. The frontend sends 'signaling-verified' on purpose
|
|
171
|
+
// (bd29058): login.clawchats.ai already did Google sign-in, so TOTP is the
|
|
172
|
+
// connector-side factor and the gateway-wide lockout above protects it.
|
|
149
173
|
const skipGoogle = !config.google.clientId || config.google.clientId === 'dev-placeholder'
|
|
150
174
|
|| idToken === 'signaling-verified'
|
|
151
175
|
|| (config.devMode && idToken === 'dev-mode-no-google');
|
|
152
176
|
if (skipGoogle) {
|
|
153
|
-
console.log('[Auth] Skipping Google ID token verification (
|
|
177
|
+
console.log('[Auth] Skipping Google ID token verification (TOTP-only auth)');
|
|
154
178
|
}
|
|
155
179
|
else {
|
|
156
180
|
try {
|
|
@@ -192,14 +216,18 @@ export async function handleAuthMessage(dc, connectionId, msg, config) {
|
|
|
192
216
|
// Caller should persist the updated config
|
|
193
217
|
}
|
|
194
218
|
else {
|
|
219
|
+
recordGlobalFailure();
|
|
195
220
|
return sendFailure(dc, connectionId, 'invalid_totp');
|
|
196
221
|
}
|
|
197
222
|
}
|
|
223
|
+
globalFailCount = 0;
|
|
224
|
+
globalLockoutCount = 0;
|
|
198
225
|
// Issue session token
|
|
199
226
|
const sessionToken = issueSessionToken(config.userId, config.google.authorizedSub, sessionDays, config.sessionSecret);
|
|
200
227
|
const expiresAt = new Date(Date.now() + Math.min(Math.max(sessionDays, 1), 30) * 86400 * 1000).toISOString();
|
|
201
228
|
clearTimeout(session.timeoutHandle);
|
|
202
229
|
authSessions.delete(connectionId);
|
|
230
|
+
authenticatedConnections.add(connectionId);
|
|
203
231
|
dc.send(JSON.stringify({
|
|
204
232
|
type: 'auth-ok',
|
|
205
233
|
sessionToken,
|
|
@@ -218,12 +246,13 @@ export function cleanupAuth(connectionId) {
|
|
|
218
246
|
clearTimeout(session.timeoutHandle);
|
|
219
247
|
authSessions.delete(connectionId);
|
|
220
248
|
}
|
|
249
|
+
authenticatedConnections.delete(connectionId);
|
|
221
250
|
}
|
|
222
251
|
/**
|
|
223
|
-
* Check if a connection
|
|
252
|
+
* Check if a connection completed auth.
|
|
224
253
|
*/
|
|
225
254
|
export function isAuthenticated(connectionId) {
|
|
226
|
-
return
|
|
255
|
+
return authenticatedConnections.has(connectionId);
|
|
227
256
|
}
|
|
228
257
|
// ---------------------------------------------------------------------------
|
|
229
258
|
// Internal helpers
|
|
@@ -234,9 +263,20 @@ function authSuccess(dc, connectionId) {
|
|
|
234
263
|
clearTimeout(session.timeoutHandle);
|
|
235
264
|
authSessions.delete(connectionId);
|
|
236
265
|
}
|
|
266
|
+
authenticatedConnections.add(connectionId);
|
|
237
267
|
dc.send(JSON.stringify({ type: 'auth-ok' }));
|
|
238
268
|
return 'authenticated';
|
|
239
269
|
}
|
|
270
|
+
function recordGlobalFailure() {
|
|
271
|
+
globalFailCount++;
|
|
272
|
+
if (globalFailCount < GLOBAL_MAX_FAILURES)
|
|
273
|
+
return;
|
|
274
|
+
const duration = Math.min(GLOBAL_LOCKOUT_BASE_MS * 2 ** globalLockoutCount, GLOBAL_LOCKOUT_MAX_MS);
|
|
275
|
+
globalLockedUntil = Date.now() + duration;
|
|
276
|
+
globalLockoutCount++;
|
|
277
|
+
globalFailCount = 0;
|
|
278
|
+
console.warn(`[Auth] ${GLOBAL_MAX_FAILURES} failed TOTP attempts — full auth locked for ${duration / 1000}s`);
|
|
279
|
+
}
|
|
240
280
|
function sendFailure(dc, connectionId, reason) {
|
|
241
281
|
const session = authSessions.get(connectionId);
|
|
242
282
|
if (!session)
|
package/dist/index.js
CHANGED
|
@@ -445,11 +445,9 @@ function setupDataChannelHandler(dc, connectionId, ctx) {
|
|
|
445
445
|
// Pre-auth non-auth message — drop silently
|
|
446
446
|
return;
|
|
447
447
|
case 'pass':
|
|
448
|
-
//
|
|
449
|
-
//
|
|
450
|
-
//
|
|
451
|
-
// acceptable because auth_timeout now triggers a P2P reconnect
|
|
452
|
-
// (Fix 4), which re-establishes the full auth flow.
|
|
448
|
+
// Completed auth on this connection — process message normally.
|
|
449
|
+
// A connection whose auth timed out or was rate-limited gets
|
|
450
|
+
// 'blocked', never 'pass'; the client reconnects (Fix 4).
|
|
453
451
|
break;
|
|
454
452
|
}
|
|
455
453
|
// Authenticated message processing
|
package/package.json
CHANGED
|
@@ -68,16 +68,121 @@ export function handleWorkspaceList(req, res, query) {
|
|
|
68
68
|
send(res, 200, { files, cwd: resolved });
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
const MAX_HINTS = 40;
|
|
72
|
+
const MAX_SEARCH_DIRS = 400;
|
|
73
|
+
|
|
74
|
+
function isFile(p) {
|
|
75
|
+
try { return fs.statSync(p).isFile(); } catch { return false; }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function exists(p) {
|
|
79
|
+
try { fs.statSync(p); return true; } catch { return false; }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function addMatch(matches, candidate) {
|
|
83
|
+
if (!isFile(candidate)) return;
|
|
84
|
+
try { matches.set(fs.realpathSync(candidate), candidate); } catch { /* vanished */ }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// True when the file sits in a git main checkout (`.git` is a folder), false in a linked
|
|
88
|
+
// worktree (`.git` is a file) or outside git.
|
|
89
|
+
function inMainCheckout(file) {
|
|
90
|
+
for (let dir = path.dirname(file); ; dir = path.dirname(dir)) {
|
|
91
|
+
try { return fs.statSync(path.join(dir, '.git')).isDirectory(); } catch { /* keep walking */ }
|
|
92
|
+
if (dir === path.dirname(dir)) return false;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// One distinct file wins; among several, a single one in a git main checkout wins (other chats'
|
|
97
|
+
// worktrees carry copies of the same file). Anything else is ambiguous.
|
|
98
|
+
function pickMatch(matches) {
|
|
99
|
+
const found = [...matches.values()];
|
|
100
|
+
if (found.length <= 1) return found[0] ?? null;
|
|
101
|
+
const main = found.filter(inMainCheckout);
|
|
102
|
+
return main.length === 1 ? main[0] : null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Directory children worth searching: no dot-folders, no node_modules.
|
|
106
|
+
function childDirs(dir) {
|
|
107
|
+
try {
|
|
108
|
+
return fs.readdirSync(dir, { withFileTypes: true })
|
|
109
|
+
.filter(e => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')
|
|
110
|
+
.map(e => path.join(dir, e.name));
|
|
111
|
+
} catch { return []; }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// The hint's folder no longer exists (typically a worktree removed after its branch merged). Search
|
|
115
|
+
// two levels below the parent of its nearest surviving ancestor, kept inside HOME, for the file.
|
|
116
|
+
function searchAroundGoneHint(hint, p, matches, searched) {
|
|
117
|
+
let survivor = path.dirname(hint);
|
|
118
|
+
while (!exists(survivor) && survivor !== path.dirname(survivor)) survivor = path.dirname(survivor);
|
|
119
|
+
const insideHome = d => d.startsWith(HOME + path.sep);
|
|
120
|
+
const base = insideHome(path.dirname(survivor)) ? path.dirname(survivor) : insideHome(survivor) ? survivor : null;
|
|
121
|
+
if (!base || searched.has(base)) return;
|
|
122
|
+
searched.add(base);
|
|
123
|
+
let budget = MAX_SEARCH_DIRS;
|
|
124
|
+
for (const child of childDirs(base)) {
|
|
125
|
+
if (--budget < 0) return;
|
|
126
|
+
addMatch(matches, path.join(child, p));
|
|
127
|
+
for (const grandchild of childDirs(child)) {
|
|
128
|
+
if (--budget < 0) return;
|
|
129
|
+
addMatch(matches, path.join(grandchild, p));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Where a file reference from chat points (specs/file-link-check.md in the clawchats repo).
|
|
136
|
+
* `~` is home and absolute paths stand as written. A relative path tries the session root, then
|
|
137
|
+
* the agent workspace. Failing those it tries every ancestor of each hint (absolute paths from
|
|
138
|
+
* the same turn's tool calls, e.g. a `cd` target); if none matches, hints whose folder is gone get
|
|
139
|
+
* a bounded search near where they were. Ties go to a git main checkout (pickMatch).
|
|
140
|
+
* Returns the absolute path, or null.
|
|
141
|
+
*/
|
|
142
|
+
export function resolveReadPath(filePath, { roots = [], hints = [] } = {}) {
|
|
143
|
+
const p = filePath.replace(/^~(?=\/|$)/, HOME);
|
|
144
|
+
if (path.isAbsolute(p)) return isFile(p) ? path.resolve(p) : null;
|
|
145
|
+
for (const root of roots) {
|
|
146
|
+
if (!root) continue;
|
|
147
|
+
const candidate = path.resolve(root, p);
|
|
148
|
+
if (isFile(candidate)) return candidate;
|
|
149
|
+
}
|
|
150
|
+
const absHints = [...new Set(hints.slice(0, MAX_HINTS)
|
|
151
|
+
.map(h => h.replace(/^~(?=\/|$)/, HOME))
|
|
152
|
+
.filter(h => path.isAbsolute(h))
|
|
153
|
+
.map(h => path.resolve(h)))];
|
|
154
|
+
const matches = new Map(); // real path -> path as found
|
|
155
|
+
const tried = new Set();
|
|
156
|
+
for (const hint of absHints) {
|
|
157
|
+
for (let dir = hint; ; dir = path.dirname(dir)) {
|
|
158
|
+
if (!tried.has(dir)) {
|
|
159
|
+
tried.add(dir);
|
|
160
|
+
addMatch(matches, path.resolve(dir, p));
|
|
161
|
+
}
|
|
162
|
+
if (dir === path.dirname(dir)) break;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (matches.size) return pickMatch(matches);
|
|
166
|
+
const searched = new Set();
|
|
167
|
+
for (const hint of absHints) {
|
|
168
|
+
if (!exists(hint)) searchAroundGoneHint(hint, p, matches, searched);
|
|
169
|
+
}
|
|
170
|
+
return pickMatch(matches);
|
|
171
|
+
}
|
|
172
|
+
|
|
71
173
|
// Reads any file the gateway user can read (file links in chat open any path, as the agent
|
|
72
|
-
// wrote it)
|
|
73
|
-
//
|
|
74
|
-
|
|
174
|
+
// wrote it); resolution in resolveReadPath. `stat=1` answers {path, size} instead of the
|
|
175
|
+
// content, so a click can check a link before opening the pane. `hints` is newline-separated.
|
|
176
|
+
// Writes and deletes stay limited to HOME.
|
|
177
|
+
export function handleWorkspaceFileRead(req, res, query, workspaceDir, sessionRoot = null) {
|
|
75
178
|
const filePath = query.path;
|
|
76
179
|
if (!filePath) return sendError(res, 400, 'Missing path parameter');
|
|
77
|
-
const
|
|
78
|
-
|
|
180
|
+
const hints = query.hints ? query.hints.split('\n').filter(Boolean) : [];
|
|
181
|
+
const resolved = resolveReadPath(filePath, { roots: [sessionRoot, workspaceDir], hints });
|
|
182
|
+
if (!resolved) return sendError(res, 404, 'File not found');
|
|
79
183
|
|
|
80
184
|
const stat = fs.statSync(resolved);
|
|
185
|
+
if (query.stat) return send(res, 200, { path: resolved, size: stat.size });
|
|
81
186
|
const ext = path.extname(resolved).toLowerCase().slice(1);
|
|
82
187
|
const binaryMime = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', bmp: 'image/bmp', ico: 'image/x-icon', pdf: 'application/pdf', mp3: 'audio/mpeg', mp4: 'video/mp4', wav: 'audio/wav', ogg: 'audio/ogg', webm: 'video/webm' };
|
|
83
188
|
const mime = binaryMime[ext];
|
|
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
|
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import os from 'node:os';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import { handleWorkspaceFileRead, handleWorkspaceCreate } from './filesystem.js';
|
|
6
|
+
import { handleWorkspaceFileRead, handleWorkspaceCreate, resolveReadPath } from './filesystem.js';
|
|
7
7
|
|
|
8
8
|
function read(filePath, workspaceDir) {
|
|
9
9
|
const out = { status: 0, body: '' };
|
|
@@ -47,6 +47,87 @@ test('file reads: ~/ expands to home', () => {
|
|
|
47
47
|
}
|
|
48
48
|
});
|
|
49
49
|
|
|
50
|
+
test('resolveReadPath: session root before workspace, then a unique match under a hint ancestor', () => {
|
|
51
|
+
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-resolve-'));
|
|
52
|
+
const mk = (rel, body = rel) => { const f = path.join(base, rel); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, body); return f; };
|
|
53
|
+
const inSession = mk('session/src/a.ts');
|
|
54
|
+
mk('ws/src/a.ts');
|
|
55
|
+
const inRepo = mk('repos/up/ui/src/pages/p.ts');
|
|
56
|
+
mk('repos/up/ui/src/pages/deep/x.md');
|
|
57
|
+
mk('one/lib/dup.ts');
|
|
58
|
+
mk('two/lib/dup.ts');
|
|
59
|
+
const roots = [path.join(base, 'session'), path.join(base, 'ws')];
|
|
60
|
+
try {
|
|
61
|
+
assert.equal(resolveReadPath('src/a.ts', { roots }), inSession);
|
|
62
|
+
assert.equal(resolveReadPath('src/a.ts', { roots: [null, path.join(base, 'ws')] }), path.join(base, 'ws/src/a.ts'));
|
|
63
|
+
assert.equal(resolveReadPath(inRepo, { roots }), inRepo);
|
|
64
|
+
assert.equal(resolveReadPath('ui/src/pages/p.ts', { roots }), null);
|
|
65
|
+
// The agent `cd`'d deep into the repo; the repo root is an ancestor of the hint.
|
|
66
|
+
assert.equal(resolveReadPath('ui/src/pages/p.ts', { roots, hints: [path.join(base, 'repos/up/ui/src/pages/deep')] }), inRepo);
|
|
67
|
+
// Two different files match: ambiguous, not found.
|
|
68
|
+
assert.equal(resolveReadPath('lib/dup.ts', { roots, hints: [path.join(base, 'one/lib'), path.join(base, 'two')] }), null);
|
|
69
|
+
// Relative hints are ignored.
|
|
70
|
+
assert.equal(resolveReadPath('ui/src/pages/p.ts', { roots, hints: ['repos/up'] }), null);
|
|
71
|
+
} finally {
|
|
72
|
+
fs.rmSync(base, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('resolveReadPath: a hint into a removed worktree finds the file in the main checkout', () => {
|
|
77
|
+
// Searches stay inside HOME, so this layout lives there.
|
|
78
|
+
const base = fs.mkdtempSync(path.join(os.homedir(), '.cc-gone-'));
|
|
79
|
+
const mk = (rel, body = rel) => { const f = path.join(base, rel); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, body); return f; };
|
|
80
|
+
fs.mkdirSync(path.join(base, 'repos/app/.git'), { recursive: true });
|
|
81
|
+
const main = mk('repos/app/known-gaps/q.md');
|
|
82
|
+
// Another chat's live worktree of the same repo has a copy (linked worktree: `.git` is a file).
|
|
83
|
+
mk('repos/worktrees/app-other/.git', 'gitdir: elsewhere');
|
|
84
|
+
mk('repos/worktrees/app-other/known-gaps/q.md');
|
|
85
|
+
const gone = path.join(base, 'repos/worktrees/app-queue/frontend');
|
|
86
|
+
try {
|
|
87
|
+
assert.equal(resolveReadPath('known-gaps/q.md', { hints: [gone] }), main);
|
|
88
|
+
// Two main checkouts with the file: ambiguous.
|
|
89
|
+
fs.mkdirSync(path.join(base, 'repos/fork/.git'), { recursive: true });
|
|
90
|
+
mk('repos/fork/known-gaps/q.md');
|
|
91
|
+
assert.equal(resolveReadPath('known-gaps/q.md', { hints: [gone] }), null);
|
|
92
|
+
// Hints that still exist never trigger the search.
|
|
93
|
+
assert.equal(resolveReadPath('known-gaps/q.md', { hints: [path.join(base, 'repos/worktrees')] }), null);
|
|
94
|
+
} finally {
|
|
95
|
+
fs.rmSync(base, { recursive: true, force: true });
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('resolveReadPath: several hint matches prefer the git main checkout', () => {
|
|
100
|
+
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-tie-'));
|
|
101
|
+
const mk = (rel, body = rel) => { const f = path.join(base, rel); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, body); return f; };
|
|
102
|
+
fs.mkdirSync(path.join(base, 'app/.git'), { recursive: true });
|
|
103
|
+
const main = mk('app/src/a.js');
|
|
104
|
+
mk('wt/.git', 'gitdir: elsewhere');
|
|
105
|
+
mk('wt/src/a.js');
|
|
106
|
+
try {
|
|
107
|
+
assert.equal(resolveReadPath('src/a.js', { hints: [path.join(base, 'app/lib'), path.join(base, 'wt/lib')] }), main);
|
|
108
|
+
} finally {
|
|
109
|
+
fs.rmSync(base, { recursive: true, force: true });
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test('file reads: stat=1 answers the resolved path and size; hints arrive newline-separated', () => {
|
|
114
|
+
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-stat-'));
|
|
115
|
+
const f = path.join(base, 'repo/docs/n.md');
|
|
116
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
117
|
+
fs.writeFileSync(f, 'hello');
|
|
118
|
+
const out = { status: 0, body: '' };
|
|
119
|
+
const res = { writeHead(s) { out.status = s; }, setHeader() {}, end(b) { out.body = String(b ?? ''); } };
|
|
120
|
+
try {
|
|
121
|
+
handleWorkspaceFileRead({}, res, { path: 'docs/n.md', stat: '1', hints: `/nonexistent\n${path.join(base, 'repo/docs')}` }, '/nonexistent-ws');
|
|
122
|
+
assert.equal(out.status, 200);
|
|
123
|
+
assert.deepEqual(JSON.parse(out.body), { path: f, size: 5 });
|
|
124
|
+
handleWorkspaceFileRead({}, res, { path: 'docs/gone.md', stat: '1' }, base, path.join(base, 'repo'));
|
|
125
|
+
assert.equal(out.status, 404);
|
|
126
|
+
} finally {
|
|
127
|
+
fs.rmSync(base, { recursive: true, force: true });
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
|
|
50
131
|
function create(query) {
|
|
51
132
|
const out = { status: 0, body: null };
|
|
52
133
|
const res = {
|
package/server/index.js
CHANGED
|
@@ -72,6 +72,21 @@ export function createApp(config = {}) {
|
|
|
72
72
|
catch (e) { console.error('[extras] style seed failed:', e.message); }
|
|
73
73
|
gatewayClient.lens = new SessionLens({ broadcast, request: (m, p, t) => gatewayClient.request(m, p, t), extras });
|
|
74
74
|
|
|
75
|
+
// A session's working root, for relative file links (gateway resolveSessionWorkspaceRoots:
|
|
76
|
+
// spawnedCwd before sessionRoot). Cached briefly; null when the gateway can't say.
|
|
77
|
+
const sessionRoots = new Map(); // key -> { root, at }
|
|
78
|
+
async function sessionRoot(key) {
|
|
79
|
+
const hit = sessionRoots.get(key);
|
|
80
|
+
if (hit && Date.now() - hit.at < 60_000) return hit.root;
|
|
81
|
+
let root = null;
|
|
82
|
+
try {
|
|
83
|
+
const s = (await gatewayClient.request('sessions.describe', { key }, 5000))?.session;
|
|
84
|
+
root = s?.spawnedCwd || s?.sessionRoot || null;
|
|
85
|
+
} catch { /* fall back to the workspace */ }
|
|
86
|
+
sessionRoots.set(key, { root, at: Date.now() });
|
|
87
|
+
return root;
|
|
88
|
+
}
|
|
89
|
+
|
|
75
90
|
// Instantiate controllers
|
|
76
91
|
const handleGatewayMedia = createGatewayMediaHandler({ gatewayWsUrl: gatewayUrl, gatewayToken });
|
|
77
92
|
|
|
@@ -153,7 +168,7 @@ export function createApp(config = {}) {
|
|
|
153
168
|
if (method === 'GET' && urlPath === '/api/file') return handleServeFile(req, res, query, workspaceDir);
|
|
154
169
|
if (method === 'GET' && urlPath === '/api/gw-media') return handleGatewayMedia(req, res, query);
|
|
155
170
|
if (method === 'GET' && urlPath === '/api/workspace') return handleWorkspaceList(req, res, query);
|
|
156
|
-
if (method === 'GET' && urlPath === '/api/workspace/file') return handleWorkspaceFileRead(req, res, query, workspaceDir);
|
|
171
|
+
if (method === 'GET' && urlPath === '/api/workspace/file') return handleWorkspaceFileRead(req, res, query, workspaceDir, query.session ? await sessionRoot(query.session) : null);
|
|
157
172
|
if (method === 'PUT' && urlPath === '/api/workspace/file') return await handleWorkspaceFileWrite(req, res, query);
|
|
158
173
|
if (method === 'DELETE' && urlPath === '/api/workspace/file') return handleWorkspaceFileDelete(req, res, query);
|
|
159
174
|
if (method === 'POST' && urlPath === '/api/workspace/upload') return await handleWorkspaceUpload(req, res, query);
|
|
@@ -183,6 +198,23 @@ export function createApp(config = {}) {
|
|
|
183
198
|
broadcast(JSON.stringify({ type: 'clawchats', event: 'project-styles-changed' }));
|
|
184
199
|
return send(res, 200, { ok: true });
|
|
185
200
|
}
|
|
201
|
+
if (method === 'GET' && urlPath === '/api/extras/bookmarks') return send(res, 200, { bookmarks: extras.listBookmarks() });
|
|
202
|
+
if (method === 'POST' && urlPath === '/api/extras/bookmarks') {
|
|
203
|
+
const bookmark = extras.addBookmark(uuid(), await parseBody(req));
|
|
204
|
+
if (!bookmark) return sendError(res, 400, 'sessionKey and messageId are required');
|
|
205
|
+
broadcast(JSON.stringify({ type: 'clawchats', event: 'bookmarks-changed' }));
|
|
206
|
+
return send(res, 200, { bookmark });
|
|
207
|
+
}
|
|
208
|
+
if ((p = matchRoute(method, urlPath, 'PATCH /api/extras/bookmarks/:id'))) {
|
|
209
|
+
const bookmark = extras.renameBookmark(p.id, (await parseBody(req)).label);
|
|
210
|
+
if (!bookmark) return sendError(res, 404, 'Bookmark not found, or empty label');
|
|
211
|
+
broadcast(JSON.stringify({ type: 'clawchats', event: 'bookmarks-changed' }));
|
|
212
|
+
return send(res, 200, { bookmark });
|
|
213
|
+
}
|
|
214
|
+
if ((p = matchRoute(method, urlPath, 'DELETE /api/extras/bookmarks/:id'))) {
|
|
215
|
+
if (extras.deleteBookmark(p.id)) broadcast(JSON.stringify({ type: 'clawchats', event: 'bookmarks-changed' }));
|
|
216
|
+
return send(res, 200, { ok: true });
|
|
217
|
+
}
|
|
186
218
|
|
|
187
219
|
|
|
188
220
|
sendError(res, 404, `Not found: ${method} ${urlPath}`);
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// project_styles color/icon and new-chat preset per gateway session group (groups are just {name, position})
|
|
5
5
|
// thread_extras per-session ClawChats data (Intelligence panel etc.), keyed by session key
|
|
6
6
|
// legacy_created creation time of chats from before the gateway recorded createdAt
|
|
7
|
+
// bookmarks messages the user bookmarked, keyed by id; one per (session key, message id)
|
|
7
8
|
|
|
8
9
|
// New-chat preset: what a new chat in the project starts with. Every field is optional;
|
|
9
10
|
// a missing field means the gateway default. `cwd` and `projectId` are exclusive places.
|
|
@@ -28,6 +29,16 @@ function parsePreset(text) {
|
|
|
28
29
|
try { return cleanPreset(JSON.parse(text)); } catch { return null; }
|
|
29
30
|
}
|
|
30
31
|
|
|
32
|
+
const str = (v) => typeof v === 'string' && v.trim() ? v.trim() : '';
|
|
33
|
+
const clip = (v, n) => str(v).slice(0, n);
|
|
34
|
+
|
|
35
|
+
function bookmarkRow(r) {
|
|
36
|
+
return {
|
|
37
|
+
id: r.id, sessionKey: r.session_key, messageId: r.message_id, role: r.role, label: r.label,
|
|
38
|
+
snippet: r.snippet, chatTitle: r.chat_title, createdAt: r.created_at, updatedAt: r.updated_at,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
31
42
|
export function createExtrasStore(getGlobalDb) {
|
|
32
43
|
let ready = false;
|
|
33
44
|
function db() {
|
|
@@ -37,6 +48,7 @@ export function createExtrasStore(getGlobalDb) {
|
|
|
37
48
|
if (!g.prepare('PRAGMA table_info(project_styles)').all().some(c => c.name === 'preset')) g.exec('ALTER TABLE project_styles ADD COLUMN preset TEXT');
|
|
38
49
|
g.exec(`CREATE TABLE IF NOT EXISTS legacy_created (session_key TEXT PRIMARY KEY, created_at INTEGER NOT NULL)`);
|
|
39
50
|
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))`);
|
|
51
|
+
g.exec(`CREATE TABLE IF NOT EXISTS bookmarks (id TEXT PRIMARY KEY, session_key TEXT NOT NULL, message_id TEXT NOT NULL, role TEXT, label TEXT NOT NULL, snippet TEXT NOT NULL, chat_title TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, UNIQUE (session_key, message_id))`);
|
|
40
52
|
ready = true;
|
|
41
53
|
}
|
|
42
54
|
return g;
|
|
@@ -113,7 +125,36 @@ export function createExtrasStore(getGlobalDb) {
|
|
|
113
125
|
},
|
|
114
126
|
|
|
115
127
|
deleteThreadExtras(sessionKey) {
|
|
116
|
-
if (sessionKey)
|
|
128
|
+
if (!sessionKey) return;
|
|
129
|
+
db().prepare('DELETE FROM thread_extras WHERE session_key = ?').run(sessionKey);
|
|
130
|
+
db().prepare('DELETE FROM bookmarks WHERE session_key = ?').run(sessionKey);
|
|
131
|
+
},
|
|
132
|
+
|
|
133
|
+
/** All bookmarks, newest first. */
|
|
134
|
+
listBookmarks() {
|
|
135
|
+
return db().prepare('SELECT * FROM bookmarks ORDER BY created_at DESC').all().map(bookmarkRow);
|
|
136
|
+
},
|
|
137
|
+
|
|
138
|
+
/** Bookmark a message; bookmarking it again returns the existing bookmark unchanged. */
|
|
139
|
+
addBookmark(id, { sessionKey, messageId, role, label, snippet, chatTitle } = {}) {
|
|
140
|
+
if (!id || !str(sessionKey) || !str(messageId)) return null;
|
|
141
|
+
const now = Date.now();
|
|
142
|
+
db().prepare('INSERT INTO bookmarks (id, session_key, message_id, role, label, snippet, chat_title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(session_key, message_id) DO NOTHING')
|
|
143
|
+
.run(id, sessionKey, messageId, role === 'user' ? 'user' : 'assistant', clip(label, 200) || 'Bookmark', clip(snippet, 600), clip(chatTitle, 200) || null, now, now);
|
|
144
|
+
return bookmarkRow(db().prepare('SELECT * FROM bookmarks WHERE session_key = ? AND message_id = ?').get(sessionKey, messageId));
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
/** Rename; returns the updated bookmark, or null if it doesn't exist. */
|
|
148
|
+
renameBookmark(id, label) {
|
|
149
|
+
const l = clip(label, 200);
|
|
150
|
+
if (!l) return null;
|
|
151
|
+
db().prepare('UPDATE bookmarks SET label = ?, updated_at = ? WHERE id = ?').run(l, Date.now(), id);
|
|
152
|
+
const r = db().prepare('SELECT * FROM bookmarks WHERE id = ?').get(id);
|
|
153
|
+
return r ? bookmarkRow(r) : null;
|
|
154
|
+
},
|
|
155
|
+
|
|
156
|
+
deleteBookmark(id) {
|
|
157
|
+
return db().prepare('DELETE FROM bookmarks WHERE id = ?').run(id).changes > 0;
|
|
117
158
|
},
|
|
118
159
|
};
|
|
119
160
|
}
|
|
@@ -43,3 +43,27 @@ test('cleanPreset: known fields only, valid permission mode, projectId wins over
|
|
|
43
43
|
assert.deepEqual(cleanPreset({ cwd: '/a', projectLabel: 'Repo' }), { cwd: '/a' });
|
|
44
44
|
assert.deepEqual(cleanPreset({ fastMode: true }), { fastMode: true });
|
|
45
45
|
});
|
|
46
|
+
|
|
47
|
+
test('bookmarks: add is idempotent per message, rename, delete, dropped with the session', () => {
|
|
48
|
+
const db = new Database(':memory:');
|
|
49
|
+
const extras = createExtrasStore(() => db);
|
|
50
|
+
const a = extras.addBookmark('b1', { sessionKey: 'agent:main:x', messageId: 'm1', role: 'assistant', label: ' Plan ', snippet: 'The plan…', chatTitle: 'Chat X' });
|
|
51
|
+
assert.equal(a.label, 'Plan');
|
|
52
|
+
assert.equal(a.chatTitle, 'Chat X');
|
|
53
|
+
// Same message again: the existing bookmark comes back unchanged.
|
|
54
|
+
const again = extras.addBookmark('b2', { sessionKey: 'agent:main:x', messageId: 'm1', label: 'Other' });
|
|
55
|
+
assert.equal(again.id, 'b1');
|
|
56
|
+
assert.equal(again.label, 'Plan');
|
|
57
|
+
assert.equal(extras.addBookmark('b3', { sessionKey: 'agent:main:x' }), null);
|
|
58
|
+
extras.addBookmark('b4', { sessionKey: 'agent:main:y', messageId: 'm9', role: 'user', label: '', snippet: 'hi' });
|
|
59
|
+
assert.deepEqual(extras.listBookmarks().map(b => [b.id, b.label]).sort(), [['b1', 'Plan'], ['b4', 'Bookmark']]);
|
|
60
|
+
|
|
61
|
+
assert.equal(extras.renameBookmark('b1', 'Bulk export plan').label, 'Bulk export plan');
|
|
62
|
+
assert.equal(extras.renameBookmark('b1', ' '), null);
|
|
63
|
+
assert.equal(extras.renameBookmark('nope', 'x'), null);
|
|
64
|
+
|
|
65
|
+
assert.equal(extras.deleteBookmark('b4'), true);
|
|
66
|
+
assert.equal(extras.deleteBookmark('b4'), false);
|
|
67
|
+
extras.deleteThreadExtras('agent:main:x');
|
|
68
|
+
assert.deepEqual(extras.listBookmarks(), []);
|
|
69
|
+
});
|