forked from stablyai/orca
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorca-runtime-files.ts
More file actions
1912 lines (1785 loc) · 64.3 KB
/
Copy pathorca-runtime-files.ts
File metadata and controls
1912 lines (1785 loc) · 64.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable max-lines -- Why: filesystem, editor-file, and search commands share the same local/SSH path authorization rules. Keeping that IO adapter together prevents separate command paths from drifting on safety checks. */
import type { ChildProcess } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { watch as watchFs } from 'node:fs'
import type { FileHandle } from 'node:fs/promises'
import {
chmod,
constants,
copyFile,
lstat,
mkdir,
open,
readFile,
readdir,
rename,
realpath,
rm,
stat,
writeFile
} from 'node:fs/promises'
import { homedir, tmpdir } from 'node:os'
import { basename, dirname, extname, join } from 'node:path'
import type {
DirEntry,
FsChangeEvent,
GitWorktreeInfo,
MarkdownDocument,
SearchOptions,
SearchResult,
Worktree
} from '../../shared/types'
import {
isPathInsideOrEqual,
isRuntimePathAbsolute,
isWindowsAbsolutePathLike,
relativePathInsideRoot,
resolveRuntimePath
} from '../../shared/cross-platform-path'
import type {
RuntimeFileListResult,
RuntimeFileOpenResult,
RuntimeFileReadChunkResult,
RuntimeFilePreviewResult,
RuntimeFileReadResult,
RuntimeTerminalPathResolution
} from '../../shared/runtime-types'
import { watchFileExplorerInWatcherProcess } from './file-watcher-host'
import { wslAwareSpawn } from '../git/runner'
import { parseWslPath, toWindowsWslPath } from '../wsl'
import { isENOENT, resolveAuthorizedPath } from '../ipc/filesystem-auth'
import { listQuickOpenFiles } from '../ipc/filesystem-list-files'
import { searchWithGitGrep } from '../ipc/filesystem-search-git'
import { getLocalGitOptionsForRegisteredWorktree } from '../ipc/local-worktree-runtime-options'
import { checkRgAvailable } from '../ipc/rg-availability'
import {
listMarkdownDocuments,
markdownDocumentsFromRelativePaths
} from '../ipc/markdown-documents'
import {
buildRgArgs,
createAccumulator,
DEFAULT_SEARCH_MAX_RESULTS,
finalize,
ingestRgJsonLine,
SEARCH_TIMEOUT_MS
} from '../../shared/text-search'
import type { Store } from '../persistence'
import {
getSshFilesystemProvider,
SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE
} from '../providers/ssh-filesystem-dispatch'
import type { FileStat, IFilesystemProvider } from '../providers/types'
import { assertNoClobberRenameDestinationAvailable } from '../../shared/filesystem-rename-collision'
import { joinWorktreeRelativePath, normalizeRuntimeRelativePath } from './runtime-relative-paths'
const MOBILE_FILE_LIST_LIMIT = 5000
const MOBILE_FILE_READ_MAX_BYTES = 512 * 1024
const RUNTIME_PREVIEWABLE_BINARY_MAX_BYTES = 10 * 1024 * 1024
const WINDOWS_RUNTIME_FILE_WATCH_DEBOUNCE_MS = 150
const TERMINAL_FILE_GRANT_TTL_MS = 10 * 60 * 1000
const OPEN_NOFOLLOW = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFOLLOW : 0
// Why: runtime files.watch subscriptions are cleaned up through synchronous RPC
// callbacks. Track native Parcel unsubscribe work so app shutdown can drain it.
const pendingRuntimeFileWatcherUnsubscribes = new Set<Promise<void>>()
const MOBILE_BINARY_EXTENSIONS = new Set([
'.avif',
'.bmp',
'.gif',
'.heic',
'.ico',
'.jpeg',
'.jpg',
'.mov',
'.mp3',
'.mp4',
'.pdf',
'.png',
'.webp',
'.zip'
])
// Raster image extensions the mobile client can render from a base64 data URI
// via files.readPreview. Mirrors mobile's classifyMobileArtifact image set;
// SVG/PDF are intentionally excluded (RN <Image> can't decode those data URIs).
const MOBILE_PREVIEWABLE_IMAGE_EXTENSIONS = new Set([
'.png',
'.jpg',
'.jpeg',
'.gif',
'.webp',
'.bmp',
'.ico'
])
type RuntimeFileStatLike = {
size?: number
dev?: number
ino?: number
nlink?: number
mtime?: number | Date
mtimeMs?: number
isDirectory?: () => boolean
}
type TerminalFileGrant = {
id: string
worktreeId: string
absolutePath: string
provider: 'local' | 'ssh'
connectionId?: string
clientId?: string
expiresAt: number
statIdentity: string | null
expiryTimer?: ReturnType<typeof setTimeout>
}
function isMobilePreviewableImagePath(relativePath: string): boolean {
const basename = basenameFromRelativePath(relativePath)
const dotIndex = basename.lastIndexOf('.')
if (dotIndex <= 0) {
return false
}
return MOBILE_PREVIEWABLE_IMAGE_EXTENSIONS.has(basename.slice(dotIndex).toLowerCase())
}
const RUNTIME_PREVIEWABLE_BINARY_MIME_TYPES: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
'.ico': 'image/x-icon',
'.pdf': 'application/pdf'
}
function trackRuntimeFileWatcherUnsubscribe(
rootPath: string,
unsubscribe: () => Promise<void>
): void {
const promise = Promise.resolve()
.then(unsubscribe)
.catch((err: unknown) => {
console.error('[runtime-files.watch] unsubscribe error', { rootPath, err })
})
.finally(() => {
pendingRuntimeFileWatcherUnsubscribes.delete(promise)
})
pendingRuntimeFileWatcherUnsubscribes.add(promise)
}
export async function awaitRuntimeFileWatcherUnsubscribes(): Promise<void> {
await Promise.allSettled(Array.from(pendingRuntimeFileWatcherUnsubscribes))
}
export type ResolvedRuntimeFileWorktree = Worktree & { git: GitWorktreeInfo }
export type ResolvedRuntimeFileTarget = {
worktree: ResolvedRuntimeFileWorktree
connectionId?: string
}
export type RuntimeFileCommandHost = {
getRuntimeId(): string
requireStore(): Store
resolveWorktreeSelector(selector: string): Promise<ResolvedRuntimeFileWorktree>
resolveRuntimeFileTarget(selector: string): Promise<ResolvedRuntimeFileTarget>
resolveTerminalCwd?(terminalHandle: string): string | null | Promise<string | null>
resolveTerminalContext?(
terminalHandle: string
): { worktreeId: string; connectionId: string | null } | null
resolveTerminalFileUriHostname?(terminalHandle: string): string | null | Promise<string | null>
hasRecentTerminalOutputPath?(
terminalHandle: string,
pathText: string,
absolutePath: string
): boolean | Promise<boolean>
resolveRuntimeGitTarget(
selector: string
): Promise<{ worktree: ResolvedRuntimeFileWorktree; connectionId?: string }>
openFile(
worktreeId: string,
filePath: string,
relativePath: string,
runtimeEnvironmentId?: string | null
): void
openDiff(
worktreeId: string,
filePath: string,
relativePath: string,
staged: boolean,
runtimeEnvironmentId?: string | null
): void
}
export class RuntimeFileCommands {
private activeRuntimeTextSearches = new Map<string, ChildProcess>()
private terminalFileGrants = new Map<string, TerminalFileGrant>()
constructor(private readonly host: RuntimeFileCommandHost) {}
async listMobileFiles(worktreeSelector: string): Promise<RuntimeFileListResult> {
const store = this.host.requireStore()
const target = await this.host.resolveRuntimeFileTarget(worktreeSelector)
const { worktree, connectionId } = target
const files = connectionId
? await this.listRemoteMobileFiles(worktree.path, connectionId)
: await listQuickOpenFiles(worktree.path, store)
const entries = files
.filter((relativePath) => isSafeMobileRelativePath(relativePath))
.sort((a, b) => a.localeCompare(b))
.slice(0, MOBILE_FILE_LIST_LIMIT)
.map((relativePath) => ({
relativePath,
basename: basenameFromRelativePath(relativePath),
kind: isMobileBinaryPath(relativePath) ? ('binary' as const) : ('text' as const)
}))
return {
worktree: worktree.id,
rootPath: worktree.path,
files: entries,
totalCount: files.length,
truncated: files.length > MOBILE_FILE_LIST_LIMIT
}
}
async openMobileFile(
worktreeSelector: string,
relativePath: string
): Promise<RuntimeFileOpenResult> {
const { worktree, connectionId } = await this.host.resolveRuntimeFileTarget(worktreeSelector)
if (!isSafeMobileRelativePath(relativePath)) {
throw new Error('invalid_relative_path')
}
const filePath = joinWorktreeRelativePath(worktree.path, relativePath)
await this.assertMobileFileExists(filePath, relativePath, connectionId)
// Previewable images open like text (the mobile viewer renders them via
// files.readPreview); other binaries stay unavailable on mobile.
const kind = isMobilePreviewableImagePath(relativePath)
? 'image'
: isMobileBinaryPath(relativePath)
? 'binary'
: isMobileMarkdownPath(relativePath)
? 'markdown'
: 'text'
if (kind === 'binary') {
return { worktree: worktree.id, relativePath, kind, opened: false }
}
// Why: the service's internal runtimeId is not a registered runtime env selector
// (those live in orca-environments.json). Passing it caused Unknown environment
// errors on content load for CLI-initiated opens (via files.open from orca cli
// used by agents). Instead pass undefined so the renderer openFile falls back to
// the current activeRuntimeEnvironmentId (or null), matching sidebar opens and
// allowing correct routing for local vs remote envs.
this.host.openFile(worktree.id, filePath, relativePath, undefined)
return { worktree: worktree.id, relativePath, kind, opened: true }
}
private async assertMobileFileExists(
filePath: string,
relativePath: string,
connectionId?: string
): Promise<void> {
try {
if (connectionId) {
const provider = getSshFilesystemProvider(connectionId)
if (!provider) {
throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE)
}
await provider.stat(filePath)
return
}
await stat(await resolveAuthorizedPath(filePath, this.host.requireStore()))
} catch (error) {
if (
isENOENT(error) ||
(connectionId && RuntimeFileCommands.isRemoteNotFoundErrorMessage(error))
) {
throw new Error(`File not found: ${relativePath}`)
}
throw error
}
}
async openMobileDiff(
worktreeSelector: string,
relativePath: string,
staged: boolean
): Promise<RuntimeFileOpenResult> {
const { worktree } = await this.host.resolveRuntimeFileTarget(worktreeSelector)
if (!isSafeMobileRelativePath(relativePath)) {
throw new Error('invalid_relative_path')
}
const kind = isMobileBinaryPath(relativePath)
? 'binary'
: isMobileMarkdownPath(relativePath)
? 'markdown'
: 'text'
const filePath = joinWorktreeRelativePath(worktree.path, relativePath)
// Why: see openMobileFile; avoid stamping internal runtimeId as runtimeEnvironmentId.
this.host.openDiff(worktree.id, filePath, relativePath, staged, undefined)
return { worktree: worktree.id, relativePath, kind, opened: true }
}
async readMobileFile(
worktreeSelector: string,
relativePath: string
): Promise<RuntimeFileReadResult> {
const store = this.host.requireStore()
const target = await this.host.resolveRuntimeFileTarget(worktreeSelector)
const { worktree, connectionId } = target
if (!isSafeMobileRelativePath(relativePath)) {
throw new Error('invalid_relative_path')
}
if (isMobileBinaryPath(relativePath)) {
throw new Error('binary_file')
}
const filePath = joinWorktreeRelativePath(worktree.path, relativePath)
const content = connectionId
? await this.readRemoteMobileFile(filePath, connectionId)
: await readLocalMobileFile(filePath, store)
const truncated = truncateMobileFilePreview(content)
return {
worktree: worktree.id,
relativePath,
content: truncated.content,
truncated: truncated.truncated,
byteLength: truncated.byteLength
}
}
// Resolves a path tapped in the mobile terminal (absolute, relative, or ~/…)
// to a worktree-relative path the file RPCs can open, plus existence.
// Relative paths resolve against `cwd` when the caller supplies it, else
// against the worktree root.
async resolveTerminalPath(
worktreeSelector: string,
pathText: string,
cwd?: string | null,
clientId?: string,
terminalHandle?: string | null
): Promise<RuntimeTerminalPathResolution> {
const store = this.host.requireStore()
const target = await this.host.resolveRuntimeFileTarget(worktreeSelector)
const { worktree, connectionId } = target
// Why: mobile may attach after OSC7 cwd metadata was emitted; the runtime
// still owns the terminal's latest cwd and can resolve the tap correctly.
const normalizedTerminalHandle =
terminalHandle && terminalHandle.trim().length > 0 ? terminalHandle.trim() : null
const terminalCwd = normalizedTerminalHandle
? await this.host.resolveTerminalCwd?.(normalizedTerminalHandle)
: null
const terminalFileUriHostname = normalizedTerminalHandle
? await this.host.resolveTerminalFileUriHostname?.(normalizedTerminalHandle)
: null
const base = terminalCwd || (cwd && cwd.trim().length > 0 ? cwd : worktree.path)
const empty: RuntimeTerminalPathResolution = {
worktree: worktree.id,
relativePath: null,
absolutePath: null,
exists: false,
isDirectory: false
}
// `~/…` is home-relative. The local home is known (os.homedir); the remote
// home is not, so don't guess — a tapped `~/…` on a remote worktree would
// mis-resolve under cwd/worktree-root, so treat it as not-openable instead.
const isTilde = pathText.startsWith('~/') || pathText.startsWith('~\\')
if (isTilde && connectionId) {
return empty
}
const expanded = isTilde ? resolveRuntimePath(homedir(), pathText.slice(2)) : pathText
const absolutePath = resolveTerminalAbsolutePath({
base,
expanded,
worktreePath: worktree.path,
connectionId,
terminalFileUriHostname
})
const relativePath = relativePathInsideRoot(worktree.path, absolutePath)
try {
if (relativePath !== null && relativePath !== '' && isSafeMobileRelativePath(relativePath)) {
const stats = connectionId
? await this.statRemoteTerminalPath(absolutePath, connectionId)
: await stat(await resolveAuthorizedPath(absolutePath, store))
return {
worktree: worktree.id,
relativePath,
absolutePath,
exists: true,
isDirectory: stats.isDirectory(),
openTarget: stats.isDirectory()
? undefined
: {
kind: 'worktree-file',
provider: connectionId ? 'ssh' : 'local',
relativePath,
absolutePath
}
}
}
// Why: mobile taps can point at agent-created artifacts outside the
// worktree. Authorize and grant the exact existing path instead of
// widening worktree-relative file RPCs to arbitrary absolute paths.
if (!normalizedTerminalHandle || !terminalCwd) {
return { ...empty, relativePath, absolutePath }
}
const terminalContext = this.host.resolveTerminalContext?.(normalizedTerminalHandle)
if (
!terminalContext ||
terminalContext.worktreeId !== worktree.id ||
(terminalContext.connectionId ?? undefined) !== connectionId
) {
return { ...empty, relativePath, absolutePath }
}
const artifactPath = await this.resolveAllowedTerminalArtifactPath({
absolutePath,
connectionId,
worktreePath: worktree.path
})
if (!artifactPath) {
return { ...empty, relativePath, absolutePath }
}
if (
!(await this.host.hasRecentTerminalOutputPath?.(
normalizedTerminalHandle,
provenancePathCandidate(pathText, absolutePath),
artifactPath
))
) {
return { ...empty, relativePath, absolutePath }
}
const stats = connectionId
? await this.statRemoteTerminalPath(artifactPath, connectionId)
: await this.statLocalTerminalPath(artifactPath)
const isDirectory = stats.isDirectory()
if (!isDirectory && isTerminalArtifactHardLinked(stats)) {
return { ...empty, relativePath, absolutePath }
}
const grant = isDirectory
? null
: this.createTerminalFileGrant({
worktreeId: worktree.id,
absolutePath: artifactPath,
provider: connectionId ? 'ssh' : 'local',
connectionId,
clientId,
stats
})
return {
worktree: worktree.id,
relativePath: null,
absolutePath: artifactPath,
exists: true,
isDirectory,
openTarget: grant
? {
kind: 'absolute-file',
provider: grant.provider,
absolutePath: artifactPath,
grantId: grant.id
}
: undefined
}
} catch (error) {
// A genuine "not found" → the path simply doesn't exist (report it, not an
// error). Transport/permission/provider failures must surface so a remote
// session doesn't silently report every tapped path as missing.
if (
isENOENT(error) ||
(connectionId && RuntimeFileCommands.isRemoteNotFoundErrorMessage(error))
) {
return { ...empty, relativePath, absolutePath }
}
throw error
}
}
// A remote stat failure that means "the file isn't there" vs a transport /
// permission / provider error. The mux drops the ErrnoException `code`, so the
// message is the only signal — match the not-found shapes the relay surfaces.
private static isRemoteNotFoundErrorMessage(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error)
return /\bENOENT\b|no such file|not found|does not exist/i.test(message)
}
private async statRemoteTerminalPath(
absolutePath: string,
connectionId: string
): Promise<RuntimeFileStatLike & { isDirectory: () => boolean }> {
const provider = getSshFilesystemProvider(connectionId)
if (!provider) {
throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE)
}
const stats = await provider.stat(absolutePath)
return { ...stats, isDirectory: () => stats.type === 'directory' }
}
private async resolveAllowedTerminalArtifactPath(args: {
absolutePath: string
connectionId?: string
worktreePath: string
}): Promise<string | null> {
if (args.connectionId) {
return this.resolveAllowedRemoteTerminalArtifactPath(args.absolutePath, args.connectionId)
}
return resolveAllowedLocalTerminalArtifactPath(args.absolutePath, args.worktreePath)
}
private async resolveAllowedRemoteTerminalArtifactPath(
absolutePath: string,
connectionId: string
): Promise<string | null> {
const provider = getSshFilesystemProvider(connectionId)
if (!provider) {
throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE)
}
const roots = ['/tmp', '/private/tmp']
const providerTempDir = await provider.getTempDir?.().catch(() => null)
if (providerTempDir) {
roots.push(providerTempDir)
}
if (!roots.some((root) => isPathInsideOrEqual(root, absolutePath))) {
return null
}
const [realArtifactPath, ...realRoots] = await Promise.all([
provider.realpath(absolutePath),
...roots.map((root) => provider.realpath(root).catch(() => root))
])
// Why: SSH reads and writes follow symlinks on the relay. Grant the
// canonical target so a /tmp link cannot escape the temp-artifact boundary.
return realRoots.some((root) => isPathInsideOrEqual(root, realArtifactPath))
? realArtifactPath
: null
}
private async statLocalTerminalPath(
absolutePath: string
): Promise<RuntimeFileStatLike & { isDirectory: () => boolean }> {
await assertLocalTerminalArtifactPathStillCanonical(absolutePath)
const handle = await open(absolutePath, 'r')
try {
return handle.stat()
} finally {
await handle.close()
}
}
private createTerminalFileGrant(args: {
worktreeId: string
absolutePath: string
provider: 'local' | 'ssh'
connectionId?: string
clientId?: string
stats: RuntimeFileStatLike
}): TerminalFileGrant {
assertTerminalArtifactNotHardLinked(args.stats)
const grant: TerminalFileGrant = {
id: randomUUID(),
worktreeId: args.worktreeId,
absolutePath: args.absolutePath,
provider: args.provider,
...(args.connectionId ? { connectionId: args.connectionId } : {}),
...(args.clientId ? { clientId: args.clientId } : {}),
expiresAt: Date.now() + TERMINAL_FILE_GRANT_TTL_MS,
statIdentity: terminalFileStatIdentity(args.stats)
}
this.terminalFileGrants.set(grant.id, grant)
this.scheduleTerminalFileGrantExpiry(grant)
return grant
}
private async requireTerminalFileGrant(
worktreeSelector: string,
grantId: string,
absolutePath: string,
clientId?: string
): Promise<{ grant: TerminalFileGrant; target: ResolvedRuntimeFileTarget }> {
const target = await this.host.resolveRuntimeFileTarget(worktreeSelector)
this.pruneExpiredTerminalFileGrants()
const grant = this.terminalFileGrants.get(grantId)
if (!grant) {
throw new Error('terminal_file_grant_expired')
}
if (grant.expiresAt <= Date.now()) {
this.releaseTerminalFileGrant(grantId, grant)
throw new Error('terminal_file_grant_expired')
}
if (
grant.worktreeId !== target.worktree.id ||
grant.absolutePath !== absolutePath ||
grant.connectionId !== target.connectionId ||
grant.clientId !== clientId
) {
throw new Error('terminal_file_grant_mismatch')
}
return { grant, target }
}
private refreshTerminalFileGrant(grant: TerminalFileGrant): void {
grant.expiresAt = Date.now() + TERMINAL_FILE_GRANT_TTL_MS
this.scheduleTerminalFileGrantExpiry(grant)
}
private pruneExpiredTerminalFileGrants(): void {
const now = Date.now()
for (const [id, grant] of this.terminalFileGrants) {
if (grant.expiresAt <= now) {
this.releaseTerminalFileGrant(id, grant)
}
}
}
revokeTerminalFileGrantsForClient(clientId: string): void {
for (const [id, grant] of this.terminalFileGrants) {
if (grant.clientId === clientId) {
this.releaseTerminalFileGrant(id, grant)
}
}
}
private releaseTerminalFileGrant(id: string, grant: TerminalFileGrant): void {
this.terminalFileGrants.delete(id)
if (grant.expiryTimer) {
clearTimeout(grant.expiryTimer)
grant.expiryTimer = undefined
}
}
private scheduleTerminalFileGrantExpiry(grant: TerminalFileGrant): void {
if (grant.expiryTimer) {
clearTimeout(grant.expiryTimer)
}
grant.expiryTimer = setTimeout(
() => {
if (this.terminalFileGrants.get(grant.id) === grant && grant.expiresAt <= Date.now()) {
this.releaseTerminalFileGrant(grant.id, grant)
}
},
Math.max(1, grant.expiresAt - Date.now())
)
grant.expiryTimer.unref?.()
}
async readTerminalArtifactFile(
worktreeSelector: string,
grantId: string,
absolutePath: string,
clientId?: string
): Promise<RuntimeFileReadResult> {
const { grant, target } = await this.requireTerminalFileGrant(
worktreeSelector,
grantId,
absolutePath,
clientId
)
if (isMobileBinaryPath(grant.absolutePath)) {
throw new Error('binary_file')
}
let content: string
if (grant.connectionId) {
const provider = await this.assertRemoteTerminalFileGrantFreshForRead(grant)
content = await this.readRemoteTerminalArtifactFile(
provider,
grant,
MOBILE_FILE_READ_MAX_BYTES
)
} else {
const handle = await openLocalTerminalArtifactGrant(grant, constants.O_RDONLY)
try {
content = await readLocalTerminalArtifactFileFromHandle(handle, grant)
} finally {
await handle.close()
}
}
this.refreshTerminalFileGrant(grant)
const truncated = truncateMobileFilePreview(content)
return {
worktree: target.worktree.id,
relativePath: grant.absolutePath,
content: truncated.content,
truncated: truncated.truncated,
byteLength: truncated.byteLength
}
}
async readTerminalArtifactPreview(
worktreeSelector: string,
grantId: string,
absolutePath: string,
clientId?: string
): Promise<RuntimeFilePreviewResult> {
const { grant } = await this.requireTerminalFileGrant(
worktreeSelector,
grantId,
absolutePath,
clientId
)
if (grant.connectionId) {
const provider = await this.assertRemoteTerminalFileGrantFreshForRead(grant)
this.refreshTerminalFileGrant(grant)
return this.readRemoteTerminalArtifactPreview(provider, grant)
}
const handle = await openLocalTerminalArtifactGrant(grant, constants.O_RDONLY)
try {
const preview = await readLocalTerminalArtifactPreviewFromHandle(handle, grant)
this.refreshTerminalFileGrant(grant)
return preview
} finally {
await handle.close()
}
}
async writeTerminalArtifactFile(
worktreeSelector: string,
grantId: string,
absolutePath: string,
content: string,
clientId?: string
): Promise<{ ok: true }> {
if (Buffer.byteLength(content, 'utf8') > MOBILE_FILE_READ_MAX_BYTES) {
throw new Error('file_too_large')
}
const { grant } = await this.requireTerminalFileGrant(
worktreeSelector,
grantId,
absolutePath,
clientId
)
if (isMobileBinaryPath(grant.absolutePath)) {
throw new Error('binary_file')
}
if (grant.connectionId) {
const { provider, fileStat } = await this.assertRemoteTerminalFileGrantFresh(grant)
if (fileStat.type === 'directory') {
throw new Error('Cannot write to a directory')
}
if (fileStat.size > MOBILE_FILE_READ_MAX_BYTES) {
throw new Error('file_too_large')
}
if (!provider.writeTerminalArtifact) {
throw new Error('terminal_file_grant_unavailable')
}
const nextStat = await provider.writeTerminalArtifact(
grant.absolutePath,
content,
this.terminalArtifactAccessOptions(grant, MOBILE_FILE_READ_MAX_BYTES)
)
grant.statIdentity = terminalFileStatIdentity(nextStat)
this.refreshTerminalFileGrant(grant)
return { ok: true }
}
let originalMode: number | null = null
const handle = await openLocalTerminalArtifactGrant(grant, constants.O_RDONLY)
try {
const fileStats = await handle.stat()
originalMode = fileStats.mode
if (fileStats.isDirectory()) {
throw new Error('Cannot write to a directory')
}
if (fileStats.size > MOBILE_FILE_READ_MAX_BYTES) {
throw new Error('file_too_large')
}
assertTerminalFileGrantFresh(grant, fileStats)
if (
isBinaryBuffer(await readFileHandleBufferBounded(handle, MOBILE_FILE_READ_MAX_BYTES + 1))
) {
throw new Error('binary_file')
}
} finally {
await handle.close()
}
const tempPath = join(
dirname(grant.absolutePath),
`.${basename(grant.absolutePath)}.${randomUUID()}.tmp`
)
try {
await writeFile(tempPath, content, { encoding: 'utf-8', flag: 'wx' })
if (typeof originalMode === 'number') {
await chmod(tempPath, originalMode & 0o7777)
}
const freshHandle = await openLocalTerminalArtifactGrant(grant, constants.O_RDONLY)
try {
assertTerminalFileGrantFresh(grant, await freshHandle.stat())
} finally {
await freshHandle.close()
}
await rename(tempPath, grant.absolutePath)
grant.statIdentity = terminalFileStatIdentity(
await this.statLocalTerminalPath(grant.absolutePath)
)
this.refreshTerminalFileGrant(grant)
return { ok: true }
} finally {
await rm(tempPath, { force: true }).catch(() => {})
}
}
private async readRemoteTerminalArtifactPreview(
provider: IFilesystemProvider,
grant: TerminalFileGrant
): Promise<RuntimeFilePreviewResult> {
const preview = await this.readRemoteTerminalArtifact(
provider,
grant,
RUNTIME_PREVIEWABLE_BINARY_MAX_BYTES
)
if (
!preview.isBinary &&
Buffer.byteLength(preview.content, 'utf8') > MOBILE_FILE_READ_MAX_BYTES
) {
throw new Error('file_too_large')
}
return preview
}
private async readRemoteTerminalArtifactFile(
provider: IFilesystemProvider,
grant: TerminalFileGrant,
maxBytes: number
): Promise<string> {
const result = await this.readRemoteTerminalArtifact(provider, grant, maxBytes)
if (result.isBinary) {
throw new Error('binary_file')
}
return result.content
}
private async readRemoteTerminalArtifact(
provider: IFilesystemProvider,
grant: TerminalFileGrant,
maxBytes: number
): Promise<RuntimeFilePreviewResult> {
if (!provider.readTerminalArtifact) {
throw new Error('terminal_file_grant_unavailable')
}
return provider.readTerminalArtifact(
grant.absolutePath,
this.terminalArtifactAccessOptions(grant, maxBytes)
)
}
private terminalArtifactAccessOptions(
grant: TerminalFileGrant,
maxBytes: number
): { expectedRealPath: string; expectedStatIdentity: string | null; maxBytes: number } {
return {
expectedRealPath: grant.absolutePath,
expectedStatIdentity: grant.statIdentity,
maxBytes
}
}
private async assertRemoteTerminalFileGrantFreshForRead(
grant: TerminalFileGrant
): Promise<IFilesystemProvider> {
const { provider } = await this.assertRemoteTerminalFileGrantFresh(grant)
return provider
}
private async assertRemoteTerminalFileGrantFresh(
grant: TerminalFileGrant
): Promise<{ provider: IFilesystemProvider; fileStat: FileStat }> {
const provider = await this.assertRemoteTerminalFileGrantPathStillCanonical(grant)
const fileStat = await provider.stat(grant.absolutePath)
assertTerminalFileGrantFresh(grant, fileStat)
return { provider, fileStat }
}
private async assertRemoteTerminalFileGrantPathStillCanonical(
grant: TerminalFileGrant
): Promise<IFilesystemProvider> {
if (!grant.connectionId) {
throw new Error('terminal_file_grant_mismatch')
}
const provider = getSshFilesystemProvider(grant.connectionId)
if (!provider) {
throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE)
}
const allowedPath = await this.resolveAllowedRemoteTerminalArtifactPath(
grant.absolutePath,
grant.connectionId
)
// Why: relay stat/read/write follow symlinks, so a remote temp artifact
// grant must be re-canonicalized after the terminal process can mutate it.
if (allowedPath !== grant.absolutePath) {
throw new Error('terminal_file_grant_stale')
}
return provider
}
async readFileExplorerDir(worktreeSelector: string, relativePath: string): Promise<DirEntry[]> {
const target = await this.resolveFileExplorerPath(worktreeSelector, relativePath)
const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null
if (target.connectionId) {
if (!provider) {
throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE)
}
return provider.readDir(target.path)
}
const dirPath = await resolveAuthorizedPath(target.path, this.host.requireStore())
const entries = await readdir(dirPath, { withFileTypes: true })
const mapped = await Promise.all(
entries.map(async (entry) => {
const entryPath = join(dirPath, entry.name)
return {
name: entry.name,
isDirectory: await isRuntimeDirectoryEntry(entry, entryPath),
isSymlink: entry.isSymbolicLink()
}
})
)
return mapped.sort((a, b) => {
if (a.isDirectory !== b.isDirectory) {
return a.isDirectory ? -1 : 1
}
return a.name.localeCompare(b.name)
})
}
async watchFileExplorer(
worktreeSelector: string,
callback: (events: FsChangeEvent[]) => void,
onTerminalError: (error: Error) => void = () => undefined,
signal?: AbortSignal
): Promise<() => void> {
const target = await this.resolveFileExplorerPath(worktreeSelector, '')
const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null
if (target.connectionId) {
if (!provider) {
throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE)
}
// Why: the RPC layer already threads AbortSignal for local watches; SSH
// must cancel the remote fs.watch request instead of waiting it out.
return provider.watch(target.path, callback, { signal })
}
const rootPath = await resolveAuthorizedPath(target.path, this.host.requireStore())
const rootStats = await stat(rootPath)
if (!rootStats.isDirectory()) {
throw new Error('not_a_directory')
}
if (process.platform === 'win32') {
return watchWindowsRuntimeFileExplorer(rootPath, callback)
}
// Why: the forked watcher keeps the blocking crawl and native faults out
// of the main/`serve` process (issues #5308 and #8212).
const dispose = await watchFileExplorerInWatcherProcess(
rootPath,
callback,
onTerminalError,
signal
)
return () => {
trackRuntimeFileWatcherUnsubscribe(rootPath, dispose)
}
}
async readFileExplorerPreview(
worktreeSelector: string,
relativePath: string
): Promise<RuntimeFilePreviewResult> {
const target = await this.resolveFileExplorerPath(worktreeSelector, relativePath)
const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null
if (target.connectionId) {
if (!provider) {
throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE)
}
const fileStats = await provider.stat(target.path)
if (fileStats.size > RUNTIME_PREVIEWABLE_BINARY_MAX_BYTES) {
throw new Error('file_too_large')
}