-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathterminal-sessions.ts
More file actions
1842 lines (1726 loc) · 62.5 KB
/
Copy pathterminal-sessions.ts
File metadata and controls
1842 lines (1726 loc) · 62.5 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
import {
type AppError,
listProjectItems,
prepareProjectSsh,
probeProjectSshReady,
recordProjectRuntimeActivity,
renderError,
waitForProjectSshReady
} from "@effect-template/lib"
import { runCommandCapture } from "@effect-template/lib/shell/command-runner"
import { parseInspectNetworkEntry } from "@effect-template/lib/shell/docker-inspect-parse"
import { CommandFailedError } from "@effect-template/lib/shell/errors"
import type { ProjectItem } from "@effect-template/lib/usecases/projects"
import type * as CommandExecutor from "@effect/platform/CommandExecutor"
import type { PlatformError } from "@effect/platform/Error"
import * as FileSystem from "@effect/platform/FileSystem"
import type * as PlatformPath from "@effect/platform/Path"
import { NodeContext } from "@effect/platform-node"
import * as ParseResult from "@effect/schema/ParseResult"
import * as Schema from "@effect/schema/Schema"
import { Effect, Either } from "effect"
import { Buffer } from "node:buffer"
import { spawn } from "node:child_process"
import { randomUUID } from "node:crypto"
import { existsSync } from "node:fs"
import type { IncomingMessage, Server as HttpServer } from "node:http"
import os from "node:os"
import path from "node:path"
import type { Duplex } from "node:stream"
import { WebSocket, WebSocketServer, type RawData } from "ws"
import type { TerminalSession, TerminalSessionStatus } from "../api/contracts.js"
import { ApiBadRequestError, ApiConflictError, ApiInternalError, ApiNotFoundError, describeUnknown } from "../api/errors.js"
import { emitProjectEvent, latestProjectCursor } from "./events.js"
import {
planTerminalImageFetch,
terminalImageFetchMaxBytes
} from "./terminal-image-fetch-core.js"
import {
createTerminalImagePastePlan,
terminalImagePasteDirectory,
type TerminalImagePastePayload
} from "./terminal-image-paste-core.js"
import {
appendTerminalOutput,
emptyTerminalOutputBuffer,
renderTerminalOutputBuffer,
type TerminalOutputBuffer
} from "./terminal-output-buffer.js"
import { spawnPtyBridge, type PtyBridge } from "./pty-bridge.js"
import { getProject, getProjectItemById, getProjectItemByKey, upProject } from "./projects.js"
import { attachWebSocketHeartbeat } from "./websocket-heartbeat.js"
type TerminalClientMessage =
| { readonly type: "input"; readonly data: string }
| { readonly type: "resize"; readonly cols: number; readonly rows: number }
| ({ readonly type: "image" } & TerminalImagePastePayload)
| { readonly type: "close" }
type TerminalServerMessage =
| { readonly type: "ready"; readonly session: TerminalSession }
| { readonly type: "output"; readonly data: string }
| { readonly type: "exit"; readonly exitCode: number | null; readonly signal: number | null }
| { readonly type: "error"; readonly message: string }
type TerminalRecord = {
session: TerminalSession
pty: PtyBridge | null
sockets: Set<WebSocket>
attachTimeout: ReturnType<typeof setTimeout> | null
detachTimeout: ReturnType<typeof setTimeout> | null
outputBuffer: TerminalOutputBuffer
projectContainerName: string
projectDisplayName: string
projectId: string
projectKey: string
projectTargetDir: string
prepared: ReturnType<typeof prepareProjectSsh>
tmuxName: string
}
// Effect encodes combined service requirements as a union of Context tags; intersections reject valid composition.
type TerminalSessionRuntime =
| CommandExecutor.CommandExecutor
| FileSystem.FileSystem
| PlatformPath.Path
type TerminalSessionStateRuntime =
| CommandExecutor.CommandExecutor
| FileSystem.FileSystem
| PlatformPath.Path
type DurableTerminalSession = {
readonly id: string
readonly projectId: string
readonly projectKey: string
readonly projectDisplayName: string
readonly tmuxName: string
readonly sshCommand: string
readonly createdAt: string
readonly updatedAt: string
readonly status: TerminalSessionStatus
readonly startedAt?: string | undefined
readonly closedAt?: string | undefined
}
type DurableTerminalSessionFile = {
readonly schemaVersion: 1
readonly lastActiveSessionId?: string | undefined
readonly sessions: ReadonlyArray<DurableTerminalSession>
}
const records = new Map<string, TerminalRecord>()
const terminalSessionPersistenceQueues = new Map<string, Promise<void>>()
const terminalActivityWrites = new Map<string, number>()
const terminalWsPathPattern = /^(?:\/api)?\/projects\/([^/]+)\/terminal-sessions\/([^/]+)\/ws$/u
const terminalWsByKeyPathPattern = /^(?:\/api)?\/projects\/by-key\/([^/]+)\/terminal-sessions\/([^/]+)\/ws$/u
const terminalSessionStateRelativePath: ReadonlyArray<string> = [".orch", "state", "terminal-sessions.json"]
const tmuxMissingMessage =
"tmux is not available in this project container. Apply docker-git config or rebuild the project image so tmux is installed, then reopen this SSH terminal session."
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu
const TerminalClientMessageSchema = Schema.parseJson(
Schema.Union(
Schema.Struct({
type: Schema.Literal("input"),
data: Schema.String
}),
Schema.Struct({
type: Schema.Literal("resize"),
cols: Schema.Number,
rows: Schema.Number
}),
Schema.Struct({
type: Schema.Literal("image"),
data: Schema.String,
mediaType: Schema.String,
name: Schema.String,
size: Schema.Number
}),
Schema.Struct({
type: Schema.Literal("close")
})
)
)
const DurableTerminalSessionSchema = Schema.Struct({
id: Schema.String,
projectId: Schema.String,
projectKey: Schema.String,
projectDisplayName: Schema.String,
tmuxName: Schema.String,
sshCommand: Schema.String,
createdAt: Schema.String,
updatedAt: Schema.String,
status: Schema.Literal("ready", "attached", "exited", "failed"),
startedAt: Schema.optional(Schema.String),
closedAt: Schema.optional(Schema.String)
})
const DurableTerminalSessionFileSchema = Schema.Struct({
schemaVersion: Schema.Literal(1),
lastActiveSessionId: Schema.optional(Schema.String),
sessions: Schema.Array(DurableTerminalSessionSchema)
})
const DurableTerminalSessionFileJsonSchema = Schema.parseJson(DurableTerminalSessionFileSchema)
export const clearTerminalSessionRuntimeForTest = (): void => {
for (const record of records.values()) {
clearAttachTimeout(record)
clearDetachTimeout(record)
if (record.pty !== null) {
const pty = record.pty
record.pty = null
pty.kill()
}
closeRecordSockets(record)
}
records.clear()
terminalSessionPersistenceQueues.clear()
terminalActivityWrites.clear()
}
const nowIso = (): string => new Date().toISOString()
const terminalActivityWriteIntervalMs = 30_000
const requestSessionId = (requestId: string | undefined): string | undefined =>
requestId !== undefined && uuidPattern.test(requestId) ? requestId : undefined
const isPathInsideDirectory = (root: string, candidate: string): boolean => {
const resolvedRoot = path.resolve(root)
const resolvedCandidate = path.resolve(candidate)
if (resolvedCandidate === resolvedRoot) {
return false
}
const prefix = resolvedRoot.endsWith(path.sep) ? resolvedRoot : `${resolvedRoot}${path.sep}`
return resolvedCandidate.startsWith(prefix)
}
const terminalSessionStatePath = (projectId: string): string => {
const projectRoot = path.resolve(projectId)
const statePath = path.resolve(projectRoot, ...terminalSessionStateRelativePath)
return isPathInsideDirectory(projectRoot, statePath)
? statePath
: path.resolve(projectRoot, ".orch", "state", "terminal-sessions.json")
}
const emptyTerminalSessionFile = (): DurableTerminalSessionFile => ({
schemaVersion: 1,
sessions: []
})
const validActiveSessionId = (state: DurableTerminalSessionFile): string | null => {
const activeSessionId = state.lastActiveSessionId
return activeSessionId !== undefined && state.sessions.some((session) => session.id === activeSessionId)
? activeSessionId
: null
}
const decodeTerminalSessionFile = (input: string): DurableTerminalSessionFile | null =>
Either.match(ParseResult.decodeUnknownEither(DurableTerminalSessionFileJsonSchema)(input), {
onLeft: () => null,
onRight: (value) => value
})
const readTerminalSessionFile = (
projectId: string
): Effect.Effect<DurableTerminalSessionFile, never, FileSystem.FileSystem> =>
Effect.gen(function*(_) {
const fs = yield* _(FileSystem.FileSystem)
const statePath = terminalSessionStatePath(projectId)
const exists = yield* _(Effect.either(fs.exists(statePath)))
const fileExists = Either.match(exists, {
onLeft: () => false,
onRight: (value) => value
})
if (!fileExists) {
return emptyTerminalSessionFile()
}
const contents = yield* _(Effect.either(fs.readFileString(statePath)))
return Either.match(contents, {
onLeft: () => emptyTerminalSessionFile(),
onRight: (value) => decodeTerminalSessionFile(value) ?? emptyTerminalSessionFile()
})
}).pipe(Effect.catchAll(() => Effect.succeed(emptyTerminalSessionFile())))
const toTerminalSessionStateError = (
action: string,
projectId: string
) =>
(error: PlatformError | ApiInternalError): ApiInternalError =>
error instanceof ApiInternalError
? error
: new ApiInternalError({
message: `Failed to ${action} terminal session state for project: ${projectId}`,
cause: error
})
const writeTerminalSessionFile = (
projectId: string,
state: DurableTerminalSessionFile
): Effect.Effect<void, ApiInternalError, FileSystem.FileSystem> =>
Effect.gen(function*(_) {
const fs = yield* _(FileSystem.FileSystem)
const statePath = terminalSessionStatePath(projectId)
yield* _(
fs.makeDirectory(path.dirname(statePath), { recursive: true }).pipe(
Effect.mapError(toTerminalSessionStateError("create", projectId))
)
)
yield* _(
fs.writeFileString(statePath, `${JSON.stringify(state, null, 2)}\n`).pipe(
Effect.mapError(toTerminalSessionStateError("write", projectId))
)
)
})
const tmuxNameForSessionId = (sessionId: string): string => {
const normalized = sessionId.replace(/[^A-Za-z0-9_-]/gu, "-").replace(/-+/gu, "-")
return `docker-git-${normalized.slice(0, 80)}`
}
const terminalSessionFromDurable = (
durable: DurableTerminalSession,
attachedClients: number
): TerminalSession => ({
id: durable.id,
projectId: durable.projectId,
sshCommand: durable.sshCommand,
status: attachedClients > 0
? "attached"
: durable.status === "attached"
? "ready"
: durable.status,
createdAt: durable.createdAt,
attachedClients,
...(durable.startedAt === undefined ? {} : { startedAt: durable.startedAt }),
...(durable.closedAt === undefined ? {} : { closedAt: durable.closedAt })
})
const durableFromSession = (
args: {
readonly projectDisplayName: string
readonly projectKey: string
readonly session: TerminalSession
readonly tmuxName: string
readonly updatedAt: string
}
): DurableTerminalSession => ({
id: args.session.id,
projectId: args.session.projectId,
projectKey: args.projectKey,
projectDisplayName: args.projectDisplayName,
tmuxName: args.tmuxName,
sshCommand: args.session.sshCommand,
createdAt: args.session.createdAt,
updatedAt: args.updatedAt,
status: args.session.status,
...(args.session.startedAt === undefined ? {} : { startedAt: args.session.startedAt }),
...(args.session.closedAt === undefined ? {} : { closedAt: args.session.closedAt })
})
const upsertDurableSession = (
projectId: string,
durable: DurableTerminalSession,
options: {
readonly activate?: boolean
} = {}
): Effect.Effect<void, ApiInternalError, FileSystem.FileSystem> =>
Effect.gen(function*(_) {
const state = yield* _(readTerminalSessionFile(projectId))
const sessions = state.sessions.filter((session) => session.id !== durable.id)
yield* _(writeTerminalSessionFile(projectId, {
...(options.activate === true ? { lastActiveSessionId: durable.id } : { lastActiveSessionId: validActiveSessionId(state) ?? undefined }),
schemaVersion: 1,
sessions: [...sessions, durable]
}))
})
const patchDurableSession = (
record: TerminalRecord,
patch: Partial<TerminalSession>
): Effect.Effect<void, ApiInternalError, FileSystem.FileSystem> =>
Effect.gen(function*(_) {
const state = yield* _(readTerminalSessionFile(record.projectId))
const updatedAt = nowIso()
const sessions = state.sessions.map((session) =>
session.id === record.session.id
? durableFromSession({
projectDisplayName: record.projectDisplayName,
projectKey: record.projectKey,
session: {
...terminalSessionFromDurable(session, 0),
...patch
},
tmuxName: session.tmuxName,
updatedAt
})
: session
)
yield* _(writeTerminalSessionFile(record.projectId, {
lastActiveSessionId: validActiveSessionId({ ...state, sessions }) ?? undefined,
schemaVersion: 1,
sessions
}))
})
const deleteDurableSession = (
projectId: string,
sessionId: string
): Effect.Effect<boolean, ApiInternalError, FileSystem.FileSystem> =>
Effect.gen(function*(_) {
const state = yield* _(readTerminalSessionFile(projectId))
const sessions = state.sessions.filter((session) => session.id !== sessionId)
if (sessions.length === state.sessions.length) {
return false
}
yield* _(writeTerminalSessionFile(projectId, {
lastActiveSessionId: state.lastActiveSessionId === sessionId
? undefined
: validActiveSessionId({ ...state, sessions }) ?? undefined,
schemaVersion: 1,
sessions
}))
return true
})
const setActiveDurableSession = (
projectId: string,
sessionId: string
): Effect.Effect<DurableTerminalSession, ApiInternalError | ApiNotFoundError, FileSystem.FileSystem> =>
Effect.gen(function*(_) {
const state = yield* _(readTerminalSessionFile(projectId))
const durable = state.sessions.find((session) => session.id === sessionId)
if (durable === undefined) {
return yield* _(Effect.fail(new ApiNotFoundError({ message: `Terminal session not found: ${sessionId}` })))
}
yield* _(writeTerminalSessionFile(projectId, {
lastActiveSessionId: sessionId,
schemaVersion: 1,
sessions: state.sessions
}))
return durable
})
const findDurableSession = (
projectId: string,
sessionId: string
): Effect.Effect<DurableTerminalSession | null, never, FileSystem.FileSystem> =>
readTerminalSessionFile(projectId).pipe(
Effect.map((state) => state.sessions.find((session) => session.id === sessionId) ?? null)
)
const isAppError = (value: unknown): value is AppError =>
typeof value === "object" && value !== null && "_tag" in value
const runTerminalSessionPersistence = (
projectId: string,
effect: Effect.Effect<void, ApiInternalError, FileSystem.FileSystem>
): void => {
const previous = terminalSessionPersistenceQueues.get(projectId) ?? Promise.resolve()
const next = previous
.catch(() => undefined)
.then(() =>
Effect.runPromise(
effect.pipe(
Effect.provide(NodeContext.layer),
Effect.catchAll((error) =>
Effect.logWarning(
`[terminal-sessions] Failed to persist state for project ${projectId}: ${describeUnknown(error)}`
)
)
)
)
)
.catch(() => undefined)
.finally(() => {
if (terminalSessionPersistenceQueues.get(projectId) === next) {
terminalSessionPersistenceQueues.delete(projectId)
}
})
terminalSessionPersistenceQueues.set(projectId, next)
}
const updateSession = (
record: TerminalRecord,
patch: Partial<TerminalSession>
): void => {
record.session = {
...record.session,
...patch
}
records.set(record.session.id, record)
runTerminalSessionPersistence(record.projectId, patchDurableSession(record, patch))
}
const attachedClientCount = (record: TerminalRecord): number => {
for (const socket of [...record.sockets]) {
if (socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) {
record.sockets.delete(socket)
}
}
return record.sockets.size
}
const syncAttachedClientCount = (record: TerminalRecord): void => {
updateSession(record, { attachedClients: attachedClientCount(record) })
}
const touchProjectInteractiveActivity = (projectId: string): void => {
const now = Date.now()
const lastWrite = terminalActivityWrites.get(projectId) ?? 0
if (now - lastWrite < terminalActivityWriteIntervalMs) {
return
}
terminalActivityWrites.set(projectId, now)
Effect.runFork(
recordProjectRuntimeActivity(projectId, "interactive").pipe(
Effect.provide(NodeContext.layer),
Effect.catchAll((error) =>
Effect.logWarning(
`[terminal-sessions] Failed to record interactive activity for project ${projectId}: ${
error instanceof Error ? error.message : describeUnknown(error)
}`
)
)
)
)
}
const toApiInternalError = (error: unknown): ApiInternalError =>
error instanceof ApiInternalError
? error
: new ApiInternalError({
message: isAppError(error) ? renderError(error) : describeUnknown(error),
cause: error
})
const toTerminalSessionLookupError = (
error: unknown
): ApiConflictError | ApiInternalError | ApiNotFoundError =>
error instanceof ApiConflictError || error instanceof ApiInternalError || error instanceof ApiNotFoundError
? error
: toApiInternalError(error)
const toTerminalSessionProjectError = (
error: unknown
): ApiInternalError | ApiNotFoundError =>
error instanceof ApiNotFoundError ? error : toApiInternalError(error)
const normalizeSshKeyPermissions = (sshKeyPath: string | null) =>
sshKeyPath === null
? Effect.void
: FileSystem.FileSystem.pipe(
Effect.flatMap((fs) => fs.chmod(sshKeyPath, 0o600).pipe(Effect.orElseSucceed(() => void 0)))
)
type ContainerNetworkEntry = {
readonly ipAddress: string
readonly name: string
}
const dockerGitApiContainerName = (): string =>
process.env["DOCKER_GIT_API_CONTAINER_NAME"]?.trim() || os.hostname().trim() || "docker-git-api"
const isContainerizedController = (): boolean => {
const configuredName = process.env["DOCKER_GIT_API_CONTAINER_NAME"]?.trim()
return (configuredName !== undefined && configuredName.length > 0) || existsSync("/.dockerenv")
}
const parseContainerNetworkEntries = (output: string): ReadonlyArray<ContainerNetworkEntry> =>
output
.trim()
.split(/\r?\n/u)
.flatMap((line) => parseInspectNetworkEntry(line))
.map(([name, ipAddress]) => ({ name, ipAddress }))
const selectReachableProjectNetwork = (
projectEntries: ReadonlyArray<ContainerNetworkEntry>,
controllerEntries: ReadonlyArray<ContainerNetworkEntry>
): ContainerNetworkEntry | null =>
projectEntries.find((entry) =>
entry.name !== "bridge" && controllerEntries.some((controllerEntry) => controllerEntry.name === entry.name)
) ??
projectEntries.find((entry) =>
controllerEntries.some((controllerEntry) => controllerEntry.name === entry.name)
) ??
null
const selectFallbackProjectNetwork = (
entries: ReadonlyArray<ContainerNetworkEntry>
): ContainerNetworkEntry | null =>
isContainerizedController()
? entries.find((entry) => entry.name === "bridge") ?? entries[0] ?? null
: null
const inspectContainerNetworks = (
containerName: string
) =>
runCommandCapture(
{
cwd: process.cwd(),
command: "docker",
args: [
"inspect",
"-f",
String.raw`{{range $k,$v := .NetworkSettings.Networks}}{{printf "%s=%s\n" $k $v.IPAddress}}{{end}}`,
containerName
]
},
[0],
(exitCode) => new CommandFailedError({ command: "docker inspect networks", exitCode })
).pipe(Effect.map(parseContainerNetworkEntries))
const connectContainerToNetwork = (
networkName: string,
containerName: string
) =>
networkName === "bridge"
? Effect.succeed(true)
: runCommandCapture(
{
cwd: process.cwd(),
command: "docker",
args: ["network", "connect", networkName, containerName]
},
[0],
(exitCode) => new CommandFailedError({ command: `docker network connect ${networkName}`, exitCode })
).pipe(
Effect.as(true),
Effect.orElseSucceed(() => false)
)
const resolveControllerReachableProject = (
projectItem: ProjectItem
) =>
Effect.gen(function*(_) {
const controllerContainer = dockerGitApiContainerName()
const networkEntries = yield* _(inspectContainerNetworks(projectItem.containerName).pipe(Effect.orElseSucceed(() => [])))
const controllerNetworks = yield* _(inspectContainerNetworks(controllerContainer).pipe(Effect.orElseSucceed(() => [])))
const alreadyReachable = selectReachableProjectNetwork(networkEntries, controllerNetworks)
if (alreadyReachable !== null) {
return {
...projectItem,
ipAddress: alreadyReachable.ipAddress
}
}
yield* _(
Effect.forEach(
networkEntries.filter((entry) => entry.name !== "bridge"),
(entry) => connectContainerToNetwork(entry.name, controllerContainer),
{ discard: true }
)
)
const refreshedControllerNetworks = yield* _(
inspectContainerNetworks(controllerContainer).pipe(Effect.orElseSucceed(() => []))
)
const preferredNetwork = selectReachableProjectNetwork(networkEntries, refreshedControllerNetworks) ??
selectFallbackProjectNetwork(networkEntries)
if (preferredNetwork === null) {
return projectItem
}
return {
...projectItem,
ipAddress: preferredNetwork.ipAddress
}
})
const encodeServerMessage = (message: TerminalServerMessage): string => JSON.stringify(message)
const renderPreparedSshCommand = (prepared: ReturnType<typeof prepareProjectSsh>): string =>
[prepared.command, ...prepared.args].join(" ")
const sendServerMessage = (socket: WebSocket | null, message: TerminalServerMessage): void => {
if (socket === null || socket.readyState !== WebSocket.OPEN) {
return
}
socket.send(encodeServerMessage(message))
}
const broadcastServerMessage = (record: TerminalRecord, message: TerminalServerMessage): void => {
for (const socket of record.sockets) {
sendServerMessage(socket, message)
}
}
const sendTerminalOutput = (record: TerminalRecord, data: string): void => {
record.outputBuffer = appendTerminalOutput(record.outputBuffer, data)
broadcastServerMessage(record, { type: "output", data })
}
const replayTerminalOutput = (record: TerminalRecord, socket: WebSocket): void => {
const data = renderTerminalOutputBuffer(record.outputBuffer)
if (data.length > 0) {
sendServerMessage(socket, { type: "output", data })
}
}
const clearAttachTimeout = (record: TerminalRecord): void => {
if (record.attachTimeout !== null) {
clearTimeout(record.attachTimeout)
record.attachTimeout = null
}
}
const clearDetachTimeout = (record: TerminalRecord): void => {
if (record.detachTimeout !== null) {
clearTimeout(record.detachTimeout)
record.detachTimeout = null
}
}
const closeSocket = (socket: WebSocket | null): void => {
if (socket === null || socket.readyState === WebSocket.CLOSED) {
return
}
socket.close()
}
const closeRecordSockets = (record: TerminalRecord): void => {
for (const socket of record.sockets) {
closeSocket(socket)
}
record.sockets.clear()
}
const cleanupRecord = (record: TerminalRecord): void => {
clearAttachTimeout(record)
clearDetachTimeout(record)
if (record.pty !== null) {
const pty = record.pty
record.pty = null
pty.kill()
}
closeRecordSockets(record)
records.delete(record.session.id)
}
const detachRecordPty = (record: TerminalRecord): void => {
if (record.pty === null) {
updateSession(record, {
attachedClients: attachedClientCount(record),
status: "ready"
})
return
}
const pty = record.pty
record.pty = null
updateSession(record, {
attachedClients: attachedClientCount(record),
status: "ready"
})
pty.kill()
}
const finalizeRecord = (
record: TerminalRecord,
status: Extract<TerminalSessionStatus, "exited" | "failed">,
exitCode: number | null,
signal: number | null
): void => {
// A clean tmux-backed PTY exit leaves the project session reattachable.
const nextStatus = exitCode === 0 || exitCode === 130 ? "ready" : status
broadcastServerMessage(record, { type: "exit", exitCode, signal })
closeRecordSockets(record)
record.pty = null
clearAttachTimeout(record)
clearDetachTimeout(record)
updateSession(record, {
attachedClients: attachedClientCount(record),
closedAt: nowIso(),
exitCode: exitCode ?? undefined,
signal: signal ?? undefined,
status: nextStatus
})
}
const decodeClientMessage = (raw: RawData): TerminalClientMessage | null =>
Either.getOrNull(
ParseResult.decodeUnknownEither(TerminalClientMessageSchema)(
typeof raw === "string"
? raw
: Array.isArray(raw)
? Buffer.concat(raw).toString("utf8")
: raw instanceof ArrayBuffer
? Buffer.from(new Uint8Array(raw)).toString("utf8")
: raw.toString("utf8")
)
)
const clampTerminalSize = (value: number, fallback: number): number =>
Number.isFinite(value) && value > 0 ? Math.max(1, Math.floor(value)) : fallback
const writePtyInput = (pty: PtyBridge | null, data: string): void => {
if (pty === null) {
return
}
try {
pty.write(data)
} catch {
return
}
}
const shellQuote = (value: string): string => `'${value.replace(/'/gu, "'\\''")}'`
// CHANGE: Predicate for when tmux should forward right-click pane events.
// WHY: Mouse-aware apps receive pane events; copy/view mode keeps tmux handling unless mouse tracking is active.
// QUOTE(TZ): issue #340 right-click must not open the default tmux menu in browser terminals.
// REF: PR #342 tmux right-click handling.
// SOURCE: n/a
// FORMAT THEOREM: mouse_any_flag or non-copy/view pane mode => predicate evaluates truthy in tmux.
// PURITY: CORE
// EFFECT: none
// INVARIANT: The predicate contains only tmux format language and no shell interpolation.
// COMPLEXITY: O(1) time/O(1) space.
/**
* Tmux format predicate used by right-click pane bindings.
*
* @returns A tmux format expression, not a shell command.
* @pure true
* @effect none
* @invariant Expression is constant and contains no user-controlled input.
* @precondition tmux understands mouse_any_flag and pane mode format variables.
* @postcondition The value is safe to embed after shellQuote.
* @complexity O(1) time/O(1) space.
* @throws Never
*/
const tmuxRightClickForwardPredicate =
"#{||:#{mouse_any_flag},#{&&:#{pane_in_mode},#{?#{m/r:(copy|view)-mode,#{pane_mode}},0,1}}}"
// CHANGE: Pane right-click bindings that are overridden at tmux startup.
// WHY: These cover down/drag/up/end and Meta-modified events that previously reached display-menu.
// QUOTE(TZ): issue #340 right-click must not open the default tmux menu in browser terminals.
// REF: PR #342 tmux right-click handling.
// SOURCE: n/a
// FORMAT THEOREM: every binding in the array is mapped to renderTmuxPaneRightClickBinding.
// PURITY: CORE
// EFFECT: none
// INVARIANT: Each entry is a static tmux root-table mouse binding name.
// COMPLEXITY: O(1) time/O(1) space.
/**
* Tmux pane right-click binding names that should conditionally forward mouse events.
*
* @pure true
* @effect none
* @invariant The array contains only static tmux binding identifiers.
* @precondition tmux root key table supports these binding names.
* @postcondition Consumers can map each entry to a shell-safe bind-key command.
* @complexity O(1) time/O(1) space.
* @throws Never
*/
const tmuxRightClickPaneBindings: ReadonlyArray<string> = [
"MouseDown3Pane",
"MouseDrag3Pane",
"MouseDragEnd3Pane",
"MouseUp3Pane",
"M-MouseDown3Pane",
"M-MouseDrag3Pane",
"M-MouseDragEnd3Pane",
"M-MouseUp3Pane"
]
// CHANGE: Non-pane right-click bindings that are suppressed at tmux startup.
// WHY: Status and border right-clicks are the tmux menu entry points that cannot be forwarded to pane apps.
// QUOTE(TZ): issue #340 right-click must not open the default tmux menu in browser terminals.
// REF: PR #342 tmux right-click handling.
// SOURCE: n/a
// FORMAT THEOREM: every binding in the array is mapped to renderTmuxRightClickSuppressBinding.
// PURITY: CORE
// EFFECT: none
// INVARIANT: Each entry is a static tmux root-table mouse binding name.
// COMPLEXITY: O(1) time/O(1) space.
/**
* Tmux status/border right-click binding names that should be unbound.
*
* @pure true
* @effect none
* @invariant The array contains only static tmux binding identifiers.
* @precondition tmux root key table supports these binding names.
* @postcondition Consumers can map each entry to a shell-safe unbind-key command.
* @complexity O(1) time/O(1) space.
* @throws Never
*/
const tmuxRightClickSuppressBindings: ReadonlyArray<string> = [
"MouseDown3Status",
"MouseDown3StatusLeft",
"MouseDown3StatusRight",
"MouseDown3Border",
"M-MouseDown3Status",
"M-MouseDown3StatusLeft",
"M-MouseDown3StatusRight",
"M-MouseDown3Border"
]
// CHANGE: Render one tmux bind-key command for a right-click pane event.
// WHY: Pane events must reach mouse-aware programs without allowing tmux display-menu.
// QUOTE(TZ): issue #340 right-click must not open the default tmux menu in browser terminals.
// REF: PR #342 tmux right-click handling.
// SOURCE: n/a
// FORMAT THEOREM: static binding => shellQuote(protected fragments) in result.
// PURITY: CORE
// EFFECT: none
// INVARIANT: Dynamic shell fragments are emitted through shellQuote.
// COMPLEXITY: O(1) time/O(1) space.
/**
* Builds a tmux root-table command for a pane right-click binding.
*
* @param binding - Static tmux mouse binding name.
* @returns Shell command that binds the event to conditional pane forwarding.
* @pure true
* @effect none
* @invariant Shell-interpreted tmux format/action fragments are quoted.
* @precondition binding is one of tmuxRightClickPaneBindings.
* @postcondition The command exits successfully even when tmux rejects a binding.
* @complexity O(1) time/O(1) space.
* @throws Never
*/
const renderTmuxPaneRightClickBinding = (binding: string): string =>
`tmux bind-key -T root ${binding} if-shell -F -t = ${shellQuote(tmuxRightClickForwardPredicate)} ${
shellQuote("select-pane -t = ; send-keys -M")
} >/dev/null 2>&1 || true`
// CHANGE: Render one tmux unbind-key command for a suppressed right-click event.
// WHY: Non-pane right-click targets are tmux UI affordances and should not open display-menu.
// QUOTE(TZ): issue #340 right-click must not open the default tmux menu in browser terminals.
// REF: PR #342 tmux right-click handling.
// SOURCE: n/a
// FORMAT THEOREM: static binding => deterministic unbind command.
// PURITY: CORE
// EFFECT: none
// INVARIANT: Result contains no user-controlled input.
// COMPLEXITY: O(1) time/O(1) space.
/**
* Builds a tmux root-table command that suppresses a non-pane right-click binding.
*
* @param binding - Static tmux mouse binding name.
* @returns Shell command that unbinds the event and tolerates unsupported bindings.
* @pure true
* @effect none
* @invariant The returned command contains only static text plus binding.
* @precondition binding is one of tmuxRightClickSuppressBindings.
* @postcondition The command exits successfully even when the binding is absent.
* @complexity O(1) time/O(1) space.
* @throws Never
*/
const renderTmuxRightClickSuppressBinding = (binding: string): string =>
`tmux unbind-key -T root ${binding} >/dev/null 2>&1 || true`
// CHANGE: Aggregate all tmux right-click startup commands.
// WHY: Terminal session startup needs one ordered command list for pane forwarding and UI suppression.
// QUOTE(TZ): PR #342 preserves right-click copy while tmux mouse tracking is active.
// REF: PR #342 tmux right-click handling.
// SOURCE: n/a
// FORMAT THEOREM: result length = paneBindings length + suppressBindings length.
// PURITY: CORE
// EFFECT: none
// INVARIANT: Pane commands precede suppress commands.
// COMPLEXITY: O(n) time/O(n) space where n is the total binding count.
/**
* Renders the complete tmux right-click binding setup command list.
*
* @returns Readonly array of shell commands for tmux startup.
* @pure true
* @effect none
* @invariant Pane forwarding commands are emitted before suppressing status/border commands.
* @precondition Binding arrays contain static tmux binding identifiers.
* @postcondition The result contains one command per configured binding.
* @complexity O(n) time/O(n) space where n is total binding count.
* @throws Never
*/
const renderTmuxRightClickBindingCommands = (): ReadonlyArray<string> => [
...tmuxRightClickPaneBindings.map(renderTmuxPaneRightClickBinding),
...tmuxRightClickSuppressBindings.map(renderTmuxRightClickSuppressBinding)
]
const writeBufferToProjectContainer = (
containerName: string,
containerPath: string,
buffer: Buffer
): Effect.Effect<void, ApiInternalError> =>
Effect.async((resume) => {
const child = spawn(
"docker",
[
"exec",
"-i",
"-u",
"dev",
containerName,
"bash",
"--noprofile",
"--norc",
"-c",
`mkdir -p ${shellQuote(terminalImagePasteDirectory)} && cat > ${shellQuote(containerPath)}`
],
{
cwd: process.cwd(),
stdio: ["pipe", "ignore", "pipe"]
}
)
const stderrChunks: Array<Buffer> = []
let completed = false
const resumeOnce = (effect: Effect.Effect<void, ApiInternalError>): void => {
if (completed) {
return
}
completed = true
resume(effect)
}
child.stderr.on("data", (chunk: Buffer | string) => {
stderrChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
})
child.stdin.on("error", (error) => {
resumeOnce(Effect.fail(new ApiInternalError({
message: `Failed to write pasted image to ${containerName}.`,
cause: error
})))
})
child.on("error", (error) => {
resumeOnce(Effect.fail(new ApiInternalError({
message: `Failed to run docker exec for ${containerName}.`,
cause: error
})))
})
child.on("close", (exitCode) => {
if (exitCode === 0) {
resumeOnce(Effect.void)
return
}
const stderr = Buffer.concat(stderrChunks).toString("utf8").trim()
resumeOnce(Effect.fail(new ApiInternalError({
message: stderr.length > 0
? `Failed to save pasted image: ${stderr}`
: `Failed to save pasted image; docker exec exited with code ${exitCode ?? "unknown"}.`
})))
})
child.stdin.end(buffer)
})
const readBufferFromProjectContainer = (