wherever-dev 0.10.14 → 0.11.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/commands/install.d.ts +21 -0
  2. package/dist/commands/install.d.ts.map +1 -1
  3. package/dist/commands/install.js +70 -3
  4. package/dist/commands/install.js.map +1 -1
  5. package/dist/conversation-search.d.ts +117 -0
  6. package/dist/conversation-search.d.ts.map +1 -0
  7. package/dist/conversation-search.js +295 -0
  8. package/dist/conversation-search.js.map +1 -0
  9. package/dist/index.js +279 -32
  10. package/dist/index.js.map +1 -1
  11. package/dist/protocol.d.ts +3 -0
  12. package/dist/protocol.d.ts.map +1 -1
  13. package/dist/session-pool.d.ts +64 -32
  14. package/dist/session-pool.d.ts.map +1 -1
  15. package/dist/session-pool.js +184 -352
  16. package/dist/session-pool.js.map +1 -1
  17. package/dist/session-transcript.d.ts +120 -0
  18. package/dist/session-transcript.d.ts.map +1 -0
  19. package/dist/session-transcript.js +813 -0
  20. package/dist/session-transcript.js.map +1 -0
  21. package/package.json +2 -1
  22. package/public/_app/immutable/assets/0.B76aBayq.css +1 -0
  23. package/public/_app/immutable/chunks/{ClTMu0mO.js → BLQ6nRXO.js} +2 -2
  24. package/public/_app/immutable/chunks/{ClTMu0mO.js.map → BLQ6nRXO.js.map} +1 -1
  25. package/public/_app/immutable/chunks/{BzFqVyJ_.js → CKmxwmEQ.js} +2 -2
  26. package/public/_app/immutable/chunks/{BzFqVyJ_.js.map → CKmxwmEQ.js.map} +1 -1
  27. package/public/_app/immutable/chunks/{CDbw105l.js → DDXW2gm3.js} +2 -2
  28. package/public/_app/immutable/chunks/{CDbw105l.js.map → DDXW2gm3.js.map} +1 -1
  29. package/public/_app/immutable/entry/{app.CqLyltZH.js → app.BXjvSIVv.js} +3 -3
  30. package/public/_app/immutable/entry/{app.CqLyltZH.js.map → app.BXjvSIVv.js.map} +1 -1
  31. package/public/_app/immutable/entry/start.BY0WA8dA.js +2 -0
  32. package/public/_app/immutable/entry/start.BY0WA8dA.js.map +1 -0
  33. package/public/_app/immutable/nodes/{0.D_7-7cgp.js → 0.HhOK-JKB.js} +2 -2
  34. package/public/_app/immutable/nodes/{0.D_7-7cgp.js.map → 0.HhOK-JKB.js.map} +1 -1
  35. package/public/_app/immutable/nodes/{1.CDxNOU-Q.js → 1.BWYloVJt.js} +2 -2
  36. package/public/_app/immutable/nodes/{1.CDxNOU-Q.js.map → 1.BWYloVJt.js.map} +1 -1
  37. package/public/_app/immutable/nodes/2.Dq6JhX_v.js +104 -0
  38. package/public/_app/immutable/nodes/2.Dq6JhX_v.js.map +1 -0
  39. package/public/_app/version.json +1 -1
  40. package/public/index.html +11 -11
  41. package/public/service-worker.js +1 -1
  42. package/public/_app/immutable/assets/0.BLdSNDwj.css +0 -1
  43. package/public/_app/immutable/entry/start.CQ4WvoOm.js +0 -2
  44. package/public/_app/immutable/entry/start.CQ4WvoOm.js.map +0 -1
  45. package/public/_app/immutable/nodes/2.D1gQZgOb.js +0 -95
  46. package/public/_app/immutable/nodes/2.D1gQZgOb.js.map +0 -1
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ 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
5
  import { SessionPool, getWhereverConfig, detectRemoteRepo } from './session-pool.js';
6
+ import { searchConversations } from './conversation-search.js';
6
7
  import { INITIAL_HISTORY_LIMIT, HISTORY_PAGE_SIZE } from './protocol.js';
7
8
  import fs from 'node:fs';
8
9
  import path from 'node:path';
@@ -276,6 +277,37 @@ function serveStaticFile(reqPath, res) {
276
277
  }
277
278
  });
278
279
  }
280
+ // Retire any still-registered VIEWER connection carrying the same clientKey: it
281
+ // is the SAME viewer's superseded socket (a reconnect), not a second viewer.
282
+ // Detach it from its session synchronously so the very next message on the new
283
+ // socket sees an accurate client count, then terminate the dead socket.
284
+ //
285
+ // CLI bridges are deliberately left ALONE: their re-registration is already
286
+ // handled by registerCliSession/unregisterCliSession, and tearing one down here
287
+ // would race a cli_register arriving on the new socket against the old socket's
288
+ // async close teardown, which could unregister the session that was just
289
+ // re-registered.
290
+ function evictPreviousConnection(clientKey, clients, pool, onSessionsUpdated) {
291
+ for (const prev of Array.from(clients.values())) {
292
+ if (prev.clientKey !== clientKey || prev.isCliBridge)
293
+ continue;
294
+ if (prev.sessionId) {
295
+ pool.removeClient(prev.sessionId, prev.id);
296
+ prev.sessionId = null;
297
+ }
298
+ clearConflictState(prev);
299
+ clients.delete(prev.id);
300
+ // Tell the superseded connection WHY it is going away, and only then kill it.
301
+ // If it is in fact alive (two tabs that ended up sharing a key, e.g. a
302
+ // duplicated tab cloning sessionStorage), it regenerates its key and comes
303
+ // back as a distinct viewer instead of evicting the other one right back in
304
+ // an endless ping-pong. Losing this frame would restore exactly that
305
+ // ping-pong, with no backstop, so it must not be discarded by the teardown.
306
+ // A genuinely dead socket never reads it and is reaped on the flush timeout.
307
+ sendThenTerminate(prev.ws, { type: 'connection_superseded' });
308
+ onSessionsUpdated();
309
+ }
310
+ }
279
311
  function generateId() {
280
312
  return Math.random().toString(36).substring(2) + Date.now().toString(36);
281
313
  }
@@ -408,6 +440,46 @@ function sendWS(ws, msg) {
408
440
  }
409
441
  }
410
442
  }
443
+ // Send a final message and THEN kill the socket, without losing the message.
444
+ // terminate() destroys the socket and discards whatever is still buffered; over
445
+ // TLS (this server's default) a small frame is frequently still buffered when
446
+ // the send call returns, so terminating in the same tick can drop it. Wait for
447
+ // the write callback, with a timer so a socket that never flushes (the usual
448
+ // case here: the peer is gone) is still reaped promptly.
449
+ function sendThenTerminate(ws, msg, flushTimeoutMs = 1_000) {
450
+ let done = false;
451
+ const kill = () => {
452
+ if (done)
453
+ return;
454
+ done = true;
455
+ try {
456
+ // terminate() (not close()) because a superseded socket is typically
457
+ // half-open: a close handshake would never complete.
458
+ if (typeof ws.terminate === 'function')
459
+ ws.terminate();
460
+ else
461
+ ws.close();
462
+ }
463
+ catch { }
464
+ };
465
+ const timer = setTimeout(kill, flushTimeoutMs);
466
+ timer.unref?.();
467
+ if (ws.readyState !== WebSocket.OPEN) {
468
+ clearTimeout(timer);
469
+ kill();
470
+ return;
471
+ }
472
+ try {
473
+ ws.send(JSON.stringify(msg), () => {
474
+ clearTimeout(timer);
475
+ kill();
476
+ });
477
+ }
478
+ catch (err) {
479
+ clearTimeout(timer);
480
+ kill();
481
+ }
482
+ }
411
483
  async function main() {
412
484
  const { port, host, token, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug } = parseArgs();
413
485
  debugEnabled = debug;
@@ -491,24 +563,10 @@ async function main() {
491
563
  // gone. Sent on every session-set change (open/leave/create/destroy). CLI
492
564
  // bridge connections are skipped (they have no banner UI).
493
565
  function broadcastFolderConflicts() {
566
+ // readOnly rides along every time so the client's composer mirrors the
567
+ // server's authority rather than inferring it from `active`.
494
568
  for (const c of clients.values()) {
495
- if (c.isCliBridge)
496
- continue;
497
- if (!c.sessionId)
498
- continue;
499
- const mine = sessionPool.getSession(c.sessionId);
500
- if (!mine)
501
- continue;
502
- let active = false;
503
- for (const s of sessionPool.getAllSessions()) {
504
- if (s.sessionFile === mine.sessionFile)
505
- continue;
506
- if (s.cwd === mine.cwd && s.clients.size > 0) {
507
- active = true;
508
- break;
509
- }
510
- }
511
- sendWS(c.ws, { type: 'folder_conflict', cwd: mine.cwd, active });
569
+ sendFolderConflict(c, sessionPool);
512
570
  }
513
571
  }
514
572
  function broadcastAgentEvent(sessionFile, event) {
@@ -720,6 +778,7 @@ async function main() {
720
778
  return;
721
779
  }
722
780
  const isApiRequest = pathname.startsWith('/sessions') ||
781
+ pathname.startsWith('/search') ||
723
782
  pathname.startsWith('/models') ||
724
783
  pathname.startsWith('/config') ||
725
784
  pathname.startsWith('/check-path') ||
@@ -739,6 +798,22 @@ async function main() {
739
798
  sendJSON(res, 200, { folders, activeSessions: active });
740
799
  return;
741
800
  }
801
+ // Full-text search over every past session, backed by the memonaut index.
802
+ // Same token gate as /sessions (via isApiRequest above). A missing index is
803
+ // answered with status:'not-indexed', never built inline: memonaut's indexer
804
+ // is synchronous and a full build would freeze every WebSocket client.
805
+ // See server/src/conversation-search.ts for the privacy composition rule.
806
+ if (pathname === '/search' && req.method === 'GET') {
807
+ const view = url.searchParams.get('view') === 'readonly' ? 'readonly' : 'default';
808
+ const limitParam = Number(url.searchParams.get('limit'));
809
+ const result = await searchConversations({
810
+ query: url.searchParams.get('q') || '',
811
+ view,
812
+ limit: Number.isFinite(limitParam) && limitParam > 0 ? limitParam : undefined,
813
+ });
814
+ sendJSON(res, 200, result);
815
+ return;
816
+ }
742
817
  if (pathname === '/models' && req.method === 'GET') {
743
818
  const models = sessionPool.getAvailableModels();
744
819
  sendJSON(res, 200, { models });
@@ -1043,6 +1118,8 @@ async function main() {
1043
1118
  sendWS(c.ws, wsMsg);
1044
1119
  c.sessionId = null;
1045
1120
  c.readOnly = false;
1121
+ // The conflict decision belonged to the session that just went away.
1122
+ clearConflictState(c);
1046
1123
  }
1047
1124
  }
1048
1125
  }
@@ -1093,6 +1170,8 @@ async function main() {
1093
1170
  sendWS(c.ws, wsMsg);
1094
1171
  c.sessionId = null;
1095
1172
  c.readOnly = false;
1173
+ // The conflict decision belonged to the session that just went away.
1174
+ clearConflictState(c);
1096
1175
  }
1097
1176
  }
1098
1177
  sessionPool.destroySession(tracked.sessionFile, 'deleted');
@@ -1394,13 +1473,43 @@ async function main() {
1394
1473
  if (httpServer) {
1395
1474
  httpServer.on('upgrade', upgradeHandler);
1396
1475
  }
1397
- wss.on('connection', (ws) => {
1476
+ wss.on('connection', (ws, req) => {
1398
1477
  const clientId = generateId();
1478
+ // Stable per-viewer identity (see WhereverClientConfig.clientKey). A client
1479
+ // that lost its socket silently (half-open TCP: phone sleep, network switch)
1480
+ // reconnects on a NEW socket while the old record still sits in the pool
1481
+ // until the heartbeat reaper notices, up to 2x HEARTBEAT_MS later. That
1482
+ // phantom counted as "another viewer", which silently turned an explicit
1483
+ // "New Session Here" into a folder conflict (read-only attach to the folder's
1484
+ // existing session). Retiring the same key's previous connection HERE, before
1485
+ // any session traffic on the new socket, closes that window. Keys are scoped
1486
+ // per tab by the web client, so two real tabs remain two distinct viewers.
1487
+ let clientKey;
1488
+ try {
1489
+ const url = new URL(req?.url || '', `http://${req?.headers?.host || 'localhost'}`);
1490
+ const raw = url.searchParams.get('clientKey');
1491
+ // Bounded: this is client-supplied text retained for the life of the
1492
+ // connection. Anything longer than a generated key is not one. Refuse it
1493
+ // rather than truncating (two distinct long keys must not collapse into one
1494
+ // identity and start evicting each other), and say so: the connection
1495
+ // silently loses supersede protection otherwise.
1496
+ if (raw && raw.length > 128) {
1497
+ console.warn(`[wherever] ignoring oversized clientKey (${raw.length} chars) from ${req?.socket?.remoteAddress ?? 'unknown'}`);
1498
+ }
1499
+ else if (raw) {
1500
+ clientKey = raw;
1501
+ }
1502
+ }
1503
+ catch { }
1504
+ if (clientKey) {
1505
+ evictPreviousConnection(clientKey, clients, sessionPool, broadcastSessionsUpdated);
1506
+ }
1399
1507
  const client = {
1400
1508
  id: clientId,
1401
1509
  ws,
1402
1510
  sessionId: null,
1403
1511
  readOnly: false,
1512
+ clientKey,
1404
1513
  };
1405
1514
  clients.set(clientId, client);
1406
1515
  // Liveness: assume alive on connect; any pong (reply to the heartbeat ping
@@ -1546,11 +1655,84 @@ This encrypts all network traffic securely and enables safe, private remote acce
1546
1655
  process.on('SIGTERM', shutdown);
1547
1656
  process.on('SIGINT', shutdown);
1548
1657
  }
1658
+ // The conflict decision belongs to the PAIRING of this client with one session.
1659
+ // Clear every part of it together whenever that pairing ends, so no half-state
1660
+ // (an observer flag without its continue, a cwd from a session we left) can be
1661
+ // read by the next attach.
1662
+ function clearConflictState(client) {
1663
+ client.conflictObserver = false;
1664
+ client.conflictContinued = false;
1665
+ client.pendingCwd = undefined;
1666
+ }
1667
+ // Recompute ONE client's folder-conflict state and settle the read-only it
1668
+ // imposed: releasing it once the conflict no longer holds is part of resolving,
1669
+ // not a side effect the callers could skip. Shared by the live broadcast, the
1670
+ // cold attach and the "Continue anyway" reply so all three speak with one
1671
+ // authority. Returns null for connections the banner does not apply to (CLI
1672
+ // bridges, clients not attached to a session).
1673
+ function resolveFolderConflictState(c, pool) {
1674
+ if (c.isCliBridge || !c.sessionId)
1675
+ return null;
1676
+ const mine = pool.getSession(c.sessionId);
1677
+ if (!mine)
1678
+ return null;
1679
+ let active = false;
1680
+ for (const s of pool.getAllSessions()) {
1681
+ if (s.sessionFile === mine.sessionFile)
1682
+ continue;
1683
+ if (s.cwd === mine.cwd && s.clients.size > 0) {
1684
+ active = true;
1685
+ break;
1686
+ }
1687
+ }
1688
+ // A conflict OBSERVER shares the occupant's session file (session_new attaches
1689
+ // it there read-only), so the scan above -- which skips this very file -- can
1690
+ // never see its conflict. Its conflict lasts exactly as long as someone else is
1691
+ // still on that session.
1692
+ if (!active && c.conflictObserver) {
1693
+ for (const cid of mine.clients) {
1694
+ if (cid !== c.id) {
1695
+ active = true;
1696
+ break;
1697
+ }
1698
+ }
1699
+ }
1700
+ // The conflict resolved (the other party left the folder/session): release the
1701
+ // read-only state it imposed, otherwise the client keeps an observe-only
1702
+ // composer forever with no banner left to lift it. A configured
1703
+ // sessions.readOnly folder is a hard rule and is never lifted here.
1704
+ if (c.conflictObserver && !active) {
1705
+ c.conflictObserver = false;
1706
+ if (!pool.isReadOnlyCwd(mine.cwd))
1707
+ c.readOnly = false;
1708
+ }
1709
+ return { cwd: mine.cwd, active };
1710
+ }
1711
+ // Resolve and report in one step. Every folder_conflict frame goes out through
1712
+ // here, so the `readOnly` it carries can never drift from the authority that
1713
+ // produced `active`.
1714
+ function sendFolderConflict(client, pool) {
1715
+ const verdict = resolveFolderConflictState(client, pool);
1716
+ if (!verdict)
1717
+ return;
1718
+ sendWS(client.ws, {
1719
+ type: 'folder_conflict',
1720
+ cwd: verdict.cwd,
1721
+ active: verdict.active,
1722
+ readOnly: client.readOnly,
1723
+ });
1724
+ }
1549
1725
  function switchClientSession(client, newSessionFile, pool, onSessionsUpdated) {
1550
1726
  if (client.sessionId && client.sessionId !== newSessionFile) {
1551
1727
  pool.removeClient(client.sessionId, client.id);
1552
1728
  }
1553
1729
  client.sessionId = newSessionFile;
1730
+ // Detaching ends the pairing the conflict decision belonged to. (An ATTACH must
1731
+ // not clear it: a "Continue anyway" clicked during a cold load is recorded
1732
+ // before this call and has to survive it.)
1733
+ if (newSessionFile === null) {
1734
+ clearConflictState(client);
1735
+ }
1554
1736
  if (onSessionsUpdated) {
1555
1737
  onSessionsUpdated();
1556
1738
  }
@@ -1611,7 +1793,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1611
1793
  for (const c of clients.values()) {
1612
1794
  if (c.sessionId === msg.sessionFile && !c.isCliBridge) {
1613
1795
  sendWS(c.ws, msgToWeb);
1614
- const history = pool.getSessionHistoryWindow(msg.sessionFile, INITIAL_HISTORY_LIMIT);
1796
+ const history = await pool.getSessionHistoryWindow(msg.sessionFile, INITIAL_HISTORY_LIMIT);
1615
1797
  sendWS(c.ws, {
1616
1798
  type: 'message_history',
1617
1799
  sessionId: sId,
@@ -1663,6 +1845,10 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1663
1845
  // 2. Build the live agent (createAgentSession -> extension/MCP load, the
1664
1846
  // seconds-long part) ASYNC, then signal session_ready so the composer
1665
1847
  // enables. Sending needs the live agent; reading does not.
1848
+ // A new load is a new decision: any earlier "Continue anyway" belongs to the
1849
+ // session we are leaving. Reset BEFORE the first await, so a continue that
1850
+ // races this load is recorded against the load, never wiped by it.
1851
+ client.conflictContinued = false;
1666
1852
  const meta = await pool.readSessionMeta(msg.sessionFile, INITIAL_HISTORY_LIMIT, msg.model);
1667
1853
  if ('error' in meta) {
1668
1854
  sendWS(client.ws, { type: 'session_error', error: meta.error });
@@ -1680,6 +1866,8 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1680
1866
  // A folder conflict also starts the client read-only until they continue.
1681
1867
  const forcedReadOnly = meta.readOnly || folderConflict;
1682
1868
  client.readOnly = forcedReadOnly;
1869
+ client.conflictObserver = folderConflict;
1870
+ client.pendingCwd = meta.cwd;
1683
1871
  // Paint immediately. `pending` is true when the live agent is not resident
1684
1872
  // yet, so the client keeps the composer disabled (with a "preparing
1685
1873
  // agent..." hint) until session_ready, while reading/scrolling work now.
@@ -1739,10 +1927,17 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1739
1927
  }
1740
1928
  pool.addClient(result.tracked.sessionFile, client.id);
1741
1929
  switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
1742
- // Preserve the folder-conflict read-only: a forced-read-only (config or
1743
- // folder conflict) client must stay read-only until it explicitly
1744
- // continues, so don't clobber it with the cwd-glob check alone.
1745
- client.readOnly = forcedReadOnly || pool.isReadOnlyCwd(result.tracked.cwd);
1930
+ // Re-derive read-only from the CURRENT decision rather than from
1931
+ // `forcedReadOnly` captured before the build: while the agent was building
1932
+ // the user may have clicked "Continue anyway" (conflictContinued), and
1933
+ // re-imposing the stale value re-locked them with no banner left to lift
1934
+ // it, while `message` dropped their sends in silence. The conflict having
1935
+ // RESOLVED during the build is handled just below by the verdict, which
1936
+ // re-scans and releases read-only.
1937
+ client.readOnly =
1938
+ meta.readOnly ||
1939
+ pool.isReadOnlyCwd(result.tracked.cwd) ||
1940
+ (client.conflictObserver === true && !client.conflictContinued);
1746
1941
  sendWS(client.ws, {
1747
1942
  type: 'session_ready',
1748
1943
  sessionId: result.tracked.sessionId,
@@ -1755,6 +1950,11 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1755
1950
  // taken over by another client mid-build; send the authoritative snapshot
1756
1951
  // for the same reason as the warm path above.
1757
1952
  sendQueueSnapshot(client, result.tracked.sessionFile, result.tracked.sessionId, pool);
1953
+ // State may have moved during the build (the conflict resolved, or the
1954
+ // user continued through it). session_ready carries no readOnly, and the
1955
+ // periodic conflict broadcast is throttled, so state the verdict here
1956
+ // explicitly rather than leaving the composer to guess for up to 2s.
1957
+ sendFolderConflict(client, pool);
1758
1958
  })();
1759
1959
  break;
1760
1960
  }
@@ -1766,7 +1966,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1766
1966
  const tracked = pool.getSession(targetFile);
1767
1967
  if (!tracked)
1768
1968
  return;
1769
- const window = pool.getSessionHistoryWindow(targetFile, HISTORY_PAGE_SIZE, msg.beforeOffset);
1969
+ const window = await pool.getSessionHistoryWindow(targetFile, HISTORY_PAGE_SIZE, msg.beforeOffset);
1770
1970
  sendWS(client.ws, {
1771
1971
  type: 'message_history_prepend',
1772
1972
  sessionId: tracked.sessionId,
@@ -1803,9 +2003,12 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1803
2003
  // existing one), so attach to that existing session as a read-only
1804
2004
  // observer and raise the warning banner. "Continue anyway"
1805
2005
  // (folder_conflict_continue) lifts read-only so both can send.
1806
- client.readOnly = true;
1807
2006
  pool.addClient(existing.sessionFile, client.id);
1808
2007
  switchClientSession(client, existing.sessionFile, pool, onSessionsUpdated);
2008
+ client.readOnly = true;
2009
+ clearConflictState(client);
2010
+ client.conflictObserver = true;
2011
+ client.pendingCwd = existing.cwd;
1809
2012
  sendWS(client.ws, {
1810
2013
  type: 'session_created',
1811
2014
  sessionId: existing.sessionId,
@@ -1816,7 +2019,7 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1816
2019
  readOnly: true,
1817
2020
  folderConflict: true,
1818
2021
  });
1819
- const history = pool.getSessionHistoryWindow(existing.sessionFile, INITIAL_HISTORY_LIMIT);
2022
+ const history = await pool.getSessionHistoryWindow(existing.sessionFile, INITIAL_HISTORY_LIMIT);
1820
2023
  sendWS(client.ws, {
1821
2024
  type: 'message_history',
1822
2025
  sessionId: existing.sessionId,
@@ -1840,6 +2043,8 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1840
2043
  pool.addClient(result.tracked.sessionFile, client.id);
1841
2044
  switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
1842
2045
  client.readOnly = false;
2046
+ clearConflictState(client);
2047
+ client.pendingCwd = result.tracked.cwd;
1843
2048
  sendWS(client.ws, {
1844
2049
  type: 'session_created',
1845
2050
  sessionId: result.tracked.sessionId,
@@ -1893,19 +2098,61 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1893
2098
  // run concurrently from here on. Guard: never lift read-only for a session
1894
2099
  // whose cwd is a configured sessions.readOnly folder (that is a hard
1895
2100
  // observe-only rule, not a dismissible warning).
2101
+ // The cwd may come from an attached session or, during a cold load's agent
2102
+ // build, from the load in progress: the user can click Continue on the
2103
+ // painted-but-not-yet-attached conversation, and dropping that click left
2104
+ // them read-only with the button already gone.
1896
2105
  const tracked = client.sessionId ? pool.getSession(client.sessionId) : null;
1897
- if (!tracked)
1898
- return;
1899
- if (pool.isReadOnlyCwd(tracked.cwd))
1900
- return;
1901
- client.readOnly = false;
2106
+ const cwd = tracked?.cwd ?? client.pendingCwd;
2107
+ // The client stamps the session it was looking at. If that resolves to a
2108
+ // DIFFERENT folder, the session changed under the click (a switch racing the
2109
+ // tap): honouring it would continue through a conflict the user never saw.
2110
+ // An unresolvable id means the target is not resident (the cold-load case
2111
+ // this continue exists for), which the cwd check covers.
2112
+ if (cwd && msg.sessionId) {
2113
+ const target = pool.getSession(msg.sessionId);
2114
+ if (target && target.cwd !== cwd)
2115
+ return;
2116
+ }
2117
+ // Durable intent: honoured at attach even if the click landed before this
2118
+ // client had a session to lift read-only on -- INCLUDING before the load it
2119
+ // belongs to has reported its cwd. A cold load reads the transcript from
2120
+ // disk, so it yields to the event loop before setting `pendingCwd`, and a
2121
+ // continue sent immediately after `session_load` is processed inside that
2122
+ // window. Dropping it there left the user read-only with the banner's
2123
+ // button already gone -- exactly the bug this intent exists to prevent.
2124
+ // The intent is scoped to this client and reset at the start of every
2125
+ // load/create, so it can only ever apply to the load in flight, and the
2126
+ // sessions.readOnly guard is re-applied at attach with the real cwd.
2127
+ client.conflictContinued = true;
2128
+ if (cwd && !pool.isReadOnlyCwd(cwd))
2129
+ client.readOnly = false;
2130
+ // Reply with this client's authoritative conflict state, ALWAYS (including
2131
+ // when the lift was refused for a sessions.readOnly folder). Same-socket
2132
+ // ordering guarantees this lands after any folder_conflict broadcast that
2133
+ // was already in flight when the continue was sent, so an in-flight update
2134
+ // carrying the pre-continue readOnly:true cannot leave the composer
2135
+ // disabled with the banner's button already gone.
2136
+ sendFolderConflict(client, pool);
1902
2137
  break;
1903
2138
  }
1904
2139
  case 'message': {
1905
2140
  if (!client.sessionId)
1906
2141
  return;
1907
- if (client.readOnly)
2142
+ if (client.readOnly) {
2143
+ // Never swallow a send. This is a legitimate refusal for an observe-only
2144
+ // session (a sessions.readOnly folder, or a folder conflict not continued
2145
+ // through), but the client only hides its composer when it AGREES it is
2146
+ // read-only -- so any future desync of that agreement used to show up as
2147
+ // text vanishing into the void. Answering makes it a visible, retryable
2148
+ // failure instead (the client surfaces session_error with a Retry).
2149
+ sendWS(client.ws, {
2150
+ type: 'session_error',
2151
+ sessionId: msg.sessionId,
2152
+ error: 'This session is read-only from here, so the message was not delivered. Use "Continue anyway" on the folder-conflict banner, or open the session that owns this folder.',
2153
+ });
1908
2154
  return;
2155
+ }
1909
2156
  // The client stamps every send with the sessionId of the session it is
1910
2157
  // actually viewing. Treat that as AUTHORITATIVE: if it does not resolve to
1911
2158
  // the same tracked session this connection is attached to, REFUSE rather