wherever-dev 0.2.0 → 0.4.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 (70) hide show
  1. package/dist/index.js +217 -17
  2. package/dist/index.js.map +1 -1
  3. package/dist/protocol.d.ts +21 -1
  4. package/dist/protocol.d.ts.map +1 -1
  5. package/dist/protocol.js +5 -1
  6. package/dist/protocol.js.map +1 -1
  7. package/dist/session-pool.d.ts +92 -2
  8. package/dist/session-pool.d.ts.map +1 -1
  9. package/dist/session-pool.js +466 -14
  10. package/dist/session-pool.js.map +1 -1
  11. package/dist/session-types.d.ts +17 -0
  12. package/dist/session-types.d.ts.map +1 -1
  13. package/package.json +1 -1
  14. package/public/_app/immutable/assets/0.CgLKPJWX.css +1 -0
  15. package/public/_app/immutable/chunks/CEg8tgYI.js +2 -0
  16. package/public/_app/immutable/chunks/CEg8tgYI.js.map +1 -0
  17. package/public/_app/immutable/chunks/CTVuBuYH.js +2 -0
  18. package/public/_app/immutable/chunks/{B5WJGjcR.js.map → CTVuBuYH.js.map} +1 -1
  19. package/public/_app/immutable/chunks/DBDAFnY6.js +2 -0
  20. package/public/_app/immutable/chunks/{BqMutrfe.js.map → DBDAFnY6.js.map} +1 -1
  21. package/public/_app/immutable/chunks/MtE7VtNZ.js +2 -0
  22. package/public/_app/immutable/chunks/{DiYtJzYU.js.map → MtE7VtNZ.js.map} +1 -1
  23. package/public/_app/immutable/chunks/S778j9fy.js +2 -0
  24. package/public/_app/immutable/chunks/{_lppinj8.js.map → S778j9fy.js.map} +1 -1
  25. package/public/_app/immutable/chunks/vMsF8lo6.js +3 -0
  26. package/public/_app/immutable/chunks/{DFxBx2vA.js.map → vMsF8lo6.js.map} +1 -1
  27. package/public/_app/immutable/chunks/ylfInSZr.js +2 -0
  28. package/public/_app/immutable/chunks/{BEWoN05F.js.map → ylfInSZr.js.map} +1 -1
  29. package/public/_app/immutable/entry/app.CklFlIiC.js +3 -0
  30. package/public/_app/immutable/entry/app.CklFlIiC.js.map +1 -0
  31. package/public/_app/immutable/entry/start.sF1k4jCY.js +2 -0
  32. package/public/_app/immutable/entry/start.sF1k4jCY.js.map +1 -0
  33. package/public/_app/immutable/nodes/0.BEHRw2jv.js +4 -0
  34. package/public/_app/immutable/nodes/{0.BzvDOlXz.js.map → 0.BEHRw2jv.js.map} +1 -1
  35. package/public/_app/immutable/nodes/1.2gk2c-6t.js +2 -0
  36. package/public/_app/immutable/nodes/{1.DMtW3tA5.js.map → 1.2gk2c-6t.js.map} +1 -1
  37. package/public/_app/immutable/nodes/2.Dto-NrSs.js +82 -0
  38. package/public/_app/immutable/nodes/2.Dto-NrSs.js.map +1 -0
  39. package/public/_app/version.json +1 -1
  40. package/public/index.html +16 -16
  41. package/public/pwa/apple-touch-icon.png +0 -0
  42. package/public/pwa/favicon-192.png +0 -0
  43. package/public/pwa/favicon-512.png +0 -0
  44. package/public/pwa/favicon.ico +0 -0
  45. package/public/pwa/favicon.svg +1 -0
  46. package/public/pwa/manifest.webmanifest +31 -7
  47. package/public/pwa/maskable-192.png +0 -0
  48. package/public/pwa/maskable-512.png +0 -0
  49. package/public/pwa/screenshot-desktop.png +0 -0
  50. package/public/pwa/screenshot-mobile.png +0 -0
  51. package/public/robots.txt +5 -0
  52. package/public/service-worker.js +1 -305
  53. package/public/_app/immutable/assets/0.DvZxoQjW.css +0 -2754
  54. package/public/_app/immutable/chunks/B5WJGjcR.js +0 -23
  55. package/public/_app/immutable/chunks/BEWoN05F.js +0 -110
  56. package/public/_app/immutable/chunks/BqMutrfe.js +0 -2129
  57. package/public/_app/immutable/chunks/DFxBx2vA.js +0 -897
  58. package/public/_app/immutable/chunks/DiYtJzYU.js +0 -396
  59. package/public/_app/immutable/chunks/_lppinj8.js +0 -879
  60. package/public/_app/immutable/chunks/rMw82gDs.js +0 -3048
  61. package/public/_app/immutable/chunks/rMw82gDs.js.map +0 -1
  62. package/public/_app/immutable/entry/app.BFki2czn.js +0 -309
  63. package/public/_app/immutable/entry/app.BFki2czn.js.map +0 -1
  64. package/public/_app/immutable/entry/start.BceUuq27.js +0 -6
  65. package/public/_app/immutable/entry/start.BceUuq27.js.map +0 -1
  66. package/public/_app/immutable/nodes/0.BzvDOlXz.js +0 -546
  67. package/public/_app/immutable/nodes/1.DMtW3tA5.js +0 -24
  68. package/public/_app/immutable/nodes/2.CnZp8abw.js +0 -5152
  69. package/public/_app/immutable/nodes/2.CnZp8abw.js.map +0 -1
  70. package/public/icon.png +0 -0
@@ -17,6 +17,229 @@ export function normalizePath(p) {
17
17
  }
18
18
  return normalized;
19
19
  }
20
+ /** True only for a real Date with a finite (valid) time value. */
21
+ function isValidDate(d) {
22
+ return d instanceof Date && Number.isFinite(d.getTime());
23
+ }
24
+ /**
25
+ * Max length of the first-message PREVIEW shipped in the /sessions list. The
26
+ * sidebar only renders a ~40-char snippet and filters on the text, so the full
27
+ * (often huge: pasted prompts, PRDs, specs) first message must never cross the
28
+ * wire for every session. This caps each entry, which is the dominant factor in
29
+ * the /sessions payload size.
30
+ */
31
+ const FIRST_MESSAGE_PREVIEW_MAX = 160;
32
+ /**
33
+ * Collapse whitespace and cap to a short preview. Keeps the /sessions payload
34
+ * tens-of-KB instead of multi-MB while preserving what the sidebar displays and
35
+ * filters on.
36
+ */
37
+ function previewText(text) {
38
+ const collapsed = (text || '').replace(/\s+/g, ' ').trim();
39
+ return collapsed.length > FIRST_MESSAGE_PREVIEW_MAX
40
+ ? collapsed.slice(0, FIRST_MESSAGE_PREVIEW_MAX) + '\u2026'
41
+ : collapsed;
42
+ }
43
+ /**
44
+ * Convert a Date to an ISO string, tolerating invalid/missing dates.
45
+ * Belt-and-suspenders guard: a single malformed session timestamp must never
46
+ * crash listSessions(), even if a bad record slips past the upstream filter.
47
+ */
48
+ function safeToISOString(d) {
49
+ return isValidDate(d) ? d.toISOString() : new Date(0).toISOString();
50
+ }
51
+ /**
52
+ * Convert a single glob pattern into a RegExp matched against a normalized,
53
+ * absolute filesystem path. Supports `*` (does not cross a path separator),
54
+ * `**` (crosses separators), and `?`. Tilde (`~`) is expanded to the home dir.
55
+ * No new dependency: this is a deliberately small, path-oriented matcher.
56
+ */
57
+ function globToRegExp(glob) {
58
+ let g = glob.trim();
59
+ if (g.startsWith('~')) {
60
+ g = path.join(os.homedir(), g.slice(1));
61
+ }
62
+ // Normalize separators and collapse a trailing slash so "/tmp/" == "/tmp".
63
+ g = g.replace(/\\/g, '/');
64
+ if (g.length > 1 && g.endsWith('/'))
65
+ g = g.slice(0, -1);
66
+ let re = '';
67
+ for (let i = 0; i < g.length; i++) {
68
+ const c = g[i];
69
+ if (c === '*') {
70
+ if (g[i + 1] === '*') {
71
+ // `**` -> any chars including separators (optionally followed by a `/`).
72
+ i++;
73
+ if (g[i + 1] === '/')
74
+ i++;
75
+ re += '.*';
76
+ }
77
+ else {
78
+ // `*` -> any chars except a path separator.
79
+ re += '[^/]*';
80
+ }
81
+ }
82
+ else if (c === '?') {
83
+ re += '[^/]';
84
+ }
85
+ else if ('\\^$.|+()[]{}'.includes(c)) {
86
+ re += '\\' + c;
87
+ }
88
+ else {
89
+ re += c;
90
+ }
91
+ }
92
+ return new RegExp('^' + re + '$');
93
+ }
94
+ /**
95
+ * Build a predicate that returns true when a resolved cwd should be IGNORED.
96
+ * A cwd matches if it equals, or is nested under, any ignore glob. Patterns are
97
+ * compiled once; an empty list yields a predicate that never matches.
98
+ */
99
+ export function makeIgnoreMatcher(patterns) {
100
+ const globs = (patterns || []).filter((p) => typeof p === 'string' && p.trim().length > 0);
101
+ if (globs.length === 0)
102
+ return () => false;
103
+ const regexps = [];
104
+ for (const g of globs) {
105
+ try {
106
+ // A pattern should ignore both the directory itself AND everything nested
107
+ // under it, regardless of how it was written:
108
+ // "/tmp" -> match "/tmp" and "/tmp/anything"
109
+ // "/tmp/**" -> match "/tmp" and "/tmp/anything"
110
+ // "/tmp/*" -> match "/tmp" and "/tmp/anything"
111
+ // So we strip a trailing /* or /** to get the base, then add both the base
112
+ // and a "/**" nested variant.
113
+ const base = g.replace(/\/+\*{1,2}$/, '').replace(/\/+$/, '') || g;
114
+ regexps.push(globToRegExp(base));
115
+ regexps.push(globToRegExp(base + '/**'));
116
+ // Also honour the pattern exactly as written (e.g. a mid-path glob).
117
+ regexps.push(globToRegExp(g));
118
+ }
119
+ catch (err) {
120
+ console.error(`Invalid sessions.ignore glob ${JSON.stringify(g)}:`, err);
121
+ }
122
+ }
123
+ return (cwd) => {
124
+ const norm = normalizePath(cwd).replace(/\\/g, '/');
125
+ return regexps.some((re) => re.test(norm));
126
+ };
127
+ }
128
+ /**
129
+ * Read only the header (first line) of a session .jsonl to recover its
130
+ * authoritative cwd, WITHOUT parsing the whole file. Returns '' if the header
131
+ * is missing/unreadable. This is the cheap pre-filter that lets us skip an
132
+ * ignored folder before reading its (potentially many, large) file bodies.
133
+ */
134
+ function readSessionCwdFromHeader(filePath) {
135
+ try {
136
+ const fd = fs.openSync(filePath, 'r');
137
+ try {
138
+ const buf = Buffer.alloc(8192);
139
+ const bytes = fs.readSync(fd, buf, 0, buf.length, 0);
140
+ const text = buf.toString('utf8', 0, bytes);
141
+ const nl = text.indexOf('\n');
142
+ const firstLine = nl === -1 ? text : text.slice(0, nl);
143
+ const header = JSON.parse(firstLine);
144
+ return typeof header?.cwd === 'string' ? header.cwd : '';
145
+ }
146
+ finally {
147
+ fs.closeSync(fd);
148
+ }
149
+ }
150
+ catch {
151
+ return '';
152
+ }
153
+ }
154
+ /**
155
+ * Resolve a session's raw header cwd into a normalized absolute path, matching
156
+ * how listSessions() buckets folders (tilde-expand; relative -> under home).
157
+ */
158
+ function resolveSessionCwd(rawCwd) {
159
+ const raw = rawCwd || '';
160
+ let cwd = raw;
161
+ if (raw.startsWith('~')) {
162
+ cwd = path.join(os.homedir(), raw.slice(1));
163
+ }
164
+ else if (!path.isAbsolute(raw)) {
165
+ cwd = path.join(os.homedir(), raw);
166
+ }
167
+ return normalizePath(cwd);
168
+ }
169
+ /**
170
+ * Parse one session .jsonl into the subset of fields the listing needs. This is
171
+ * the directory-aware path's equivalent of pi's internal buildSessionInfo
172
+ * (which is not exported), used ONLY for folders that survived the ignore
173
+ * pre-filter. Returns null for a non-session / empty / unreadable file.
174
+ */
175
+ function buildDiskSessionInfo(filePath) {
176
+ try {
177
+ const content = fs.readFileSync(filePath, 'utf8');
178
+ const lines = content.trim().split('\n');
179
+ const entries = [];
180
+ for (const line of lines) {
181
+ if (!line.trim())
182
+ continue;
183
+ try {
184
+ entries.push(JSON.parse(line));
185
+ }
186
+ catch { /* skip malformed line */ }
187
+ }
188
+ if (entries.length === 0)
189
+ return null;
190
+ const header = entries[0];
191
+ if (header?.type !== 'session')
192
+ return null;
193
+ const stats = fs.statSync(filePath);
194
+ let messageCount = 0;
195
+ let firstMessage = '';
196
+ let name;
197
+ let lastMessageTime = 0;
198
+ for (const entry of entries) {
199
+ if (entry?.type === 'session_info') {
200
+ name = (entry.name && String(entry.name).trim()) || undefined;
201
+ }
202
+ if (entry?.type !== 'message')
203
+ continue;
204
+ messageCount++;
205
+ const message = entry.message;
206
+ const role = message?.role;
207
+ if (role !== 'user' && role !== 'assistant')
208
+ continue;
209
+ let textContent = '';
210
+ const c = message?.content;
211
+ if (typeof c === 'string') {
212
+ textContent = c;
213
+ }
214
+ else if (Array.isArray(c)) {
215
+ textContent = c.map((p) => (typeof p?.text === 'string' ? p.text : '')).join('');
216
+ }
217
+ if (!textContent)
218
+ continue;
219
+ if (!firstMessage && role === 'user')
220
+ firstMessage = textContent;
221
+ const t = typeof entry.timestamp === 'string' ? new Date(entry.timestamp).getTime() : NaN;
222
+ if (Number.isFinite(t))
223
+ lastMessageTime = Math.max(lastMessageTime, t);
224
+ }
225
+ const headerTime = typeof header.timestamp === 'string' ? new Date(header.timestamp).getTime() : NaN;
226
+ const created = Number.isFinite(headerTime) ? new Date(headerTime) : new Date(NaN);
227
+ const modified = lastMessageTime > 0 ? new Date(lastMessageTime) : stats.mtime;
228
+ return {
229
+ path: filePath,
230
+ id: typeof header.id === 'string' ? header.id : '',
231
+ cwd: typeof header.cwd === 'string' ? header.cwd : '',
232
+ name,
233
+ created,
234
+ modified,
235
+ messageCount,
236
+ firstMessage: firstMessage || '(no messages)',
237
+ };
238
+ }
239
+ catch {
240
+ return null;
241
+ }
242
+ }
20
243
  export function getWhereverConfig() {
21
244
  const configDir = path.join(os.homedir(), '.wherever');
22
245
  const configPath = path.join(configDir, 'config.json');
@@ -46,6 +269,52 @@ export function getWhereverConfig() {
46
269
  }
47
270
  return {};
48
271
  }
272
+ const SEARCH_WORKSPACE_AGENTS_MD = `# Search workspace
273
+
274
+ This folder is a **search workspace**, not a coding project. Sessions started
275
+ here (from the wherever search bar, or via \`pisearch\`) exist to answer questions
276
+ with current information from the live web.
277
+
278
+ ## How to behave here
279
+
280
+ - Use the **web-search skill**: lead with \`web_search\`, open the most promising
281
+ 1-3 results with \`web_fetch\` to verify, then answer.
282
+ - Answer the question **directly and concisely**, then list the **source URLs**
283
+ you actually used. Prefer recent, authoritative sources; weight recency for
284
+ time-sensitive questions.
285
+ - **Do not start a coding task** or edit files unless explicitly asked. There is
286
+ no project to build here.
287
+ - If the web tools cannot reach Ollama (connection refused / 401), say so and
288
+ tell the user to start Ollama or run \`ollama signin\`. Do not silently answer
289
+ from memory without flagging it.
290
+ `;
291
+ /**
292
+ * If resolvedCwd is the configured search folder, drop a default AGENTS.md into
293
+ * it when none exists. Resolves the config's searchFolder (tilde-expanded) and
294
+ * compares it to resolvedCwd via normalizePath. Best-effort: never throws, never
295
+ * overwrites an existing AGENTS.md.
296
+ */
297
+ export function maybeSeedSearchWorkspace(resolvedCwd) {
298
+ try {
299
+ const config = getWhereverConfig();
300
+ let searchFolder = config.searchFolder;
301
+ if (!searchFolder)
302
+ return;
303
+ if (searchFolder.startsWith('~')) {
304
+ searchFolder = path.join(os.homedir(), searchFolder.slice(1));
305
+ }
306
+ if (normalizePath(searchFolder) !== normalizePath(resolvedCwd))
307
+ return;
308
+ const agentsPath = path.join(resolvedCwd, 'AGENTS.md');
309
+ if (fs.existsSync(agentsPath))
310
+ return;
311
+ fs.writeFileSync(agentsPath, SEARCH_WORKSPACE_AGENTS_MD, 'utf8');
312
+ console.log(`Seeded search workspace AGENTS.md in ${resolvedCwd}`);
313
+ }
314
+ catch (err) {
315
+ console.error('Failed to seed search workspace AGENTS.md:', err);
316
+ }
317
+ }
49
318
  export function setupUpstreamTracking(resolvedCwd) {
50
319
  try {
51
320
  let defaultBranch = '';
@@ -225,6 +494,11 @@ export class SessionPool {
225
494
  if (!fs.existsSync(resolvedCwd)) {
226
495
  fs.mkdirSync(resolvedCwd, { recursive: true });
227
496
  }
497
+ // If this is the configured search folder, seed a default AGENTS.md so
498
+ // search sessions behave correctly even in the browser path (where the
499
+ // web-search skill is only discoverable, not preloaded). Self-healing:
500
+ // re-created if the folder was deleted. Never clobbers an existing file.
501
+ maybeSeedSearchWorkspace(resolvedCwd);
228
502
  // Git initialization if requested
229
503
  if (gitInit) {
230
504
  try {
@@ -515,19 +789,153 @@ export class SessionPool {
515
789
  }
516
790
  return messages;
517
791
  }
518
- async listSessions() {
519
- const diskSessions = await SessionManager.listAll();
792
+ /**
793
+ * Tail-first windowed history. Returns the last `limit` messages (the most
794
+ * recent), along with the total count and the offset of the first returned
795
+ * message, so the client can lazily request older history.
796
+ *
797
+ * `beforeOffset`, when provided, returns the window of `limit` messages
798
+ * ending just before that offset (used for "load older" requests).
799
+ */
800
+ getSessionHistoryWindow(sessionFileOrId, limit, beforeOffset) {
801
+ const all = this.getSessionHistory(sessionFileOrId);
802
+ const totalCount = all.length;
803
+ if (limit <= 0 || totalCount === 0) {
804
+ const end = beforeOffset ?? totalCount;
805
+ return { messages: [], totalCount, offset: Math.max(0, Math.min(end, totalCount)) };
806
+ }
807
+ const end = beforeOffset === undefined
808
+ ? totalCount
809
+ : Math.max(0, Math.min(beforeOffset, totalCount));
810
+ const start = Math.max(0, end - limit);
811
+ return {
812
+ messages: all.slice(start, end),
813
+ totalCount,
814
+ offset: start,
815
+ };
816
+ }
817
+ /**
818
+ * List session folders.
819
+ * - view='default' (the dashboard's main list): excludes `sessions.ignore`
820
+ * AND `sessions.readOnly` folders.
821
+ * - view='readonly' (the separate read-only page): returns ONLY the
822
+ * `sessions.readOnly` folders (still excluding `sessions.ignore`), each
823
+ * tagged `readOnly: true`.
824
+ * In both cases, excluded folders are pruned BEFORE their file bodies are
825
+ * read (cheap one-header probe per folder), so they cost nothing to scan.
826
+ */
827
+ async listSessions(view = 'default') {
828
+ const cfg = getWhereverConfig().sessions;
829
+ const ignorePatterns = cfg?.ignore;
830
+ const readOnlyPatterns = cfg?.readOnly;
831
+ const isIgnored = makeIgnoreMatcher(ignorePatterns);
832
+ const isReadOnly = makeIgnoreMatcher(readOnlyPatterns);
833
+ const hasIgnore = !!ignorePatterns && ignorePatterns.length > 0;
834
+ const hasReadOnly = !!readOnlyPatterns && readOnlyPatterns.length > 0;
835
+ // Fast path: no ignore AND no read-only patterns, and the caller wants the
836
+ // default view -> keep pi's listAll() exactly as before (zero behaviour or
837
+ // perf change for users who haven't opted in).
838
+ if (view === 'default' && !hasIgnore && !hasReadOnly) {
839
+ const diskSessions = await SessionManager.listAll();
840
+ return this.buildFolders(diskSessions.map((s) => ({
841
+ path: s.path,
842
+ id: s.id,
843
+ cwd: s.cwd,
844
+ name: s.name,
845
+ created: s.created,
846
+ modified: s.modified,
847
+ messageCount: s.messageCount,
848
+ firstMessage: s.firstMessage,
849
+ })));
850
+ }
851
+ // A folder is KEPT only if its cwd belongs in the requested view:
852
+ // - default: not ignored AND not read-only.
853
+ // - readonly: not ignored AND read-only.
854
+ const folderWanted = (cwd) => {
855
+ if (isIgnored(cwd))
856
+ return false;
857
+ return view === 'readonly' ? isReadOnly(cwd) : !isReadOnly(cwd);
858
+ };
859
+ // Directory-aware path: prune unwanted folders BEFORE reading their file
860
+ // bodies, so the excluded sessions do not slow down /sessions.
861
+ const sessionsRoot = path.join(this.agentDir, 'sessions');
862
+ let dirNames = [];
863
+ try {
864
+ dirNames = fs
865
+ .readdirSync(sessionsRoot, { withFileTypes: true })
866
+ .filter((e) => e.isDirectory())
867
+ .map((e) => e.name);
868
+ }
869
+ catch {
870
+ return [];
871
+ }
872
+ const survivingFiles = [];
873
+ let prunedFolders = 0;
874
+ for (const dirName of dirNames) {
875
+ const dirPath = path.join(sessionsRoot, dirName);
876
+ let files;
877
+ try {
878
+ files = fs.readdirSync(dirPath).filter((f) => f.endsWith('.jsonl'));
879
+ }
880
+ catch {
881
+ continue;
882
+ }
883
+ if (files.length === 0)
884
+ continue;
885
+ // Cheap pre-filter: read ONLY the header of the first file to recover the
886
+ // authoritative cwd. All sessions in one folder share a cwd, so one header
887
+ // decides the whole folder. If the folder is not wanted in this view, skip
888
+ // it entirely (its file bodies are never read).
889
+ const probeCwd = resolveSessionCwd(readSessionCwdFromHeader(path.join(dirPath, files[0])));
890
+ if (probeCwd && !folderWanted(probeCwd)) {
891
+ prunedFolders++;
892
+ continue;
893
+ }
894
+ for (const f of files)
895
+ survivingFiles.push(path.join(dirPath, f));
896
+ }
897
+ const infos = [];
898
+ for (const file of survivingFiles) {
899
+ const info = buildDiskSessionInfo(file);
900
+ if (!info)
901
+ continue;
902
+ // Defensive per-session re-check (mixed/edge cases the folder probe missed).
903
+ if (!folderWanted(resolveSessionCwd(info.cwd)))
904
+ continue;
905
+ infos.push(info);
906
+ }
907
+ if (prunedFolders > 0) {
908
+ console.log(`[wherever] /sessions (${view}): skipped ${prunedFolders} folder(s) before reading file bodies`);
909
+ }
910
+ return this.buildFolders(infos, view === 'readonly' ? isReadOnly : undefined);
911
+ }
912
+ /** True when the given (raw or resolved) cwd matches a sessions.readOnly glob. */
913
+ isReadOnlyCwd(cwd) {
914
+ const patterns = getWhereverConfig().sessions?.readOnly;
915
+ if (!patterns || patterns.length === 0)
916
+ return false;
917
+ return makeIgnoreMatcher(patterns)(resolveSessionCwd(cwd));
918
+ }
919
+ /**
920
+ * Group flat disk-session infos into per-cwd folders, dropping stub sessions
921
+ * with no valid creation time, and sorted newest-first. Shared by both the
922
+ * fast (listAll) and directory-aware listing paths. When `isReadOnly` is
923
+ * provided, each folder is tagged `readOnly` per its cwd.
924
+ */
925
+ buildFolders(diskSessions, isReadOnly) {
520
926
  const folderMap = new Map();
521
927
  for (const s of diskSessions) {
522
- const rawCwd = s.cwd || '';
523
- let cwd = rawCwd;
524
- if (rawCwd.startsWith('~')) {
525
- cwd = path.join(os.homedir(), rawCwd.slice(1));
928
+ // Skip incomplete/stub session files: a valid-looking `session` header
929
+ // can still be missing its `timestamp` (e.g. test stubs written as
930
+ // {"type":"session","id":"abc","cwd":"."}). Upstream tolerates a
931
+ // missing timestamp for `modified` (falls back to file mtime) but not
932
+ // for `created`, leaving it as an Invalid Date. Such a session has no
933
+ // meaningful creation time, so we drop it from the list rather than
934
+ // surfacing a bogus 1970 entry.
935
+ if (!isValidDate(s.created)) {
936
+ continue;
526
937
  }
527
- else if (!path.isAbsolute(rawCwd)) {
528
- cwd = path.join(os.homedir(), rawCwd);
529
- }
530
- cwd = normalizePath(cwd);
938
+ const cwd = resolveSessionCwd(s.cwd);
531
939
  if (!folderMap.has(cwd)) {
532
940
  folderMap.set(cwd, []);
533
941
  }
@@ -536,10 +944,12 @@ export class SessionPool {
536
944
  path: s.path,
537
945
  id: s.id,
538
946
  name: s.name,
539
- created: s.created.toISOString(),
540
- modified: s.modified.toISOString(),
947
+ created: safeToISOString(s.created),
948
+ modified: safeToISOString(s.modified),
541
949
  messageCount: s.messageCount,
542
- firstMessage: s.firstMessage,
950
+ // Capped, whitespace-collapsed PREVIEW (not the full first message): the
951
+ // dominant lever on /sessions payload size.
952
+ firstMessage: previewText(s.firstMessage),
543
953
  isActive: !!active,
544
954
  clientCount: active ? active.clients.size : 0,
545
955
  });
@@ -547,7 +957,12 @@ export class SessionPool {
547
957
  const folders = [];
548
958
  for (const [cwdPath, sessions] of folderMap.entries()) {
549
959
  const name = path.basename(cwdPath) || cwdPath;
550
- folders.push({ path: cwdPath, name, sessions: sessions.sort((a, b) => b.modified.localeCompare(a.modified)) });
960
+ folders.push({
961
+ path: cwdPath,
962
+ name,
963
+ sessions: sessions.sort((a, b) => b.modified.localeCompare(a.modified)),
964
+ readOnly: isReadOnly ? isReadOnly(cwdPath) : undefined,
965
+ });
551
966
  }
552
967
  return folders.sort((a, b) => {
553
968
  const aTime = a.sessions[0]?.modified || '';
@@ -704,6 +1119,31 @@ export class SessionPool {
704
1119
  return false;
705
1120
  return tracked.type === 'server' ? tracked.agentSession.isStreaming : tracked.isStreaming;
706
1121
  }
1122
+ /**
1123
+ * Context-window usage for a session, for the "11.3% / 1.0M" UI indicator.
1124
+ * Server sessions compute it from the live agent; CLI-bridge sessions return
1125
+ * the latest snapshot the bridge reported (the server does not run their
1126
+ * agent). Returns undefined when unknown (no model / no usage yet).
1127
+ */
1128
+ getContextUsage(sessionFileOrId) {
1129
+ const tracked = this.getSession(sessionFileOrId);
1130
+ if (!tracked)
1131
+ return undefined;
1132
+ if (tracked.type === 'server') {
1133
+ const usage = tracked.agentSession.getContextUsage();
1134
+ if (!usage)
1135
+ return undefined;
1136
+ return { tokens: usage.tokens, contextWindow: usage.contextWindow, percent: usage.percent };
1137
+ }
1138
+ return tracked.contextUsage;
1139
+ }
1140
+ /** Record a context-usage snapshot reported by a CLI bridge for its session. */
1141
+ setCliContextUsage(sessionFileOrId, usage) {
1142
+ const tracked = this.getSession(sessionFileOrId);
1143
+ if (tracked && tracked.type === 'cli') {
1144
+ tracked.contextUsage = usage;
1145
+ }
1146
+ }
707
1147
  scheduleIdleCheck(sessionFileOrId) {
708
1148
  const tracked = this.getSession(sessionFileOrId);
709
1149
  if (!tracked)
@@ -801,6 +1241,12 @@ export class SessionPool {
801
1241
  if (!result.error && result.tracked) {
802
1242
  result.tracked.clients = tracked.clients;
803
1243
  if (this.onEvent) {
1244
+ if (tracked.isStreaming) {
1245
+ this.onEvent(sessionFile, {
1246
+ type: 'session_error',
1247
+ error: 'CLI terminal disconnected. Active execution was aborted.'
1248
+ });
1249
+ }
804
1250
  this.onEvent(sessionFile, { type: 'agent_end' });
805
1251
  }
806
1252
  }
@@ -827,6 +1273,12 @@ export class SessionPool {
827
1273
  tracked.model = modelStr;
828
1274
  }
829
1275
  }
1276
+ else if (event.type === 'context_usage') {
1277
+ // The CLI bridge reports its agent's context usage (the server cannot
1278
+ // compute it for CLI sessions). Cache it so getContextUsage() can serve it
1279
+ // on join, and let it flow through onEvent for live broadcast.
1280
+ tracked.contextUsage = event.contextUsage ?? null;
1281
+ }
830
1282
  if (this.onEvent) {
831
1283
  this.onEvent(sessionFile, event);
832
1284
  }