wherever-dev 0.10.13 → 0.10.15
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/index.js +302 -36
- package/dist/index.js.map +1 -1
- package/dist/protocol.d.ts +3 -0
- package/dist/protocol.d.ts.map +1 -1
- package/dist/session-pool.d.ts +6 -0
- package/dist/session-pool.d.ts.map +1 -1
- package/dist/session-pool.js +45 -28
- package/dist/session-pool.js.map +1 -1
- package/package.json +1 -1
- package/public/_app/immutable/chunks/Dma3J3qQ.js +2 -0
- package/public/_app/immutable/chunks/{Dbf0zjW2.js.map → Dma3J3qQ.js.map} +1 -1
- package/public/_app/immutable/chunks/{CtPQjCBP.js → L93I-H4j.js} +2 -2
- package/public/_app/immutable/chunks/{CtPQjCBP.js.map → L93I-H4j.js.map} +1 -1
- package/public/_app/immutable/chunks/{8eypMp_V.js → vpatnBE2.js} +2 -2
- package/public/_app/immutable/chunks/{8eypMp_V.js.map → vpatnBE2.js.map} +1 -1
- package/public/_app/immutable/entry/{app.BNS6jUfJ.js → app.CqtGQvSV.js} +3 -3
- package/public/_app/immutable/entry/{app.BNS6jUfJ.js.map → app.CqtGQvSV.js.map} +1 -1
- package/public/_app/immutable/entry/start.C2OvHZ6Z.js +2 -0
- package/public/_app/immutable/entry/start.C2OvHZ6Z.js.map +1 -0
- package/public/_app/immutable/nodes/{0.COQnYGwL.js → 0.6DAAbCKP.js} +2 -2
- package/public/_app/immutable/nodes/{0.COQnYGwL.js.map → 0.6DAAbCKP.js.map} +1 -1
- package/public/_app/immutable/nodes/{1.irnAmVhW.js → 1.Y9ZXDXG1.js} +2 -2
- package/public/_app/immutable/nodes/{1.irnAmVhW.js.map → 1.Y9ZXDXG1.js.map} +1 -1
- package/public/_app/immutable/nodes/2.CNwl77oM.js +95 -0
- package/public/_app/immutable/nodes/2.CNwl77oM.js.map +1 -0
- package/public/_app/version.json +1 -1
- package/public/index.html +14 -12
- package/public/service-worker.js +1 -1
- package/public/_app/immutable/chunks/Dbf0zjW2.js +0 -2
- package/public/_app/immutable/entry/start.CY5doj7d.js +0 -2
- package/public/_app/immutable/entry/start.CY5doj7d.js.map +0 -1
- package/public/_app/immutable/nodes/2.kEWDQAI7.js +0 -95
- package/public/_app/immutable/nodes/2.kEWDQAI7.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -8,13 +8,20 @@ import fs from 'node:fs';
|
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { fileURLToPath } from 'node:url';
|
|
10
10
|
import os from 'node:os';
|
|
11
|
-
import {
|
|
11
|
+
import { execFileSync } from 'node:child_process';
|
|
12
12
|
import { runInstall, runUninstall, runServiceStatus, parseInstallOptions, printInstallHelp, } from './commands/install.js';
|
|
13
13
|
const __filename = fileURLToPath(import.meta.url);
|
|
14
14
|
const __dirname = path.dirname(__filename);
|
|
15
15
|
const devStaticPath = path.resolve(__dirname, '../../web/build');
|
|
16
16
|
const prodStaticPath = path.resolve(__dirname, '../public');
|
|
17
17
|
const staticDir = fs.existsSync(devStaticPath) ? devStaticPath : prodStaticPath;
|
|
18
|
+
// When true (set via --debug), the served dashboard index.html is rewritten so
|
|
19
|
+
// eruda's custom-plugin loader is enabled. Plugin loading is the only eruda
|
|
20
|
+
// feature that takes a URL parameter into a <script src>, so it is kept off by
|
|
21
|
+
// default to avoid a DOM-XSS vector; the operator flips it on locally to debug.
|
|
22
|
+
let debugEnabled = false;
|
|
23
|
+
const ERUDA_PLUGINS_META_FALSE = 'wherever-eruda-plugins" content="false"';
|
|
24
|
+
const ERUDA_PLUGINS_META_TRUE = 'wherever-eruda-plugins" content="true"';
|
|
18
25
|
const MIME_TYPES = {
|
|
19
26
|
'.html': 'text/html',
|
|
20
27
|
'.js': 'text/javascript',
|
|
@@ -129,6 +136,14 @@ function expandTilde(p) {
|
|
|
129
136
|
return path.join(os.homedir(), p.slice(1));
|
|
130
137
|
return p;
|
|
131
138
|
}
|
|
139
|
+
/** True iff `p` resolves to the home directory or somewhere beneath it. Used to
|
|
140
|
+
* scope /check-path and /autocomplete-path so an authenticated caller cannot use
|
|
141
|
+
* them to enumerate arbitrary directories outside the home folder. */
|
|
142
|
+
function isWithinHome(p) {
|
|
143
|
+
const home = os.homedir();
|
|
144
|
+
const normalized = path.resolve(p);
|
|
145
|
+
return normalized === home || normalized.startsWith(home + path.sep);
|
|
146
|
+
}
|
|
132
147
|
// Match a folder path against a remoteRepoRules `pattern`. The path is an
|
|
133
148
|
// absolute, tilde-expanded path (e.g. /home/user/dev/...), so a pattern that
|
|
134
149
|
// starts with a literal `~` (as users naturally write, mirroring commonFolders)
|
|
@@ -250,11 +265,48 @@ function serveStaticFile(reqPath, res) {
|
|
|
250
265
|
res.end(`Server Error: ${err.code}`);
|
|
251
266
|
}
|
|
252
267
|
else {
|
|
268
|
+
// --debug: flip the eruda custom-plugin flag in the served HTML shell so
|
|
269
|
+
// the dashboard can load eruda plugins from ?eruda=<pkg>. Off otherwise,
|
|
270
|
+
// which closes the DOM-XSS vector for any non-debug deployment.
|
|
271
|
+
if (debugEnabled && filePath.endsWith('index.html')) {
|
|
272
|
+
data = Buffer.from(data.toString().replace(ERUDA_PLUGINS_META_FALSE, ERUDA_PLUGINS_META_TRUE));
|
|
273
|
+
}
|
|
253
274
|
res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': cacheControl });
|
|
254
275
|
res.end(data);
|
|
255
276
|
}
|
|
256
277
|
});
|
|
257
278
|
}
|
|
279
|
+
// Retire any still-registered VIEWER connection carrying the same clientKey: it
|
|
280
|
+
// is the SAME viewer's superseded socket (a reconnect), not a second viewer.
|
|
281
|
+
// Detach it from its session synchronously so the very next message on the new
|
|
282
|
+
// socket sees an accurate client count, then terminate the dead socket.
|
|
283
|
+
//
|
|
284
|
+
// CLI bridges are deliberately left ALONE: their re-registration is already
|
|
285
|
+
// handled by registerCliSession/unregisterCliSession, and tearing one down here
|
|
286
|
+
// would race a cli_register arriving on the new socket against the old socket's
|
|
287
|
+
// async close teardown, which could unregister the session that was just
|
|
288
|
+
// re-registered.
|
|
289
|
+
function evictPreviousConnection(clientKey, clients, pool, onSessionsUpdated) {
|
|
290
|
+
for (const prev of Array.from(clients.values())) {
|
|
291
|
+
if (prev.clientKey !== clientKey || prev.isCliBridge)
|
|
292
|
+
continue;
|
|
293
|
+
if (prev.sessionId) {
|
|
294
|
+
pool.removeClient(prev.sessionId, prev.id);
|
|
295
|
+
prev.sessionId = null;
|
|
296
|
+
}
|
|
297
|
+
clearConflictState(prev);
|
|
298
|
+
clients.delete(prev.id);
|
|
299
|
+
// Tell the superseded connection WHY it is going away, and only then kill it.
|
|
300
|
+
// If it is in fact alive (two tabs that ended up sharing a key, e.g. a
|
|
301
|
+
// duplicated tab cloning sessionStorage), it regenerates its key and comes
|
|
302
|
+
// back as a distinct viewer instead of evicting the other one right back in
|
|
303
|
+
// an endless ping-pong. Losing this frame would restore exactly that
|
|
304
|
+
// ping-pong, with no backstop, so it must not be discarded by the teardown.
|
|
305
|
+
// A genuinely dead socket never reads it and is reaped on the flush timeout.
|
|
306
|
+
sendThenTerminate(prev.ws, { type: 'connection_superseded' });
|
|
307
|
+
onSessionsUpdated();
|
|
308
|
+
}
|
|
309
|
+
}
|
|
258
310
|
function generateId() {
|
|
259
311
|
return Math.random().toString(36).substring(2) + Date.now().toString(36);
|
|
260
312
|
}
|
|
@@ -273,6 +325,10 @@ function parseArgs() {
|
|
|
273
325
|
let sslCert = process.env.PI_REMOTE_SSL_CERT || undefined;
|
|
274
326
|
let noSsl = process.env.PI_REMOTE_NO_SSL === 'true' || process.env.PI_REMOTE_HTTP === 'true';
|
|
275
327
|
let httpLocalhostFallbackPort = undefined;
|
|
328
|
+
// Enables the eruda custom-plugin loader in the served dashboard (local
|
|
329
|
+
// debugging only). Off by default: plugin loading takes a URL param into a
|
|
330
|
+
// <script src>, which is a DOM-XSS vector unless explicitly opted into.
|
|
331
|
+
let debug = process.env.PI_DEBUG === 'true' || process.env.WHEREVER_DEBUG === 'true';
|
|
276
332
|
if (process.env.PI_REMOTE_HTTP_LOCALHOST_FALLBACK) {
|
|
277
333
|
const envVal = process.env.PI_REMOTE_HTTP_LOCALHOST_FALLBACK;
|
|
278
334
|
if (envVal === 'true') {
|
|
@@ -307,6 +363,9 @@ function parseArgs() {
|
|
|
307
363
|
case '--http':
|
|
308
364
|
noSsl = true;
|
|
309
365
|
break;
|
|
366
|
+
case '--debug':
|
|
367
|
+
debug = true;
|
|
368
|
+
break;
|
|
310
369
|
case '--http-localhost-fallback': {
|
|
311
370
|
const nextArg = args[i + 1];
|
|
312
371
|
if (nextArg && !nextArg.startsWith('--')) {
|
|
@@ -326,7 +385,7 @@ function parseArgs() {
|
|
|
326
385
|
}
|
|
327
386
|
}
|
|
328
387
|
}
|
|
329
|
-
return { port, host, token, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort };
|
|
388
|
+
return { port, host, token, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug };
|
|
330
389
|
}
|
|
331
390
|
function authenticate(req, token) {
|
|
332
391
|
if (!token)
|
|
@@ -380,8 +439,49 @@ function sendWS(ws, msg) {
|
|
|
380
439
|
}
|
|
381
440
|
}
|
|
382
441
|
}
|
|
442
|
+
// Send a final message and THEN kill the socket, without losing the message.
|
|
443
|
+
// terminate() destroys the socket and discards whatever is still buffered; over
|
|
444
|
+
// TLS (this server's default) a small frame is frequently still buffered when
|
|
445
|
+
// the send call returns, so terminating in the same tick can drop it. Wait for
|
|
446
|
+
// the write callback, with a timer so a socket that never flushes (the usual
|
|
447
|
+
// case here: the peer is gone) is still reaped promptly.
|
|
448
|
+
function sendThenTerminate(ws, msg, flushTimeoutMs = 1_000) {
|
|
449
|
+
let done = false;
|
|
450
|
+
const kill = () => {
|
|
451
|
+
if (done)
|
|
452
|
+
return;
|
|
453
|
+
done = true;
|
|
454
|
+
try {
|
|
455
|
+
// terminate() (not close()) because a superseded socket is typically
|
|
456
|
+
// half-open: a close handshake would never complete.
|
|
457
|
+
if (typeof ws.terminate === 'function')
|
|
458
|
+
ws.terminate();
|
|
459
|
+
else
|
|
460
|
+
ws.close();
|
|
461
|
+
}
|
|
462
|
+
catch { }
|
|
463
|
+
};
|
|
464
|
+
const timer = setTimeout(kill, flushTimeoutMs);
|
|
465
|
+
timer.unref?.();
|
|
466
|
+
if (ws.readyState !== WebSocket.OPEN) {
|
|
467
|
+
clearTimeout(timer);
|
|
468
|
+
kill();
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
try {
|
|
472
|
+
ws.send(JSON.stringify(msg), () => {
|
|
473
|
+
clearTimeout(timer);
|
|
474
|
+
kill();
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
catch (err) {
|
|
478
|
+
clearTimeout(timer);
|
|
479
|
+
kill();
|
|
480
|
+
}
|
|
481
|
+
}
|
|
383
482
|
async function main() {
|
|
384
|
-
const { port, host, token, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort } = parseArgs();
|
|
483
|
+
const { port, host, token, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug } = parseArgs();
|
|
484
|
+
debugEnabled = debug;
|
|
385
485
|
const sessionPool = new SessionPool(idleTimeout);
|
|
386
486
|
await sessionPool.initialize();
|
|
387
487
|
const clients = new Map();
|
|
@@ -399,8 +499,7 @@ async function main() {
|
|
|
399
499
|
console.log('Generating self-signed SSL certificates for secure HTTPS/WSS...');
|
|
400
500
|
try {
|
|
401
501
|
fs.mkdirSync(certsDir, { recursive: true });
|
|
402
|
-
|
|
403
|
-
execSync(cmd, { stdio: 'ignore' });
|
|
502
|
+
execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-keyout', defaultKeyPath, '-out', defaultCertPath, '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=localhost'], { stdio: 'ignore' });
|
|
404
503
|
console.log(`Self-signed certificates generated successfully in ${certsDir}`);
|
|
405
504
|
}
|
|
406
505
|
catch (err) {
|
|
@@ -463,24 +562,10 @@ async function main() {
|
|
|
463
562
|
// gone. Sent on every session-set change (open/leave/create/destroy). CLI
|
|
464
563
|
// bridge connections are skipped (they have no banner UI).
|
|
465
564
|
function broadcastFolderConflicts() {
|
|
565
|
+
// readOnly rides along every time so the client's composer mirrors the
|
|
566
|
+
// server's authority rather than inferring it from `active`.
|
|
466
567
|
for (const c of clients.values()) {
|
|
467
|
-
|
|
468
|
-
continue;
|
|
469
|
-
if (!c.sessionId)
|
|
470
|
-
continue;
|
|
471
|
-
const mine = sessionPool.getSession(c.sessionId);
|
|
472
|
-
if (!mine)
|
|
473
|
-
continue;
|
|
474
|
-
let active = false;
|
|
475
|
-
for (const s of sessionPool.getAllSessions()) {
|
|
476
|
-
if (s.sessionFile === mine.sessionFile)
|
|
477
|
-
continue;
|
|
478
|
-
if (s.cwd === mine.cwd && s.clients.size > 0) {
|
|
479
|
-
active = true;
|
|
480
|
-
break;
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
sendWS(c.ws, { type: 'folder_conflict', cwd: mine.cwd, active });
|
|
568
|
+
sendFolderConflict(c, sessionPool);
|
|
484
569
|
}
|
|
485
570
|
}
|
|
486
571
|
function broadcastAgentEvent(sessionFile, event) {
|
|
@@ -695,6 +780,7 @@ async function main() {
|
|
|
695
780
|
pathname.startsWith('/models') ||
|
|
696
781
|
pathname.startsWith('/config') ||
|
|
697
782
|
pathname.startsWith('/check-path') ||
|
|
783
|
+
pathname.startsWith('/check-remote-repo') ||
|
|
698
784
|
pathname.startsWith('/autocomplete-path') ||
|
|
699
785
|
pathname.startsWith('/session/');
|
|
700
786
|
if (isApiRequest && !authenticate(req, token)) {
|
|
@@ -753,6 +839,12 @@ async function main() {
|
|
|
753
839
|
else {
|
|
754
840
|
resolved = path.resolve(qPath);
|
|
755
841
|
}
|
|
842
|
+
// Scope to the home folder so this endpoint cannot be used to probe
|
|
843
|
+
// arbitrary paths elsewhere on the server.
|
|
844
|
+
if (!isWithinHome(resolved)) {
|
|
845
|
+
sendJSON(res, 403, { error: 'Path is outside the home directory' });
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
756
848
|
const exists = fs.existsSync(resolved);
|
|
757
849
|
let isGit = false;
|
|
758
850
|
if (exists) {
|
|
@@ -833,6 +925,12 @@ async function main() {
|
|
|
833
925
|
else {
|
|
834
926
|
resolvedParent = path.resolve(parentPath);
|
|
835
927
|
}
|
|
928
|
+
// Scope to the home folder so this endpoint cannot be used to enumerate
|
|
929
|
+
// directories elsewhere on the server.
|
|
930
|
+
if (!isWithinHome(resolvedParent)) {
|
|
931
|
+
sendJSON(res, 403, { error: 'Path is outside the home directory' });
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
836
934
|
const config = getWhereverConfig();
|
|
837
935
|
// Resolve the query path
|
|
838
936
|
let resolvedQuery = qPath;
|
|
@@ -1002,6 +1100,8 @@ async function main() {
|
|
|
1002
1100
|
sendWS(c.ws, wsMsg);
|
|
1003
1101
|
c.sessionId = null;
|
|
1004
1102
|
c.readOnly = false;
|
|
1103
|
+
// The conflict decision belonged to the session that just went away.
|
|
1104
|
+
clearConflictState(c);
|
|
1005
1105
|
}
|
|
1006
1106
|
}
|
|
1007
1107
|
}
|
|
@@ -1031,9 +1131,11 @@ async function main() {
|
|
|
1031
1131
|
else {
|
|
1032
1132
|
resolved = path.resolve(sessionFile);
|
|
1033
1133
|
}
|
|
1034
|
-
// Security check: only allow deleting files
|
|
1035
|
-
|
|
1036
|
-
|
|
1134
|
+
// Security check: only allow deleting session .jsonl files that live
|
|
1135
|
+
// inside the server's sessions directory, so an authenticated caller
|
|
1136
|
+
// cannot unlink arbitrary .jsonl files elsewhere on disk.
|
|
1137
|
+
if (!sessionPool.isSessionFile(resolved)) {
|
|
1138
|
+
sendJSON(res, 400, { error: 'Invalid session file: not a session in the sessions directory' });
|
|
1037
1139
|
return;
|
|
1038
1140
|
}
|
|
1039
1141
|
// Get the active session if any, using either the sessionFile path or resolved path
|
|
@@ -1050,6 +1152,8 @@ async function main() {
|
|
|
1050
1152
|
sendWS(c.ws, wsMsg);
|
|
1051
1153
|
c.sessionId = null;
|
|
1052
1154
|
c.readOnly = false;
|
|
1155
|
+
// The conflict decision belonged to the session that just went away.
|
|
1156
|
+
clearConflictState(c);
|
|
1053
1157
|
}
|
|
1054
1158
|
}
|
|
1055
1159
|
sessionPool.destroySession(tracked.sessionFile, 'deleted');
|
|
@@ -1351,13 +1455,43 @@ async function main() {
|
|
|
1351
1455
|
if (httpServer) {
|
|
1352
1456
|
httpServer.on('upgrade', upgradeHandler);
|
|
1353
1457
|
}
|
|
1354
|
-
wss.on('connection', (ws) => {
|
|
1458
|
+
wss.on('connection', (ws, req) => {
|
|
1355
1459
|
const clientId = generateId();
|
|
1460
|
+
// Stable per-viewer identity (see WhereverClientConfig.clientKey). A client
|
|
1461
|
+
// that lost its socket silently (half-open TCP: phone sleep, network switch)
|
|
1462
|
+
// reconnects on a NEW socket while the old record still sits in the pool
|
|
1463
|
+
// until the heartbeat reaper notices, up to 2x HEARTBEAT_MS later. That
|
|
1464
|
+
// phantom counted as "another viewer", which silently turned an explicit
|
|
1465
|
+
// "New Session Here" into a folder conflict (read-only attach to the folder's
|
|
1466
|
+
// existing session). Retiring the same key's previous connection HERE, before
|
|
1467
|
+
// any session traffic on the new socket, closes that window. Keys are scoped
|
|
1468
|
+
// per tab by the web client, so two real tabs remain two distinct viewers.
|
|
1469
|
+
let clientKey;
|
|
1470
|
+
try {
|
|
1471
|
+
const url = new URL(req?.url || '', `http://${req?.headers?.host || 'localhost'}`);
|
|
1472
|
+
const raw = url.searchParams.get('clientKey');
|
|
1473
|
+
// Bounded: this is client-supplied text retained for the life of the
|
|
1474
|
+
// connection. Anything longer than a generated key is not one. Refuse it
|
|
1475
|
+
// rather than truncating (two distinct long keys must not collapse into one
|
|
1476
|
+
// identity and start evicting each other), and say so: the connection
|
|
1477
|
+
// silently loses supersede protection otherwise.
|
|
1478
|
+
if (raw && raw.length > 128) {
|
|
1479
|
+
console.warn(`[wherever] ignoring oversized clientKey (${raw.length} chars) from ${req?.socket?.remoteAddress ?? 'unknown'}`);
|
|
1480
|
+
}
|
|
1481
|
+
else if (raw) {
|
|
1482
|
+
clientKey = raw;
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
catch { }
|
|
1486
|
+
if (clientKey) {
|
|
1487
|
+
evictPreviousConnection(clientKey, clients, sessionPool, broadcastSessionsUpdated);
|
|
1488
|
+
}
|
|
1356
1489
|
const client = {
|
|
1357
1490
|
id: clientId,
|
|
1358
1491
|
ws,
|
|
1359
1492
|
sessionId: null,
|
|
1360
1493
|
readOnly: false,
|
|
1494
|
+
clientKey,
|
|
1361
1495
|
};
|
|
1362
1496
|
clients.set(clientId, client);
|
|
1363
1497
|
// Liveness: assume alive on connect; any pong (reply to the heartbeat ping
|
|
@@ -1503,11 +1637,84 @@ This encrypts all network traffic securely and enables safe, private remote acce
|
|
|
1503
1637
|
process.on('SIGTERM', shutdown);
|
|
1504
1638
|
process.on('SIGINT', shutdown);
|
|
1505
1639
|
}
|
|
1640
|
+
// The conflict decision belongs to the PAIRING of this client with one session.
|
|
1641
|
+
// Clear every part of it together whenever that pairing ends, so no half-state
|
|
1642
|
+
// (an observer flag without its continue, a cwd from a session we left) can be
|
|
1643
|
+
// read by the next attach.
|
|
1644
|
+
function clearConflictState(client) {
|
|
1645
|
+
client.conflictObserver = false;
|
|
1646
|
+
client.conflictContinued = false;
|
|
1647
|
+
client.pendingCwd = undefined;
|
|
1648
|
+
}
|
|
1649
|
+
// Recompute ONE client's folder-conflict state and settle the read-only it
|
|
1650
|
+
// imposed: releasing it once the conflict no longer holds is part of resolving,
|
|
1651
|
+
// not a side effect the callers could skip. Shared by the live broadcast, the
|
|
1652
|
+
// cold attach and the "Continue anyway" reply so all three speak with one
|
|
1653
|
+
// authority. Returns null for connections the banner does not apply to (CLI
|
|
1654
|
+
// bridges, clients not attached to a session).
|
|
1655
|
+
function resolveFolderConflictState(c, pool) {
|
|
1656
|
+
if (c.isCliBridge || !c.sessionId)
|
|
1657
|
+
return null;
|
|
1658
|
+
const mine = pool.getSession(c.sessionId);
|
|
1659
|
+
if (!mine)
|
|
1660
|
+
return null;
|
|
1661
|
+
let active = false;
|
|
1662
|
+
for (const s of pool.getAllSessions()) {
|
|
1663
|
+
if (s.sessionFile === mine.sessionFile)
|
|
1664
|
+
continue;
|
|
1665
|
+
if (s.cwd === mine.cwd && s.clients.size > 0) {
|
|
1666
|
+
active = true;
|
|
1667
|
+
break;
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
// A conflict OBSERVER shares the occupant's session file (session_new attaches
|
|
1671
|
+
// it there read-only), so the scan above -- which skips this very file -- can
|
|
1672
|
+
// never see its conflict. Its conflict lasts exactly as long as someone else is
|
|
1673
|
+
// still on that session.
|
|
1674
|
+
if (!active && c.conflictObserver) {
|
|
1675
|
+
for (const cid of mine.clients) {
|
|
1676
|
+
if (cid !== c.id) {
|
|
1677
|
+
active = true;
|
|
1678
|
+
break;
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
// The conflict resolved (the other party left the folder/session): release the
|
|
1683
|
+
// read-only state it imposed, otherwise the client keeps an observe-only
|
|
1684
|
+
// composer forever with no banner left to lift it. A configured
|
|
1685
|
+
// sessions.readOnly folder is a hard rule and is never lifted here.
|
|
1686
|
+
if (c.conflictObserver && !active) {
|
|
1687
|
+
c.conflictObserver = false;
|
|
1688
|
+
if (!pool.isReadOnlyCwd(mine.cwd))
|
|
1689
|
+
c.readOnly = false;
|
|
1690
|
+
}
|
|
1691
|
+
return { cwd: mine.cwd, active };
|
|
1692
|
+
}
|
|
1693
|
+
// Resolve and report in one step. Every folder_conflict frame goes out through
|
|
1694
|
+
// here, so the `readOnly` it carries can never drift from the authority that
|
|
1695
|
+
// produced `active`.
|
|
1696
|
+
function sendFolderConflict(client, pool) {
|
|
1697
|
+
const verdict = resolveFolderConflictState(client, pool);
|
|
1698
|
+
if (!verdict)
|
|
1699
|
+
return;
|
|
1700
|
+
sendWS(client.ws, {
|
|
1701
|
+
type: 'folder_conflict',
|
|
1702
|
+
cwd: verdict.cwd,
|
|
1703
|
+
active: verdict.active,
|
|
1704
|
+
readOnly: client.readOnly,
|
|
1705
|
+
});
|
|
1706
|
+
}
|
|
1506
1707
|
function switchClientSession(client, newSessionFile, pool, onSessionsUpdated) {
|
|
1507
1708
|
if (client.sessionId && client.sessionId !== newSessionFile) {
|
|
1508
1709
|
pool.removeClient(client.sessionId, client.id);
|
|
1509
1710
|
}
|
|
1510
1711
|
client.sessionId = newSessionFile;
|
|
1712
|
+
// Detaching ends the pairing the conflict decision belonged to. (An ATTACH must
|
|
1713
|
+
// not clear it: a "Continue anyway" clicked during a cold load is recorded
|
|
1714
|
+
// before this call and has to survive it.)
|
|
1715
|
+
if (newSessionFile === null) {
|
|
1716
|
+
clearConflictState(client);
|
|
1717
|
+
}
|
|
1511
1718
|
if (onSessionsUpdated) {
|
|
1512
1719
|
onSessionsUpdated();
|
|
1513
1720
|
}
|
|
@@ -1620,6 +1827,10 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
|
|
|
1620
1827
|
// 2. Build the live agent (createAgentSession -> extension/MCP load, the
|
|
1621
1828
|
// seconds-long part) ASYNC, then signal session_ready so the composer
|
|
1622
1829
|
// enables. Sending needs the live agent; reading does not.
|
|
1830
|
+
// A new load is a new decision: any earlier "Continue anyway" belongs to the
|
|
1831
|
+
// session we are leaving. Reset BEFORE the first await, so a continue that
|
|
1832
|
+
// races this load is recorded against the load, never wiped by it.
|
|
1833
|
+
client.conflictContinued = false;
|
|
1623
1834
|
const meta = await pool.readSessionMeta(msg.sessionFile, INITIAL_HISTORY_LIMIT, msg.model);
|
|
1624
1835
|
if ('error' in meta) {
|
|
1625
1836
|
sendWS(client.ws, { type: 'session_error', error: meta.error });
|
|
@@ -1637,6 +1848,8 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
|
|
|
1637
1848
|
// A folder conflict also starts the client read-only until they continue.
|
|
1638
1849
|
const forcedReadOnly = meta.readOnly || folderConflict;
|
|
1639
1850
|
client.readOnly = forcedReadOnly;
|
|
1851
|
+
client.conflictObserver = folderConflict;
|
|
1852
|
+
client.pendingCwd = meta.cwd;
|
|
1640
1853
|
// Paint immediately. `pending` is true when the live agent is not resident
|
|
1641
1854
|
// yet, so the client keeps the composer disabled (with a "preparing
|
|
1642
1855
|
// agent..." hint) until session_ready, while reading/scrolling work now.
|
|
@@ -1696,10 +1909,17 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
|
|
|
1696
1909
|
}
|
|
1697
1910
|
pool.addClient(result.tracked.sessionFile, client.id);
|
|
1698
1911
|
switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
|
|
1699
|
-
//
|
|
1700
|
-
//
|
|
1701
|
-
//
|
|
1702
|
-
|
|
1912
|
+
// Re-derive read-only from the CURRENT decision rather than from
|
|
1913
|
+
// `forcedReadOnly` captured before the build: while the agent was building
|
|
1914
|
+
// the user may have clicked "Continue anyway" (conflictContinued), and
|
|
1915
|
+
// re-imposing the stale value re-locked them with no banner left to lift
|
|
1916
|
+
// it, while `message` dropped their sends in silence. The conflict having
|
|
1917
|
+
// RESOLVED during the build is handled just below by the verdict, which
|
|
1918
|
+
// re-scans and releases read-only.
|
|
1919
|
+
client.readOnly =
|
|
1920
|
+
meta.readOnly ||
|
|
1921
|
+
pool.isReadOnlyCwd(result.tracked.cwd) ||
|
|
1922
|
+
(client.conflictObserver === true && !client.conflictContinued);
|
|
1703
1923
|
sendWS(client.ws, {
|
|
1704
1924
|
type: 'session_ready',
|
|
1705
1925
|
sessionId: result.tracked.sessionId,
|
|
@@ -1712,6 +1932,11 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
|
|
|
1712
1932
|
// taken over by another client mid-build; send the authoritative snapshot
|
|
1713
1933
|
// for the same reason as the warm path above.
|
|
1714
1934
|
sendQueueSnapshot(client, result.tracked.sessionFile, result.tracked.sessionId, pool);
|
|
1935
|
+
// State may have moved during the build (the conflict resolved, or the
|
|
1936
|
+
// user continued through it). session_ready carries no readOnly, and the
|
|
1937
|
+
// periodic conflict broadcast is throttled, so state the verdict here
|
|
1938
|
+
// explicitly rather than leaving the composer to guess for up to 2s.
|
|
1939
|
+
sendFolderConflict(client, pool);
|
|
1715
1940
|
})();
|
|
1716
1941
|
break;
|
|
1717
1942
|
}
|
|
@@ -1760,9 +1985,12 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
|
|
|
1760
1985
|
// existing one), so attach to that existing session as a read-only
|
|
1761
1986
|
// observer and raise the warning banner. "Continue anyway"
|
|
1762
1987
|
// (folder_conflict_continue) lifts read-only so both can send.
|
|
1763
|
-
client.readOnly = true;
|
|
1764
1988
|
pool.addClient(existing.sessionFile, client.id);
|
|
1765
1989
|
switchClientSession(client, existing.sessionFile, pool, onSessionsUpdated);
|
|
1990
|
+
client.readOnly = true;
|
|
1991
|
+
clearConflictState(client);
|
|
1992
|
+
client.conflictObserver = true;
|
|
1993
|
+
client.pendingCwd = existing.cwd;
|
|
1766
1994
|
sendWS(client.ws, {
|
|
1767
1995
|
type: 'session_created',
|
|
1768
1996
|
sessionId: existing.sessionId,
|
|
@@ -1797,6 +2025,8 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
|
|
|
1797
2025
|
pool.addClient(result.tracked.sessionFile, client.id);
|
|
1798
2026
|
switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
|
|
1799
2027
|
client.readOnly = false;
|
|
2028
|
+
clearConflictState(client);
|
|
2029
|
+
client.pendingCwd = result.tracked.cwd;
|
|
1800
2030
|
sendWS(client.ws, {
|
|
1801
2031
|
type: 'session_created',
|
|
1802
2032
|
sessionId: result.tracked.sessionId,
|
|
@@ -1850,19 +2080,55 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
|
|
|
1850
2080
|
// run concurrently from here on. Guard: never lift read-only for a session
|
|
1851
2081
|
// whose cwd is a configured sessions.readOnly folder (that is a hard
|
|
1852
2082
|
// observe-only rule, not a dismissible warning).
|
|
2083
|
+
// The cwd may come from an attached session or, during a cold load's agent
|
|
2084
|
+
// build, from the load in progress: the user can click Continue on the
|
|
2085
|
+
// painted-but-not-yet-attached conversation, and dropping that click left
|
|
2086
|
+
// them read-only with the button already gone.
|
|
1853
2087
|
const tracked = client.sessionId ? pool.getSession(client.sessionId) : null;
|
|
1854
|
-
|
|
2088
|
+
const cwd = tracked?.cwd ?? client.pendingCwd;
|
|
2089
|
+
if (!cwd)
|
|
1855
2090
|
return;
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
2091
|
+
// The client stamps the session it was looking at. If that resolves to a
|
|
2092
|
+
// DIFFERENT folder, the session changed under the click (a switch racing the
|
|
2093
|
+
// tap): honouring it would continue through a conflict the user never saw.
|
|
2094
|
+
// An unresolvable id means the target is not resident (the cold-load case
|
|
2095
|
+
// this continue exists for), which the cwd check above already covers.
|
|
2096
|
+
if (msg.sessionId) {
|
|
2097
|
+
const target = pool.getSession(msg.sessionId);
|
|
2098
|
+
if (target && target.cwd !== cwd)
|
|
2099
|
+
return;
|
|
2100
|
+
}
|
|
2101
|
+
// Durable intent: honoured at attach even if the click landed before this
|
|
2102
|
+
// client had a session to lift read-only on.
|
|
2103
|
+
client.conflictContinued = true;
|
|
2104
|
+
if (!pool.isReadOnlyCwd(cwd))
|
|
2105
|
+
client.readOnly = false;
|
|
2106
|
+
// Reply with this client's authoritative conflict state, ALWAYS (including
|
|
2107
|
+
// when the lift was refused for a sessions.readOnly folder). Same-socket
|
|
2108
|
+
// ordering guarantees this lands after any folder_conflict broadcast that
|
|
2109
|
+
// was already in flight when the continue was sent, so an in-flight update
|
|
2110
|
+
// carrying the pre-continue readOnly:true cannot leave the composer
|
|
2111
|
+
// disabled with the banner's button already gone.
|
|
2112
|
+
sendFolderConflict(client, pool);
|
|
1859
2113
|
break;
|
|
1860
2114
|
}
|
|
1861
2115
|
case 'message': {
|
|
1862
2116
|
if (!client.sessionId)
|
|
1863
2117
|
return;
|
|
1864
|
-
if (client.readOnly)
|
|
2118
|
+
if (client.readOnly) {
|
|
2119
|
+
// Never swallow a send. This is a legitimate refusal for an observe-only
|
|
2120
|
+
// session (a sessions.readOnly folder, or a folder conflict not continued
|
|
2121
|
+
// through), but the client only hides its composer when it AGREES it is
|
|
2122
|
+
// read-only -- so any future desync of that agreement used to show up as
|
|
2123
|
+
// text vanishing into the void. Answering makes it a visible, retryable
|
|
2124
|
+
// failure instead (the client surfaces session_error with a Retry).
|
|
2125
|
+
sendWS(client.ws, {
|
|
2126
|
+
type: 'session_error',
|
|
2127
|
+
sessionId: msg.sessionId,
|
|
2128
|
+
error: 'This session is read-only from here, so the message was not delivered. Use "Continue anyway" on the folder-conflict banner, or open the session that owns this folder.',
|
|
2129
|
+
});
|
|
1865
2130
|
return;
|
|
2131
|
+
}
|
|
1866
2132
|
// The client stamps every send with the sessionId of the session it is
|
|
1867
2133
|
// actually viewing. Treat that as AUTHORITATIVE: if it does not resolve to
|
|
1868
2134
|
// the same tracked session this connection is attached to, REFUSE rather
|