wherever-dev 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/drafts.d.ts +7 -0
  2. package/dist/drafts.d.ts.map +1 -1
  3. package/dist/drafts.js +10 -3
  4. package/dist/drafts.js.map +1 -1
  5. package/dist/index.js +691 -46
  6. package/dist/index.js.map +1 -1
  7. package/dist/protocol.d.ts +35 -0
  8. package/dist/protocol.d.ts.map +1 -1
  9. package/dist/protocol.js.map +1 -1
  10. package/dist/remote-candidates.d.ts +52 -0
  11. package/dist/remote-candidates.d.ts.map +1 -0
  12. package/dist/remote-candidates.js +147 -0
  13. package/dist/remote-candidates.js.map +1 -0
  14. package/dist/restore-jobs.d.ts +236 -0
  15. package/dist/restore-jobs.d.ts.map +1 -0
  16. package/dist/restore-jobs.js +716 -0
  17. package/dist/restore-jobs.js.map +1 -0
  18. package/dist/session-pool.d.ts +71 -8
  19. package/dist/session-pool.d.ts.map +1 -1
  20. package/dist/session-pool.js +192 -68
  21. package/dist/session-pool.js.map +1 -1
  22. package/dist/session-types.d.ts +12 -0
  23. package/dist/session-types.d.ts.map +1 -1
  24. package/package.json +1 -1
  25. package/public/_app/immutable/assets/0.CUi0Pn9k.css +1 -0
  26. package/public/_app/immutable/chunks/CJs7WGCY.js +2 -0
  27. package/public/_app/immutable/chunks/{CuGyzHtA.js.map → CJs7WGCY.js.map} +1 -1
  28. package/public/_app/immutable/chunks/{sERBGsNa.js → Cr3SOBcX.js} +2 -2
  29. package/public/_app/immutable/chunks/{sERBGsNa.js.map → Cr3SOBcX.js.map} +1 -1
  30. package/public/_app/immutable/chunks/{55QXfSWV.js → DsMrx0D-.js} +2 -2
  31. package/public/_app/immutable/chunks/{55QXfSWV.js.map → DsMrx0D-.js.map} +1 -1
  32. package/public/_app/immutable/entry/{app.DN0r_HfQ.js → app.q0JTyYdd.js} +3 -3
  33. package/public/_app/immutable/entry/{app.DN0r_HfQ.js.map → app.q0JTyYdd.js.map} +1 -1
  34. package/public/_app/immutable/entry/start.Dn511egP.js +2 -0
  35. package/public/_app/immutable/entry/start.Dn511egP.js.map +1 -0
  36. package/public/_app/immutable/nodes/{0.BhHgt5Z6.js → 0.BhjoTMlz.js} +2 -2
  37. package/public/_app/immutable/nodes/{0.BhHgt5Z6.js.map → 0.BhjoTMlz.js.map} +1 -1
  38. package/public/_app/immutable/nodes/{1.B9mDAaoD.js → 1.CKIQ9-uZ.js} +2 -2
  39. package/public/_app/immutable/nodes/{1.B9mDAaoD.js.map → 1.CKIQ9-uZ.js.map} +1 -1
  40. package/public/_app/immutable/nodes/2.CBHW8874.js +120 -0
  41. package/public/_app/immutable/nodes/2.CBHW8874.js.map +1 -0
  42. package/public/_app/version.json +1 -1
  43. package/public/index.html +11 -11
  44. package/public/service-worker.js +1 -1
  45. package/public/_app/immutable/assets/0.BS_EGmNW.css +0 -1
  46. package/public/_app/immutable/chunks/CuGyzHtA.js +0 -2
  47. package/public/_app/immutable/entry/start.CSyfkZFS.js +0 -2
  48. package/public/_app/immutable/entry/start.CSyfkZFS.js.map +0 -1
  49. package/public/_app/immutable/nodes/2.BjlQDhkN.js +0 -110
  50. package/public/_app/immutable/nodes/2.BjlQDhkN.js.map +0 -1
package/dist/index.js CHANGED
@@ -2,9 +2,11 @@
2
2
  import { createServer as createHttpServer } from 'node:http';
3
3
  import { createServer as createHttpsServer, request as httpRequest } from 'node:https';
4
4
  import { WebSocketServer, WebSocket } from 'ws';
5
- import { SessionPool, getWhereverConfig, detectRemoteRepo } from './session-pool.js';
5
+ import { SessionPool, getWhereverConfig, getWhereverCertsDir, detectRemoteRepo, normalizePath, invalidateFolderExistence } from './session-pool.js';
6
6
  import { readDrafts, addDraft, deleteDraft, validateDraftInput } from './drafts.js';
7
7
  import { searchConversations } from './conversation-search.js';
8
+ import { matchRemoteRepoRule, resolveRemoteCandidates } from './remote-candidates.js';
9
+ import { RestoreJobRegistry } from './restore-jobs.js';
8
10
  import { INITIAL_HISTORY_LIMIT, HISTORY_PAGE_SIZE } from './protocol.js';
9
11
  import fs from 'node:fs';
10
12
  import path from 'node:path';
@@ -146,20 +148,6 @@ function isWithinHome(p) {
146
148
  const normalized = path.resolve(p);
147
149
  return normalized === home || normalized.startsWith(home + path.sep);
148
150
  }
149
- // Match a folder path against a remoteRepoRules `pattern`. The path is an
150
- // absolute, tilde-expanded path (e.g. /home/user/dev/...), so a pattern that
151
- // starts with a literal `~` (as users naturally write, mirroring commonFolders)
152
- // would never match. Expand a leading `~` in the pattern to the home dir before
153
- // building the RegExp so `~/dev/...` matches the resolved path. An invalid
154
- // regex is treated as a non-match rather than throwing.
155
- function repoRuleMatches(pattern, resolvedPath) {
156
- try {
157
- return new RegExp(expandTilde(pattern)).test(resolvedPath);
158
- }
159
- catch {
160
- return false;
161
- }
162
- }
163
151
  /**
164
152
  * Resolve the allowed download roots for a session. Deny-by-default: only files
165
153
  * whose REAL path lives under one of these roots are served. Always includes the
@@ -312,19 +300,123 @@ function evictPreviousConnection(clientKey, clients, pool, onSessionsUpdated) {
312
300
  function generateId() {
313
301
  return Math.random().toString(36).substring(2) + Date.now().toString(36);
314
302
  }
303
+ /**
304
+ * Resolve the auth token WITHOUT requiring it on the command line.
305
+ *
306
+ * Anything in argv is world-readable: `ps -ef` (and /proc/<pid>/cmdline, which
307
+ * is mode 0444) shows the full command line of every process on the machine to
308
+ * every local user, so `--token <secret>` leaks the secret to any account on
309
+ * the box. That is fine for a laptop and NOT fine for a shared/bare-metal host,
310
+ * which is why the environment is the preferred channel for real deployments.
311
+ *
312
+ * Precedence, highest first:
313
+ * 1. `--token <value>` - explicit argv, kept for compatibility. LEAKS via ps.
314
+ * 2. `WHEREVER_TOKEN` - preferred for deployments.
315
+ * 3. `WHEREVER_TOKEN_FILE` - path to a file whose (trimmed) CONTENT is the
316
+ * token. The natural shape for a secret manager
317
+ * (sops-nix, systemd `LoadCredential`) which
318
+ * renders a root-owned 0400 file; nothing
319
+ * secret then exists in argv OR in the
320
+ * environment block.
321
+ * 4. `PI_REMOTE_TOKEN` - the pre-existing variable, still honoured.
322
+ *
323
+ * TRIMMING IS ASYMMETRIC ON PURPOSE, and the asymmetry is a compatibility rule,
324
+ * not an oversight. The two NEW sources are trimmed, because a secret manager
325
+ * renders a file with a trailing newline and `WHEREVER_TOKEN=$(cat ...)` is the
326
+ * obvious thing to write. The two PRE-EXISTING sources (`--token`,
327
+ * `PI_REMOTE_TOKEN`) are taken VERBATIM, exactly as before, because
328
+ * `authenticate()` compares the raw query parameter with `===`: trimming them
329
+ * would silently change WHICH string authenticates on an install that already
330
+ * has whitespace in its token, locking out every saved client URL. Likewise
331
+ * `--token` wins whenever the FLAG WAS GIVEN, even with an empty or missing
332
+ * value, because that is what the old `case '--token': token = args[++i]`
333
+ * did -- it overwrote whatever the environment had.
334
+ *
335
+ * An unreadable or empty `WHEREVER_TOKEN_FILE` is FATAL rather than "fall
336
+ * through to no token": silently starting an UNAUTHENTICATED server because a
337
+ * secret failed to mount is the one failure mode that must never happen
338
+ * quietly. Note this only fires when the file is the source actually being
339
+ * consulted: an explicit `--token`/`WHEREVER_TOKEN` above it still wins, and
340
+ * the server is authenticated either way.
341
+ */
342
+ function resolveToken(cliToken, cliTokenGiven) {
343
+ // `cliTokenGiven`, not `cliToken`, so that `--token ''` (and a trailing
344
+ // `--token` with no value) still SUPPRESSES the environment, as it did before.
345
+ if (cliTokenGiven)
346
+ return { token: cliToken || undefined, source: '--token' };
347
+ const envToken = process.env.WHEREVER_TOKEN;
348
+ if (envToken && envToken.trim())
349
+ return { token: envToken.trim(), source: 'WHEREVER_TOKEN' };
350
+ warnIfSetButBlank('WHEREVER_TOKEN', envToken);
351
+ const tokenFile = process.env.WHEREVER_TOKEN_FILE;
352
+ if (tokenFile && tokenFile.trim()) {
353
+ const resolvedPath = expandTilde(tokenFile.trim());
354
+ let contents;
355
+ try {
356
+ contents = fs.readFileSync(resolvedPath, 'utf8');
357
+ }
358
+ catch (err) {
359
+ console.error(`FATAL: WHEREVER_TOKEN_FILE is set to ${resolvedPath} but it could not be read ` +
360
+ `(${err.message}). Refusing to start: continuing would silently run an ` +
361
+ `UNAUTHENTICATED server.`);
362
+ process.exit(1);
363
+ }
364
+ const trimmed = contents.trim();
365
+ if (!trimmed) {
366
+ console.error(`FATAL: WHEREVER_TOKEN_FILE (${resolvedPath}) is empty. Refusing to start: continuing ` +
367
+ `would silently run an UNAUTHENTICATED server.`);
368
+ process.exit(1);
369
+ }
370
+ return { token: trimmed, source: `WHEREVER_TOKEN_FILE (${resolvedPath})` };
371
+ }
372
+ warnIfSetButBlank('WHEREVER_TOKEN_FILE', tokenFile);
373
+ // VERBATIM, including surrounding whitespace: see the trimming note above.
374
+ // `' '` is truthy and therefore enforced, exactly as it was before.
375
+ const legacy = process.env.PI_REMOTE_TOKEN;
376
+ if (legacy)
377
+ return { token: legacy, source: 'PI_REMOTE_TOKEN' };
378
+ return { token: undefined, source: 'none' };
379
+ }
380
+ /**
381
+ * A token variable that is SET but blank is almost always a secret that failed
382
+ * to render (a truncated file, a `$(cat ...)` that errored, a half-landed
383
+ * activation), and the consequence is an UNAUTHENTICATED server that looks
384
+ * perfectly healthy. It cannot be fatal -- `VAR=` is also the ordinary way to
385
+ * neutralise an inherited variable, which the test harness relies on -- so it
386
+ * is made LOUD instead. Silence is the only unacceptable outcome here.
387
+ */
388
+ function warnIfSetButBlank(name, value) {
389
+ if (value === undefined || value.length === 0)
390
+ return; // unset, or explicitly neutralised
391
+ if (value.trim().length > 0)
392
+ return;
393
+ console.warn(`[wherever] ${name} is set but contains only whitespace. Treating it as NOT SET. ` +
394
+ `If a secret was meant to be rendered here, it did not arrive, and this server may ` +
395
+ `be starting WITHOUT AUTHENTICATION.`);
396
+ }
315
397
  function parseArgs() {
316
398
  const args = process.argv.slice(2);
317
399
  let port = parseInt(process.env.PI_REMOTE_PORT || '31415', 10);
318
400
  let host = process.env.PI_REMOTE_HOST || '127.0.0.1';
319
- let token = process.env.PI_REMOTE_TOKEN || undefined;
401
+ // Kept separate from the env-derived token so `resolveToken` below can apply
402
+ // one documented precedence chain instead of "whoever assigned last wins".
403
+ // `cliTokenGiven` tracks the FLAG's presence separately from its VALUE, so
404
+ // `--token ''` still suppresses the environment the way it always did.
405
+ let cliToken = undefined;
406
+ let cliTokenGiven = false;
320
407
  // Idle eviction window. Longer than the old 5 min so a dip-in/dip-out mobile
321
408
  // user returns to a still-WARM session (no agent rebuild) most of the time.
322
409
  // With fast-first load a cold return is no longer slow to READ, but a warm
323
410
  // session also avoids the async agent build entirely. Override via
324
411
  // PI_IDLE_TIMEOUT (ms). See docs/plan-speed-up-long-session-load.md.
325
412
  let idleTimeout = parseInt(process.env.PI_IDLE_TIMEOUT || '1200000', 10);
326
- let sslKey = process.env.PI_REMOTE_SSL_KEY || undefined;
327
- let sslCert = process.env.PI_REMOTE_SSL_CERT || undefined;
413
+ // TLS material is addressed by PATH, and each half is resolved INDEPENDENTLY
414
+ // (flag > WHEREVER_* > PI_REMOTE_*). On a declaratively-managed host the key
415
+ // arrives from a secret manager at an arbitrary root-owned path (e.g.
416
+ // /run/secrets/wherever-key.pem) while the certificate is a world-readable
417
+ // file somewhere else entirely, so neither may be tied to a home directory.
418
+ let sslKey = process.env.WHEREVER_SSL_KEY || process.env.PI_REMOTE_SSL_KEY || undefined;
419
+ let sslCert = process.env.WHEREVER_SSL_CERT || process.env.PI_REMOTE_SSL_CERT || undefined;
328
420
  let noSsl = process.env.PI_REMOTE_NO_SSL === 'true' || process.env.PI_REMOTE_HTTP === 'true';
329
421
  let httpLocalhostFallbackPort = undefined;
330
422
  // Enables the eruda custom-plugin loader in the served dashboard (local
@@ -350,7 +442,8 @@ function parseArgs() {
350
442
  host = args[++i] || '127.0.0.1';
351
443
  break;
352
444
  case '--token':
353
- token = args[++i];
445
+ cliToken = args[++i];
446
+ cliTokenGiven = true;
354
447
  break;
355
448
  case '--idle-timeout':
356
449
  idleTimeout = parseInt(args[++i] || '300000', 10);
@@ -387,7 +480,22 @@ function parseArgs() {
387
480
  }
388
481
  }
389
482
  }
390
- return { port, host, token, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug };
483
+ const { token, source: tokenSource } = resolveToken(cliToken, cliTokenGiven);
484
+ // Scrub the token out of our own environment once it is resolved. Node builds
485
+ // a child's environment from `process.env`, and this server spawns children
486
+ // that are not ours to trust with it: the agent's own `bash` tool
487
+ // (session-pool.ts) and the memonaut indexer (conversation-search.ts) both
488
+ // inherit it, so `!env` typed in the dashboard -- or a prompt-injected agent
489
+ // running `echo $WHEREVER_TOKEN` -- would print the server's auth token into a
490
+ // transcript that is then indexed to disk. The value is already captured in
491
+ // `token` above; nothing reads these variables again.
492
+ delete process.env.WHEREVER_TOKEN;
493
+ delete process.env.PI_REMOTE_TOKEN;
494
+ return { port, host, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug };
495
+ }
496
+ /** Loopback-only binds are the safe default; everything else is reachable by others. */
497
+ function isLoopbackHost(host) {
498
+ return host === '127.0.0.1' || host === 'localhost' || host === '::1' || host.startsWith('127.');
391
499
  }
392
500
  function authenticate(req, token) {
393
501
  if (!token)
@@ -482,30 +590,64 @@ function sendThenTerminate(ws, msg, flushTimeoutMs = 1_000) {
482
590
  }
483
591
  }
484
592
  async function main() {
485
- const { port, host, token, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug } = parseArgs();
593
+ const { port, host, token, tokenSource, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug } = parseArgs();
486
594
  debugEnabled = debug;
487
595
  const sessionPool = new SessionPool(idleTimeout);
488
596
  await sessionPool.initialize();
489
597
  const clients = new Map();
490
- let actualSslKey = sslKey;
491
- let actualSslCert = sslCert;
598
+ // expandTilde so `~/certs/...` works from a systemd `Environment=` line or an
599
+ // EnvironmentFile, neither of which is shell-expanded. Without it the read
600
+ // below fails and (before the explicit-TLS check further down) the server
601
+ // quietly served plaintext instead.
602
+ let actualSslKey = sslKey ? expandTilde(sslKey) : sslKey;
603
+ let actualSslCert = sslCert ? expandTilde(sslCert) : sslCert;
492
604
  let isSecure = !noSsl;
605
+ let tlsExplicitlyConfigured = false;
493
606
  if (isSecure) {
607
+ // A key and a certificate only work as a PAIR, so "exactly one supplied" is a
608
+ // misconfiguration. It used to be silent: the `!key || !cert` test threw away
609
+ // the half that WAS supplied and used the self-signed pair, so an operator who
610
+ // pointed --ssl-key at a real key and forgot the cert got a working server
611
+ // presenting a completely different certificate, with nothing in the log. Say
612
+ // so, loudly; the behaviour (fall back to the self-signed pair) is unchanged.
613
+ if (!!actualSslKey !== !!actualSslCert) {
614
+ const supplied = actualSslKey ? '--ssl-key / WHEREVER_SSL_KEY' : '--ssl-cert / WHEREVER_SSL_CERT';
615
+ const missing = actualSslKey ? '--ssl-cert / WHEREVER_SSL_CERT' : '--ssl-key / WHEREVER_SSL_KEY';
616
+ console.warn(`[wherever] ${supplied} was supplied but ${missing} was not. A key and a certificate ` +
617
+ `must be given together; IGNORING the one supplied and using the self-signed pair instead.`);
618
+ actualSslKey = undefined;
619
+ actualSslCert = undefined;
620
+ }
621
+ // Whether the operator POINTED AT specific TLS material, as opposed to
622
+ // letting the server mint its own. It decides what happens if that material
623
+ // cannot be loaded further down: see the `tlsExplicitlyConfigured` branch.
624
+ tlsExplicitlyConfigured = !!(actualSslKey && actualSslCert);
494
625
  if (!actualSslKey || !actualSslCert) {
495
- // Automatic self-signed certificate generation
496
- const homeDir = os.homedir();
497
- const certsDir = path.join(homeDir, '.wherever', 'certs');
626
+ // Automatic self-signed certificate generation. These files are WRITTEN, so
627
+ // they belong to the state dir (WHEREVER_STATE_DIR, defaulting to the config
628
+ // dir, itself defaulting to ~/.wherever) -- with both unset this is exactly
629
+ // the ~/.wherever/certs it has always been.
630
+ const certsDir = getWhereverCertsDir();
631
+ // 0700 on creation: the state dir can now be pointed at a shared location
632
+ // (/var/lib/...), and a world-writable certs dir would let a local user
633
+ // swap in their own key/cert pair. An existing directory keeps its mode.
498
634
  const defaultKeyPath = path.join(certsDir, 'localhost.key');
499
635
  const defaultCertPath = path.join(certsDir, 'localhost.crt');
500
636
  if (!fs.existsSync(defaultKeyPath) || !fs.existsSync(defaultCertPath)) {
501
637
  console.log('Generating self-signed SSL certificates for secure HTTPS/WSS...');
502
638
  try {
503
- fs.mkdirSync(certsDir, { recursive: true });
639
+ fs.mkdirSync(certsDir, { recursive: true, mode: 0o700 });
504
640
  execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-keyout', defaultKeyPath, '-out', defaultCertPath, '-sha256', '-days', '3650', '-nodes', '-subj', '/CN=localhost'], { stdio: 'ignore' });
641
+ // Assert 0600 ourselves rather than trusting openssl's default: it is
642
+ // a private key, and the mode it lands with has varied by version.
643
+ try {
644
+ fs.chmodSync(defaultKeyPath, 0o600);
645
+ }
646
+ catch { }
505
647
  console.log(`Self-signed certificates generated successfully in ${certsDir}`);
506
648
  }
507
649
  catch (err) {
508
- console.warn('Failed to generate self-signed certificates using OpenSSL. Falling back to HTTP.', err.message);
650
+ console.warn(`Failed to generate self-signed certificates in ${certsDir} using OpenSSL. Falling back to HTTP.`, err.message);
509
651
  isSecure = false;
510
652
  }
511
653
  }
@@ -785,6 +927,7 @@ async function main() {
785
927
  pathname.startsWith('/config') ||
786
928
  pathname.startsWith('/check-path') ||
787
929
  pathname.startsWith('/check-remote-repo') ||
930
+ pathname.startsWith('/remote-candidates') ||
788
931
  pathname.startsWith('/autocomplete-path') ||
789
932
  pathname.startsWith('/session/');
790
933
  if (isApiRequest && !authenticate(req, token)) {
@@ -943,14 +1086,12 @@ async function main() {
943
1086
  // Check matching remote rules
944
1087
  let matchingRule = null;
945
1088
  const config = getWhereverConfig();
946
- if (config.remoteRepoRules && Array.isArray(config.remoteRepoRules)) {
947
- const rule = config.remoteRepoRules.find(r => repoRuleMatches(r.pattern, resolved));
948
- if (rule) {
949
- matchingRule = {
950
- provider: rule.provider,
951
- visibility: rule.visibility || 'private'
952
- };
953
- }
1089
+ const rule = matchRemoteRepoRule(config.remoteRepoRules, resolved);
1090
+ if (rule) {
1091
+ matchingRule = {
1092
+ provider: rule.provider,
1093
+ visibility: rule.visibility || 'private'
1094
+ };
954
1095
  }
955
1096
  sendJSON(res, 200, { exists, isGit, resolvedPath: resolved, matchingRule });
956
1097
  return;
@@ -976,9 +1117,7 @@ async function main() {
976
1117
  resolved = path.resolve(qPath);
977
1118
  }
978
1119
  const config = getWhereverConfig();
979
- const rule = (config.remoteRepoRules && Array.isArray(config.remoteRepoRules))
980
- ? config.remoteRepoRules.find(r => repoRuleMatches(r.pattern, resolved))
981
- : undefined;
1120
+ const rule = matchRemoteRepoRule(config.remoteRepoRules, resolved);
982
1121
  if (!rule) {
983
1122
  sendJSON(res, 200, { exists: false, matched: false });
984
1123
  return;
@@ -992,6 +1131,41 @@ async function main() {
992
1131
  });
993
1132
  return;
994
1133
  }
1134
+ // Restore pre-fill: which repository does this (probably missing) folder
1135
+ // correspond to? Answers an ORDERED, ADVISORY list of SSH candidates --
1136
+ // the provider probe first, then the `<host-token>/<owner>/<repo>` path
1137
+ // convention (see server/src/remote-candidates.ts). Never HTTPS.
1138
+ //
1139
+ // Beside /check-remote-repo and for the same reason: the probe shells out to
1140
+ // a provider CLI, so this is called ON DEMAND (the restore panel opening),
1141
+ // never per keystroke and never on the session-load path.
1142
+ if (pathname === '/remote-candidates' && req.method === 'GET') {
1143
+ const qPath = url.searchParams.get('path');
1144
+ if (!qPath) {
1145
+ sendJSON(res, 400, { error: 'Missing path' });
1146
+ return;
1147
+ }
1148
+ let resolved = qPath;
1149
+ if (qPath.startsWith('~')) {
1150
+ resolved = path.join(os.homedir(), qPath.slice(1));
1151
+ }
1152
+ else if (!path.isAbsolute(qPath)) {
1153
+ resolved = path.join(os.homedir(), qPath);
1154
+ }
1155
+ else {
1156
+ resolved = path.resolve(qPath);
1157
+ }
1158
+ // Same scoping as /check-path: an authenticated caller cannot use this to
1159
+ // ask questions about paths outside the home folder.
1160
+ if (!isWithinHome(resolved)) {
1161
+ sendJSON(res, 403, { error: 'Path is outside the home directory' });
1162
+ return;
1163
+ }
1164
+ const config = getWhereverConfig();
1165
+ const candidates = resolveRemoteCandidates(resolved, config.remoteRepoRules, detectRemoteRepo);
1166
+ sendJSON(res, 200, { resolvedPath: resolved, candidates });
1167
+ return;
1168
+ }
995
1169
  if (pathname === '/autocomplete-path' && req.method === 'GET') {
996
1170
  const qPath = url.searchParams.get('path') || '';
997
1171
  let parentPath = '';
@@ -1270,7 +1444,19 @@ async function main() {
1270
1444
  sendJSON(res, 400, { error: 'Missing cwd' });
1271
1445
  return;
1272
1446
  }
1273
- const result = await sessionPool.createNewSession(cwd, model, gitInit, createRemote, repoVisibility, cloneRemote);
1447
+ // Same CLONE branch as the WebSocket `session_new`, through the same
1448
+ // restore job registry, so this endpoint gains recursive submodules and
1449
+ // loses nothing. There is no progress channel on a plain HTTP request,
1450
+ // so it simply waits for the job it started (or joined); any WebSocket
1451
+ // client looking at that folder still gets the live frames.
1452
+ if (cloneRemote) {
1453
+ const outcome = await cloneForNewSession(resolveCreateCwd(cwd), clients, sessionPool);
1454
+ if (outcome.status === 'failed') {
1455
+ sendJSON(res, 500, { error: outcome.error });
1456
+ return;
1457
+ }
1458
+ }
1459
+ const result = await sessionPool.createNewSession(cwd, model, gitInit, createRemote, repoVisibility);
1274
1460
  if (result.error) {
1275
1461
  sendJSON(res, 500, { error: result.error });
1276
1462
  }
@@ -1508,6 +1694,20 @@ async function main() {
1508
1694
  }
1509
1695
  }
1510
1696
  catch (err) {
1697
+ // Falling back to plaintext is only acceptable for material the server
1698
+ // chose for itself. When the operator EXPLICITLY pointed at a key and a
1699
+ // certificate, silently serving HTTP on the same (possibly 0.0.0.0)
1700
+ // address is the same fail-open ADR 0007 rules out for the token file:
1701
+ // it is the exact shape of a secret that has not been decrypted yet, and
1702
+ // clients would then send their token in cleartext to a server that looks
1703
+ // healthy. Refuse to start instead.
1704
+ if (tlsExplicitlyConfigured) {
1705
+ console.error(`FATAL: TLS was explicitly configured (key ${actualSslKey}, cert ${actualSslCert}) but ` +
1706
+ `could not be loaded: ${err.message}. Refusing to start: falling back to ` +
1707
+ `plaintext HTTP would silently expose traffic (and the auth token) on ${host}:${port}. ` +
1708
+ `Pass --no-ssl if plaintext is genuinely what you want.`);
1709
+ process.exit(1);
1710
+ }
1511
1711
  console.error(`Failed to load SSL certificates from ${actualSslKey} and ${actualSslCert}. Falling back to HTTP.`, err.message);
1512
1712
  server = createHttpServer(requestHandler);
1513
1713
  }
@@ -1687,8 +1887,24 @@ async function main() {
1687
1887
  wss.on('close', () => clearInterval(heartbeat));
1688
1888
  server.listen(port, host, () => {
1689
1889
  const protocol = isSecureServer ? 'https' : 'http';
1690
- const authInfo = token ? ' (token-protected)' : ' (no authentication)';
1890
+ // The SOURCE, never the token itself: this line goes to the journal, which
1891
+ // is readable by more people than the secret is.
1892
+ const authInfo = token ? ` (token-protected via ${tokenSource})` : ' (no authentication)';
1691
1893
  console.log(`\n🔐 Wherever Server: ${protocol}://${host}:${port}${authInfo}`);
1894
+ if (token && tokenSource === '--token') {
1895
+ console.warn('[wherever] the token came from the command line, which is visible to every user on this ' +
1896
+ 'machine via `ps`. For a real deployment set WHEREVER_TOKEN (or WHEREVER_TOKEN_FILE) instead.');
1897
+ }
1898
+ // Binding off-loopback with no token is a valid, long-supported choice (it
1899
+ // is how a trusted mesh/VPN setup runs), so it stays permitted. But it is
1900
+ // also exactly what a failed secret render looks like, and the two are
1901
+ // indistinguishable from the outside, so it must not slip by as one
1902
+ // parenthetical word in an otherwise cheerful startup line.
1903
+ if (!token && !isLoopbackHost(host)) {
1904
+ console.warn(`[wherever] WARNING: listening on ${host} with NO AUTHENTICATION. Anyone who can reach ` +
1905
+ `this address has full agent and filesystem access. If you meant to configure a token, ` +
1906
+ `it did not arrive: check WHEREVER_TOKEN / WHEREVER_TOKEN_FILE.`);
1907
+ }
1692
1908
  if (isSecureServer) {
1693
1909
  console.log(`
1694
1910
  👉 FIRST TIME CONNECTING?
@@ -1770,11 +1986,229 @@ function resolveFolderConflictState(c, pool) {
1770
1986
  // sessions.readOnly folder is a hard rule and is never lifted here.
1771
1987
  if (c.conflictObserver && !active) {
1772
1988
  c.conflictObserver = false;
1773
- if (!pool.isReadOnlyCwd(mine.cwd))
1989
+ if (!hasHardReadOnly(c, pool, mine.cwd))
1774
1990
  c.readOnly = false;
1775
1991
  }
1776
1992
  return { cwd: mine.cwd, active };
1777
1993
  }
1994
+ // Read-only PRECEDENCE in one place. Of the three reasons a client can be
1995
+ // read-only, two are HARD and one is dismissible:
1996
+ // - a configured `sessions.readOnly` folder: a policy rule, never lifted;
1997
+ // - FOLDER MISSING: the working folder does not exist on this machine, so
1998
+ // there is nothing to drive; lifted only by restoring it and RELOADING;
1999
+ // - a folder conflict: two live sessions in one folder, lifted by the user's
2000
+ // "Continue anyway".
2001
+ // Every site that LIFTS read-only asks this first, so the dismissible reason can
2002
+ // never dismiss a hard one.
2003
+ function hasHardReadOnly(client, pool, cwd) {
2004
+ return pool.isReadOnlyCwd(cwd) || client.folderMissingCwd !== undefined;
2005
+ }
2006
+ // ---------------------------------------------------------------------------
2007
+ // Restore jobs over the WebSocket
2008
+ // ---------------------------------------------------------------------------
2009
+ // The ONE registry of restore jobs for this server process. Jobs are keyed by
2010
+ // the resolved absolute TARGET PATH and owned by the server (`docs/adr/0009`),
2011
+ // so the registry is deliberately process-wide rather than per-connection: that
2012
+ // is exactly what makes a clone survive the socket that started it, be shared by
2013
+ // a second device, and never be started twice for one folder. Constructing it is
2014
+ // inert (nothing runs until `request()`), so it can live at module scope beside
2015
+ // the handlers that drive it.
2016
+ const restoreJobs = new RestoreJobRegistry();
2017
+ // The live broadcast subscription for each observed path, so it can be dropped
2018
+ // the moment its job settles. This is the SERVER's single subscription per path,
2019
+ // NOT a per-client one: which clients a frame reaches is derived per frame (see
2020
+ // clientWatchesRestorePath), so no client bookkeeping exists to leak.
2021
+ const restoreObservers = new Map();
2022
+ /**
2023
+ * Does this client currently have the restore target on screen?
2024
+ *
2025
+ * The three places a client's folder can be recorded, and why each is needed:
2026
+ * - its ATTACHED session's cwd: the ordinary case, a live session in the folder;
2027
+ * - `pendingCwd`: a load painted but not yet attached (a cold load spends
2028
+ * seconds there);
2029
+ * - `folderMissingCwd`: a folder-missing load, which deliberately attaches to
2030
+ * NOTHING and clears `pendingCwd` with it -- so this is the only record of
2031
+ * the folder such a client is looking at, and it is precisely the client the
2032
+ * restore panel is rendered for.
2033
+ *
2034
+ * Matching is what SUBSCRIPTION means here: it is evaluated per frame rather
2035
+ * than registered per socket, so a dropped phone leaves nothing behind and a
2036
+ * reconnecting one is matched again for free.
2037
+ */
2038
+ function clientWatchesRestorePath(c, pool, targetPath) {
2039
+ if (c.isCliBridge)
2040
+ return false;
2041
+ const attached = c.sessionId ? pool.getSession(c.sessionId)?.cwd : undefined;
2042
+ for (const candidate of [attached, c.pendingCwd, c.folderMissingCwd]) {
2043
+ if (candidate && path.resolve(candidate) === targetPath)
2044
+ return true;
2045
+ }
2046
+ return false;
2047
+ }
2048
+ function broadcastRestore(clients, pool, targetPath, msg) {
2049
+ for (const c of clients.values()) {
2050
+ if (clientWatchesRestorePath(c, pool, targetPath))
2051
+ sendWS(c.ws, msg);
2052
+ }
2053
+ }
2054
+ /**
2055
+ * Start relaying one path's restore job to whoever is watching that path.
2056
+ *
2057
+ * Idempotent (a second requester joining a running job must not double-relay),
2058
+ * and self-releasing: the subscription is dropped inside `onSettled`, which the
2059
+ * registry guarantees for every terminal state, so an observer cannot outlive
2060
+ * its job. Subscribe BEFORE requesting the job, because a request can settle
2061
+ * synchronously (a spawn that throws) and a frame emitted before the subscription
2062
+ * exists would simply be lost.
2063
+ */
2064
+ function observeRestorePath(targetPath, clients, pool) {
2065
+ if (restoreObservers.has(targetPath))
2066
+ return;
2067
+ const unsubscribe = restoreJobs.subscribe(targetPath, {
2068
+ onProgress: (_progress, job) => {
2069
+ broadcastRestore(clients, pool, targetPath, { type: 'restore_progress', targetPath, job });
2070
+ },
2071
+ onSettled: (job) => {
2072
+ broadcastRestore(clients, pool, targetPath, { type: 'restore_complete', targetPath, job });
2073
+ releaseRestoreObserver(targetPath);
2074
+ },
2075
+ });
2076
+ restoreObservers.set(targetPath, unsubscribe);
2077
+ }
2078
+ function releaseRestoreObserver(targetPath) {
2079
+ const unsubscribe = restoreObservers.get(targetPath);
2080
+ if (!unsubscribe)
2081
+ return;
2082
+ restoreObservers.delete(targetPath);
2083
+ unsubscribe();
2084
+ }
2085
+ // The listing's per-folder existence answers, awaiting invalidation, keyed the
2086
+ // same way. A SECOND, INDEPENDENT subscription to the registry: the session
2087
+ // browser's "missing" mark is not a client of the restore panel, and routing its
2088
+ // invalidation through the broadcast relay above would make one the other's
2089
+ // plumbing. Neither reaches into the registry's internals and neither is wired
2090
+ // through the other (see CONTEXT.md, "the module owns the observation seam").
2091
+ const folderExistenceObservers = new Map();
2092
+ /**
2093
+ * Drop the listing's cached existence answer for a path when the restore job
2094
+ * there SETTLES.
2095
+ *
2096
+ * A restore is the one moment wherever itself changes whether a folder is on
2097
+ * this machine, so without this the browser would keep marking a just-restored
2098
+ * folder "missing" for the rest of the cache's TTL. Every terminal state
2099
+ * invalidates (a cancelled clone REMOVES a directory it created, so the cached
2100
+ * answer is equally suspect), but only a `done` job asks the connected clients
2101
+ * to refetch: that is what makes the mark disappear with no manual refresh.
2102
+ *
2103
+ * Idempotent per path and self-releasing inside `onSettled`, exactly like the
2104
+ * broadcast observer.
2105
+ */
2106
+ function observeRestoreForFolderExistence(targetPath, onSessionsUpdated) {
2107
+ if (folderExistenceObservers.has(targetPath))
2108
+ return;
2109
+ const unsubscribe = restoreJobs.subscribe(targetPath, {
2110
+ onSettled: (job) => {
2111
+ invalidateFolderExistence(targetPath);
2112
+ releaseFolderExistenceObserver(targetPath);
2113
+ if (job.state === 'done')
2114
+ onSessionsUpdated?.();
2115
+ },
2116
+ });
2117
+ folderExistenceObservers.set(targetPath, unsubscribe);
2118
+ }
2119
+ function releaseFolderExistenceObserver(targetPath) {
2120
+ const unsubscribe = folderExistenceObservers.get(targetPath);
2121
+ if (!unsubscribe)
2122
+ return;
2123
+ folderExistenceObservers.delete(targetPath);
2124
+ unsubscribe();
2125
+ }
2126
+ /**
2127
+ * Resolve a caller-supplied `cwd` the way session creation does: `~` and a bare
2128
+ * relative path both mean "under the home directory", everything else is
2129
+ * resolved as given. Kept identical to `SessionPool.createNewSession`'s own
2130
+ * resolution so the restore job's key, the frames it is broadcast under and the
2131
+ * folder the session is finally created in are ONE path.
2132
+ */
2133
+ function resolveCreateCwd(cwd) {
2134
+ if (cwd.startsWith('~'))
2135
+ return normalizePath(path.join(os.homedir(), cwd.slice(1)));
2136
+ if (!path.isAbsolute(cwd))
2137
+ return normalizePath(path.join(os.homedir(), cwd));
2138
+ return normalizePath(path.resolve(cwd));
2139
+ }
2140
+ /**
2141
+ * The CLONE branch of session creation, run through the restore job registry.
2142
+ *
2143
+ * This is the OTHER entry point of `docs/adr/0009`, and it exists so there is
2144
+ * exactly ONE clone implementation in the codebase: the same path-keyed jobs,
2145
+ * the same recursive `--recurse-submodules` engine, the same URL allowlist and
2146
+ * home-directory guard, and the same honest progress frames the restore panel
2147
+ * renders. What it does NOT share is the ending: a loaded session offers a
2148
+ * RELOAD (a live agent is a load-time decision), but here there is no session to
2149
+ * reload until the clone lands, so the caller CONTINUES into creation itself.
2150
+ *
2151
+ * The job is awaited rather than reported-and-forgotten precisely because the
2152
+ * create depends on it. It stays cancellable while it runs: the job is
2153
+ * server-owned and path-keyed, so the ordinary `restore_cancel` frame reaches
2154
+ * it and settles it `cancelled`, which fails the create here.
2155
+ *
2156
+ * `onStarted` is how the WebSocket caller tells ITS client which job to paint;
2157
+ * the HTTP caller has no progress channel and simply waits. Broadcasts reach
2158
+ * every client whose folder matches the path either way.
2159
+ */
2160
+ async function cloneForNewSession(targetPath, clients, pool, onStarted) {
2161
+ const config = getWhereverConfig();
2162
+ const rule = matchRemoteRepoRule(config.remoteRepoRules, targetPath);
2163
+ if (!rule)
2164
+ return { status: 'skipped' };
2165
+ // The SAME probe the dashboard's clone-or-create dialog asked (via
2166
+ // /check-remote-repo) before offering to clone. The URL is resolved HERE, on
2167
+ // the server, rather than taken from the client: the create path has no
2168
+ // editable URL field, so a client-supplied one would be a new, unasked-for
2169
+ // authority. (The restore panel's editable field is the deliberate exception,
2170
+ // and it is validated by the registry all the same.)
2171
+ //
2172
+ // Note what is NOT used: `resolveRemoteCandidates`, whose path-convention
2173
+ // candidate is a GUESS offered to a human who can edit it. There is no field
2174
+ // to edit here, so an unprobed guess would be cloned blind. A probe that finds
2175
+ // nothing SKIPS the clone and lets the ordinary create proceed, exactly as the
2176
+ // deleted synchronous path did.
2177
+ const probe = detectRemoteRepo(rule, path.basename(targetPath));
2178
+ if (!probe.exists || !probe.sshUrl)
2179
+ return { status: 'skipped' };
2180
+ // Subscribe BEFORE requesting: a request can settle inside the call (a spawn
2181
+ // that throws) and a frame emitted before the subscription exists is lost.
2182
+ observeRestorePath(targetPath, clients, pool);
2183
+ // No refetch callback here: this clone is followed by the session creation it
2184
+ // exists for, which broadcasts `sessions_updated` on its own.
2185
+ observeRestoreForFolderExistence(targetPath);
2186
+ const result = restoreJobs.request({ kind: 'clone', targetPath, url: probe.sshUrl });
2187
+ if (!result.ok) {
2188
+ // A refusal is not a job: nothing will ever settle here, so neither
2189
+ // subscription may be left waiting for a completion that is not coming.
2190
+ if (restoreJobs.get(targetPath)?.state !== 'running') {
2191
+ releaseRestoreObserver(targetPath);
2192
+ releaseFolderExistenceObserver(targetPath);
2193
+ }
2194
+ return { status: 'failed', error: result.message };
2195
+ }
2196
+ onStarted?.(result.outcome, result.job);
2197
+ const settled = await restoreJobs.settled(targetPath).catch(() => undefined);
2198
+ if (settled?.state === 'done')
2199
+ return { status: 'cloned' };
2200
+ if (settled?.state === 'cancelled') {
2201
+ return {
2202
+ status: 'failed',
2203
+ error: `The clone into ${targetPath} was cancelled, so no session was created.`,
2204
+ };
2205
+ }
2206
+ return {
2207
+ status: 'failed',
2208
+ error: settled?.failure?.message ??
2209
+ `Failed to clone ${probe.sshUrl} into ${targetPath}, so no session was created.`,
2210
+ };
2211
+ }
1778
2212
  // Resolve and report in one step. Every folder_conflict frame goes out through
1779
2213
  // here, so the `readOnly` it carries can never drift from the authority that
1780
2214
  // produced `active`.
@@ -1916,6 +2350,9 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1916
2350
  // session we are leaving. Reset BEFORE the first await, so a continue that
1917
2351
  // races this load is recorded against the load, never wiped by it.
1918
2352
  client.conflictContinued = false;
2353
+ // Same reasoning for the missing-folder lock: it belongs to the session we
2354
+ // are leaving, and must not leak into the one we are opening.
2355
+ client.folderMissingCwd = undefined;
1919
2356
  const meta = await pool.readSessionMeta(msg.sessionFile, INITIAL_HISTORY_LIMIT, msg.model);
1920
2357
  if ('error' in meta) {
1921
2358
  sendWS(client.ws, { type: 'session_error', error: meta.error });
@@ -1929,9 +2366,27 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1929
2366
  // aborting the other session -- both then run concurrently.
1930
2367
  const conflict = pool.detectConflict(meta.sessionFile, meta.cwd);
1931
2368
  const folderConflict = conflict.conflict && !!conflict.otherSessionId;
2369
+ // This session's working folder is not usable as a working folder. TWO
2370
+ // things produce that, and they are one state because they have one
2371
+ // remedy and one rendering:
2372
+ // - it does NOT EXIST (the transcript synced, the clone did not), the
2373
+ // cheap meta read's `stat`;
2374
+ // - a RESTORE JOB is materialising it RIGHT NOW. `git clone` creates the
2375
+ // target directory in its first breath, so the existence check alone
2376
+ // says "present" for the whole of a multi-minute clone, and a client
2377
+ // loading in that window (a reconnect, a second device) would be handed
2378
+ // a live agent pointed at a HALF-CLONED tree. That is the same silent
2379
+ // breakage this state exists to replace.
2380
+ // The conversation is still READABLE either way -- reading never needed the
2381
+ // folder -- but the client is locked and, on the cold path below, no live
2382
+ // agent is built at all.
2383
+ const restoreInFlight = restoreJobs.get(meta.cwd)?.state === 'running';
2384
+ const folderMissing = meta.folderMissing || restoreInFlight;
2385
+ client.folderMissingCwd = folderMissing ? meta.cwd : undefined;
1932
2386
  // A session whose cwd matches a sessions.readOnly glob is forced read-only.
1933
- // A folder conflict also starts the client read-only until they continue.
1934
- const forcedReadOnly = meta.readOnly || folderConflict;
2387
+ // A missing folder forces it too (hard, see hasHardReadOnly). A folder
2388
+ // conflict also starts the client read-only until they continue.
2389
+ const forcedReadOnly = meta.readOnly || folderMissing || folderConflict;
1935
2390
  client.readOnly = forcedReadOnly;
1936
2391
  client.conflictObserver = folderConflict;
1937
2392
  client.pendingCwd = meta.cwd;
@@ -1947,6 +2402,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1947
2402
  isStreaming: meta.resident ? pool.isStreaming(meta.sessionFile) : false,
1948
2403
  readOnly: forcedReadOnly,
1949
2404
  folderConflict,
2405
+ folderMissing,
1950
2406
  contextUsage: meta.resident ? (pool.getContextUsage(meta.sessionFile) ?? null) : null,
1951
2407
  pending: !meta.resident,
1952
2408
  });
@@ -1957,6 +2413,26 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1957
2413
  totalCount: meta.history.totalCount,
1958
2414
  offset: meta.history.offset,
1959
2415
  });
2416
+ // State the missing folder explicitly, naming the absolute path, so the
2417
+ // client can replace its composer with a notice that says WHICH folder to
2418
+ // restore instead of an unexplained lock. A client that predates the frame
2419
+ // simply ignores it; the server's refusal to accept its sends is what
2420
+ // protects it either way.
2421
+ //
2422
+ // Any restore job already running for this folder rides along, so a client
2423
+ // arriving MID-CLONE (a reconnect, a second device, a phone waking up)
2424
+ // repaints the running job from this one frame instead of being offered a
2425
+ // second clone. Live frames follow on their own, because this client now
2426
+ // matches the job path (see clientWatchesRestorePath).
2427
+ if (folderMissing) {
2428
+ const job = restoreJobs.get(meta.cwd);
2429
+ sendWS(client.ws, {
2430
+ type: 'folder_missing',
2431
+ sessionId: meta.sessionId,
2432
+ cwd: meta.cwd,
2433
+ ...(job ? { job } : {}),
2434
+ });
2435
+ }
1960
2436
  // Already resident (warm): attach immediately, no async build needed.
1961
2437
  if (meta.resident) {
1962
2438
  pool.addClient(meta.sessionFile, client.id);
@@ -1978,6 +2454,24 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1978
2454
  sendQueueSnapshot(client, meta.sessionFile, meta.sessionId, pool);
1979
2455
  break;
1980
2456
  }
2457
+ // Cold + folder missing: do NOT build the live agent. Building one would
2458
+ // SUCCEED (pi's settings/resource loading tolerate a nonexistent cwd) and
2459
+ // hand back an agent whose every tool call is broken -- the silent failure
2460
+ // this state exists to replace. So the load ends here: painted, locked,
2461
+ // explained. Curing it takes a restore plus a RELOAD, because whether a
2462
+ // session has a live agent is a load-time decision.
2463
+ //
2464
+ // Detach from whatever we were attached to before as well: this load never
2465
+ // attaches anywhere, and staying on the previous session would leave a
2466
+ // phantom viewer holding a folder the user has left.
2467
+ // (A RESIDENT session is handled by the branch above and keeps its running
2468
+ // agent: a folder that vanished under a live session is out of scope here,
2469
+ // we only refuse to hand out a fresh write capability.)
2470
+ if (folderMissing) {
2471
+ switchClientSession(client, null, pool, onSessionsUpdated);
2472
+ client.readOnly = true;
2473
+ break;
2474
+ }
1981
2475
  // Cold: build the live agent in the background, then attach + signal ready.
1982
2476
  // Errors degrade to a session_error (the conversation stays readable).
1983
2477
  void (async () => {
@@ -2070,7 +2564,34 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2070
2564
  // "Continue anyway" could only unlock THAT conversation, never give them the
2071
2565
  // fresh one. So: create the session (forceNew), then report the folder
2072
2566
  // conflict, if any, AGAINST the new session.
2073
- const result = await pool.createNewSession(msg.cwd, msg.model, msg.gitInit, msg.createRemote, msg.repoVisibility, msg.cloneRemote, true);
2567
+ //
2568
+ // CLONE-AN-EXISTING-REMOTE first, when that is what the user chose in the
2569
+ // clone-or-create dialog. It runs as a RESTORE JOB (one clone
2570
+ // implementation, `docs/adr/0009`): the client is told which job to paint
2571
+ // and then watches the ordinary `restore_progress` frames, instead of
2572
+ // staring at a blocking overlay its 25s create watchdog would give up on
2573
+ // while git was still running. Creating a REMOTE (the other branch of that
2574
+ // dialog) is untouched and still happens inside createNewSession.
2575
+ if (msg.cloneRemote) {
2576
+ const targetPath = resolveCreateCwd(msg.cwd);
2577
+ // The restore broadcast is DERIVED from a path match against each
2578
+ // client's folder, and this client has no session yet: recording the
2579
+ // target as its pending cwd is what puts it in scope for its own clone.
2580
+ client.pendingCwd = targetPath;
2581
+ const outcome = await cloneForNewSession(targetPath, clients, pool, (result, job) => {
2582
+ sendWS(client.ws, { type: 'restore_started', targetPath, outcome: result, job });
2583
+ });
2584
+ if (outcome.status === 'failed') {
2585
+ // The clone is the create's first step, so its failure IS the create's
2586
+ // failure: report it on the create's own channel (the mapped cause,
2587
+ // from the registry) and make no session. The restore_complete frame
2588
+ // carrying git's raw output was broadcast beside it.
2589
+ client.pendingCwd = undefined;
2590
+ sendWS(client.ws, { type: 'session_error', error: outcome.error });
2591
+ return;
2592
+ }
2593
+ }
2594
+ const result = await pool.createNewSession(msg.cwd, msg.model, msg.gitInit, msg.createRemote, msg.repoVisibility, true);
2074
2595
  if (result.error) {
2075
2596
  sendWS(client.ws, { type: 'session_error', error: result.error });
2076
2597
  return;
@@ -2080,6 +2601,9 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2080
2601
  pool.addClient(result.tracked.sessionFile, client.id);
2081
2602
  switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
2082
2603
  clearConflictState(client);
2604
+ // Creating a session CREATES its folder (mkdir/clone), so this one exists
2605
+ // by construction: clear any missing-folder lock the previous session left.
2606
+ client.folderMissingCwd = undefined;
2083
2607
  client.pendingCwd = result.tracked.cwd;
2084
2608
  // Is somebody else still live in this folder? Then two agents would be
2085
2609
  // editing the same working tree, which is exactly what the folder-conflict
@@ -2131,6 +2655,10 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2131
2655
  break;
2132
2656
  }
2133
2657
  case 'session_leave': {
2658
+ // The lock belongs to the session being left, so it goes with it. (A
2659
+ // folder-missing load never attaches, so `sessionId` can already be null
2660
+ // here and the flag must be cleared regardless.)
2661
+ client.folderMissingCwd = undefined;
2134
2662
  if (client.sessionId) {
2135
2663
  switchClientSession(client, null, pool, onSessionsUpdated);
2136
2664
  client.readOnly = false;
@@ -2172,7 +2700,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2172
2700
  // load/create, so it can only ever apply to the load in flight, and the
2173
2701
  // sessions.readOnly guard is re-applied at attach with the real cwd.
2174
2702
  client.conflictContinued = true;
2175
- if (cwd && !pool.isReadOnlyCwd(cwd))
2703
+ if (cwd && !hasHardReadOnly(client, pool, cwd))
2176
2704
  client.readOnly = false;
2177
2705
  // Reply with this client's authoritative conflict state, ALWAYS (including
2178
2706
  // when the lift was refused for a sessions.readOnly folder). Same-socket
@@ -2183,7 +2711,107 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2183
2711
  sendFolderConflict(client, pool);
2184
2712
  break;
2185
2713
  }
2714
+ case 'restore_start': {
2715
+ // RESTORE the working folder at `targetPath`: clone the repository back, or
2716
+ // create the folder. The job is server-owned and path-keyed, so this is a
2717
+ // request to the REGISTRY, not an operation on this socket.
2718
+ const raw = typeof msg.targetPath === 'string' ? msg.targetPath.trim() : '';
2719
+ if (!raw) {
2720
+ sendWS(client.ws, {
2721
+ type: 'restore_rejected',
2722
+ targetPath: '',
2723
+ reason: 'invalid-target',
2724
+ message: 'A target path is required.',
2725
+ });
2726
+ break;
2727
+ }
2728
+ // Resolve the same way the registry does, so the broadcast key, the frames
2729
+ // and the job all name ONE path.
2730
+ const targetPath = path.resolve(expandTilde(raw));
2731
+ // Subscribe first: a request can settle inside the call (a spawn that
2732
+ // throws), and a frame emitted before the subscription exists is lost.
2733
+ observeRestorePath(targetPath, clients, pool);
2734
+ observeRestoreForFolderExistence(targetPath, onSessionsUpdated);
2735
+ const request = msg.action === 'create'
2736
+ ? { kind: 'create', targetPath, gitInit: msg.gitInit === true }
2737
+ : { kind: 'clone', targetPath, url: typeof msg.url === 'string' ? msg.url.trim() : '' };
2738
+ const result = restoreJobs.request(request);
2739
+ if (!result.ok) {
2740
+ // Nothing was spawned or created, so there is no job to observe and no
2741
+ // completion coming. Say why, to the requester only, and let go of the
2742
+ // subscriptions we optimistically took.
2743
+ if (restoreJobs.get(targetPath)?.state !== 'running') {
2744
+ releaseRestoreObserver(targetPath);
2745
+ releaseFolderExistenceObserver(targetPath);
2746
+ }
2747
+ sendWS(client.ws, {
2748
+ type: 'restore_rejected',
2749
+ targetPath,
2750
+ reason: result.reason,
2751
+ message: result.message,
2752
+ });
2753
+ break;
2754
+ }
2755
+ // `outcome` and `job.url` together are what stop a second device from being
2756
+ // silently answered as though ITS edited url had been accepted.
2757
+ sendWS(client.ws, {
2758
+ type: 'restore_started',
2759
+ targetPath,
2760
+ outcome: result.outcome,
2761
+ job: result.job,
2762
+ });
2763
+ if (result.job.state !== 'running') {
2764
+ // Settled inside request() (a spawn failure), so no observer will ever
2765
+ // report it: state the outcome here instead of leaving the panel spinning.
2766
+ releaseRestoreObserver(targetPath);
2767
+ broadcastRestore(clients, pool, targetPath, {
2768
+ type: 'restore_complete',
2769
+ targetPath,
2770
+ job: result.job,
2771
+ });
2772
+ }
2773
+ break;
2774
+ }
2775
+ case 'restore_cancel': {
2776
+ const raw = typeof msg.targetPath === 'string' ? msg.targetPath.trim() : '';
2777
+ if (!raw)
2778
+ break;
2779
+ const targetPath = path.resolve(expandTilde(raw));
2780
+ // The job is path-keyed and server-owned, so any client watching the folder
2781
+ // may cancel it -- including one that did not start it, which is the whole
2782
+ // point when the device that did is the one that went away. The registry
2783
+ // settles the job (authoritatively) and the observer broadcasts the
2784
+ // `cancelled` completion to everyone watching, so nothing is answered here.
2785
+ if (restoreJobs.cancel(targetPath))
2786
+ break;
2787
+ // Nothing was running: re-state the current (retained) job to the asker so a
2788
+ // stale panel converges instead of waiting for a completion that already
2789
+ // happened.
2790
+ const job = restoreJobs.get(targetPath);
2791
+ if (job)
2792
+ sendWS(client.ws, { type: 'restore_complete', targetPath, job });
2793
+ break;
2794
+ }
2186
2795
  case 'message': {
2796
+ // The session's working folder does not exist on this machine, so no live
2797
+ // agent was built for it and there is nothing to attach to (which would
2798
+ // otherwise make this a SILENT drop on the sessionId check below). Refuse
2799
+ // by path, naming it, so the client can say what to restore.
2800
+ if (client.folderMissingCwd) {
2801
+ // Word it for the state the folder is actually in: a restore already
2802
+ // running is a wait, not a "go and restore it".
2803
+ const restoring = restoreJobs.get(client.folderMissingCwd)?.state === 'running';
2804
+ sendWS(client.ws, {
2805
+ type: 'session_error',
2806
+ sessionId: msg.sessionId,
2807
+ error: restoring
2808
+ ? `This session's working folder (${client.folderMissingCwd}) is still being restored, ` +
2809
+ 'so the message was not delivered. Wait for the restore to finish, then reload the session.'
2810
+ : `This session's working folder does not exist on this machine (${client.folderMissingCwd}), ` +
2811
+ 'so the message was not delivered. Restore the folder, then reload the session.',
2812
+ });
2813
+ return;
2814
+ }
2187
2815
  if (!client.sessionId)
2188
2816
  return;
2189
2817
  if (client.readOnly) {
@@ -2321,6 +2949,23 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2321
2949
  });
2322
2950
  break;
2323
2951
  }
2952
+ // An upload WRITES a file to disk, so it is a write capability and belongs
2953
+ // behind the same verdict as a send. Without this, a client on an
2954
+ // observe-only session (a sessions.readOnly folder, an uncontinued folder
2955
+ // conflict, or a missing folder) could not send a message referencing an
2956
+ // attachment but could still drop the attachment itself into the upload
2957
+ // dir. Refuse out loud rather than silently, for the same reason the
2958
+ // message handler does: a client only hides its composer when it AGREES it
2959
+ // is read-only, so any desync must be visible instead of swallowed.
2960
+ if (client.readOnly) {
2961
+ sendWS(client.ws, {
2962
+ type: 'file_upload_error',
2963
+ uploadId,
2964
+ sessionId,
2965
+ error: 'This session is read-only from here, so the file was not uploaded.',
2966
+ });
2967
+ break;
2968
+ }
2324
2969
  try {
2325
2970
  const tracked = pool.getSession(sessionId);
2326
2971
  const cwd = tracked?.cwd;