wherever-dev 0.13.0 → 0.15.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 (45) hide show
  1. package/dist/index.js +514 -33
  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 +81 -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.BnOlDJL_.css +1 -0
  22. package/public/_app/immutable/chunks/{DdFruy3e.js → Bz1TwIe2.js} +2 -2
  23. package/public/_app/immutable/chunks/{DdFruy3e.js.map → Bz1TwIe2.js.map} +1 -1
  24. package/public/_app/immutable/chunks/{CyQq9q8L.js → C8qcA14p.js} +2 -2
  25. package/public/_app/immutable/chunks/{CyQq9q8L.js.map → C8qcA14p.js.map} +1 -1
  26. package/public/_app/immutable/chunks/{vSWNc7VF.js → txj4ly0C.js} +2 -2
  27. package/public/_app/immutable/chunks/{vSWNc7VF.js.map → txj4ly0C.js.map} +1 -1
  28. package/public/_app/immutable/entry/{app.BzMua2z6.js → app.D1b-njuQ.js} +3 -3
  29. package/public/_app/immutable/entry/{app.BzMua2z6.js.map → app.D1b-njuQ.js.map} +1 -1
  30. package/public/_app/immutable/entry/start.BAywGKzl.js +2 -0
  31. package/public/_app/immutable/entry/start.BAywGKzl.js.map +1 -0
  32. package/public/_app/immutable/nodes/{0.BDXduH3G.js → 0.CKIKfeo9.js} +2 -2
  33. package/public/_app/immutable/nodes/{0.BDXduH3G.js.map → 0.CKIKfeo9.js.map} +1 -1
  34. package/public/_app/immutable/nodes/{1.CqJo-807.js → 1.0v9Av_yb.js} +2 -2
  35. package/public/_app/immutable/nodes/{1.CqJo-807.js.map → 1.0v9Av_yb.js.map} +1 -1
  36. package/public/_app/immutable/nodes/2.FcSNf0tp.js +120 -0
  37. package/public/_app/immutable/nodes/2.FcSNf0tp.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/entry/start.B0ap2dTz.js +0 -2
  43. package/public/_app/immutable/entry/start.B0ap2dTz.js.map +0 -1
  44. package/public/_app/immutable/nodes/2.C6-6KHYk.js +0 -110
  45. 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)) {
@@ -1057,13 +1046,33 @@ async function main() {
1057
1046
  const searchDefaultModel = searchFolder
1058
1047
  ? sessionPool.getDefaultModelFor(searchFolder)
1059
1048
  : null;
1049
+ // The label defaults to the machine hostname so two servers sharing the
1050
+ // same sessions over cloned folders are distinguishable with zero config.
1051
+ // An explicit "" or false opts out entirely (the pre-appearance look):
1052
+ // empty strings are FALSY, so the opt-out must be checked before the
1053
+ // hostname fallback, not with `||`.
1054
+ const appearance = config.appearance || {};
1055
+ const accent = appearance.accent || null;
1056
+ const pattern = appearance.pattern || 'none';
1057
+ const label = appearance.label === false || (typeof appearance.label === 'string' && appearance.label.trim() === '')
1058
+ ? ''
1059
+ : appearance.label || os.hostname();
1060
1060
  sendJSON(res, 200, {
1061
1061
  gitInitDefault: !!config.gitInitDefault,
1062
1062
  uploadMethod: config.uploads?.method || 'websocket',
1063
1063
  downloadsEnabled: config.downloads?.enabled !== false,
1064
1064
  searchFolder: searchFolder || null,
1065
1065
  searchCreateRemote: !!config.searchCreateRemote,
1066
- searchDefaultModel
1066
+ searchDefaultModel,
1067
+ appearance: {
1068
+ label,
1069
+ accent,
1070
+ colors: appearance.colors || null,
1071
+ // Explicit `frame: false` turns the top bar off; `frame: true` forces it
1072
+ // on even without an accent (it then uses the compiled default blue).
1073
+ frame: appearance.frame !== undefined ? !!appearance.frame : !!accent,
1074
+ pattern: ['stripes', 'dots', 'grid'].includes(pattern) ? pattern : 'none',
1075
+ },
1067
1076
  });
1068
1077
  return;
1069
1078
  }
@@ -1097,14 +1106,12 @@ async function main() {
1097
1106
  // Check matching remote rules
1098
1107
  let matchingRule = null;
1099
1108
  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
- }
1109
+ const rule = matchRemoteRepoRule(config.remoteRepoRules, resolved);
1110
+ if (rule) {
1111
+ matchingRule = {
1112
+ provider: rule.provider,
1113
+ visibility: rule.visibility || 'private'
1114
+ };
1108
1115
  }
1109
1116
  sendJSON(res, 200, { exists, isGit, resolvedPath: resolved, matchingRule });
1110
1117
  return;
@@ -1130,9 +1137,7 @@ async function main() {
1130
1137
  resolved = path.resolve(qPath);
1131
1138
  }
1132
1139
  const config = getWhereverConfig();
1133
- const rule = (config.remoteRepoRules && Array.isArray(config.remoteRepoRules))
1134
- ? config.remoteRepoRules.find(r => repoRuleMatches(r.pattern, resolved))
1135
- : undefined;
1140
+ const rule = matchRemoteRepoRule(config.remoteRepoRules, resolved);
1136
1141
  if (!rule) {
1137
1142
  sendJSON(res, 200, { exists: false, matched: false });
1138
1143
  return;
@@ -1146,6 +1151,41 @@ async function main() {
1146
1151
  });
1147
1152
  return;
1148
1153
  }
1154
+ // Restore pre-fill: which repository does this (probably missing) folder
1155
+ // correspond to? Answers an ORDERED, ADVISORY list of SSH candidates --
1156
+ // the provider probe first, then the `<host-token>/<owner>/<repo>` path
1157
+ // convention (see server/src/remote-candidates.ts). Never HTTPS.
1158
+ //
1159
+ // Beside /check-remote-repo and for the same reason: the probe shells out to
1160
+ // a provider CLI, so this is called ON DEMAND (the restore panel opening),
1161
+ // never per keystroke and never on the session-load path.
1162
+ if (pathname === '/remote-candidates' && req.method === 'GET') {
1163
+ const qPath = url.searchParams.get('path');
1164
+ if (!qPath) {
1165
+ sendJSON(res, 400, { error: 'Missing path' });
1166
+ return;
1167
+ }
1168
+ let resolved = qPath;
1169
+ if (qPath.startsWith('~')) {
1170
+ resolved = path.join(os.homedir(), qPath.slice(1));
1171
+ }
1172
+ else if (!path.isAbsolute(qPath)) {
1173
+ resolved = path.join(os.homedir(), qPath);
1174
+ }
1175
+ else {
1176
+ resolved = path.resolve(qPath);
1177
+ }
1178
+ // Same scoping as /check-path: an authenticated caller cannot use this to
1179
+ // ask questions about paths outside the home folder.
1180
+ if (!isWithinHome(resolved)) {
1181
+ sendJSON(res, 403, { error: 'Path is outside the home directory' });
1182
+ return;
1183
+ }
1184
+ const config = getWhereverConfig();
1185
+ const candidates = resolveRemoteCandidates(resolved, config.remoteRepoRules, detectRemoteRepo);
1186
+ sendJSON(res, 200, { resolvedPath: resolved, candidates });
1187
+ return;
1188
+ }
1149
1189
  if (pathname === '/autocomplete-path' && req.method === 'GET') {
1150
1190
  const qPath = url.searchParams.get('path') || '';
1151
1191
  let parentPath = '';
@@ -1424,7 +1464,19 @@ async function main() {
1424
1464
  sendJSON(res, 400, { error: 'Missing cwd' });
1425
1465
  return;
1426
1466
  }
1427
- const result = await sessionPool.createNewSession(cwd, model, gitInit, createRemote, repoVisibility, cloneRemote);
1467
+ // Same CLONE branch as the WebSocket `session_new`, through the same
1468
+ // restore job registry, so this endpoint gains recursive submodules and
1469
+ // loses nothing. There is no progress channel on a plain HTTP request,
1470
+ // so it simply waits for the job it started (or joined); any WebSocket
1471
+ // client looking at that folder still gets the live frames.
1472
+ if (cloneRemote) {
1473
+ const outcome = await cloneForNewSession(resolveCreateCwd(cwd), clients, sessionPool);
1474
+ if (outcome.status === 'failed') {
1475
+ sendJSON(res, 500, { error: outcome.error });
1476
+ return;
1477
+ }
1478
+ }
1479
+ const result = await sessionPool.createNewSession(cwd, model, gitInit, createRemote, repoVisibility);
1428
1480
  if (result.error) {
1429
1481
  sendJSON(res, 500, { error: result.error });
1430
1482
  }
@@ -1954,11 +2006,229 @@ function resolveFolderConflictState(c, pool) {
1954
2006
  // sessions.readOnly folder is a hard rule and is never lifted here.
1955
2007
  if (c.conflictObserver && !active) {
1956
2008
  c.conflictObserver = false;
1957
- if (!pool.isReadOnlyCwd(mine.cwd))
2009
+ if (!hasHardReadOnly(c, pool, mine.cwd))
1958
2010
  c.readOnly = false;
1959
2011
  }
1960
2012
  return { cwd: mine.cwd, active };
1961
2013
  }
2014
+ // Read-only PRECEDENCE in one place. Of the three reasons a client can be
2015
+ // read-only, two are HARD and one is dismissible:
2016
+ // - a configured `sessions.readOnly` folder: a policy rule, never lifted;
2017
+ // - FOLDER MISSING: the working folder does not exist on this machine, so
2018
+ // there is nothing to drive; lifted only by restoring it and RELOADING;
2019
+ // - a folder conflict: two live sessions in one folder, lifted by the user's
2020
+ // "Continue anyway".
2021
+ // Every site that LIFTS read-only asks this first, so the dismissible reason can
2022
+ // never dismiss a hard one.
2023
+ function hasHardReadOnly(client, pool, cwd) {
2024
+ return pool.isReadOnlyCwd(cwd) || client.folderMissingCwd !== undefined;
2025
+ }
2026
+ // ---------------------------------------------------------------------------
2027
+ // Restore jobs over the WebSocket
2028
+ // ---------------------------------------------------------------------------
2029
+ // The ONE registry of restore jobs for this server process. Jobs are keyed by
2030
+ // the resolved absolute TARGET PATH and owned by the server (`docs/adr/0009`),
2031
+ // so the registry is deliberately process-wide rather than per-connection: that
2032
+ // is exactly what makes a clone survive the socket that started it, be shared by
2033
+ // a second device, and never be started twice for one folder. Constructing it is
2034
+ // inert (nothing runs until `request()`), so it can live at module scope beside
2035
+ // the handlers that drive it.
2036
+ const restoreJobs = new RestoreJobRegistry();
2037
+ // The live broadcast subscription for each observed path, so it can be dropped
2038
+ // the moment its job settles. This is the SERVER's single subscription per path,
2039
+ // NOT a per-client one: which clients a frame reaches is derived per frame (see
2040
+ // clientWatchesRestorePath), so no client bookkeeping exists to leak.
2041
+ const restoreObservers = new Map();
2042
+ /**
2043
+ * Does this client currently have the restore target on screen?
2044
+ *
2045
+ * The three places a client's folder can be recorded, and why each is needed:
2046
+ * - its ATTACHED session's cwd: the ordinary case, a live session in the folder;
2047
+ * - `pendingCwd`: a load painted but not yet attached (a cold load spends
2048
+ * seconds there);
2049
+ * - `folderMissingCwd`: a folder-missing load, which deliberately attaches to
2050
+ * NOTHING and clears `pendingCwd` with it -- so this is the only record of
2051
+ * the folder such a client is looking at, and it is precisely the client the
2052
+ * restore panel is rendered for.
2053
+ *
2054
+ * Matching is what SUBSCRIPTION means here: it is evaluated per frame rather
2055
+ * than registered per socket, so a dropped phone leaves nothing behind and a
2056
+ * reconnecting one is matched again for free.
2057
+ */
2058
+ function clientWatchesRestorePath(c, pool, targetPath) {
2059
+ if (c.isCliBridge)
2060
+ return false;
2061
+ const attached = c.sessionId ? pool.getSession(c.sessionId)?.cwd : undefined;
2062
+ for (const candidate of [attached, c.pendingCwd, c.folderMissingCwd]) {
2063
+ if (candidate && path.resolve(candidate) === targetPath)
2064
+ return true;
2065
+ }
2066
+ return false;
2067
+ }
2068
+ function broadcastRestore(clients, pool, targetPath, msg) {
2069
+ for (const c of clients.values()) {
2070
+ if (clientWatchesRestorePath(c, pool, targetPath))
2071
+ sendWS(c.ws, msg);
2072
+ }
2073
+ }
2074
+ /**
2075
+ * Start relaying one path's restore job to whoever is watching that path.
2076
+ *
2077
+ * Idempotent (a second requester joining a running job must not double-relay),
2078
+ * and self-releasing: the subscription is dropped inside `onSettled`, which the
2079
+ * registry guarantees for every terminal state, so an observer cannot outlive
2080
+ * its job. Subscribe BEFORE requesting the job, because a request can settle
2081
+ * synchronously (a spawn that throws) and a frame emitted before the subscription
2082
+ * exists would simply be lost.
2083
+ */
2084
+ function observeRestorePath(targetPath, clients, pool) {
2085
+ if (restoreObservers.has(targetPath))
2086
+ return;
2087
+ const unsubscribe = restoreJobs.subscribe(targetPath, {
2088
+ onProgress: (_progress, job) => {
2089
+ broadcastRestore(clients, pool, targetPath, { type: 'restore_progress', targetPath, job });
2090
+ },
2091
+ onSettled: (job) => {
2092
+ broadcastRestore(clients, pool, targetPath, { type: 'restore_complete', targetPath, job });
2093
+ releaseRestoreObserver(targetPath);
2094
+ },
2095
+ });
2096
+ restoreObservers.set(targetPath, unsubscribe);
2097
+ }
2098
+ function releaseRestoreObserver(targetPath) {
2099
+ const unsubscribe = restoreObservers.get(targetPath);
2100
+ if (!unsubscribe)
2101
+ return;
2102
+ restoreObservers.delete(targetPath);
2103
+ unsubscribe();
2104
+ }
2105
+ // The listing's per-folder existence answers, awaiting invalidation, keyed the
2106
+ // same way. A SECOND, INDEPENDENT subscription to the registry: the session
2107
+ // browser's "missing" mark is not a client of the restore panel, and routing its
2108
+ // invalidation through the broadcast relay above would make one the other's
2109
+ // plumbing. Neither reaches into the registry's internals and neither is wired
2110
+ // through the other (see CONTEXT.md, "the module owns the observation seam").
2111
+ const folderExistenceObservers = new Map();
2112
+ /**
2113
+ * Drop the listing's cached existence answer for a path when the restore job
2114
+ * there SETTLES.
2115
+ *
2116
+ * A restore is the one moment wherever itself changes whether a folder is on
2117
+ * this machine, so without this the browser would keep marking a just-restored
2118
+ * folder "missing" for the rest of the cache's TTL. Every terminal state
2119
+ * invalidates (a cancelled clone REMOVES a directory it created, so the cached
2120
+ * answer is equally suspect), but only a `done` job asks the connected clients
2121
+ * to refetch: that is what makes the mark disappear with no manual refresh.
2122
+ *
2123
+ * Idempotent per path and self-releasing inside `onSettled`, exactly like the
2124
+ * broadcast observer.
2125
+ */
2126
+ function observeRestoreForFolderExistence(targetPath, onSessionsUpdated) {
2127
+ if (folderExistenceObservers.has(targetPath))
2128
+ return;
2129
+ const unsubscribe = restoreJobs.subscribe(targetPath, {
2130
+ onSettled: (job) => {
2131
+ invalidateFolderExistence(targetPath);
2132
+ releaseFolderExistenceObserver(targetPath);
2133
+ if (job.state === 'done')
2134
+ onSessionsUpdated?.();
2135
+ },
2136
+ });
2137
+ folderExistenceObservers.set(targetPath, unsubscribe);
2138
+ }
2139
+ function releaseFolderExistenceObserver(targetPath) {
2140
+ const unsubscribe = folderExistenceObservers.get(targetPath);
2141
+ if (!unsubscribe)
2142
+ return;
2143
+ folderExistenceObservers.delete(targetPath);
2144
+ unsubscribe();
2145
+ }
2146
+ /**
2147
+ * Resolve a caller-supplied `cwd` the way session creation does: `~` and a bare
2148
+ * relative path both mean "under the home directory", everything else is
2149
+ * resolved as given. Kept identical to `SessionPool.createNewSession`'s own
2150
+ * resolution so the restore job's key, the frames it is broadcast under and the
2151
+ * folder the session is finally created in are ONE path.
2152
+ */
2153
+ function resolveCreateCwd(cwd) {
2154
+ if (cwd.startsWith('~'))
2155
+ return normalizePath(path.join(os.homedir(), cwd.slice(1)));
2156
+ if (!path.isAbsolute(cwd))
2157
+ return normalizePath(path.join(os.homedir(), cwd));
2158
+ return normalizePath(path.resolve(cwd));
2159
+ }
2160
+ /**
2161
+ * The CLONE branch of session creation, run through the restore job registry.
2162
+ *
2163
+ * This is the OTHER entry point of `docs/adr/0009`, and it exists so there is
2164
+ * exactly ONE clone implementation in the codebase: the same path-keyed jobs,
2165
+ * the same recursive `--recurse-submodules` engine, the same URL allowlist and
2166
+ * home-directory guard, and the same honest progress frames the restore panel
2167
+ * renders. What it does NOT share is the ending: a loaded session offers a
2168
+ * RELOAD (a live agent is a load-time decision), but here there is no session to
2169
+ * reload until the clone lands, so the caller CONTINUES into creation itself.
2170
+ *
2171
+ * The job is awaited rather than reported-and-forgotten precisely because the
2172
+ * create depends on it. It stays cancellable while it runs: the job is
2173
+ * server-owned and path-keyed, so the ordinary `restore_cancel` frame reaches
2174
+ * it and settles it `cancelled`, which fails the create here.
2175
+ *
2176
+ * `onStarted` is how the WebSocket caller tells ITS client which job to paint;
2177
+ * the HTTP caller has no progress channel and simply waits. Broadcasts reach
2178
+ * every client whose folder matches the path either way.
2179
+ */
2180
+ async function cloneForNewSession(targetPath, clients, pool, onStarted) {
2181
+ const config = getWhereverConfig();
2182
+ const rule = matchRemoteRepoRule(config.remoteRepoRules, targetPath);
2183
+ if (!rule)
2184
+ return { status: 'skipped' };
2185
+ // The SAME probe the dashboard's clone-or-create dialog asked (via
2186
+ // /check-remote-repo) before offering to clone. The URL is resolved HERE, on
2187
+ // the server, rather than taken from the client: the create path has no
2188
+ // editable URL field, so a client-supplied one would be a new, unasked-for
2189
+ // authority. (The restore panel's editable field is the deliberate exception,
2190
+ // and it is validated by the registry all the same.)
2191
+ //
2192
+ // Note what is NOT used: `resolveRemoteCandidates`, whose path-convention
2193
+ // candidate is a GUESS offered to a human who can edit it. There is no field
2194
+ // to edit here, so an unprobed guess would be cloned blind. A probe that finds
2195
+ // nothing SKIPS the clone and lets the ordinary create proceed, exactly as the
2196
+ // deleted synchronous path did.
2197
+ const probe = detectRemoteRepo(rule, path.basename(targetPath));
2198
+ if (!probe.exists || !probe.sshUrl)
2199
+ return { status: 'skipped' };
2200
+ // Subscribe BEFORE requesting: a request can settle inside the call (a spawn
2201
+ // that throws) and a frame emitted before the subscription exists is lost.
2202
+ observeRestorePath(targetPath, clients, pool);
2203
+ // No refetch callback here: this clone is followed by the session creation it
2204
+ // exists for, which broadcasts `sessions_updated` on its own.
2205
+ observeRestoreForFolderExistence(targetPath);
2206
+ const result = restoreJobs.request({ kind: 'clone', targetPath, url: probe.sshUrl });
2207
+ if (!result.ok) {
2208
+ // A refusal is not a job: nothing will ever settle here, so neither
2209
+ // subscription may be left waiting for a completion that is not coming.
2210
+ if (restoreJobs.get(targetPath)?.state !== 'running') {
2211
+ releaseRestoreObserver(targetPath);
2212
+ releaseFolderExistenceObserver(targetPath);
2213
+ }
2214
+ return { status: 'failed', error: result.message };
2215
+ }
2216
+ onStarted?.(result.outcome, result.job);
2217
+ const settled = await restoreJobs.settled(targetPath).catch(() => undefined);
2218
+ if (settled?.state === 'done')
2219
+ return { status: 'cloned' };
2220
+ if (settled?.state === 'cancelled') {
2221
+ return {
2222
+ status: 'failed',
2223
+ error: `The clone into ${targetPath} was cancelled, so no session was created.`,
2224
+ };
2225
+ }
2226
+ return {
2227
+ status: 'failed',
2228
+ error: settled?.failure?.message ??
2229
+ `Failed to clone ${probe.sshUrl} into ${targetPath}, so no session was created.`,
2230
+ };
2231
+ }
1962
2232
  // Resolve and report in one step. Every folder_conflict frame goes out through
1963
2233
  // here, so the `readOnly` it carries can never drift from the authority that
1964
2234
  // produced `active`.
@@ -2100,6 +2370,9 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2100
2370
  // session we are leaving. Reset BEFORE the first await, so a continue that
2101
2371
  // races this load is recorded against the load, never wiped by it.
2102
2372
  client.conflictContinued = false;
2373
+ // Same reasoning for the missing-folder lock: it belongs to the session we
2374
+ // are leaving, and must not leak into the one we are opening.
2375
+ client.folderMissingCwd = undefined;
2103
2376
  const meta = await pool.readSessionMeta(msg.sessionFile, INITIAL_HISTORY_LIMIT, msg.model);
2104
2377
  if ('error' in meta) {
2105
2378
  sendWS(client.ws, { type: 'session_error', error: meta.error });
@@ -2113,9 +2386,27 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2113
2386
  // aborting the other session -- both then run concurrently.
2114
2387
  const conflict = pool.detectConflict(meta.sessionFile, meta.cwd);
2115
2388
  const folderConflict = conflict.conflict && !!conflict.otherSessionId;
2389
+ // This session's working folder is not usable as a working folder. TWO
2390
+ // things produce that, and they are one state because they have one
2391
+ // remedy and one rendering:
2392
+ // - it does NOT EXIST (the transcript synced, the clone did not), the
2393
+ // cheap meta read's `stat`;
2394
+ // - a RESTORE JOB is materialising it RIGHT NOW. `git clone` creates the
2395
+ // target directory in its first breath, so the existence check alone
2396
+ // says "present" for the whole of a multi-minute clone, and a client
2397
+ // loading in that window (a reconnect, a second device) would be handed
2398
+ // a live agent pointed at a HALF-CLONED tree. That is the same silent
2399
+ // breakage this state exists to replace.
2400
+ // The conversation is still READABLE either way -- reading never needed the
2401
+ // folder -- but the client is locked and, on the cold path below, no live
2402
+ // agent is built at all.
2403
+ const restoreInFlight = restoreJobs.get(meta.cwd)?.state === 'running';
2404
+ const folderMissing = meta.folderMissing || restoreInFlight;
2405
+ client.folderMissingCwd = folderMissing ? meta.cwd : undefined;
2116
2406
  // 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;
2407
+ // A missing folder forces it too (hard, see hasHardReadOnly). A folder
2408
+ // conflict also starts the client read-only until they continue.
2409
+ const forcedReadOnly = meta.readOnly || folderMissing || folderConflict;
2119
2410
  client.readOnly = forcedReadOnly;
2120
2411
  client.conflictObserver = folderConflict;
2121
2412
  client.pendingCwd = meta.cwd;
@@ -2131,6 +2422,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2131
2422
  isStreaming: meta.resident ? pool.isStreaming(meta.sessionFile) : false,
2132
2423
  readOnly: forcedReadOnly,
2133
2424
  folderConflict,
2425
+ folderMissing,
2134
2426
  contextUsage: meta.resident ? (pool.getContextUsage(meta.sessionFile) ?? null) : null,
2135
2427
  pending: !meta.resident,
2136
2428
  });
@@ -2141,6 +2433,26 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2141
2433
  totalCount: meta.history.totalCount,
2142
2434
  offset: meta.history.offset,
2143
2435
  });
2436
+ // State the missing folder explicitly, naming the absolute path, so the
2437
+ // client can replace its composer with a notice that says WHICH folder to
2438
+ // restore instead of an unexplained lock. A client that predates the frame
2439
+ // simply ignores it; the server's refusal to accept its sends is what
2440
+ // protects it either way.
2441
+ //
2442
+ // Any restore job already running for this folder rides along, so a client
2443
+ // arriving MID-CLONE (a reconnect, a second device, a phone waking up)
2444
+ // repaints the running job from this one frame instead of being offered a
2445
+ // second clone. Live frames follow on their own, because this client now
2446
+ // matches the job path (see clientWatchesRestorePath).
2447
+ if (folderMissing) {
2448
+ const job = restoreJobs.get(meta.cwd);
2449
+ sendWS(client.ws, {
2450
+ type: 'folder_missing',
2451
+ sessionId: meta.sessionId,
2452
+ cwd: meta.cwd,
2453
+ ...(job ? { job } : {}),
2454
+ });
2455
+ }
2144
2456
  // Already resident (warm): attach immediately, no async build needed.
2145
2457
  if (meta.resident) {
2146
2458
  pool.addClient(meta.sessionFile, client.id);
@@ -2162,6 +2474,24 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2162
2474
  sendQueueSnapshot(client, meta.sessionFile, meta.sessionId, pool);
2163
2475
  break;
2164
2476
  }
2477
+ // Cold + folder missing: do NOT build the live agent. Building one would
2478
+ // SUCCEED (pi's settings/resource loading tolerate a nonexistent cwd) and
2479
+ // hand back an agent whose every tool call is broken -- the silent failure
2480
+ // this state exists to replace. So the load ends here: painted, locked,
2481
+ // explained. Curing it takes a restore plus a RELOAD, because whether a
2482
+ // session has a live agent is a load-time decision.
2483
+ //
2484
+ // Detach from whatever we were attached to before as well: this load never
2485
+ // attaches anywhere, and staying on the previous session would leave a
2486
+ // phantom viewer holding a folder the user has left.
2487
+ // (A RESIDENT session is handled by the branch above and keeps its running
2488
+ // agent: a folder that vanished under a live session is out of scope here,
2489
+ // we only refuse to hand out a fresh write capability.)
2490
+ if (folderMissing) {
2491
+ switchClientSession(client, null, pool, onSessionsUpdated);
2492
+ client.readOnly = true;
2493
+ break;
2494
+ }
2165
2495
  // Cold: build the live agent in the background, then attach + signal ready.
2166
2496
  // Errors degrade to a session_error (the conversation stays readable).
2167
2497
  void (async () => {
@@ -2254,7 +2584,34 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2254
2584
  // "Continue anyway" could only unlock THAT conversation, never give them the
2255
2585
  // fresh one. So: create the session (forceNew), then report the folder
2256
2586
  // 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);
2587
+ //
2588
+ // CLONE-AN-EXISTING-REMOTE first, when that is what the user chose in the
2589
+ // clone-or-create dialog. It runs as a RESTORE JOB (one clone
2590
+ // implementation, `docs/adr/0009`): the client is told which job to paint
2591
+ // and then watches the ordinary `restore_progress` frames, instead of
2592
+ // staring at a blocking overlay its 25s create watchdog would give up on
2593
+ // while git was still running. Creating a REMOTE (the other branch of that
2594
+ // dialog) is untouched and still happens inside createNewSession.
2595
+ if (msg.cloneRemote) {
2596
+ const targetPath = resolveCreateCwd(msg.cwd);
2597
+ // The restore broadcast is DERIVED from a path match against each
2598
+ // client's folder, and this client has no session yet: recording the
2599
+ // target as its pending cwd is what puts it in scope for its own clone.
2600
+ client.pendingCwd = targetPath;
2601
+ const outcome = await cloneForNewSession(targetPath, clients, pool, (result, job) => {
2602
+ sendWS(client.ws, { type: 'restore_started', targetPath, outcome: result, job });
2603
+ });
2604
+ if (outcome.status === 'failed') {
2605
+ // The clone is the create's first step, so its failure IS the create's
2606
+ // failure: report it on the create's own channel (the mapped cause,
2607
+ // from the registry) and make no session. The restore_complete frame
2608
+ // carrying git's raw output was broadcast beside it.
2609
+ client.pendingCwd = undefined;
2610
+ sendWS(client.ws, { type: 'session_error', error: outcome.error });
2611
+ return;
2612
+ }
2613
+ }
2614
+ const result = await pool.createNewSession(msg.cwd, msg.model, msg.gitInit, msg.createRemote, msg.repoVisibility, true);
2258
2615
  if (result.error) {
2259
2616
  sendWS(client.ws, { type: 'session_error', error: result.error });
2260
2617
  return;
@@ -2264,6 +2621,9 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2264
2621
  pool.addClient(result.tracked.sessionFile, client.id);
2265
2622
  switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
2266
2623
  clearConflictState(client);
2624
+ // Creating a session CREATES its folder (mkdir/clone), so this one exists
2625
+ // by construction: clear any missing-folder lock the previous session left.
2626
+ client.folderMissingCwd = undefined;
2267
2627
  client.pendingCwd = result.tracked.cwd;
2268
2628
  // Is somebody else still live in this folder? Then two agents would be
2269
2629
  // editing the same working tree, which is exactly what the folder-conflict
@@ -2315,6 +2675,10 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2315
2675
  break;
2316
2676
  }
2317
2677
  case 'session_leave': {
2678
+ // The lock belongs to the session being left, so it goes with it. (A
2679
+ // folder-missing load never attaches, so `sessionId` can already be null
2680
+ // here and the flag must be cleared regardless.)
2681
+ client.folderMissingCwd = undefined;
2318
2682
  if (client.sessionId) {
2319
2683
  switchClientSession(client, null, pool, onSessionsUpdated);
2320
2684
  client.readOnly = false;
@@ -2356,7 +2720,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2356
2720
  // load/create, so it can only ever apply to the load in flight, and the
2357
2721
  // sessions.readOnly guard is re-applied at attach with the real cwd.
2358
2722
  client.conflictContinued = true;
2359
- if (cwd && !pool.isReadOnlyCwd(cwd))
2723
+ if (cwd && !hasHardReadOnly(client, pool, cwd))
2360
2724
  client.readOnly = false;
2361
2725
  // Reply with this client's authoritative conflict state, ALWAYS (including
2362
2726
  // when the lift was refused for a sessions.readOnly folder). Same-socket
@@ -2367,7 +2731,107 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2367
2731
  sendFolderConflict(client, pool);
2368
2732
  break;
2369
2733
  }
2734
+ case 'restore_start': {
2735
+ // RESTORE the working folder at `targetPath`: clone the repository back, or
2736
+ // create the folder. The job is server-owned and path-keyed, so this is a
2737
+ // request to the REGISTRY, not an operation on this socket.
2738
+ const raw = typeof msg.targetPath === 'string' ? msg.targetPath.trim() : '';
2739
+ if (!raw) {
2740
+ sendWS(client.ws, {
2741
+ type: 'restore_rejected',
2742
+ targetPath: '',
2743
+ reason: 'invalid-target',
2744
+ message: 'A target path is required.',
2745
+ });
2746
+ break;
2747
+ }
2748
+ // Resolve the same way the registry does, so the broadcast key, the frames
2749
+ // and the job all name ONE path.
2750
+ const targetPath = path.resolve(expandTilde(raw));
2751
+ // Subscribe first: a request can settle inside the call (a spawn that
2752
+ // throws), and a frame emitted before the subscription exists is lost.
2753
+ observeRestorePath(targetPath, clients, pool);
2754
+ observeRestoreForFolderExistence(targetPath, onSessionsUpdated);
2755
+ const request = msg.action === 'create'
2756
+ ? { kind: 'create', targetPath, gitInit: msg.gitInit === true }
2757
+ : { kind: 'clone', targetPath, url: typeof msg.url === 'string' ? msg.url.trim() : '' };
2758
+ const result = restoreJobs.request(request);
2759
+ if (!result.ok) {
2760
+ // Nothing was spawned or created, so there is no job to observe and no
2761
+ // completion coming. Say why, to the requester only, and let go of the
2762
+ // subscriptions we optimistically took.
2763
+ if (restoreJobs.get(targetPath)?.state !== 'running') {
2764
+ releaseRestoreObserver(targetPath);
2765
+ releaseFolderExistenceObserver(targetPath);
2766
+ }
2767
+ sendWS(client.ws, {
2768
+ type: 'restore_rejected',
2769
+ targetPath,
2770
+ reason: result.reason,
2771
+ message: result.message,
2772
+ });
2773
+ break;
2774
+ }
2775
+ // `outcome` and `job.url` together are what stop a second device from being
2776
+ // silently answered as though ITS edited url had been accepted.
2777
+ sendWS(client.ws, {
2778
+ type: 'restore_started',
2779
+ targetPath,
2780
+ outcome: result.outcome,
2781
+ job: result.job,
2782
+ });
2783
+ if (result.job.state !== 'running') {
2784
+ // Settled inside request() (a spawn failure), so no observer will ever
2785
+ // report it: state the outcome here instead of leaving the panel spinning.
2786
+ releaseRestoreObserver(targetPath);
2787
+ broadcastRestore(clients, pool, targetPath, {
2788
+ type: 'restore_complete',
2789
+ targetPath,
2790
+ job: result.job,
2791
+ });
2792
+ }
2793
+ break;
2794
+ }
2795
+ case 'restore_cancel': {
2796
+ const raw = typeof msg.targetPath === 'string' ? msg.targetPath.trim() : '';
2797
+ if (!raw)
2798
+ break;
2799
+ const targetPath = path.resolve(expandTilde(raw));
2800
+ // The job is path-keyed and server-owned, so any client watching the folder
2801
+ // may cancel it -- including one that did not start it, which is the whole
2802
+ // point when the device that did is the one that went away. The registry
2803
+ // settles the job (authoritatively) and the observer broadcasts the
2804
+ // `cancelled` completion to everyone watching, so nothing is answered here.
2805
+ if (restoreJobs.cancel(targetPath))
2806
+ break;
2807
+ // Nothing was running: re-state the current (retained) job to the asker so a
2808
+ // stale panel converges instead of waiting for a completion that already
2809
+ // happened.
2810
+ const job = restoreJobs.get(targetPath);
2811
+ if (job)
2812
+ sendWS(client.ws, { type: 'restore_complete', targetPath, job });
2813
+ break;
2814
+ }
2370
2815
  case 'message': {
2816
+ // The session's working folder does not exist on this machine, so no live
2817
+ // agent was built for it and there is nothing to attach to (which would
2818
+ // otherwise make this a SILENT drop on the sessionId check below). Refuse
2819
+ // by path, naming it, so the client can say what to restore.
2820
+ if (client.folderMissingCwd) {
2821
+ // Word it for the state the folder is actually in: a restore already
2822
+ // running is a wait, not a "go and restore it".
2823
+ const restoring = restoreJobs.get(client.folderMissingCwd)?.state === 'running';
2824
+ sendWS(client.ws, {
2825
+ type: 'session_error',
2826
+ sessionId: msg.sessionId,
2827
+ error: restoring
2828
+ ? `This session's working folder (${client.folderMissingCwd}) is still being restored, ` +
2829
+ 'so the message was not delivered. Wait for the restore to finish, then reload the session.'
2830
+ : `This session's working folder does not exist on this machine (${client.folderMissingCwd}), ` +
2831
+ 'so the message was not delivered. Restore the folder, then reload the session.',
2832
+ });
2833
+ return;
2834
+ }
2371
2835
  if (!client.sessionId)
2372
2836
  return;
2373
2837
  if (client.readOnly) {
@@ -2505,6 +2969,23 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
2505
2969
  });
2506
2970
  break;
2507
2971
  }
2972
+ // An upload WRITES a file to disk, so it is a write capability and belongs
2973
+ // behind the same verdict as a send. Without this, a client on an
2974
+ // observe-only session (a sessions.readOnly folder, an uncontinued folder
2975
+ // conflict, or a missing folder) could not send a message referencing an
2976
+ // attachment but could still drop the attachment itself into the upload
2977
+ // dir. Refuse out loud rather than silently, for the same reason the
2978
+ // message handler does: a client only hides its composer when it AGREES it
2979
+ // is read-only, so any desync must be visible instead of swallowed.
2980
+ if (client.readOnly) {
2981
+ sendWS(client.ws, {
2982
+ type: 'file_upload_error',
2983
+ uploadId,
2984
+ sessionId,
2985
+ error: 'This session is read-only from here, so the file was not uploaded.',
2986
+ });
2987
+ break;
2988
+ }
2508
2989
  try {
2509
2990
  const tracked = pool.getSession(sessionId);
2510
2991
  const cwd = tracked?.cwd;