wherever-dev 0.13.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 (46) hide show
  1. package/dist/index.js +493 -32
  2. package/dist/index.js.map +1 -1
  3. package/dist/protocol.d.ts +35 -0
  4. package/dist/protocol.d.ts.map +1 -1
  5. package/dist/protocol.js.map +1 -1
  6. package/dist/remote-candidates.d.ts +52 -0
  7. package/dist/remote-candidates.d.ts.map +1 -0
  8. package/dist/remote-candidates.js +147 -0
  9. package/dist/remote-candidates.js.map +1 -0
  10. package/dist/restore-jobs.d.ts +236 -0
  11. package/dist/restore-jobs.d.ts.map +1 -0
  12. package/dist/restore-jobs.js +716 -0
  13. package/dist/restore-jobs.js.map +1 -0
  14. package/dist/session-pool.d.ts +48 -8
  15. package/dist/session-pool.d.ts.map +1 -1
  16. package/dist/session-pool.js +159 -67
  17. package/dist/session-pool.js.map +1 -1
  18. package/dist/session-types.d.ts +12 -0
  19. package/dist/session-types.d.ts.map +1 -1
  20. package/package.json +1 -1
  21. package/public/_app/immutable/assets/0.CUi0Pn9k.css +1 -0
  22. package/public/_app/immutable/chunks/CJs7WGCY.js +2 -0
  23. package/public/_app/immutable/chunks/{DdFruy3e.js.map → CJs7WGCY.js.map} +1 -1
  24. package/public/_app/immutable/chunks/{vSWNc7VF.js → Cr3SOBcX.js} +2 -2
  25. package/public/_app/immutable/chunks/{vSWNc7VF.js.map → Cr3SOBcX.js.map} +1 -1
  26. package/public/_app/immutable/chunks/{CyQq9q8L.js → DsMrx0D-.js} +2 -2
  27. package/public/_app/immutable/chunks/{CyQq9q8L.js.map → DsMrx0D-.js.map} +1 -1
  28. package/public/_app/immutable/entry/{app.BzMua2z6.js → app.q0JTyYdd.js} +3 -3
  29. package/public/_app/immutable/entry/{app.BzMua2z6.js.map → app.q0JTyYdd.js.map} +1 -1
  30. package/public/_app/immutable/entry/start.Dn511egP.js +2 -0
  31. package/public/_app/immutable/entry/start.Dn511egP.js.map +1 -0
  32. package/public/_app/immutable/nodes/{0.BDXduH3G.js → 0.BhjoTMlz.js} +2 -2
  33. package/public/_app/immutable/nodes/{0.BDXduH3G.js.map → 0.BhjoTMlz.js.map} +1 -1
  34. package/public/_app/immutable/nodes/{1.CqJo-807.js → 1.CKIQ9-uZ.js} +2 -2
  35. package/public/_app/immutable/nodes/{1.CqJo-807.js.map → 1.CKIQ9-uZ.js.map} +1 -1
  36. package/public/_app/immutable/nodes/2.CBHW8874.js +120 -0
  37. package/public/_app/immutable/nodes/2.CBHW8874.js.map +1 -0
  38. package/public/_app/version.json +1 -1
  39. package/public/index.html +11 -11
  40. package/public/service-worker.js +1 -1
  41. package/public/_app/immutable/assets/0.BS_EGmNW.css +0 -1
  42. package/public/_app/immutable/chunks/DdFruy3e.js +0 -2
  43. package/public/_app/immutable/entry/start.B0ap2dTz.js +0 -2
  44. package/public/_app/immutable/entry/start.B0ap2dTz.js.map +0 -1
  45. package/public/_app/immutable/nodes/2.C6-6KHYk.js +0 -110
  46. package/public/_app/immutable/nodes/2.C6-6KHYk.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, getWhereverCertsDir, 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
@@ -939,6 +927,7 @@ async function main() {
939
927
  pathname.startsWith('/config') ||
940
928
  pathname.startsWith('/check-path') ||
941
929
  pathname.startsWith('/check-remote-repo') ||
930
+ pathname.startsWith('/remote-candidates') ||
942
931
  pathname.startsWith('/autocomplete-path') ||
943
932
  pathname.startsWith('/session/');
944
933
  if (isApiRequest && !authenticate(req, token)) {
@@ -1097,14 +1086,12 @@ async function main() {
1097
1086
  // Check matching remote rules
1098
1087
  let matchingRule = null;
1099
1088
  const config = getWhereverConfig();
1100
- if (config.remoteRepoRules && Array.isArray(config.remoteRepoRules)) {
1101
- const rule = config.remoteRepoRules.find(r => repoRuleMatches(r.pattern, resolved));
1102
- if (rule) {
1103
- matchingRule = {
1104
- provider: rule.provider,
1105
- visibility: rule.visibility || 'private'
1106
- };
1107
- }
1089
+ const rule = matchRemoteRepoRule(config.remoteRepoRules, resolved);
1090
+ if (rule) {
1091
+ matchingRule = {
1092
+ provider: rule.provider,
1093
+ visibility: rule.visibility || 'private'
1094
+ };
1108
1095
  }
1109
1096
  sendJSON(res, 200, { exists, isGit, resolvedPath: resolved, matchingRule });
1110
1097
  return;
@@ -1130,9 +1117,7 @@ async function main() {
1130
1117
  resolved = path.resolve(qPath);
1131
1118
  }
1132
1119
  const config = getWhereverConfig();
1133
- const rule = (config.remoteRepoRules && Array.isArray(config.remoteRepoRules))
1134
- ? config.remoteRepoRules.find(r => repoRuleMatches(r.pattern, resolved))
1135
- : undefined;
1120
+ const rule = matchRemoteRepoRule(config.remoteRepoRules, resolved);
1136
1121
  if (!rule) {
1137
1122
  sendJSON(res, 200, { exists: false, matched: false });
1138
1123
  return;
@@ -1146,6 +1131,41 @@ async function main() {
1146
1131
  });
1147
1132
  return;
1148
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
+ }
1149
1169
  if (pathname === '/autocomplete-path' && req.method === 'GET') {
1150
1170
  const qPath = url.searchParams.get('path') || '';
1151
1171
  let parentPath = '';
@@ -1424,7 +1444,19 @@ async function main() {
1424
1444
  sendJSON(res, 400, { error: 'Missing cwd' });
1425
1445
  return;
1426
1446
  }
1427
- 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);
1428
1460
  if (result.error) {
1429
1461
  sendJSON(res, 500, { error: result.error });
1430
1462
  }
@@ -1954,11 +1986,229 @@ function resolveFolderConflictState(c, pool) {
1954
1986
  // sessions.readOnly folder is a hard rule and is never lifted here.
1955
1987
  if (c.conflictObserver && !active) {
1956
1988
  c.conflictObserver = false;
1957
- if (!pool.isReadOnlyCwd(mine.cwd))
1989
+ if (!hasHardReadOnly(c, pool, mine.cwd))
1958
1990
  c.readOnly = false;
1959
1991
  }
1960
1992
  return { cwd: mine.cwd, active };
1961
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
+ }
1962
2212
  // Resolve and report in one step. Every folder_conflict frame goes out through
1963
2213
  // here, so the `readOnly` it carries can never drift from the authority that
1964
2214
  // produced `active`.
@@ -2100,6 +2350,9 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2100
2350
  // session we are leaving. Reset BEFORE the first await, so a continue that
2101
2351
  // races this load is recorded against the load, never wiped by it.
2102
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;
2103
2356
  const meta = await pool.readSessionMeta(msg.sessionFile, INITIAL_HISTORY_LIMIT, msg.model);
2104
2357
  if ('error' in meta) {
2105
2358
  sendWS(client.ws, { type: 'session_error', error: meta.error });
@@ -2113,9 +2366,27 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2113
2366
  // aborting the other session -- both then run concurrently.
2114
2367
  const conflict = pool.detectConflict(meta.sessionFile, meta.cwd);
2115
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;
2116
2386
  // A session whose cwd matches a sessions.readOnly glob is forced read-only.
2117
- // A folder conflict also starts the client read-only until they continue.
2118
- 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;
2119
2390
  client.readOnly = forcedReadOnly;
2120
2391
  client.conflictObserver = folderConflict;
2121
2392
  client.pendingCwd = meta.cwd;
@@ -2131,6 +2402,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2131
2402
  isStreaming: meta.resident ? pool.isStreaming(meta.sessionFile) : false,
2132
2403
  readOnly: forcedReadOnly,
2133
2404
  folderConflict,
2405
+ folderMissing,
2134
2406
  contextUsage: meta.resident ? (pool.getContextUsage(meta.sessionFile) ?? null) : null,
2135
2407
  pending: !meta.resident,
2136
2408
  });
@@ -2141,6 +2413,26 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2141
2413
  totalCount: meta.history.totalCount,
2142
2414
  offset: meta.history.offset,
2143
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
+ }
2144
2436
  // Already resident (warm): attach immediately, no async build needed.
2145
2437
  if (meta.resident) {
2146
2438
  pool.addClient(meta.sessionFile, client.id);
@@ -2162,6 +2454,24 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2162
2454
  sendQueueSnapshot(client, meta.sessionFile, meta.sessionId, pool);
2163
2455
  break;
2164
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
+ }
2165
2475
  // Cold: build the live agent in the background, then attach + signal ready.
2166
2476
  // Errors degrade to a session_error (the conversation stays readable).
2167
2477
  void (async () => {
@@ -2254,7 +2564,34 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2254
2564
  // "Continue anyway" could only unlock THAT conversation, never give them the
2255
2565
  // fresh one. So: create the session (forceNew), then report the folder
2256
2566
  // conflict, if any, AGAINST the new session.
2257
- 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);
2258
2595
  if (result.error) {
2259
2596
  sendWS(client.ws, { type: 'session_error', error: result.error });
2260
2597
  return;
@@ -2264,6 +2601,9 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2264
2601
  pool.addClient(result.tracked.sessionFile, client.id);
2265
2602
  switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
2266
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;
2267
2607
  client.pendingCwd = result.tracked.cwd;
2268
2608
  // Is somebody else still live in this folder? Then two agents would be
2269
2609
  // editing the same working tree, which is exactly what the folder-conflict
@@ -2315,6 +2655,10 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2315
2655
  break;
2316
2656
  }
2317
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;
2318
2662
  if (client.sessionId) {
2319
2663
  switchClientSession(client, null, pool, onSessionsUpdated);
2320
2664
  client.readOnly = false;
@@ -2356,7 +2700,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2356
2700
  // load/create, so it can only ever apply to the load in flight, and the
2357
2701
  // sessions.readOnly guard is re-applied at attach with the real cwd.
2358
2702
  client.conflictContinued = true;
2359
- if (cwd && !pool.isReadOnlyCwd(cwd))
2703
+ if (cwd && !hasHardReadOnly(client, pool, cwd))
2360
2704
  client.readOnly = false;
2361
2705
  // Reply with this client's authoritative conflict state, ALWAYS (including
2362
2706
  // when the lift was refused for a sessions.readOnly folder). Same-socket
@@ -2367,7 +2711,107 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2367
2711
  sendFolderConflict(client, pool);
2368
2712
  break;
2369
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
+ }
2370
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
+ }
2371
2815
  if (!client.sessionId)
2372
2816
  return;
2373
2817
  if (client.readOnly) {
@@ -2505,6 +2949,23 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2505
2949
  });
2506
2950
  break;
2507
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
+ }
2508
2969
  try {
2509
2970
  const tracked = pool.getSession(sessionId);
2510
2971
  const cwd = tracked?.cwd;