@myrialabs/clopen 0.4.40 → 0.4.42

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 (141) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +6 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +50 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/index.ts +18 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
  20. package/backend/database/migrations/082_create_git_identities.ts +122 -0
  21. package/backend/database/migrations/index.ts +28 -0
  22. package/backend/database/queries/file-share-queries.ts +163 -0
  23. package/backend/database/queries/git-identity-queries.ts +290 -0
  24. package/backend/database/queries/index.ts +8 -4
  25. package/backend/database/queries/profile-queries.ts +5 -3
  26. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  27. package/backend/database/queries/push-subscription-queries.ts +99 -0
  28. package/backend/database/queries/skill-queries.ts +96 -18
  29. package/backend/engine/adapters/claude/environment.ts +11 -1
  30. package/backend/engine/adapters/claude/stream.ts +3 -2
  31. package/backend/engine/adapters/cline/stream.ts +3 -3
  32. package/backend/engine/adapters/codex/stream.ts +38 -6
  33. package/backend/engine/adapters/copilot/stream.ts +3 -3
  34. package/backend/engine/adapters/cursor/stream.ts +25 -3
  35. package/backend/engine/adapters/opencode/server.ts +26 -2
  36. package/backend/engine/adapters/opencode/stream.ts +8 -7
  37. package/backend/engine/adapters/pi/stream.ts +2 -2
  38. package/backend/engine/adapters/qwen/stream.ts +5 -3
  39. package/backend/engine/artifact-sync.ts +26 -20
  40. package/backend/engine/docs/artifacts.md +81 -22
  41. package/backend/engine/docs/quick-reference.md +2 -1
  42. package/backend/engine/resolve-model.test.ts +108 -0
  43. package/backend/engine/resolve-model.ts +53 -10
  44. package/backend/engine/structured-helpers.ts +22 -0
  45. package/backend/engine/types.ts +10 -0
  46. package/backend/files/file-shares.ts +369 -0
  47. package/backend/files/path-browsing.ts +27 -21
  48. package/backend/git/git-executor.ts +28 -2
  49. package/backend/git/git-service.ts +59 -40
  50. package/backend/git/identity/cli.test.ts +58 -0
  51. package/backend/git/identity/cli.ts +201 -0
  52. package/backend/git/identity/credential-helper.test.ts +242 -0
  53. package/backend/git/identity/env.test.ts +214 -0
  54. package/backend/git/identity/env.ts +193 -0
  55. package/backend/git/identity/import-local.test.ts +199 -0
  56. package/backend/git/identity/import-local.ts +141 -0
  57. package/backend/git/identity/index.ts +78 -0
  58. package/backend/git/identity/keys.ts +183 -0
  59. package/backend/git/identity/resolve.ts +140 -0
  60. package/backend/git/identity/scope-config.test.ts +145 -0
  61. package/backend/git/identity/scope-config.ts +175 -0
  62. package/backend/git/identity/service.ts +297 -0
  63. package/backend/http/files-shared.test.ts +505 -0
  64. package/backend/http/files-shared.ts +351 -0
  65. package/backend/http/push.ts +150 -0
  66. package/backend/index.ts +24 -0
  67. package/backend/instructions/index.ts +1 -1
  68. package/backend/instructions/sync.ts +30 -6
  69. package/backend/memory/compose.ts +2 -2
  70. package/backend/memory/consolidate.ts +2 -2
  71. package/backend/memory/extract/episodic.ts +2 -2
  72. package/backend/memory/judge.ts +2 -2
  73. package/backend/preview/browser/browser-console-manager.ts +214 -34
  74. package/backend/preview/browser/browser-pool.ts +526 -123
  75. package/backend/preview/browser/browser-preview-service.ts +192 -8
  76. package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
  77. package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
  78. package/backend/preview/browser/browser-tab-manager.ts +291 -65
  79. package/backend/preview/browser/capture-profile.ts +15 -1
  80. package/backend/preview/browser/types.ts +26 -1
  81. package/backend/profiles/service.ts +7 -6
  82. package/backend/push/sender.ts +172 -0
  83. package/backend/push/tags.ts +25 -0
  84. package/backend/push/vapid-keys.ts +77 -0
  85. package/backend/push/webpush-crypto.test.ts +200 -0
  86. package/backend/push/webpush-crypto.ts +231 -0
  87. package/backend/skills/detect.ts +28 -0
  88. package/backend/skills/index.ts +22 -4
  89. package/backend/skills/invoke.test.ts +114 -0
  90. package/backend/skills/invoke.ts +222 -0
  91. package/backend/skills/service.ts +194 -44
  92. package/backend/skills/spec.ts +35 -0
  93. package/backend/skills/sync.ts +85 -55
  94. package/backend/subagents/detect.ts +2 -3
  95. package/backend/subagents/sync.ts +15 -8
  96. package/backend/terminal/ptykit.ts +24 -0
  97. package/backend/work/pull-requests.ts +2 -2
  98. package/backend/ws/chat/stream.ts +100 -8
  99. package/backend/ws/files/index.ts +4 -0
  100. package/backend/ws/files/share.ts +95 -0
  101. package/backend/ws/git/branch-name.ts +2 -2
  102. package/backend/ws/git/branch.ts +17 -6
  103. package/backend/ws/git/commit-message.ts +2 -2
  104. package/backend/ws/git/commit.ts +6 -5
  105. package/backend/ws/git/conflict.ts +3 -2
  106. package/backend/ws/git/identity-context.ts +91 -0
  107. package/backend/ws/git/identity.ts +200 -0
  108. package/backend/ws/git/index.ts +3 -1
  109. package/backend/ws/git/remote.ts +57 -11
  110. package/backend/ws/index.ts +3 -4
  111. package/backend/ws/preview/browser/data.ts +60 -0
  112. package/backend/ws/preview/browser/interact.ts +6 -0
  113. package/backend/ws/preview/browser/tab-info.ts +9 -1
  114. package/backend/ws/preview/browser/tab.ts +64 -8
  115. package/backend/ws/preview/index.ts +21 -0
  116. package/backend/ws/profiles/crud.ts +2 -3
  117. package/backend/ws/skills/catalog.ts +5 -1
  118. package/backend/ws/skills/crud.ts +128 -22
  119. package/backend/ws/skills/index.ts +4 -1
  120. package/backend/ws/user/crud.ts +12 -3
  121. package/bin/clopen.ts +9 -0
  122. package/dist/assets/{index-D4igjF6e.js → index-BynqyvF4.js} +1 -1
  123. package/dist/assets/{index-DONNwiXm.js → index-DLoJsmNQ.js} +1 -1
  124. package/dist/assets/{main-BrfXH1bL.js → main-CUyZAmqt.js} +601 -592
  125. package/dist/assets/main-DVCW3cfr.css +1 -0
  126. package/dist/index.html +7 -2
  127. package/dist/sw.js +112 -0
  128. package/package.json +2 -2
  129. package/shared/constants/engine-tools.ts +31 -6
  130. package/shared/constants/notification-messages.ts +142 -0
  131. package/shared/types/git-identity.ts +112 -0
  132. package/shared/types/unified/stream.ts +7 -0
  133. package/backend/commands/detect.ts +0 -25
  134. package/backend/commands/index.ts +0 -9
  135. package/backend/commands/service.ts +0 -178
  136. package/backend/commands/store.ts +0 -45
  137. package/backend/commands/sync.ts +0 -94
  138. package/backend/database/queries/command-queries.ts +0 -82
  139. package/backend/ws/commands/crud.ts +0 -157
  140. package/backend/ws/commands/index.ts +0 -8
  141. package/dist/assets/main-CT1PygsW.css +0 -1
@@ -0,0 +1,369 @@
1
+ /**
2
+ * Shareable single-file links ("Share Link…" in the File Explorer).
3
+ *
4
+ * A share token grants bearer access to exactly ONE file via the public route
5
+ * `GET /api/files/shared?share=<token>` — no session, no login on the
6
+ * receiving device. The link is built against the same public origin Remote
7
+ * Access resolves (`share:ensure-origin`: configured domain, current origin,
8
+ * or a Cloudflare quick tunnel), so no new reachability system is needed.
9
+ *
10
+ * The creator picks two things per link, and the defaults are the strict ones:
11
+ * - one-time (default) or reusable until it lapses;
12
+ * - a short deadline (default {@link DEFAULT_FILE_SHARE_TTL_MINUTES} minutes),
13
+ * a longer one, or none at all — a link only a revoke can end.
14
+ *
15
+ * Security model (mirrors the invite/device-code flows):
16
+ * - Only the raw token's SHA-256 hash is kept; the raw token is returned once,
17
+ * at creation time, and is embedded in the shared URL.
18
+ * - Tokens live in SQLite (`file_shares`, migration 080) like device codes, so
19
+ * a restart does not silently kill links a user already handed out.
20
+ * - Creation reuses the exact project-scoped path check the download route
21
+ * uses (`requireFilePathAccessFor`), so a user can only share files they
22
+ * could download themselves. Directories are rejected.
23
+ * - That same check is re-run on every open: if the creator loses access to
24
+ * the path (removed from the project, project deleted, account deleted),
25
+ * every link they minted for it stops serving immediately.
26
+ * - Links are single-file bound: the HTTP route resolves the path from the
27
+ * token and ignores any caller-supplied path, so a link can never be
28
+ * retargeted at another file.
29
+ * - A one-time link fails closed after its first open; a reusable one fails
30
+ * closed at its deadline, or when revoked.
31
+ * - Management (list, revoke) is keyed by the row id, never by the token: the
32
+ * raw token only ever exists in the browser that minted it, so a revoke
33
+ * keyed on the secret would die with that view.
34
+ */
35
+
36
+ import { stat } from 'node:fs/promises';
37
+ import { basename, relative, isAbsolute, sep } from 'node:path';
38
+
39
+ import { debug } from '$shared/utils/logger';
40
+ import { authQueries, fileShareQueries } from '../database/queries';
41
+ import { projectQueries } from '../database/queries/project-queries';
42
+ import { worktreeQueries } from '../database/queries/worktree-queries';
43
+ import { generateFileShareToken, hashToken } from '../auth/tokens';
44
+ import { requireFilePathAccessFor } from '../ws/files/path-access';
45
+
46
+ /**
47
+ * Default lifetime of a new link, in minutes.
48
+ *
49
+ * Five, matching the register of the other one-shot credentials in this app
50
+ * rather than the register of a download page: the link answers "send me that
51
+ * file now", and a URL that outlives the moment only widens the window in
52
+ * which someone else's chat history still opens it. Longer deadlines — and no
53
+ * deadline at all — are a per-link choice, not the default.
54
+ */
55
+ export const DEFAULT_FILE_SHARE_TTL_MINUTES = 5;
56
+
57
+ /** Upper bound on a chosen deadline (30 days). "Never" is expressed as null. */
58
+ export const MAX_FILE_SHARE_TTL_MINUTES = 30 * 24 * 60;
59
+
60
+ /**
61
+ * Streaming continuation window after a one-time link is consumed.
62
+ *
63
+ * A video/audio player does not fetch the file once: it issues many byte-range
64
+ * requests (initial probe, buffering, seek, replay) against the same URL. The
65
+ * one-time rule still applies to *opens* — any full (non-range) GET after the
66
+ * first open fails closed — but range requests keep working for this window
67
+ * so an already-open player can seek and replay. The window is bound to the
68
+ * client that burned the link (see {@link consumerFingerprint}), so a leaked
69
+ * URL cannot be range-read by anybody else inside it.
70
+ */
71
+ export const FILE_SHARE_DRAIN_MS = 30 * 60 * 1000;
72
+
73
+ export interface FileShareView {
74
+ /** Canonical absolute path of the shared file (resolved at creation). */
75
+ filePath: string;
76
+ createdBy: string;
77
+ oneTime: boolean;
78
+ expiresAt: string | null;
79
+ /** True when a one-time link is burned and this is a continuation. */
80
+ draining: boolean;
81
+ }
82
+
83
+ /** Thrown for every "this link cannot serve bytes" case — the route answers 410. */
84
+ export class FileShareGoneError extends Error {
85
+ constructor(message = 'Invalid or expired share link') {
86
+ super(message);
87
+ this.name = 'FileShareGoneError';
88
+ }
89
+ }
90
+
91
+ export interface FileShareOptions {
92
+ /** Burn on the first open. Defaults to true. */
93
+ oneTime?: boolean;
94
+ /**
95
+ * Minutes until the link lapses, or null for "until revoked". Undefined
96
+ * falls back to {@link DEFAULT_FILE_SHARE_TTL_MINUTES}.
97
+ */
98
+ expiresInMinutes?: number | null;
99
+ }
100
+
101
+ /**
102
+ * Stable, non-reversible identifier for the client opening a link.
103
+ *
104
+ * Only used to keep the post-burn continuation window with the player that
105
+ * actually opened the file. It is deliberately coarse (IP + user agent): a
106
+ * different device or browser never matches, while the same player's seek and
107
+ * replay requests always do.
108
+ */
109
+ export function consumerFingerprint(ip?: string | null, userAgent?: string | null): string {
110
+ return hashToken(`${ip ?? ''}|${userAgent ?? ''}`);
111
+ }
112
+
113
+ /**
114
+ * Re-run the creator's project-scoped access check against the shared path.
115
+ * A link is only ever as alive as the access that minted it.
116
+ */
117
+ async function assertCreatorStillHasAccess(filePath: string, createdBy: string): Promise<void> {
118
+ const user = authQueries.getUserById(createdBy);
119
+ if (!user) {
120
+ throw new FileShareGoneError();
121
+ }
122
+ try {
123
+ await requireFilePathAccessFor(filePath, user.role, user.id);
124
+ } catch {
125
+ throw new FileShareGoneError();
126
+ }
127
+ }
128
+
129
+ /** True when `candidate` sits under `root` (plain prefix test, no symlink walk). */
130
+ function isUnder(root: string, candidate: string): boolean {
131
+ const rel = relative(root, candidate);
132
+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
133
+ }
134
+
135
+ export interface FileShareLocation {
136
+ /** Owning project (or the project a worktree belongs to), when there is one. */
137
+ projectName: string | null;
138
+ /** Worktree the file sits in, when it is not the main tree. */
139
+ worktreeName: string | null;
140
+ /** Path relative to that root, or the absolute path when none contains it. */
141
+ relativePath: string;
142
+ }
143
+
144
+ /**
145
+ * Describe where a shared file lives, so a list of links reads as
146
+ * "clopen · backend/http/files-shared.ts" rather than five rows all called
147
+ * `index.ts`. Falls back to the absolute path when nothing owns it.
148
+ *
149
+ * Separators are normalised to `/` for display — a Windows server would
150
+ * otherwise render a path no one can compare against the Explorer tree.
151
+ */
152
+ export function describeShareLocation(filePath: string): FileShareLocation {
153
+ let best: { root: string; projectName: string; worktreeName: string | null } | null = null;
154
+
155
+ for (const project of projectQueries.getAll()) {
156
+ if (isUnder(project.path, filePath) && (!best || project.path.length > best.root.length)) {
157
+ best = { root: project.path, projectName: project.name, worktreeName: null };
158
+ }
159
+ for (const worktree of worktreeQueries.getByProjectId(project.id)) {
160
+ if (isUnder(worktree.path, filePath) && (!best || worktree.path.length > best.root.length)) {
161
+ best = { root: worktree.path, projectName: project.name, worktreeName: worktree.name };
162
+ }
163
+ }
164
+ }
165
+
166
+ if (!best) {
167
+ return { projectName: null, worktreeName: null, relativePath: filePath.split(sep).join('/') };
168
+ }
169
+ return {
170
+ projectName: best.projectName,
171
+ worktreeName: best.worktreeName,
172
+ relativePath: relative(best.root, filePath).split(sep).join('/')
173
+ };
174
+ }
175
+
176
+ /**
177
+ * Mint a share token for a single file. The caller must already be
178
+ * authenticated over the WebSocket; access is enforced with the same
179
+ * project-scoped policy as the download route.
180
+ */
181
+ export async function createFileShareLink(
182
+ requestedPath: string,
183
+ role: string | null,
184
+ userId: string | null,
185
+ options: FileShareOptions = {}
186
+ ): Promise<{ shareId: string; shareToken: string; oneTime: boolean; expiresAt: string | null }> {
187
+ if (!userId) {
188
+ throw new Error('Access denied');
189
+ }
190
+ const resolvedPath = await requireFilePathAccessFor(requestedPath, role, userId);
191
+
192
+ const stats = await stat(resolvedPath).catch(() => null);
193
+ if (!stats) {
194
+ throw new Error('File not found');
195
+ }
196
+ if (stats.isDirectory()) {
197
+ throw new Error('Cannot share a folder — compress it first');
198
+ }
199
+
200
+ const oneTime = options.oneTime ?? true;
201
+ const minutes = options.expiresInMinutes === undefined
202
+ ? DEFAULT_FILE_SHARE_TTL_MINUTES
203
+ : options.expiresInMinutes;
204
+ if (minutes !== null && (!Number.isFinite(minutes) || minutes < 1 || minutes > MAX_FILE_SHARE_TTL_MINUTES)) {
205
+ throw new Error('Invalid expiry');
206
+ }
207
+
208
+ sweepStaleFileShares();
209
+
210
+ const shareToken = generateFileShareToken();
211
+ const now = new Date();
212
+ const expiresAt = minutes === null ? null : new Date(now.getTime() + minutes * 60_000).toISOString();
213
+ const row = fileShareQueries.create({
214
+ tokenHash: hashToken(shareToken),
215
+ filePath: resolvedPath,
216
+ createdBy: userId,
217
+ oneTime,
218
+ expiresAt,
219
+ createdAt: now.toISOString()
220
+ });
221
+ debug.log('file', `File share created for ${resolvedPath} (${oneTime ? 'one-time' : 'reusable'})`);
222
+ return { shareId: row.id, shareToken, oneTime, expiresAt };
223
+ }
224
+
225
+ /**
226
+ * Resolve a raw share token WITHOUT burning it.
227
+ *
228
+ * Throws {@link FileShareGoneError} when the token is unknown, lapsed,
229
+ * revoked, no longer backed by creator access, or — for a one-time link —
230
+ * already consumed by a different client. A one-time token consumed by *this*
231
+ * client inside the continuation window resolves with `draining: true`: the
232
+ * route then serves byte ranges only, never another full open.
233
+ */
234
+ export async function peekFileShare(shareToken: string, fingerprint: string): Promise<FileShareView> {
235
+ const hash = hashToken(shareToken);
236
+ const row = fileShareQueries.getByHash(hash);
237
+ if (!row) {
238
+ throw new FileShareGoneError();
239
+ }
240
+
241
+ const now = Date.now();
242
+ if (row.expires_at && new Date(row.expires_at).getTime() <= now) {
243
+ fileShareQueries.deleteByHash(hash);
244
+ throw new FileShareGoneError();
245
+ }
246
+
247
+ const oneTime = row.one_time === 1;
248
+ if (oneTime && row.consumed_at) {
249
+ const consumedAt = new Date(row.consumed_at).getTime();
250
+ if (!Number.isFinite(consumedAt) || now - consumedAt > FILE_SHARE_DRAIN_MS) {
251
+ throw new FileShareGoneError();
252
+ }
253
+ if (row.consumer_hash !== fingerprint) {
254
+ throw new FileShareGoneError();
255
+ }
256
+ }
257
+
258
+ await assertCreatorStillHasAccess(row.file_path, row.created_by);
259
+
260
+ return {
261
+ filePath: row.file_path,
262
+ createdBy: row.created_by,
263
+ oneTime,
264
+ expiresAt: row.expires_at,
265
+ draining: oneTime && row.consumed_at !== null
266
+ };
267
+ }
268
+
269
+ /**
270
+ * Burn the single use of a one-time link on behalf of `fingerprint`.
271
+ *
272
+ * Returns false when the burn was lost — the token was already consumed
273
+ * (by a concurrent first open) or lapsed between the peek and here. The
274
+ * caller re-peeks: the same client continues as a range continuation, a
275
+ * stranger gets the gone response.
276
+ */
277
+ export function consumeFileShareLink(shareToken: string, fingerprint: string): boolean {
278
+ const changes = fileShareQueries.consume(hashToken(shareToken), new Date().toISOString(), fingerprint);
279
+ return changes === 1;
280
+ }
281
+
282
+ /** Count an open of a reusable link, so the list can report that it was used. */
283
+ export function recordFileShareOpen(shareToken: string): void {
284
+ fileShareQueries.recordOpen(hashToken(shareToken), new Date().toISOString());
285
+ }
286
+
287
+ /**
288
+ * Revoke a share by its row id. The creator or an admin may revoke; returns
289
+ * false when the id is unknown (already used up, lapsed, or revoked).
290
+ *
291
+ * Revoking a link that is inside its continuation window also ends that
292
+ * window, so a stream in progress stops on the next range request.
293
+ */
294
+ export function revokeFileShareLink(
295
+ shareId: string,
296
+ role: string | null,
297
+ userId: string | null
298
+ ): boolean {
299
+ const row = fileShareQueries.getById(shareId);
300
+ if (!row) return false;
301
+ if (role !== 'admin' && row.created_by !== userId) {
302
+ throw new Error('Access denied');
303
+ }
304
+ return fileShareQueries.deleteById(shareId) > 0;
305
+ }
306
+
307
+ /** One entry of the share-management list. Carries no token material. */
308
+ export interface FileShareSummary {
309
+ id: string;
310
+ /** Absolute path — the tooltip, and the fallback when nothing owns the file. */
311
+ filePath: string;
312
+ fileName: string;
313
+ projectName: string | null;
314
+ worktreeName: string | null;
315
+ /** Path within the project/worktree, `/`-separated on every platform. */
316
+ relativePath: string;
317
+ createdBy: string;
318
+ createdByName: string | null;
319
+ createdAt: string;
320
+ oneTime: boolean;
321
+ /** ISO deadline, or null for "until revoked". */
322
+ expiresAt: string | null;
323
+ /** How many times the link has been opened — 0 means nobody has yet. */
324
+ openCount: number;
325
+ lastOpenedAt: string | null;
326
+ /** Set once a one-time link has been burned. */
327
+ consumedAt: string | null;
328
+ }
329
+
330
+ /**
331
+ * List live share links: an admin sees every user's, everyone else sees their
332
+ * own. Lapsed rows are filtered by the query, so the list answers "what is
333
+ * reachable right now" rather than "what was ever created".
334
+ */
335
+ export function listFileShares(role: string | null, userId: string | null): FileShareSummary[] {
336
+ if (!userId) {
337
+ throw new Error('Access denied');
338
+ }
339
+ const now = new Date().toISOString();
340
+ const rows = role === 'admin'
341
+ ? fileShareQueries.listAll(now)
342
+ : fileShareQueries.listForUser(userId, now);
343
+
344
+ return rows.map((row) => {
345
+ const location = describeShareLocation(row.file_path);
346
+ return {
347
+ id: row.id,
348
+ filePath: row.file_path,
349
+ fileName: basename(row.file_path),
350
+ projectName: location.projectName,
351
+ worktreeName: location.worktreeName,
352
+ relativePath: location.relativePath,
353
+ createdBy: row.created_by,
354
+ createdByName: row.created_by_name,
355
+ createdAt: row.created_at,
356
+ oneTime: row.one_time === 1,
357
+ expiresAt: row.expires_at,
358
+ openCount: row.open_count,
359
+ lastOpenedAt: row.last_opened_at,
360
+ consumedAt: row.consumed_at
361
+ };
362
+ });
363
+ }
364
+
365
+ /** Drop links that can never serve bytes again (lapsed, or drained out). */
366
+ export function sweepStaleFileShares(): number {
367
+ const drainCutoff = new Date(Date.now() - FILE_SHARE_DRAIN_MS).toISOString();
368
+ return fileShareQueries.deleteStale(drainCutoff);
369
+ }
@@ -345,28 +345,34 @@ export async function handleWindowsDrives(): Promise<PathBrowseData> {
345
345
  extension?: string;
346
346
  }> = [];
347
347
 
348
- // Get list of available drives using wmic with simple output format
349
- const proc = Bun.spawn(['wmic', 'logicaldisk', 'get', 'caption'], {
350
- stdout: 'pipe',
351
- stderr: 'ignore'
352
- });
353
- const stdout = await new Response(proc.stdout).text();
354
-
355
- const lines = stdout.split('\n')
356
- .map(line => line.trim())
357
- .filter(line => line && line !== 'Caption' && line.match(/^[A-Z]:$/));
358
-
359
- for (const drive of lines) {
360
- // wmic already validated that these drives exist
361
- // Just add them directly without further validation
362
- const drivePath = drive + '\\';
363
- drives.push({
364
- name: `${drive} Drive`,
365
- type: 'directory',
366
- path: drivePath,
367
- modified: new Date().toISOString(),
368
- kind: 'drive'
348
+ // Get list of available drives using wmic with simple output format.
349
+ // wmic is gone on recent Windows 11 builds (spawn throws) — fall through
350
+ // to the probe below instead of failing the whole drives listing.
351
+ try {
352
+ const proc = Bun.spawn(['wmic', 'logicaldisk', 'get', 'caption'], {
353
+ stdout: 'pipe',
354
+ stderr: 'ignore'
369
355
  });
356
+ const stdout = await new Response(proc.stdout).text();
357
+
358
+ const lines = stdout.split('\n')
359
+ .map(line => line.trim())
360
+ .filter(line => line && line !== 'Caption' && line.match(/^[A-Z]:$/));
361
+
362
+ for (const drive of lines) {
363
+ // wmic already validated that these drives exist
364
+ // Just add them directly without further validation
365
+ const drivePath = drive + '\\';
366
+ drives.push({
367
+ name: `${drive} Drive`,
368
+ type: 'directory',
369
+ path: drivePath,
370
+ modified: new Date().toISOString(),
371
+ kind: 'drive'
372
+ });
373
+ }
374
+ } catch {
375
+ debug.debug('file', 'wmic unavailable, probing drive letters instead');
370
376
  }
371
377
 
372
378
  if (drives.length === 0) {
@@ -7,6 +7,15 @@ import { debug } from '$shared/utils/logger';
7
7
  import { getCleanSpawnEnv } from '../utils/env';
8
8
  import { resolveBinary } from '../utils/cli';
9
9
 
10
+ /**
11
+ * The environment fragment carrying a caller's git identity.
12
+ *
13
+ * An alias rather than a bare `Record<string, string>` so the operations that
14
+ * accept one say so in their signature — which is how a reader tells the
15
+ * commands that care who is running them from the ones that do not.
16
+ */
17
+ export type GitIdentityEnv = Record<string, string>;
18
+
10
19
  export interface GitExecResult {
11
20
  stdout: string;
12
21
  stderr: string;
@@ -23,6 +32,21 @@ export interface GitExecOptions {
23
32
  * not logged as one — `check-ignore` exits 1 to say "nothing matched".
24
33
  */
25
34
  okExitCodes?: number[];
35
+ /**
36
+ * Extra environment for this invocation — in practice the `GIT_CONFIG_*`
37
+ * block that carries the caller's git identity (see
38
+ * `backend/git/identity/env.ts`).
39
+ *
40
+ * Passed per command rather than resolved here because resolving an identity
41
+ * costs a database read, and `git status` runs many times a second. Commands
42
+ * that create an object or talk to a remote ask for it; the read-only ones
43
+ * never pay for it.
44
+ *
45
+ * Applied last, so an identity can override the fixed variables below. That
46
+ * ordering matters for `core.sshCommand`, which nothing else here sets but a
47
+ * future variable might.
48
+ */
49
+ env?: Record<string, string>;
26
50
  }
27
51
 
28
52
  /**
@@ -36,7 +60,7 @@ export async function execGit(
36
60
  ): Promise<GitExecResult> {
37
61
  const options: GitExecOptions =
38
62
  typeof timeoutOrOptions === 'number' ? { timeout: timeoutOrOptions } : timeoutOrOptions;
39
- const { timeout = 30000, stdin, okExitCodes = [] } = options;
63
+ const { timeout = 30000, stdin, okExitCodes = [], env: extraEnv } = options;
40
64
  debug.log('git', `Executing: git ${args.join(' ')} in ${cwd}`);
41
65
 
42
66
  const gitPath = resolveBinary('git');
@@ -70,7 +94,9 @@ export async function execGit(
70
94
  GIT_SEQUENCE_EDITOR: 'true',
71
95
  // Use English output for consistent parsing
72
96
  LANG: 'en_US.UTF-8',
73
- LC_ALL: 'en_US.UTF-8'
97
+ LC_ALL: 'en_US.UTF-8',
98
+ // The caller's git identity, last so it wins.
99
+ ...extraEnv
74
100
  }
75
101
  });
76
102