gestalt-mobile 0.72.5 → 0.72.7

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-BbeZkUkt.js"></script>
20
- <link rel="stylesheet" crossorigin href="/assets/index-BQD63G5z.css">
19
+ <script type="module" crossorigin src="/assets/index-DOhG_AXn.js"></script>
20
+ <link rel="stylesheet" crossorigin href="/assets/index-BsZAXyTF.css">
21
21
  </head>
22
22
  <body>
23
23
  <div id="app"></div>
@@ -4,7 +4,6 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { z } from 'zod';
7
- import { CLEAN_TMP_FAILED_FOLDER_LIMIT, } from '../../../../shared/contracts/tmp-cleanup.js';
8
7
  import { problem } from '../../../platform/http/problem.js';
9
8
  const requestSchema = z.object({}).strict();
10
9
  const counter = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
@@ -35,7 +34,6 @@ const responseSchema = z.object({
35
34
  .max(200)
36
35
  .regex(/^tmp\/sessions\/(?:\.cleanup-)?[a-z0-9-]+$/),
37
36
  }))
38
- .max(CLEAN_TMP_FAILED_FOLDER_LIMIT)
39
37
  .optional(),
40
38
  });
41
39
  export function registerCleanTmp(app, cleanup) {
@@ -3,7 +3,6 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- import { CLEAN_TMP_FAILED_FOLDER_LIMIT, } from '../../../../shared/contracts/tmp-cleanup.js';
7
6
  export function emptyScratchCounts() {
8
7
  return {
9
8
  removed: 0,
@@ -62,10 +61,8 @@ export class CleanSessionScratch {
62
61
  result.workspaces.removed++;
63
62
  result.folders.skipped += counts.skipped;
64
63
  result.folders.failed += counts.failed;
65
- if (counts.failedFolders?.length) {
66
- const details = (result.folders.failedFolders ??= []);
67
- details.push(...counts.failedFolders.slice(0, CLEAN_TMP_FAILED_FOLDER_LIMIT - details.length));
68
- }
64
+ for (const folder of counts.failedFolders ?? [])
65
+ (result.folders.failedFolders ??= []).push(folder);
69
66
  for (const reason of Object.keys(counts.reasons))
70
67
  result.folders.reasons[reason] += counts.reasons[reason];
71
68
  result.workspaces[counts.failed ? 'failed' : counts.skipped ? 'skipped' : 'cleaned']++;
@@ -3,7 +3,15 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
+ import { isForgetCleanupFolder, } from '../../../../shared/contracts/session-forget.js';
6
7
  import { WorkspaceSessionConflict } from '../application/workspace-conflict.js';
8
+ export class WorkspaceCleanupFailure extends Error {
9
+ folders;
10
+ constructor(folders, cause) {
11
+ super('SESSION_CLEANUP_FAILED', { cause });
12
+ this.folders = folders;
13
+ }
14
+ }
7
15
  export class ForgetSession {
8
16
  deps;
9
17
  pending = new Map();
@@ -59,7 +67,10 @@ export class ForgetSession {
59
67
  const cleanup = await this.deps.clean(session, operation.operationId);
60
68
  if (cleanup && typeof cleanup === 'object')
61
69
  releaseCleanup = () => cleanup.release();
62
- operation = { ...operation, scratchRetained: cleanup === 'retained' ? true : undefined };
70
+ operation = {
71
+ ...operation,
72
+ scratchRetained: cleanup === 'retained' ? true : cleanup?.scratchRetained,
73
+ };
63
74
  failureCode = 'SESSION_FORGET_FAILED';
64
75
  if (advance('finalizing').phase === 'completed')
65
76
  return operation;
@@ -68,6 +79,9 @@ export class ForgetSession {
68
79
  return operation;
69
80
  }
70
81
  catch (error) {
82
+ const cleanupFolders = failureCode === 'SESSION_CLEANUP_FAILED' && error instanceof WorkspaceCleanupFailure
83
+ ? error.folders.filter(isForgetCleanupFolder)
84
+ : [];
71
85
  operation = this.deps.operations.update({
72
86
  ...operation,
73
87
  phase: 'failed',
@@ -76,6 +90,7 @@ export class ForgetSession {
76
90
  ...(error instanceof WorkspaceSessionConflict
77
91
  ? { blockingSessionId: error.sessionId }
78
92
  : {}),
93
+ ...(cleanupFolders.length ? { cleanupFolders } : {}),
79
94
  });
80
95
  this.deps.changed(operation);
81
96
  return operation;
@@ -66,6 +66,8 @@ export function migrate(database) {
66
66
  );`);
67
67
  if (!forgetColumns.some((column) => column.name === 'blocking_session_id'))
68
68
  database.exec('ALTER TABLE session_forget_operations ADD COLUMN blocking_session_id TEXT');
69
+ if (!forgetColumns.some((column) => column.name === 'cleanup_folders_json'))
70
+ database.exec('ALTER TABLE session_forget_operations ADD COLUMN cleanup_folders_json TEXT CHECK(cleanup_folders_json IS NULL OR json_valid(cleanup_folders_json))');
69
71
  const workspaceLockColumns = database
70
72
  .prepare('PRAGMA table_info(workspace_forget_locks)')
71
73
  .all();
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { randomUUID } from 'node:crypto';
7
+ import { isForgetCleanupFolder, } from '../../../shared/contracts/session-forget.js';
7
8
  import { canonicalSessionWorkspace } from './sqlite-workspace-lifecycle.js';
8
9
  import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
9
10
  export class SqliteForgetOperationStore {
@@ -15,6 +16,10 @@ export class SqliteForgetOperationStore {
15
16
  const row = this.db
16
17
  .prepare('SELECT * FROM session_forget_operations WHERE session_id = ?')
17
18
  .get(id);
19
+ const folders = row?.cleanup_folders_json
20
+ ? JSON.parse(row.cleanup_folders_json)
21
+ : null;
22
+ const cleanupFolders = Array.isArray(folders) ? folders.filter(isForgetCleanupFolder) : [];
18
23
  return row
19
24
  ? {
20
25
  operationId: row.operation_id,
@@ -24,6 +29,7 @@ export class SqliteForgetOperationStore {
24
29
  ...(row.failure_code ? { failureCode: row.failure_code } : {}),
25
30
  ...(row.scratch_retained ? { scratchRetained: true } : {}),
26
31
  ...(row.blocking_session_id ? { blockingSessionId: row.blocking_session_id } : {}),
32
+ ...(cleanupFolders.length ? { cleanupFolders } : {}),
27
33
  }
28
34
  : null;
29
35
  }
@@ -71,9 +77,9 @@ export class SqliteForgetOperationStore {
71
77
  }
72
78
  update(operation) {
73
79
  this.db
74
- .prepare(`UPDATE session_forget_operations SET phase = ?, updated_at = ?, failure_code = ?, scratch_retained = ?, blocking_session_id = ?
80
+ .prepare(`UPDATE session_forget_operations SET phase = ?, updated_at = ?, failure_code = ?, scratch_retained = ?, blocking_session_id = ?, cleanup_folders_json = ?
75
81
  WHERE session_id = ? AND operation_id = ? AND phase != 'completed'`)
76
- .run(operation.phase, operation.updatedAt, operation.failureCode ?? null, operation.scratchRetained ? 1 : 0, operation.blockingSessionId ?? null, operation.sessionId, operation.operationId);
82
+ .run(operation.phase, operation.updatedAt, operation.failureCode ?? null, operation.scratchRetained ? 1 : 0, operation.blockingSessionId ?? null, operation.cleanupFolders?.length ? JSON.stringify(operation.cleanupFolders) : null, operation.sessionId, operation.operationId);
77
83
  return this.find(operation.sessionId);
78
84
  }
79
85
  finalize(operation) {
@@ -6,7 +6,6 @@
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { lstat, mkdir, open, readdir, realpath, rename, rm, rmdir } from 'node:fs/promises';
8
8
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
- import { CLEAN_TMP_FAILED_FOLDER_LIMIT } from '../../../shared/contracts/tmp-cleanup.js';
10
9
  import { emptyScratchCounts, } from '../../features/sessions/clean-tmp/use-case.js';
11
10
  import { mobileScratchOwnerId, privateDirectory, scratchMarkerName } from './scratch-filesystem.js';
12
11
  import { claimOwnerFence } from './owner-fence.js';
@@ -54,7 +53,10 @@ export class FilesystemScratchCleanup {
54
53
  }
55
54
  async cleanWorkspace(workspacePath, protectedSessions, onlyOwnerId, authorized, authorizedSessionId, inherited) {
56
55
  await this.canonicalWorkspace(workspacePath);
57
- const counts = emptyScratchCounts();
56
+ const counts = {
57
+ ...emptyScratchCounts(),
58
+ leasedMobileSessions: [],
59
+ };
58
60
  const workspaceName = basename(workspacePath) || 'root workspace';
59
61
  const temporary = join(workspacePath, 'tmp');
60
62
  try {
@@ -110,19 +112,35 @@ export class FilesystemScratchCleanup {
110
112
  const marker = await readManagedScratchOwner(directory, workspacePath, ownerId);
111
113
  await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
112
114
  (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
113
- await this.releasedLeases(directory, marker);
115
+ if ((await readdir(directory)).includes('.association-lock'))
116
+ reject('busy');
117
+ const leases = await readManagedScratchLeases(directory, marker);
118
+ if (leases.some((lease) => lease.state !== 'released' || lease.consumers.length !== 0)) {
119
+ if (authorized && marker.ownerKind === 'mobile-session') {
120
+ if (marker.runtime)
121
+ await validateRuntime(marker, marker.runtime, true);
122
+ counts.leasedMobileSessions.push({
123
+ sessionId: marker.sessionId,
124
+ runtimeDirectory: marker.runtime?.directory,
125
+ });
126
+ }
127
+ reject('lease');
128
+ }
114
129
  if (authorized) {
115
130
  await this.retireNestedNamespaces(directory, protectedSessions, authorized, authorizedSessionId, containment);
116
131
  if (marker.runtime && (await validateRuntime(marker, marker.runtime, true)))
117
132
  await this.retireNestedNamespaces(marker.runtime.directory, protectedSessions, authorized, authorizedSessionId, containment);
118
133
  }
119
- await this.validatePayload(directory);
134
+ // Manual Clean Tmp bounds opportunistic inspection. Explicit Forget
135
+ // has to finish checking large owners before retiring the session.
136
+ const inspectionBudget = () => (authorized ? undefined : { entries: 0 });
137
+ await this.validatePayload(directory, inspectionBudget());
120
138
  if (marker.runtime) {
121
139
  const present = await validateRuntime(marker, marker.runtime, true);
122
140
  if (present) {
123
141
  await this.assertProtection(directory, join(container, ownerId), marker, protectedSessions, authorized, onlyOwnerId ??
124
142
  (authorizedSessionId ? mobileScratchOwnerId(authorizedSessionId) : undefined));
125
- await this.validatePayload(marker.runtime.directory);
143
+ await this.validatePayload(marker.runtime.directory, inspectionBudget());
126
144
  }
127
145
  }
128
146
  await privateDirectory(directory, false);
@@ -219,8 +237,8 @@ export class FilesystemScratchCleanup {
219
237
  counts.reasons.io++;
220
238
  }
221
239
  }
222
- if (outcome === 'failed' &&
223
- (counts.failedFolders?.length ?? 0) < CLEAN_TMP_FAILED_FOLDER_LIMIT &&
240
+ if ((outcome === 'failed' ||
241
+ (outcome === 'skipped' && authorized && managedScratchOwnerId(name))) &&
224
242
  !/[\\/\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(workspaceName)) {
225
243
  (counts.failedFolders ??= []).push({
226
244
  workspaceName,
@@ -231,16 +249,9 @@ export class FilesystemScratchCleanup {
231
249
  }
232
250
  return counts;
233
251
  }
234
- async releasedLeases(directory, marker) {
235
- if ((await readdir(directory)).includes('.association-lock'))
236
- reject('busy');
237
- const leases = await readManagedScratchLeases(directory, marker);
238
- if (leases.some((lease) => lease.state !== 'released' || lease.consumers.length !== 0))
239
- reject('lease');
240
- }
241
252
  /** Final workspace authority can retire positively attributed nested namespaces,
242
253
  * but every nested roster, lease, inode and fence still has to pass its gate. */
243
- async retireNestedNamespaces(directory, protectedSessions, authorized, authorizedSessionId, inherited, skipContainer = false, depth = 0, budget = { entries: 0 }) {
254
+ async retireNestedNamespaces(directory, protectedSessions, authorized, authorizedSessionId, inherited, skipContainer = false, depth = 0) {
244
255
  if (depth > 128 || !authorized())
245
256
  reject('protected');
246
257
  let entries;
@@ -253,8 +264,6 @@ export class FilesystemScratchCleanup {
253
264
  throw error;
254
265
  }
255
266
  for (const entry of entries) {
256
- if (++budget.entries > 100000)
257
- reject('unrecognized');
258
267
  const name = entry.name.toString();
259
268
  if (skipContainer && name === 'sessions')
260
269
  continue;
@@ -285,7 +294,7 @@ export class FilesystemScratchCleanup {
285
294
  throw error;
286
295
  }
287
296
  }
288
- await this.retireNestedNamespaces(path, protectedSessions, authorized, authorizedSessionId, inherited, name === 'tmp', depth + 1, budget);
297
+ await this.retireNestedNamespaces(path, protectedSessions, authorized, authorizedSessionId, inherited, name === 'tmp', depth + 1);
289
298
  }
290
299
  }
291
300
  async retireRuntime(directory, marker) {
@@ -360,7 +369,7 @@ export class FilesystemScratchCleanup {
360
369
  }
361
370
  }
362
371
  }
363
- async validatePayload(directory, root = directory, depth = 0, budget = { entries: 0 }) {
372
+ async validatePayload(directory, budget, root = directory, depth = 0) {
364
373
  if (depth > 128)
365
374
  reject('unrecognized');
366
375
  // Even an empty nested namespace is not authority to retire a workspace's
@@ -371,10 +380,10 @@ export class FilesystemScratchCleanup {
371
380
  reject('unrecognized');
372
381
  for (const entry of await readdir(directory, { encoding: 'buffer', withFileTypes: true })) {
373
382
  const child = entry.name;
383
+ if (budget && ++budget.entries > 100_000)
384
+ reject('unrecognized');
374
385
  if (child.toString() === workspacePublicationName)
375
386
  reject('busy');
376
- if (++budget.entries > 100_000)
377
- reject('unrecognized');
378
387
  if (directory !== root &&
379
388
  [
380
389
  scratchMarkerName,
@@ -394,7 +403,7 @@ export class FilesystemScratchCleanup {
394
403
  // lstat never follows them, and rm unlinks them without deleting their targets.
395
404
  // Owner paths and authority metadata retain their separate no-link checks.
396
405
  if (info.isDirectory())
397
- await this.validatePayload(path, root, depth + 1, budget);
406
+ await this.validatePayload(path, budget, root, depth + 1);
398
407
  }
399
408
  }
400
409
  }
@@ -7,6 +7,7 @@ import { lstatSync, mkdirSync, realpathSync, renameSync } from 'node:fs';
7
7
  import { lstat, readdir, rm } from 'node:fs/promises';
8
8
  import { join } from 'node:path';
9
9
  import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
10
+ import { WorkspaceCleanupFailure, } from '../../features/sessions/forget-session/use-case.js';
10
11
  import { canonicalSessionWorkspace, workspaceContains, } from '../persistence/sqlite-workspace-lifecycle.js';
11
12
  import { FilesystemScratchCleanup } from './filesystem-scratch-cleanup.js';
12
13
  import { claimWorkspacePublication } from './workspace-publication.js';
@@ -39,19 +40,37 @@ export class FilesystemWorkspaceForget {
39
40
  // Keep the physical publication fence through durable finalization. It is
40
41
  // outside tmp, so a retiring namespace cannot hide it from new publishers.
41
42
  const release = await claimWorkspacePublication(workspace);
43
+ let cleanupFolders = ['tmp'];
42
44
  try {
43
45
  const cleanup = new FilesystemScratchCleanup();
44
46
  await cleanup.retireNestedNamespaces(temporary, knownSessions, authorized, session.id, undefined, true);
45
47
  const counts = await cleanup.cleanWorkspace(workspace, knownSessions, undefined, authorized, session.id);
46
- if (counts.skipped || counts.failed)
48
+ if (counts.skipped || counts.failed) {
49
+ if (counts.failedFolders?.length)
50
+ cleanupFolders = counts.failedFolders.map(({ relativePath }) => relativePath);
51
+ // An earlier completed Forget may have left a borrower in this workspace.
52
+ // Its release is independent of the last session. Keep tmp in place.
53
+ if (!counts.failed &&
54
+ counts.leasedMobileSessions.length === counts.skipped &&
55
+ counts.leasedMobileSessions.every(({ sessionId }) => this.previouslyRetained(sessionId))) {
56
+ const retained = new Set(counts.leasedMobileSessions.flatMap(({ runtimeDirectory }) => runtimeDirectory ?? []));
57
+ if ((!process.getuid || !(await hasRuntimeOwner({ workspacePath: workspace }, retained))) &&
58
+ authorized())
59
+ return { release, scratchRetained: true };
60
+ }
47
61
  throw new Error('SESSION_CLEANUP_FAILED');
62
+ }
63
+ cleanupFolders = [];
48
64
  if (process.getuid && (await hasRuntimeOwner({ workspacePath: workspace })))
49
65
  throw new Error('SESSION_CLEANUP_FAILED');
66
+ cleanupFolders = ['tmp'];
50
67
  const retired = this.retire(session, operationId, workspace, temporary, authorized);
51
68
  if (retired) {
69
+ cleanupFolders = [`.gestalt/forgotten-tmp/${operationId}`];
52
70
  await this.assertRetired(retired);
53
71
  await rm(retired, { recursive: true, force: true, maxRetries: 3 });
54
72
  }
73
+ cleanupFolders = ['tmp'];
55
74
  // A non-cooperating external publisher must not turn retained files into a
56
75
  // successful final Forget. New Mobile starts remain durably fenced.
57
76
  try {
@@ -66,10 +85,17 @@ export class FilesystemWorkspaceForget {
66
85
  }
67
86
  catch (error) {
68
87
  await release();
88
+ if (cleanupFolders.length)
89
+ throw new WorkspaceCleanupFailure(cleanupFolders, error);
69
90
  throw error;
70
91
  }
71
92
  }
72
- async assertRetired(directory, depth = 0, budget = { entries: 0 }) {
93
+ previouslyRetained(id) {
94
+ return !!this.db
95
+ .prepare("SELECT 1 FROM session_forget_operations WHERE session_id=? AND phase='completed' AND scratch_retained=1")
96
+ .get(id);
97
+ }
98
+ async assertRetired(directory, depth = 0) {
73
99
  if (depth > 128)
74
100
  throw new Error('SESSION_CLEANUP_FAILED');
75
101
  let entries;
@@ -82,17 +108,16 @@ export class FilesystemWorkspaceForget {
82
108
  throw error;
83
109
  }
84
110
  for (const entry of entries) {
85
- if (++budget.entries > 100000 ||
86
- [
87
- '.gestalt-owner.json',
88
- '.gestalt-runtime.json',
89
- '.controller-lock',
90
- '.containment-lock',
91
- '.gestalt-scratch-lock',
92
- ].includes(entry.name.toString()))
111
+ if ([
112
+ '.gestalt-owner.json',
113
+ '.gestalt-runtime.json',
114
+ '.controller-lock',
115
+ '.containment-lock',
116
+ '.gestalt-scratch-lock',
117
+ ].includes(entry.name.toString()))
93
118
  throw new Error('SESSION_CLEANUP_FAILED');
94
119
  if (entry.isDirectory() && !entry.isSymbolicLink())
95
- await this.assertRetired(Buffer.concat([Buffer.from(directory), Buffer.from('/'), entry.name]), depth + 1, budget);
120
+ await this.assertRetired(Buffer.concat([Buffer.from(directory), Buffer.from('/'), entry.name]), depth + 1);
96
121
  }
97
122
  }
98
123
  retire(session, operationId, workspace, temporary, authorized) {
@@ -106,7 +106,7 @@ export async function validateRuntime(owner, runtime, allowRetiring = false) {
106
106
  return true;
107
107
  }
108
108
  /** A missing workspace does not authorize abandoning an external payload root. */
109
- export async function hasRuntimeOwner(owner) {
109
+ export async function hasRuntimeOwner(owner, retainedDirectories) {
110
110
  const container = await runtimeContainer();
111
111
  try {
112
112
  await privateDirectory(container, false);
@@ -126,6 +126,7 @@ export async function hasRuntimeOwner(owner) {
126
126
  await privateDirectory(join(container, name), false);
127
127
  const record = (await readMarker(join(container, name, runtimeMarkerName)));
128
128
  if (record.workspacePath === owner.workspacePath &&
129
+ !retainedDirectories?.has(join(container, name)) &&
129
130
  (owner.ownerId === undefined || record.ownerId === owner.ownerId))
130
131
  return true;
131
132
  }
@@ -3,4 +3,8 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- export {};
6
+ export function isForgetCleanupFolder(value) {
7
+ return (typeof value === 'string' &&
8
+ value.length <= 200 &&
9
+ /^(?:tmp(?:\/sessions(?:\/(?:\.cleanup-)?[a-z0-9-]+)?)?|\.gestalt\/forgotten-tmp\/[0-9a-f-]{36})$/.test(value));
10
+ }
@@ -3,4 +3,4 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- export const CLEAN_TMP_FAILED_FOLDER_LIMIT = 3;
6
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.72.5",
3
+ "version": "0.72.7",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",