-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathDockerRuntime.ts
More file actions
1271 lines (1135 loc) · 44 KB
/
DockerRuntime.ts
File metadata and controls
1271 lines (1135 loc) · 44 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
/**
* Docker runtime implementation that executes commands inside Docker containers.
*
* Features:
* - Each workspace runs in its own container
* - Container name derived from project+workspace name
* - Uses docker exec for command execution
* - Hardcoded paths: srcBaseDir=/src, bgOutputDir=/tmp/mux-bashes
* - Managed lifecycle: container created/destroyed with workspace
*
* Extends RemoteRuntime for shared exec/file operations.
*/
import { spawn, exec } from "child_process";
import { createHash } from "crypto";
import * as path from "path";
import * as fs from "fs/promises";
import * as os from "os";
import type {
ExecOptions,
WorkspaceCreationParams,
WorkspaceCreationResult,
WorkspaceInitParams,
WorkspaceInitResult,
WorkspaceForkParams,
WorkspaceForkResult,
InitLogger,
EnsureReadyResult,
} from "./Runtime";
import { RuntimeError } from "./Runtime";
import { RemoteRuntime, type SpawnResult } from "./RemoteRuntime";
import { runInitHookOnRuntime, runWorkspaceInitHook } from "./initHook";
import { getProjectName } from "@/node/utils/runtime/helpers";
import { getErrorMessage } from "@/common/utils/errors";
import { syncProjectViaGitBundle } from "./gitBundleSync";
import { GIT_NO_HOOKS_ENV, gitNoHooksPrefix } from "@/node/utils/gitNoHooksEnv";
import {
getHostGitconfigPath,
hasHostGitconfig,
resolveGhToken,
resolveSshAgentForwarding,
} from "./credentialForwarding";
import { streamToString, shescape } from "./streamUtils";
import { syncRuntimeGitSubmodules } from "./submoduleSync";
/** Hardcoded source directory inside container */
const CONTAINER_SRC_DIR = "/src";
/**
* Result of running a Docker command
*/
interface DockerCommandResult {
exitCode: number;
stdout: string;
stderr: string;
}
/**
* Sanitize container-provided uid/gid before embedding in host-side shell commands.
* Container images can override `id`; only decimal numeric IDs are valid for chown.
*/
function sanitizeContainerUserId(rawValue: string): string {
const trimmedValue = rawValue.trim();
return /^\d+$/.test(trimmedValue) ? trimmedValue : "0";
}
/** Result of checking if a container already exists and is valid for reuse */
type ContainerCheckResult =
| { action: "skip" } // Valid forked container, skip setup
| { action: "cleanup"; reason: string } // Exists but invalid, needs removal
| { action: "create" }; // Doesn't exist, proceed to create
/**
* Run a Docker CLI command and return result.
* Unlike execAsync, this always resolves (never rejects) and returns exit code.
*/
function runDockerCommand(command: string, timeoutMs = 30000): Promise<DockerCommandResult> {
return new Promise((resolve) => {
let stdout = "";
let stderr = "";
let timedOut = false;
const child = exec(command);
const timer = setTimeout(() => {
timedOut = true;
child.kill();
resolve({ exitCode: -1, stdout, stderr: "Command timed out" });
}, timeoutMs);
child.stdout?.on("data", (data: Buffer) => {
stdout += data.toString();
});
child.stderr?.on("data", (data: Buffer) => {
stderr += data.toString();
});
child.on("close", (code) => {
clearTimeout(timer);
if (timedOut) return;
resolve({ exitCode: code ?? -1, stdout, stderr });
});
child.on("error", (err) => {
clearTimeout(timer);
if (timedOut) return;
resolve({ exitCode: -1, stdout, stderr: err.message });
});
});
}
/**
* Run a command with array args (no shell interpolation).
* Similar to runDockerCommand but safer for paths with special characters.
*/
function runSpawnCommand(
command: string,
args: string[],
timeoutMs = 30000
): Promise<DockerCommandResult> {
return new Promise((resolve) => {
let stdout = "";
let stderr = "";
let timedOut = false;
const child = spawn(command, args);
const timer = setTimeout(() => {
timedOut = true;
child.kill();
resolve({ exitCode: -1, stdout, stderr: "Command timed out" });
}, timeoutMs);
child.stdout?.on("data", (data: Buffer) => {
stdout += data.toString();
});
child.stderr?.on("data", (data: Buffer) => {
stderr += data.toString();
});
child.on("close", (code) => {
clearTimeout(timer);
if (timedOut) return;
resolve({ exitCode: code ?? -1, stdout, stderr });
});
child.on("error", (err) => {
clearTimeout(timer);
if (timedOut) return;
resolve({ exitCode: -1, stdout, stderr: err.message });
});
});
}
/**
* Build Docker args for credential sharing.
* Forwards SSH agent into the container.
* Note: ~/.gitconfig is copied (not mounted) after container creation so gh can modify it.
* Uses agent forwarding only (no ~/.ssh mount) to avoid passphrase/permission issues.
*/
function buildCredentialArgs(): string[] {
const args: string[] = [];
// SSH agent forwarding (no ~/.ssh mount - causes passphrase/permission issues)
const sshForwarding = resolveSshAgentForwarding("/ssh-agent");
if (sshForwarding) {
args.push("-v", `${sshForwarding.hostSocketPath}:${sshForwarding.targetSocketPath}:ro`);
args.push("-e", `SSH_AUTH_SOCK=${sshForwarding.targetSocketPath}`);
}
// GitHub CLI auth via token
const ghToken = resolveGhToken();
if (ghToken) {
args.push("-e", `GH_TOKEN=${ghToken}`);
}
return args;
}
/**
* Run docker run with streaming output (for image pull progress).
* Streams stdout/stderr to initLogger for visibility during image pulls.
*/
function streamDockerRun(
containerName: string,
image: string,
initLogger: InitLogger,
options?: { abortSignal?: AbortSignal; shareCredentials?: boolean; timeoutMs?: number }
): Promise<DockerCommandResult> {
const { abortSignal, shareCredentials, timeoutMs = 600000 } = options ?? {};
return new Promise((resolve) => {
let stdout = "";
let stderr = "";
let resolved = false;
const finish = (result: DockerCommandResult) => {
if (resolved) return;
resolved = true;
clearTimeout(timer);
abortSignal?.removeEventListener("abort", abortHandler);
resolve(result);
};
// Build docker run args
const dockerArgs = ["run", "-d", "--name", containerName];
if (shareCredentials) {
dockerArgs.push(...buildCredentialArgs());
}
dockerArgs.push(image, "sleep", "infinity");
// Use spawn for streaming output - array args don't need shell escaping
const child = spawn("docker", dockerArgs);
const timer = setTimeout(() => {
child.kill();
void runDockerCommand(`docker rm -f ${containerName}`, 10000);
finish({ exitCode: -1, stdout, stderr: "Container creation timed out" });
}, timeoutMs);
const abortHandler = () => {
child.kill();
// Container might have been created before abort - clean it up
void runDockerCommand(`docker rm -f ${containerName}`, 10000);
finish({ exitCode: -1, stdout, stderr: "Aborted" });
};
abortSignal?.addEventListener("abort", abortHandler);
child.stdout?.on("data", (data: Buffer) => {
const text = data.toString();
stdout += text;
// docker run -d outputs container ID to stdout, not useful to stream
});
child.stderr?.on("data", (data: Buffer) => {
const text = data.toString();
stderr += text;
// Stream pull progress to init logger
for (const line of text.split("\n").filter((l) => l.trim())) {
initLogger.logStdout(line);
}
});
child.on("close", (code) => {
finish({ exitCode: code ?? -1, stdout, stderr });
});
child.on("error", (err) => {
finish({ exitCode: -1, stdout, stderr: err.message });
});
});
}
export interface DockerRuntimeConfig {
/** Docker image to use (e.g., node:20) */
image: string;
/**
* Container name for existing workspaces.
* When creating a new workspace, this is computed during createWorkspace().
* When recreating runtime for an existing workspace, this should be passed
* to allow exec operations without calling createWorkspace again.
*/
containerName?: string;
/** Forward SSH agent and mount ~/.gitconfig read-only into container */
shareCredentials?: boolean;
}
/**
* Sanitize a string for use in Docker container names.
* Docker names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]*
*/
function sanitizeContainerName(name: string): string {
return name
.replace(/[^a-zA-Z0-9_.-]/g, "-")
.replace(/^[^a-zA-Z0-9]+/, "")
.replace(/-+/g, "-");
}
/**
* Generate container name from project path and workspace name.
* Format: mux-{projectName}-{workspaceName}-{hash}
* Hash suffix prevents collisions (e.g., feature/foo vs feature-foo)
*/
export function getContainerName(projectPath: string, workspaceName: string): string {
const projectName = getProjectName(projectPath);
const hash = createHash("sha256")
.update(`${projectPath}:${workspaceName}`)
.digest("hex")
.slice(0, 6);
// Reserve 7 chars for "-{hash}", leaving 56 for base
const base = sanitizeContainerName(`mux-${projectName}-${workspaceName}`).slice(0, 56);
return `${base}-${hash}`;
}
/**
* Docker runtime implementation that executes commands inside Docker containers.
* Extends RemoteRuntime for shared exec/file operations.
*/
export class DockerRuntime extends RemoteRuntime {
private readonly config: DockerRuntimeConfig;
/** Container name - set during construction (for existing) or createWorkspace (for new) */
private containerName?: string;
/** Container user info - detected after container creation/start */
private containerUid?: string;
private containerGid?: string;
private containerHome?: string;
constructor(config: DockerRuntimeConfig) {
super();
this.config = config;
// If container name is provided (existing workspace), store it
if (config.containerName) {
this.containerName = config.containerName;
}
}
/**
* Get the container name (if set)
*/
public getContainerName(): string | undefined {
return this.containerName;
}
/**
* Get Docker image name
*/
public getImage(): string {
return this.config.image;
}
// ===== RemoteRuntime abstract method implementations =====
protected readonly commandPrefix = "Docker";
protected getBasePath(): string {
return CONTAINER_SRC_DIR;
}
protected quoteForRemote(filePath: string): string {
// Expand ~ to container user's home (detected at runtime, defaults to /root)
const home = this.containerHome ?? "/root";
const expanded = filePath.startsWith("~/")
? `${home}/${filePath.slice(2)}`
: filePath === "~"
? home
: filePath;
return shescape.quote(expanded);
}
protected cdCommand(cwd: string): string {
return `cd ${shescape.quote(cwd)}`;
}
protected spawnRemoteProcess(
fullCommand: string,
_options: ExecOptions & { deadlineMs?: number }
): Promise<SpawnResult> {
// Verify container name is available
if (!this.containerName) {
throw new RuntimeError(
"Docker runtime not initialized with container name. " +
"For existing workspaces, pass containerName in config. " +
"For new workspaces, call createWorkspace first.",
"exec"
);
}
// Build docker exec args.
//
// Note: RemoteRuntime.exec() injects env vars via `export ...`, so we don't need `docker exec -e`
// here (and avoiding `-e` keeps quoting behavior consistent with SSH).
const dockerArgs: string[] = ["exec", "-i", this.containerName, "bash", "-c", fullCommand];
// Spawn docker exec command
const process = spawn("docker", dockerArgs, {
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
});
return Promise.resolve({ process });
}
/**
* Override buildWriteCommand to preserve symlinks and file permissions.
*
* This matches SSHRuntime behavior: write through the symlink to the final target,
* while keeping the symlink itself intact.
*/
protected buildWriteCommand(quotedPath: string, quotedTempPath: string): string {
// Default to 644 (world-readable) for new files, particularly important for
// plan files in /var/mux which need to be readable by VS Code Dev Containers
return `RESOLVED=$(readlink -f ${quotedPath} 2>/dev/null || echo ${quotedPath}) && PERMS=$(stat -c '%a' "$RESOLVED" 2>/dev/null || echo 644) && mkdir -p $(dirname "$RESOLVED") && cat > ${quotedTempPath} && chmod "$PERMS" ${quotedTempPath} && mv ${quotedTempPath} "$RESOLVED"`;
}
// ===== Runtime interface implementations =====
resolvePath(filePath: string): Promise<string> {
// DockerRuntime uses a fixed workspace base (/src), but we still want reasonable shell-style
// behavior for callers that pass "~" or "~/...".
//
// NOTE: Some base images (e.g., codercom/*-base) run as a non-root user (like "coder"), so
// "~" should resolve to that user's home (e.g., /home/coder), not /root.
const home = this.containerHome ?? "/root";
if (filePath === "~") {
return Promise.resolve(home);
}
if (filePath.startsWith("~/")) {
return Promise.resolve(path.posix.join(home, filePath.slice(2)));
}
return Promise.resolve(
filePath.startsWith("/") ? filePath : path.posix.join(CONTAINER_SRC_DIR, filePath)
);
}
getWorkspacePath(_projectPath: string, _workspaceName: string): string {
// For Docker, workspace path is always /src inside the container
return CONTAINER_SRC_DIR;
}
async createWorkspace(params: WorkspaceCreationParams): Promise<WorkspaceCreationResult> {
const { projectPath, directoryName } = params;
// Container identity should follow the workspace entry name rather than the git branch.
// The two are usually equal today, but the runtime contract keeps them distinct.
const containerName = getContainerName(projectPath, directoryName);
// Check if container already exists (collision detection)
const checkResult = await runDockerCommand(`docker inspect ${containerName}`, 10000);
if (checkResult.exitCode === 0) {
return {
success: false,
error: `Workspace already exists: container ${containerName}`,
};
}
// Distinguish "container doesn't exist" from actual Docker errors
if (!checkResult.stderr.toLowerCase().includes("no such object")) {
return {
success: false,
error: `Docker error: ${checkResult.stderr || checkResult.stdout || "unknown error"}`,
};
}
// Store container name - actual container creation happens in postCreateSetup
// so that image pull progress is visible in the init section
this.containerName = containerName;
return {
success: true,
workspacePath: CONTAINER_SRC_DIR,
};
}
/**
* Post-create setup: provision container OR detect fork and setup credentials.
* Runs after mux persists workspace metadata so build logs stream to UI in real-time.
*
* Handles ALL environment setup:
* - Fresh workspace: provisions container (create, sync, checkout, credentials)
* - Fork: detects existing container, logs "from fork", sets up credentials
* - Stale container: removes and re-provisions
*
* After this completes, the container is ready for initWorkspace() to run the hook.
*/
async postCreateSetup(params: WorkspaceInitParams): Promise<void> {
const {
projectPath,
branchName,
trunkBranch,
workspacePath,
initLogger,
abortSignal,
env,
skipInitHook,
} = params;
if (!this.containerName) {
throw new Error("Container not initialized. Call createWorkspace first.");
}
const containerName = this.containerName;
// Check if container already exists (e.g., from successful fork or aborted previous attempt)
const containerCheck = await this.checkExistingContainer(
containerName,
workspacePath,
branchName
);
switch (containerCheck.action) {
case "skip":
// Fork path: container already valid, just log and setup credentials
initLogger.logStep(
skipInitHook
? "Container already running (from fork), skipping init hook..."
: "Container already running (from fork), running init hook..."
);
await this.setupCredentials(containerName, env);
return;
case "cleanup":
initLogger.logStep(containerCheck.reason);
await runDockerCommand(`docker rm -f ${containerName}`, 10000);
break;
case "create":
break;
}
// Provision container (throws on error - caller handles)
await this.provisionContainer({
containerName,
projectPath,
workspacePath,
branchName,
trunkBranch,
initLogger,
abortSignal,
env,
trusted: params.trusted,
});
}
/**
* Initialize workspace by running .mux/init hook.
* Assumes postCreateSetup() has already been called to provision/prepare the container.
*
* This method ONLY runs the hook - all container provisioning and credential setup
* is handled by postCreateSetup().
*/
async initWorkspace(params: WorkspaceInitParams): Promise<WorkspaceInitResult> {
if (!this.containerName) {
return {
success: false,
error: "Container not initialized. Call createWorkspace first.",
};
}
// Do NOT delete container on hook failure - user can debug.
return runWorkspaceInitHook({
params,
runtimeType: "docker",
hookCheckPath: params.projectPath,
runHook: async ({ muxEnv, initLogger, abortSignal }) => {
const hookPath = `${params.workspacePath}/.mux/init`;
await runInitHookOnRuntime(
this,
hookPath,
params.workspacePath,
muxEnv,
initLogger,
abortSignal
);
},
});
}
/**
* Check if a container already exists and whether it's valid for reuse.
* Returns action to take: skip setup, cleanup invalid container, or create new.
*/
private async checkExistingContainer(
containerName: string,
workspacePath: string,
branchName: string
): Promise<ContainerCheckResult> {
const exists = await runDockerCommand(`docker inspect ${containerName}`, 10000);
if (exists.exitCode !== 0) return { action: "create" };
const isRunning = await runDockerCommand(
`docker inspect -f '{{.State.Running}}' ${containerName}`,
10000
);
if (isRunning.exitCode !== 0 || isRunning.stdout.trim() !== "true") {
return { action: "cleanup", reason: "Removing stale container from previous attempt..." };
}
// Container running - validate it has an initialized git repo
const gitCheck = await runDockerCommand(
`docker exec ${containerName} test -d ${workspacePath}/.git`,
5000
);
if (gitCheck.exitCode !== 0) {
return {
action: "cleanup",
reason: "Container exists but repo not initialized, recreating...",
};
}
// Verify correct branch is checked out
// (handles edge case: crash after clone but before checkout left container on wrong branch)
const branchCheck = await runDockerCommand(
`docker exec ${containerName} git -C ${workspacePath} rev-parse --abbrev-ref HEAD`,
5000
);
if (branchCheck.exitCode !== 0 || branchCheck.stdout.trim() !== branchName) {
return { action: "cleanup", reason: "Container exists but wrong branch, recreating..." };
}
return { action: "skip" };
}
/**
* Copy gitconfig and configure gh CLI credential helper in container.
* Called for both new containers and reused forked containers.
*/
private async setupCredentials(
containerName: string,
env?: Record<string, string>
): Promise<void> {
if (!this.config.shareCredentials) return;
// Copy host gitconfig into container (not mounted, so gh can modify it)
if (hasHostGitconfig()) {
await runDockerCommand(
`docker cp ${getHostGitconfigPath()} ${containerName}:/root/.gitconfig`,
10000
);
}
// Configure gh CLI as git credential helper if GH_TOKEN is available
// GH_TOKEN can come from project secrets (env) or host environment (buildCredentialArgs)
const ghToken = resolveGhToken(env);
if (ghToken) {
await runDockerCommand(
`docker exec -e GH_TOKEN=${shescape.quote(ghToken)} ${containerName} sh -c 'command -v gh >/dev/null && gh auth setup-git || true'`,
10000
);
}
}
/**
* Provision container: create, sync project, checkout branch.
* Throws on error (does not call logComplete - caller handles that).
* Used by postCreateSetup() for streaming logs before initWorkspace().
*/
private async provisionContainer(params: {
containerName: string;
projectPath: string;
workspacePath: string;
branchName: string;
trunkBranch: string;
initLogger: InitLogger;
abortSignal?: AbortSignal;
env?: Record<string, string>;
trusted?: boolean;
}): Promise<void> {
const {
containerName,
projectPath,
workspacePath,
branchName,
trunkBranch,
initLogger,
abortSignal,
env,
} = params;
// 1. Create container (with image pull if needed)
initLogger.logStep(`Creating container from ${this.config.image}...`);
if (abortSignal?.aborted) {
throw new Error("Workspace creation aborted");
}
// Create and start container with streaming output for image pull progress
const runResult = await streamDockerRun(containerName, this.config.image, initLogger, {
abortSignal,
shareCredentials: this.config.shareCredentials,
});
if (runResult.exitCode !== 0) {
await runDockerCommand(`docker rm -f ${containerName}`, 10000);
throw new Error(`Failed to create container: ${runResult.stderr}`);
}
// Detect container's default user (may be non-root, e.g., codercom/enterprise-base runs as "coder")
const [uidResult, gidResult, homeResult] = await Promise.all([
runDockerCommand(`docker exec ${containerName} id -u`, 5000),
runDockerCommand(`docker exec ${containerName} id -g`, 5000),
runDockerCommand(`docker exec ${containerName} sh -c 'echo $HOME'`, 5000),
]);
this.containerUid = sanitizeContainerUserId(uidResult.stdout);
this.containerGid = sanitizeContainerUserId(gidResult.stdout);
this.containerHome = homeResult.stdout.trim() || "/root";
// Create /src directory and /var/mux/plans in container
// Use --user root to create directories, then chown to container's default user
// /var/mux is used instead of ~/.mux because /root has 700 permissions,
// which makes it inaccessible to VS Code Dev Containers (non-root user)
initLogger.logStep("Preparing workspace directory...");
const mkdirResult = await runDockerCommand(
`docker exec --user root ${containerName} sh -c 'mkdir -p ${CONTAINER_SRC_DIR} /var/mux/plans && chown ${this.containerUid}:${this.containerGid} ${CONTAINER_SRC_DIR} /var/mux /var/mux/plans'`,
10000
);
if (mkdirResult.exitCode !== 0) {
await runDockerCommand(`docker rm -f ${containerName}`, 10000);
throw new Error(`Failed to create workspace directory: ${mkdirResult.stderr}`);
}
initLogger.logStep("Container ready");
// Setup credentials (gitconfig + gh auth)
await this.setupCredentials(containerName, env);
// 2. Sync project to container using git bundle + docker cp
initLogger.logStep("Syncing project files to container...");
try {
await this.syncProjectToContainer(
projectPath,
containerName,
workspacePath,
initLogger,
abortSignal,
params.trusted
);
} catch (error) {
await runDockerCommand(`docker rm -f ${containerName}`, 10000);
throw new Error(`Failed to sync project: ${getErrorMessage(error)}`);
}
initLogger.logStep("Files synced successfully");
// 3. Checkout branch
// Disable git hooks for untrusted projects (prevents post-checkout execution)
const nhp = gitNoHooksPrefix(params.trusted);
initLogger.logStep(`Checking out branch: ${branchName}`);
const checkoutCmd = `${nhp}git checkout ${shescape.quote(branchName)} 2>/dev/null || ${nhp}git checkout -b ${shescape.quote(branchName)} ${shescape.quote(trunkBranch)}`;
const checkoutStream = await this.exec(checkoutCmd, {
cwd: workspacePath,
timeout: 300,
abortSignal,
});
const [stdout, stderr, exitCode] = await Promise.all([
streamToString(checkoutStream.stdout),
streamToString(checkoutStream.stderr),
checkoutStream.exitCode,
]);
if (exitCode !== 0) {
await runDockerCommand(`docker rm -f ${containerName}`, 10000);
throw new Error(`Failed to checkout branch: ${stderr || stdout}`);
}
initLogger.logStep("Branch checked out successfully");
await this.materializeCheckedOutWorkspace({
containerName,
workspacePath,
initLogger,
abortSignal,
env,
trusted: params.trusted,
});
}
private async materializeCheckedOutWorkspace(args: {
containerName: string;
workspacePath: string;
initLogger: InitLogger;
abortSignal?: AbortSignal;
env?: Record<string, string>;
trusted?: boolean;
}): Promise<void> {
try {
// Container provisioning owns checkout completeness so initWorkspace can focus on
// running repo-controlled hooks against an already-materialized source tree.
await syncRuntimeGitSubmodules({
runtime: this,
workspacePath: args.workspacePath,
initLogger: args.initLogger,
abortSignal: args.abortSignal,
env: args.env,
trusted: args.trusted,
});
} catch (error) {
try {
await this.removeProvisioningContainer(args.containerName);
} catch (cleanupError) {
throw new Error(
`${getErrorMessage(error)} (cleanup failed: ${getErrorMessage(cleanupError)})`
);
}
throw error;
}
}
private async removeProvisioningContainer(containerName: string): Promise<void> {
const removeResult = await runDockerCommand(`docker rm -f ${containerName}`, 10000);
if (removeResult.exitCode !== 0) {
throw new Error(removeResult.stderr || removeResult.stdout || "docker rm failed");
}
}
private async syncProjectToContainer(
projectPath: string,
containerName: string,
workspacePath: string,
initLogger: InitLogger,
abortSignal?: AbortSignal,
trusted?: boolean
): Promise<void> {
const timestamp = Date.now();
const bundleFilename = `mux-bundle-${timestamp}.bundle`;
const remoteBundlePath = `/tmp/${bundleFilename}`;
// Use os.tmpdir() for host path (Windows doesn't have /tmp)
const localBundlePath = path.join(os.tmpdir(), bundleFilename);
await syncProjectViaGitBundle({
projectPath,
workspacePath,
remoteTmpDir: "/tmp",
remoteBundlePath,
exec: (command, options) => this.exec(command, options),
quoteRemotePath: (path) => this.quoteForRemote(path),
initLogger,
abortSignal,
cloneStep: "Cloning repository in container...",
trusted,
createRemoteBundle: async ({ remoteBundlePath, initLogger, abortSignal }) => {
try {
if (abortSignal?.aborted) {
throw new Error("Sync operation aborted before starting");
}
const bundleResult = await runDockerCommand(
`git -C "${projectPath}" bundle create "${localBundlePath}" --all`,
300000
);
if (bundleResult.exitCode !== 0) {
throw new Error(`Failed to create bundle: ${bundleResult.stderr}`);
}
initLogger.logStep("Copying bundle to container...");
const copyResult = await runDockerCommand(
`docker cp "${localBundlePath}" ${containerName}:${remoteBundlePath}`,
300000
);
if (copyResult.exitCode !== 0) {
throw new Error(`Failed to copy bundle: ${copyResult.stderr}`);
}
return {
cleanupLocal: async () => {
await runDockerCommand(`rm -f "${localBundlePath}"`, 5000);
},
};
} catch (error) {
await runDockerCommand(`rm -f "${localBundlePath}"`, 5000);
throw error;
}
},
});
}
// eslint-disable-next-line @typescript-eslint/require-await
async renameWorkspace(
_projectPath: string,
_oldName: string,
_newName: string,
_abortSignal?: AbortSignal
): Promise<
{ success: true; oldPath: string; newPath: string } | { success: false; error: string }
> {
// For Docker, renaming means:
// 1. Create new container with new name
// 2. Copy /src from old container to new
// 3. Remove old container
// This is complex and error-prone, so we don't support it for now
return {
success: false,
error:
"Renaming Docker workspaces is not supported. Create a new workspace and delete the old one.",
};
}
async deleteWorkspace(
projectPath: string,
workspaceName: string,
force: boolean,
abortSignal?: AbortSignal
): Promise<{ success: true; deletedPath: string } | { success: false; error: string }> {
if (abortSignal?.aborted) {
return { success: false, error: "Delete operation aborted" };
}
const containerName = getContainerName(projectPath, workspaceName);
const deletedPath = CONTAINER_SRC_DIR;
try {
// Check if container exists
const inspectResult = await runDockerCommand(`docker inspect ${containerName}`, 10000);
if (inspectResult.exitCode !== 0) {
// Only treat as "doesn't exist" if Docker says so
if (inspectResult.stderr.toLowerCase().includes("no such object")) {
return { success: true, deletedPath };
}
return {
success: false,
error: `Docker error: ${inspectResult.stderr || inspectResult.stdout || "unknown error"}`,
};
}
if (!force) {
// Check if container is already running before we start it
const wasRunning = await runDockerCommand(
`docker inspect -f '{{.State.Running}}' ${containerName}`,
10000
);
const containerWasRunning =
wasRunning.exitCode === 0 && wasRunning.stdout.trim() === "true";
// Start container if stopped (docker start is idempotent - succeeds if already running)
const startResult = await runDockerCommand(`docker start ${containerName}`, 30000);
if (startResult.exitCode !== 0) {
// Container won't start - skip dirty checks, allow deletion
// (container is broken/orphaned, user likely wants to clean up)
} else {
// Helper to stop container if we started it (don't leave it running on check failure)
const stopIfWeStartedIt = async () => {
if (!containerWasRunning) {
await runDockerCommand(`docker stop ${containerName}`, 10000);
}
};
// Check for uncommitted changes
const checkResult = await runDockerCommand(
`docker exec ${containerName} bash -c 'cd ${CONTAINER_SRC_DIR} && git diff --quiet --exit-code && git diff --quiet --cached --exit-code'`,
10000
);
if (checkResult.exitCode !== 0) {
await stopIfWeStartedIt();
return {
success: false,
error: "Workspace contains uncommitted changes. Use force flag to delete anyway.",
};
}
// Check for unpushed commits (only if remotes exist - repos with no remotes would show all commits)
const hasRemotes = await runDockerCommand(
`docker exec ${containerName} bash -c 'cd ${CONTAINER_SRC_DIR} && git remote | grep -q .'`,
10000
);
if (hasRemotes.exitCode === 0) {
const unpushedResult = await runDockerCommand(
`docker exec ${containerName} bash -c 'cd ${CONTAINER_SRC_DIR} && git log --branches --not --remotes --oneline'`,
10000
);
if (unpushedResult.exitCode === 0 && unpushedResult.stdout.trim()) {
await stopIfWeStartedIt();
return {
success: false,
error: `Workspace contains unpushed commits:\n\n${unpushedResult.stdout.trim()}`,
};
}
}
}
}
// Stop and remove container
const rmResult = await runDockerCommand(`docker rm -f ${containerName}`, 30000);
if (rmResult.exitCode !== 0) {
return {
success: false,
error: `Failed to remove container: ${rmResult.stderr}`,
};
}
return { success: true, deletedPath };
} catch (error) {
return { success: false, error: `Failed to delete workspace: ${getErrorMessage(error)}` };
}
}
async forkWorkspace(params: WorkspaceForkParams): Promise<WorkspaceForkResult> {
const { projectPath, sourceWorkspaceName, newWorkspaceName, initLogger } = params;
const srcContainerName = getContainerName(projectPath, sourceWorkspaceName);
const destContainerName = getContainerName(projectPath, newWorkspaceName);
const hostTempPath = path.join(os.tmpdir(), `mux-fork-${Date.now()}.bundle`);
const containerBundlePath = "/tmp/fork.bundle";
let destContainerCreated = false;
let forkSucceeded = false;
try {
// 1. Verify source container exists
const srcCheck = await runDockerCommand(`docker inspect ${srcContainerName}`, 10000);
if (srcCheck.exitCode !== 0) {
return {
success: false,
error: `Source workspace container not found: ${srcContainerName}`,
};
}
// 2. Get current branch from source
initLogger.logStep("Detecting source workspace branch...");
const branchResult = await runDockerCommand(