gestalt-mobile 0.72.2 → 0.72.4

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.
@@ -16,8 +16,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later
16
16
  <link rel="icon" href="/icons/gestalt-mobile-192.png" />
17
17
  <link rel="apple-touch-icon" href="/icons/gestalt-mobile-180.png" />
18
18
  <title>Gestalt Mobile</title>
19
- <script type="module" crossorigin src="/assets/index-C--Oj-7W.js"></script>
20
- <link rel="stylesheet" crossorigin href="/assets/index-CwgSPgbi.css">
19
+ <script type="module" crossorigin src="/assets/index-BvGciLl2.js"></script>
20
+ <link rel="stylesheet" crossorigin href="/assets/index-BQD63G5z.css">
21
21
  </head>
22
22
  <body>
23
23
  <div id="app"></div>
@@ -9469,6 +9469,103 @@ describe('production composition', () => {
9469
9469
  });
9470
9470
  await third.close();
9471
9471
  }, 20000);
9472
+ it.each(['initialize', 'thread/start'])('releases a failed %s start so a new session can use the same workspace', async (failedMethod) => {
9473
+ const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
9474
+ const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-mobile-state-'));
9475
+ ownTemporaryPaths(root, dataDir);
9476
+ await mkdir(join(root, 'workspace'));
9477
+ let fail = true;
9478
+ const released = vi.fn(async () => { });
9479
+ const app = await composeAuthorizedApp({
9480
+ root,
9481
+ dataDir,
9482
+ relyingParty,
9483
+ profiles: {
9484
+ list: async () => [],
9485
+ require: async () => ({ name: 'default', state: 'ok', status: 'ready' }),
9486
+ },
9487
+ installedCodexVersion: 'codex-cli 0.167.2',
9488
+ startAppServers: true,
9489
+ launchAppServer: (options) => {
9490
+ const process = fakeAppServer([]);
9491
+ return {
9492
+ ...process,
9493
+ closeAndWait: released,
9494
+ rpc: {
9495
+ ...process.rpc,
9496
+ request: async (method, params) => {
9497
+ if (options.environment && fail && method === failedMethod) {
9498
+ fail = false;
9499
+ throw new CodexJsonRpcError(-32600, 'Invalid startup settings');
9500
+ }
9501
+ return process.rpc.request(method, params);
9502
+ },
9503
+ },
9504
+ };
9505
+ },
9506
+ });
9507
+ try {
9508
+ const workspace = (await app.inject('/api/bootstrap')).json().workspaces[0].children[0];
9509
+ const payload = { workspaceId: workspace.id, profile: 'default', provider: 'codex' };
9510
+ const failed = await app.inject({ method: 'POST', url: '/api/sessions', payload });
9511
+ expect(failed.statusCode).toBe(500);
9512
+ const db = new DatabaseSync(join(dataDir, 'relay.sqlite'));
9513
+ try {
9514
+ expect(db.prepare('SELECT state,desired_state,thread_id FROM relay_sessions').all()).toEqual([{ state: 'stopped', desired_state: 'stopped', thread_id: null }]);
9515
+ }
9516
+ finally {
9517
+ db.close();
9518
+ }
9519
+ expect(released).toHaveBeenCalled();
9520
+ const retry = await app.inject({ method: 'POST', url: '/api/sessions', payload });
9521
+ expect(retry.statusCode).toBe(202);
9522
+ expect(retry.json()).toMatchObject({ state: 'ready', threadId: 'thread-1' });
9523
+ }
9524
+ finally {
9525
+ await app.close();
9526
+ }
9527
+ });
9528
+ it.each(['starting', 'recovering'])('clears a persisted %s session without a thread when the relay restarts', async (state) => {
9529
+ const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
9530
+ const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-mobile-state-'));
9531
+ ownTemporaryPaths(root, dataDir);
9532
+ await mkdir(join(root, 'workspace'));
9533
+ const options = {
9534
+ root,
9535
+ dataDir,
9536
+ relyingParty,
9537
+ profiles: {
9538
+ list: async () => [],
9539
+ require: async () => ({ name: 'default', state: 'ok', status: 'ready' }),
9540
+ },
9541
+ installedCodexVersion: 'codex-cli 0.167.2',
9542
+ startAppServers: false,
9543
+ launchAppServer: () => fakeAppServer([]),
9544
+ };
9545
+ const first = await composeAuthorizedApp(options);
9546
+ const workspace = (await first.inject('/api/bootstrap')).json().workspaces[0].children[0];
9547
+ const payload = { workspaceId: workspace.id, profile: 'default', provider: 'codex' };
9548
+ const created = await first.inject({ method: 'POST', url: '/api/sessions', payload });
9549
+ expect(created.statusCode).toBe(202);
9550
+ await first.close();
9551
+ const db = new DatabaseSync(join(dataDir, 'relay.sqlite'));
9552
+ try {
9553
+ db.prepare('UPDATE relay_sessions SET state=? WHERE id=?').run(state, created.json().id);
9554
+ }
9555
+ finally {
9556
+ db.close();
9557
+ }
9558
+ const restarted = await composeAuthorizedApp(options);
9559
+ try {
9560
+ await restarted.listen({ host: '127.0.0.1', port: 0 });
9561
+ expect((await restarted.inject(`/api/sessions/${created.json().id}`)).json()).toMatchObject({ state: 'stopped', desiredState: 'stopped', threadId: null });
9562
+ const retry = await restarted.inject({ method: 'POST', url: '/api/sessions', payload });
9563
+ expect(retry.statusCode).toBe(202);
9564
+ }
9565
+ finally {
9566
+ await restarted.close();
9567
+ }
9568
+ });
9472
9569
  it('detaches active persisted threads when the relay restarts without resuming a writer', async () => {
9473
9570
  const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
9474
9571
  const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-mobile-state-'));
@@ -1786,9 +1786,22 @@ export async function composeRelayApp(options) {
1786
1786
  const now = new Date().toISOString();
1787
1787
  dismissPendingInteractions(session.id, now);
1788
1788
  const owner = ownerRuntime(session);
1789
- if (!owner)
1790
- throw new Error('LLM_RUNTIME_UNAVAILABLE');
1791
- return withWorkspaceAdmission(session.id, () => owner.start(session, now));
1789
+ return withWorkspaceAdmission(session.id, async () => {
1790
+ try {
1791
+ if (!owner)
1792
+ throw new Error('LLM_RUNTIME_UNAVAILABLE');
1793
+ return await owner.start(session, now);
1794
+ }
1795
+ catch (error) {
1796
+ // Publication and scratch admission precede provider startup.
1797
+ // Release its resources before allowing another workspace writer.
1798
+ await owner?.releaseForForget(session);
1799
+ const current = sessions.find(session.id);
1800
+ if (current && current.desiredState === 'active')
1801
+ saveSession(RelaySession.rehydrate(current).stop(new Date().toISOString()).snapshot);
1802
+ throw error;
1803
+ }
1804
+ });
1792
1805
  }
1793
1806
  : undefined,
1794
1807
  };
@@ -2590,9 +2603,7 @@ export async function composeRelayApp(options) {
2590
2603
  throw error;
2591
2604
  }
2592
2605
  const detachActiveSessions = async () => {
2593
- await mapWithConcurrency(sessions
2594
- .list()
2595
- .filter((session) => persistedSessionIds.has(session.id) && session.threadId !== null), 2, async (session) => {
2606
+ await mapWithConcurrency(sessions.list().filter((session) => persistedSessionIds.has(session.id)), 2, async (session) => {
2596
2607
  if (forgetOperations.find(session.id))
2597
2608
  return;
2598
2609
  // The status lease must repopulate the authoritative plan projection before
@@ -2602,6 +2613,10 @@ export async function composeRelayApp(options) {
2602
2613
  saveSession(RelaySession.rehydrate(session).stop(new Date().toISOString()).snapshot);
2603
2614
  await (session.provider === 'kimi' ? kimiRuntime : runtime)?.release(session.id);
2604
2615
  }
2616
+ // An interrupted initial start has no thread to watch or resume, but
2617
+ // its durable active reservation must still be detached on restart.
2618
+ if (session.threadId === null)
2619
+ return;
2605
2620
  await runtime?.watchPlanStatus(session);
2606
2621
  autopilot.restore(session.id);
2607
2622
  // A prior process cannot resolve its original JSON-RPC request. Turn
@@ -8,7 +8,7 @@ import { createHash } from 'node:crypto';
8
8
  import { isAbsolute, relative, resolve, sep } from 'node:path';
9
9
  import { parseSupervisedPlan } from '../../features/plans/application/parse-supervised-plan.js';
10
10
  import { OrgPlanDiscovery } from './org-plan-discovery.js';
11
- import { isArchivedOrgPlan } from './org-plan-archive-tag.js';
11
+ import { archiveOrgPlan, isArchivedOrgPlan } from './org-plan-archive-tag.js';
12
12
  const maximumBytes = 1_048_576;
13
13
  /** Cached `.gestalt` Org discovery, with bounded parallel metadata checks. */
14
14
  export class FilesystemWorkspacePlanCatalog {
@@ -51,22 +51,22 @@ export class FilesystemWorkspacePlanCatalog {
51
51
  while (next < planNames.length) {
52
52
  const index = next++;
53
53
  const name = planNames[index];
54
- let signature;
54
+ let metadata;
55
55
  try {
56
- const metadata = await this.filesystem.lstat(resolve(workspace, ...name.split('/')));
56
+ metadata = await this.filesystem.lstat(resolve(workspace, ...name.split('/')));
57
57
  if (!metadata.isFile() || metadata.isSymbolicLink())
58
58
  continue;
59
- signature = [
60
- metadata.dev,
61
- metadata.ino,
62
- metadata.size,
63
- metadata.mtimeMs,
64
- metadata.ctimeMs,
65
- ].join(':');
66
59
  }
67
60
  catch {
68
61
  continue;
69
62
  }
63
+ const signature = [
64
+ metadata.dev,
65
+ metadata.ino,
66
+ metadata.size,
67
+ metadata.mtimeMs,
68
+ metadata.ctimeMs,
69
+ ].join(':');
70
70
  const previous = cache.files.get(name);
71
71
  if (previous?.signature === signature) {
72
72
  try {
@@ -78,7 +78,7 @@ export class FilesystemWorkspacePlanCatalog {
78
78
  catch {
79
79
  continue;
80
80
  }
81
- entries[index] = previous.entry;
81
+ entries[index] = previous;
82
82
  files.set(name, previous);
83
83
  continue;
84
84
  }
@@ -86,6 +86,7 @@ export class FilesystemWorkspacePlanCatalog {
86
86
  if (candidate.kind === 'missing')
87
87
  continue;
88
88
  let entry;
89
+ let copyKey;
89
90
  if (candidate.kind === 'unavailable') {
90
91
  entry = toFallbackEntry(name);
91
92
  }
@@ -101,13 +102,21 @@ export class FilesystemWorkspacePlanCatalog {
101
102
  : toFallbackEntry(name, candidate.source);
102
103
  if (isArchivedOrgPlan(candidate.source))
103
104
  entry = { ...entry, archived: true };
104
- files.set(name, { signature, entry });
105
+ copyKey = catalogCopyKey(name, candidate.source);
105
106
  }
106
- entries[index] = entry;
107
+ const file = {
108
+ signature,
109
+ entry,
110
+ sortDate: catalogDate(entry.date, metadata.mtimeMs),
111
+ copyKey,
112
+ };
113
+ if (candidate.kind === 'readable')
114
+ files.set(name, file);
115
+ entries[index] = file;
107
116
  }
108
117
  }));
109
118
  cache.files = files;
110
- cache.entries = entries.filter((entry) => entry !== null);
119
+ cache.entries = orderCatalog(entries);
111
120
  cache.refreshedAt = this.now();
112
121
  return cache.entries;
113
122
  }
@@ -256,18 +265,59 @@ function toEntry(planName, plan) {
256
265
  };
257
266
  }
258
267
  function toFallbackEntry(planName, source) {
268
+ const date = orgHeader('DATE', source);
259
269
  return {
260
270
  planName,
261
271
  title: fallbackTitle(planName, source),
272
+ ...(date === undefined ? {} : { date }),
262
273
  previewAvailable: false,
263
274
  };
264
275
  }
265
- function fallbackTitle(planName, source) {
266
- const declaredTitle = source
276
+ function orgHeader(key, source) {
277
+ const pattern = new RegExp(`^#\\+${key}:(?:[ \\t](.*))?$`, 'i');
278
+ return source
267
279
  ?.replace(/\r\n?/g, '\n')
268
280
  .split('\n')
269
- .map((line) => /^#\+TITLE:(?:[ \t](.*))?$/i.exec(line)?.[1]?.trim())
270
- .find((title) => title);
281
+ .map((line) => pattern.exec(line)?.[1]?.trim())
282
+ .find((value) => value);
283
+ }
284
+ function fallbackTitle(planName, source) {
271
285
  const filename = planName.split('/').at(-1) ?? planName;
272
- return declaredTitle ?? filename.slice(0, -'.org'.length);
286
+ return orgHeader('TITLE', source) ?? filename.slice(0, -'.org'.length);
287
+ }
288
+ function catalogCopyKey(planName, source) {
289
+ const parts = planName.split('/');
290
+ const owner = parts.slice(0, parts.indexOf('.gestalt')).join('/');
291
+ // A copied plan stays collapsed after archiving the selected original.
292
+ const digest = createHash('sha256').update(archiveOrgPlan(source)).digest('hex');
293
+ return JSON.stringify([owner, parts.at(-1), digest]);
294
+ }
295
+ function catalogDate(date, modifiedAt) {
296
+ const day = /^(?:<|\[)?(\d{4}-\d{2}-\d{2})(?=$|[T \t>\]])/.exec(date ?? '')?.[1];
297
+ if (!day)
298
+ return modifiedAt;
299
+ const parsed = new Date(`${day}T00:00:00Z`);
300
+ return parsed.toJSON()?.startsWith(day) ? parsed.getTime() : modifiedAt;
301
+ }
302
+ function orderCatalog(entries) {
303
+ const unique = new Map();
304
+ for (const file of entries) {
305
+ if (!file)
306
+ continue;
307
+ const key = file.copyKey ?? file.entry.planName;
308
+ const previous = unique.get(key);
309
+ if (!previous ||
310
+ file.entry.planName.split('/').length < previous.entry.planName.split('/').length)
311
+ unique.set(key, file);
312
+ }
313
+ const completed = (entry) => Boolean(entry.allDone || entry.archived);
314
+ return [...unique.values()]
315
+ .sort((left, right) => {
316
+ const leftDone = completed(left.entry);
317
+ const rightDone = completed(right.entry);
318
+ return (Number(leftDone) - Number(rightDone) ||
319
+ (leftDone ? 0 : right.sortDate - left.sortDate) ||
320
+ left.entry.planName.localeCompare(right.entry.planName));
321
+ })
322
+ .map(({ entry }) => entry);
273
323
  }
@@ -34,7 +34,34 @@ export class OrgPlanDiscovery {
34
34
  this.execute = execute;
35
35
  }
36
36
  async list(workspace) {
37
- const args = ['.', '-type', 'f', '-name', '*.org', '-path', '*/.gestalt/*', '-print0'];
37
+ // Mark checkout roots without walking their Git metadata. A repository under
38
+ // a .gestalt directory is an internal checkout, not another project to list.
39
+ const args = [
40
+ '.',
41
+ '-name',
42
+ '.git',
43
+ '-print0',
44
+ '-prune',
45
+ '-o',
46
+ '-type',
47
+ 'd',
48
+ '(',
49
+ '-path',
50
+ '*/tmp/sessions',
51
+ '-o',
52
+ '-path',
53
+ '*/.gestalt/evidence',
54
+ ')',
55
+ '-prune',
56
+ '-o',
57
+ '-type',
58
+ 'f',
59
+ '-name',
60
+ '*.org',
61
+ '-path',
62
+ '*/.gestalt/*',
63
+ '-print0',
64
+ ];
38
65
  let output;
39
66
  try {
40
67
  output = await this.execute(this.command, args, workspace);
@@ -45,11 +72,23 @@ export class OrgPlanDiscovery {
45
72
  this.command = 'find';
46
73
  output = await this.execute('find', args, workspace);
47
74
  }
48
- return [
75
+ const paths = [
49
76
  ...new Set(output
50
77
  .split('\0')
51
78
  .filter(Boolean)
52
79
  .map((path) => path.replace(/^\.\//, ''))),
53
80
  ];
81
+ const internalCheckouts = new Set(paths
82
+ .filter((path) => path.endsWith('/.git') && path.split('/').slice(0, -2).includes('.gestalt'))
83
+ .map((path) => path.slice(0, -'/.git'.length)));
84
+ return paths.filter((path) => {
85
+ if (!path.endsWith('.org'))
86
+ return false;
87
+ for (let end = path.lastIndexOf('/'); end > 0; end = path.lastIndexOf('/', end - 1)) {
88
+ if (internalCheckouts.has(path.slice(0, end)))
89
+ return false;
90
+ }
91
+ return true;
92
+ });
54
93
  }
55
94
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.72.2",
3
+ "version": "0.72.4",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",