-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathSSHRuntime.ts
More file actions
1657 lines (1491 loc) · 60.1 KB
/
SSHRuntime.ts
File metadata and controls
1657 lines (1491 loc) · 60.1 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
/**
* SSH runtime implementation that executes commands and file operations
* over SSH using the ssh command-line tool.
*
* Features:
* - Uses system ssh command (respects ~/.ssh/config)
* - Supports SSH config aliases, ProxyJump, ControlMaster, etc.
* - No password prompts (assumes key-based auth or ssh-agent)
* - Atomic file writes via temp + rename
*
* IMPORTANT: All SSH operations MUST include a timeout to prevent hangs from network issues.
* Timeouts should be either set literally for internal operations or forwarded from upstream
* for user-initiated operations.
*
* Extends RemoteRuntime for shared exec/file operations.
*/
import { spawn, type ChildProcess } from "child_process";
import * as path from "path";
import type {
EnsureReadyOptions,
EnsureReadyResult,
ExecOptions,
WorkspaceCreationParams,
WorkspaceCreationResult,
WorkspaceInitParams,
WorkspaceInitResult,
WorkspaceForkParams,
WorkspaceForkResult,
InitLogger,
} from "./Runtime";
import { WORKSPACE_REPO_MISSING_ERROR } from "./Runtime";
import { RemoteRuntime, type SpawnResult } from "./RemoteRuntime";
import { log } from "@/node/services/log";
import {
checkInitHookExists,
getMuxEnv,
runInitHookOnRuntime,
shouldSkipInitHook,
} from "./initHook";
import { expandTildeForSSH as expandHookPath } from "./tildeExpansion";
import { expandTildeForSSH, cdCommandForSSH } from "./tildeExpansion";
import { getProjectName, execBuffered } from "@/node/utils/runtime/helpers";
import { getErrorMessage } from "@/common/utils/errors";
import { type SSHRuntimeConfig } from "./sshConnectionPool";
import { getOriginUrlForBundle } from "./gitBundleSync";
import { gitNoHooksPrefix } from "@/node/utils/gitNoHooksEnv";
import type { PtyHandle, PtySessionParams, SSHTransport } from "./transports";
import { streamToString, shescape } from "./streamUtils";
import { sanitizeWorkspaceNameForPath } from "@/common/utils/validation/workspaceValidation";
/** Name of the shared bare repo directory under each project on the remote. */
const BASE_REPO_DIR = ".mux-base.git";
/** Staging namespace for bundle-imported branch refs. Branches land here instead
* of refs/heads/* so they don't collide with branches checked out in worktrees. */
const BUNDLE_REF_PREFIX = "refs/mux-bundle/";
function logSSHBackoffWait(initLogger: InitLogger, waitMs: number): void {
const secs = Math.max(1, Math.ceil(waitMs / 1000));
initLogger.logStep(`SSH unavailable; retrying in ${secs}s...`);
}
async function pipeReadableToWebWritable(
readable: NodeJS.ReadableStream | null | undefined,
writable: WritableStream<Uint8Array>,
abortSignal?: AbortSignal
): Promise<void> {
if (!readable) {
throw new Error("Missing git bundle output stream");
}
const writer = writable.getWriter();
try {
for await (const chunk of readable) {
if (abortSignal?.aborted) {
throw new Error("Bundle creation aborted");
}
const data =
typeof chunk === "string"
? Buffer.from(chunk)
: chunk instanceof Uint8Array
? chunk
: Buffer.from(chunk);
await writer.write(data);
}
await writer.close();
} catch (error) {
try {
await writer.abort(error);
} catch {
writer.releaseLock();
}
throw error;
}
}
function createAbortController(
timeoutMs: number | undefined,
abortSignal?: AbortSignal
): { signal: AbortSignal; dispose: () => void; didTimeout: () => boolean } {
const controller = new AbortController();
let timedOut = false;
const onAbort = () => controller.abort();
if (abortSignal) {
if (abortSignal.aborted) {
controller.abort();
} else {
abortSignal.addEventListener("abort", onAbort, { once: true });
}
}
const timeoutHandle =
timeoutMs === undefined
? undefined
: setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs);
return {
signal: controller.signal,
didTimeout: () => timedOut,
dispose: () => {
if (timeoutHandle) {
clearTimeout(timeoutHandle);
}
abortSignal?.removeEventListener("abort", onAbort);
},
};
}
async function waitForProcessExit(proc: ChildProcess): Promise<number> {
return new Promise((resolve, reject) => {
proc.on("close", (code) => resolve(code ?? 0));
proc.on("error", (err) => reject(err));
});
}
/** Truncate SSH stderr for error logging (keep first line, max 200 chars) */
function truncateSSHError(stderr: string): string {
const trimmed = stderr.trim();
if (!trimmed) return "exit code 255";
// Take first line only (SSH errors are usually single-line)
const firstLine = trimmed.split("\n")[0];
if (firstLine.length <= 200) return firstLine;
return firstLine.slice(0, 197) + "...";
}
// Re-export SSHRuntimeConfig from connection pool (defined there to avoid circular deps)
export type { SSHRuntimeConfig } from "./sshConnectionPool";
/**
* Compute the path to the shared bare base repo for a project on the remote.
* Convention: <srcBaseDir>/<projectName>/.mux-base.git
*
* Exported for unit testing; runtime code should use the private
* `SSHRuntime.getBaseRepoPath()` method instead.
*/
export function computeBaseRepoPath(srcBaseDir: string, projectPath: string): string {
const projectName = getProjectName(projectPath);
return path.posix.join(srcBaseDir, projectName, BASE_REPO_DIR);
}
/**
* SSH runtime implementation that executes commands and file operations
* over SSH using the ssh command-line tool.
*
* Extends RemoteRuntime for shared exec/file operations.
*/
export class SSHRuntime extends RemoteRuntime {
private readonly config: SSHRuntimeConfig;
private readonly transport: SSHTransport;
private readonly ensureReadyProjectPath?: string;
private readonly ensureReadyWorkspaceName?: string;
/** Cached resolved bgOutputDir (tilde expanded to absolute path) */
private resolvedBgOutputDir: string | null = null;
constructor(
config: SSHRuntimeConfig,
transport: SSHTransport,
options?: {
projectPath?: string;
workspaceName?: string;
}
) {
super();
// Note: srcBaseDir may contain tildes - they will be resolved via resolvePath() before use
// The WORKSPACE_CREATE IPC handler resolves paths before storing in config
this.config = config;
this.transport = transport;
this.ensureReadyProjectPath = options?.projectPath;
this.ensureReadyWorkspaceName = options?.workspaceName;
}
/**
* Get resolved background output directory (tilde expanded), caching the result.
* This ensures all background process paths are absolute from the start.
* Public for use by BackgroundProcessExecutor.
*/
async getBgOutputDir(): Promise<string> {
if (this.resolvedBgOutputDir !== null) {
return this.resolvedBgOutputDir;
}
let dir = this.config.bgOutputDir ?? "/tmp/mux-bashes";
if (dir === "~" || dir.startsWith("~/")) {
const result = await execBuffered(this, 'echo "$HOME"', { cwd: "/", timeout: 10 });
let home: string;
if (result.exitCode === 0 && result.stdout.trim()) {
home = result.stdout.trim();
} else {
log.warn(
`SSHRuntime: Failed to resolve $HOME (exitCode=${result.exitCode}). Falling back to /tmp.`
);
home = "/tmp";
}
dir = dir === "~" ? home : `${home}/${dir.slice(2)}`;
}
this.resolvedBgOutputDir = dir;
return this.resolvedBgOutputDir;
}
/** Create a PTY session using the underlying transport. */
public createPtySession(params: PtySessionParams): Promise<PtyHandle> {
return this.transport.createPtySession(params);
}
/** Get SSH configuration (for PTY terminal spawning). */
public getConfig(): SSHRuntimeConfig {
return this.config;
}
// ===== RemoteRuntime abstract method implementations =====
protected readonly commandPrefix: string = "SSH";
protected getBasePath(): string {
return this.config.srcBaseDir;
}
protected quoteForRemote(filePath: string): string {
return expandTildeForSSH(filePath);
}
protected cdCommand(cwd: string): string {
return cdCommandForSSH(cwd);
}
/**
* Handle exit codes for SSH connection pool health tracking.
*/
protected override onExitCode(exitCode: number, _options: ExecOptions, stderr: string): void {
// Connection-level failures should inform transport backoff. The meaning of
// specific exit codes (like 255) is transport-dependent.
if (this.transport.isConnectionFailure(exitCode, stderr)) {
this.transport.reportFailure(truncateSSHError(stderr));
} else {
this.transport.markHealthy();
}
}
protected async spawnRemoteProcess(
fullCommand: string,
options: ExecOptions
): Promise<SpawnResult> {
return this.transport.spawnRemoteProcess(fullCommand, {
forcePTY: options.forcePTY,
timeout: options.timeout,
abortSignal: options.abortSignal,
});
}
/**
* Override buildWriteCommand for SSH to handle symlinks and preserve permissions.
*/
protected buildWriteCommand(quotedPath: string, quotedTempPath: string): string {
// Resolve symlinks to get the actual target path, preserving the symlink itself
// If target exists, save its permissions to restore after write
// If path doesn't exist, use 600 as default
// Then write atomically using mv (all-or-nothing for readers)
return `RESOLVED=$(readlink -f ${quotedPath} 2>/dev/null || echo ${quotedPath}) && PERMS=$(stat -c '%a' "$RESOLVED" 2>/dev/null || echo 600) && mkdir -p $(dirname "$RESOLVED") && cat > ${quotedTempPath} && chmod "$PERMS" ${quotedTempPath} && mv ${quotedTempPath} "$RESOLVED"`;
}
// ===== Runtime interface implementations =====
async resolvePath(filePath: string): Promise<string> {
// Expand ~ on the remote host.
// Note: `p='~/x'; echo "$p"` does NOT expand ~ (tilde expansion happens before assignment).
// We do explicit expansion using parameter substitution (no reliance on `realpath`, `readlink -f`, etc.).
const script = [
`p=${shescape.quote(filePath)}`,
'if [ "$p" = "~" ]; then',
' echo "$HOME"',
'elif [ "${p#\\~/}" != "$p" ]; then',
' echo "$HOME/${p#\\~/}"',
'elif [ "${p#/}" != "$p" ]; then',
' echo "$p"',
"else",
' echo "$PWD/$p"',
"fi",
].join("\n");
const command = `bash -lc ${shescape.quote(script)}`;
// Wait for connection establishment (including host-key confirmation) before
// starting the 10s command timeout. Otherwise users who take >10s to accept
// the host key prompt will hit a false timeout immediately after acceptance.
const resolvePathTimeoutMs = 10_000;
await this.transport.acquireConnection({
timeoutMs: resolvePathTimeoutMs,
maxWaitMs: resolvePathTimeoutMs,
});
const abortController = createAbortController(resolvePathTimeoutMs);
try {
const result = await execBuffered(this, command, {
cwd: "/tmp",
abortSignal: abortController.signal,
});
if (abortController.didTimeout()) {
throw new Error(`SSH command timed out after 10000ms: ${command}`);
}
if (result.exitCode !== 0) {
const message = result.stderr || result.stdout || "Unknown error";
throw new Error(`Failed to resolve SSH path: ${message}`);
}
return result.stdout.trim();
} finally {
abortController.dispose();
}
}
getWorkspacePath(projectPath: string, workspaceName: string): string {
const projectName = getProjectName(projectPath);
// In-place workspaces use absolute paths as workspace names — do not sanitize
// those since path.posix.join already handles them correctly and sanitizing
// would turn e.g. "/home/user/project" into "-home-user-project".
const safeName = path.posix.isAbsolute(workspaceName)
? workspaceName
: sanitizeWorkspaceNameForPath(workspaceName);
return path.posix.join(this.config.srcBaseDir, projectName, safeName);
}
/**
* Path to the shared bare repo for a project on the remote.
* All worktree-based workspaces share this object store.
*/
private getBaseRepoPath(projectPath: string): string {
return computeBaseRepoPath(this.config.srcBaseDir, projectPath);
}
/**
* Ensure the shared bare repo exists on the remote for a project.
* Creates it lazily on first use. Returns the shell-expanded path arg
* for use in subsequent commands.
*/
private async ensureBaseRepo(
projectPath: string,
initLogger: InitLogger,
abortSignal?: AbortSignal
): Promise<string> {
const baseRepoPath = this.getBaseRepoPath(projectPath);
const baseRepoPathArg = expandTildeForSSH(baseRepoPath);
const check = await execBuffered(this, `test -d ${baseRepoPathArg}`, {
cwd: "/tmp",
timeout: 10,
abortSignal,
});
if (check.exitCode !== 0) {
initLogger.logStep("Creating shared base repository...");
const parentDir = path.posix.dirname(baseRepoPath);
await execBuffered(this, `mkdir -p ${expandTildeForSSH(parentDir)}`, {
cwd: "/tmp",
timeout: 10,
abortSignal,
});
const initResult = await execBuffered(this, `git init --bare ${baseRepoPathArg}`, {
cwd: "/tmp",
timeout: 30,
abortSignal,
});
if (initResult.exitCode !== 0) {
throw new Error(`Failed to create base repo: ${initResult.stderr || initResult.stdout}`);
}
}
return baseRepoPathArg;
}
/**
* Detect whether a remote workspace is a git worktree (`.git` is a file)
* vs a legacy full clone (`.git` is a directory).
*/
private async isWorktreeWorkspace(
workspacePath: string,
abortSignal?: AbortSignal
): Promise<boolean> {
const gitPath = path.posix.join(workspacePath, ".git");
const result = await execBuffered(this, `test -f ${this.quoteForRemote(gitPath)}`, {
cwd: "/tmp",
timeout: 10,
abortSignal,
});
return result.exitCode === 0;
}
/**
* Resolve the bundle staging ref for the trunk branch.
* Returns refs/mux-bundle/<trunkBranch> if it exists, otherwise falls back
* to the first available ref under refs/mux-bundle/ (handles main vs master
* mismatches). Returns null if no bundle refs exist.
*/
private async resolveBundleTrunkRef(
baseRepoPathArg: string,
trunkBranch: string,
abortSignal?: AbortSignal
): Promise<string | null> {
// Preferred: exact match for the expected trunk branch.
const preferredRef = `${BUNDLE_REF_PREFIX}${trunkBranch}`;
const check = await execBuffered(
this,
`git -C ${baseRepoPathArg} rev-parse --verify ${shescape.quote(preferredRef)}`,
{ cwd: "/tmp", timeout: 10, abortSignal }
);
if (check.exitCode === 0) {
return preferredRef;
}
// Fallback: pick the first ref under refs/mux-bundle/ (handles main↔master mismatch).
const listResult = await execBuffered(
this,
`git -C ${baseRepoPathArg} for-each-ref --format='%(refname)' ${BUNDLE_REF_PREFIX} --count=1`,
{ cwd: "/tmp", timeout: 10, abortSignal }
);
const fallbackRef = listResult.stdout.trim();
if (listResult.exitCode === 0 && fallbackRef.length > 0) {
log.info(`Bundle trunk ref mismatch: expected ${preferredRef}, using ${fallbackRef}`);
return fallbackRef;
}
return null;
}
override async ensureReady(options?: EnsureReadyOptions): Promise<EnsureReadyResult> {
const repoCheck = await this.checkWorkspaceRepo(options);
if (repoCheck) {
if (!repoCheck.ready) {
options?.statusSink?.({
phase: "error",
runtimeType: "ssh",
detail: repoCheck.error,
});
return repoCheck;
}
options?.statusSink?.({ phase: "ready", runtimeType: "ssh" });
return { ready: true };
}
return { ready: true };
}
protected async checkWorkspaceRepo(
options?: EnsureReadyOptions
): Promise<EnsureReadyResult | null> {
if (!this.ensureReadyProjectPath || !this.ensureReadyWorkspaceName) {
return null;
}
const statusSink = options?.statusSink;
statusSink?.({
phase: "checking",
runtimeType: "ssh",
detail: "Checking repository...",
});
if (options?.signal?.aborted) {
return { ready: false, error: "Aborted", errorType: "runtime_start_failed" };
}
const workspacePath = this.getWorkspacePath(
this.ensureReadyProjectPath,
this.ensureReadyWorkspaceName
);
const gitDir = path.posix.join(workspacePath, ".git");
const gitDirProbe = this.quoteForRemote(gitDir);
let testResult: { exitCode: number; stderr: string };
try {
// .git is a file for worktrees; accept either file or directory so existing SSH/Coder
// worktree checkouts don't get flagged as setup failures.
testResult = await execBuffered(this, `test -d ${gitDirProbe} || test -f ${gitDirProbe}`, {
cwd: "~",
timeout: 10,
abortSignal: options?.signal,
});
} catch (error) {
return {
ready: false,
error: `Failed to reach SSH host: ${getErrorMessage(error)}`,
errorType: "runtime_start_failed",
};
}
if (testResult.exitCode !== 0) {
if (this.transport.isConnectionFailure(testResult.exitCode, testResult.stderr)) {
return {
ready: false,
error: `Failed to reach SSH host: ${testResult.stderr || "connection failure"}`,
errorType: "runtime_start_failed",
};
}
return {
ready: false,
error: WORKSPACE_REPO_MISSING_ERROR,
errorType: "runtime_not_ready",
};
}
let revResult: { exitCode: number; stderr: string; stdout: string };
try {
revResult = await execBuffered(
this,
`git -C ${this.quoteForRemote(workspacePath)} rev-parse --git-dir`,
{
cwd: "~",
timeout: 10,
abortSignal: options?.signal,
}
);
} catch (error) {
return {
ready: false,
error: `Failed to verify repository: ${getErrorMessage(error)}`,
errorType: "runtime_start_failed",
};
}
if (revResult.exitCode !== 0) {
const stderr = revResult.stderr.trim();
const stdout = revResult.stdout.trim();
const errorDetail = stderr || stdout || "git unavailable";
const isCommandMissing =
revResult.exitCode === 127 || /command not found/i.test(stderr || stdout);
if (
isCommandMissing ||
this.transport.isConnectionFailure(revResult.exitCode, revResult.stderr)
) {
return {
ready: false,
error: `Failed to verify repository: ${errorDetail}`,
errorType: "runtime_start_failed",
};
}
return {
ready: false,
error: WORKSPACE_REPO_MISSING_ERROR,
errorType: "runtime_not_ready",
};
}
return { ready: true };
}
/**
* Sync project to remote using git bundle
*
* Uses `git bundle` to create a packfile and clones it on the remote.
*
* Benefits over git archive:
* - Creates a real git repository on remote (can run git commands)
* - Better parity with git worktrees (full .git directory with metadata)
* - Enables remote git operations (commit, branch, status, diff, etc.)
* - Only tracked files in checkout (no node_modules, build artifacts)
* - Includes full history for flexibility
*
* Benefits over rsync/scp:
* - Much faster (only tracked files)
* - No external dependencies (git is always available)
* - Simpler implementation
*/
/**
* Transfer a git bundle to the remote and return its path.
* Callers are responsible for cleanup of the remote bundle file.
*/
private async transferBundleToRemote(
projectPath: string,
initLogger: InitLogger,
abortSignal?: AbortSignal
): Promise<string> {
const timestamp = Date.now();
const remoteBundlePath = `~/.mux-bundle-${timestamp}.bundle`;
await this.transport.acquireConnection({
abortSignal,
onWait: (waitMs) => logSSHBackoffWait(initLogger, waitMs),
});
if (abortSignal?.aborted) {
throw new Error("Bundle creation aborted");
}
initLogger.logStep("Creating git bundle...");
// Use --branches --tags instead of --all to exclude refs/remotes/origin/*
// from the bundle. Those tracking refs are from the local machine's last
// fetch and can be arbitrarily stale — importing them into the shared bare
// base repo would give worktrees a wrong "commits behind" count.
const gitProc = spawn(
"git",
["-C", projectPath, "bundle", "create", "-", "--branches", "--tags"],
{
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
}
);
// Handle stderr manually - do NOT use streamProcessToLogger here.
// It attaches a stdout listener that drains data before pipeReadableToWebWritable
// can consume it, corrupting the bundle.
let stderr = "";
gitProc.stderr?.on("data", (data: Buffer) => {
const chunk = data.toString();
stderr += chunk;
for (const line of chunk.split("\n").filter(Boolean)) {
initLogger.logStderr(line);
}
});
const remoteAbortController = createAbortController(300_000, abortSignal);
const remoteStream = await this.exec(`cat > ${this.quoteForRemote(remoteBundlePath)}`, {
cwd: "~",
abortSignal: remoteAbortController.signal,
});
try {
try {
await pipeReadableToWebWritable(gitProc.stdout, remoteStream.stdin, abortSignal);
} catch (error) {
gitProc.kill();
throw error;
}
const [gitExitCode, remoteExitCode] = await Promise.all([
waitForProcessExit(gitProc),
remoteStream.exitCode,
]);
if (remoteAbortController.didTimeout()) {
throw new Error(
`SSH command timed out after 300000ms: cat > ${this.quoteForRemote(remoteBundlePath)}`
);
}
if (abortSignal?.aborted) {
throw new Error("Bundle creation aborted");
}
if (gitExitCode !== 0) {
throw new Error(`Failed to create bundle: ${stderr}`);
}
if (remoteExitCode !== 0) {
const remoteStderr = await streamToString(remoteStream.stderr);
throw new Error(`Failed to upload bundle: ${remoteStderr}`);
}
} finally {
remoteAbortController.dispose();
}
return remoteBundlePath;
}
/**
* Sync local project to the shared bare base repo on the remote via git bundle.
*
* Branches land in a staging namespace (refs/mux-bundle/*) to avoid colliding
* with branches checked out in existing worktrees. Tags go to refs/tags/*
* directly. Remote tracking refs are excluded entirely.
* Idempotent — re-running is a no-op when nothing changed.
*/
protected async syncProjectToRemote(
projectPath: string,
_workspacePath: string,
initLogger: InitLogger,
abortSignal?: AbortSignal
): Promise<void> {
const baseRepoPathArg = await this.ensureBaseRepo(projectPath, initLogger, abortSignal);
const remoteBundlePath = await this.transferBundleToRemote(
projectPath,
initLogger,
abortSignal
);
const remoteBundlePathArg = this.quoteForRemote(remoteBundlePath);
try {
// Import branches and tags from the bundle into the shared bare repo.
// Branches land in refs/mux-bundle/* (staging namespace) instead of
// refs/heads/* to avoid colliding with branches checked out in existing
// worktrees — git refuses to update any ref checked out in a worktree.
// Tags go directly to refs/tags/* (they're never checked out).
initLogger.logStep("Importing bundle into shared base repository...");
const fetchResult = await execBuffered(
this,
`git -C ${baseRepoPathArg} fetch ${remoteBundlePathArg} '+refs/heads/*:${BUNDLE_REF_PREFIX}*' '+refs/tags/*:refs/tags/*'`,
{ cwd: "/tmp", timeout: 300, abortSignal }
);
if (fetchResult.exitCode !== 0) {
throw new Error(
`Failed to import bundle into base repo: ${fetchResult.stderr || fetchResult.stdout}`
);
}
// Set the origin remote on the bare repo so worktrees inherit it.
const { originUrl } = await this.getOriginUrlForSync(projectPath, initLogger);
if (originUrl) {
initLogger.logStep(`Setting origin remote to ${originUrl}...`);
// Use add-or-update pattern: try set-url first, fall back to add.
await execBuffered(
this,
`git -C ${baseRepoPathArg} remote set-url origin ${shescape.quote(originUrl)} 2>/dev/null || git -C ${baseRepoPathArg} remote add origin ${shescape.quote(originUrl)}`,
{ cwd: "/tmp", timeout: 10, abortSignal }
);
}
initLogger.logStep("Repository synced to base successfully");
} finally {
// Best-effort cleanup of the remote bundle file.
try {
await execBuffered(this, `rm -f ${remoteBundlePathArg}`, {
cwd: "/tmp",
timeout: 10,
});
} catch {
// Ignore cleanup errors.
}
}
}
/** Get origin URL from local project for setting on the remote base repo. */
private async getOriginUrlForSync(
projectPath: string,
initLogger: InitLogger
): Promise<{ originUrl: string | null }> {
return getOriginUrlForBundle(projectPath, initLogger, /* logErrors */ false);
}
async createWorkspace(params: WorkspaceCreationParams): Promise<WorkspaceCreationResult> {
try {
const { projectPath, branchName, initLogger, abortSignal } = params;
// Compute workspace path using canonical method
const workspacePath = this.getWorkspacePath(projectPath, branchName);
// Prepare parent directory for git clone (fast - returns immediately)
// Note: git clone will create the workspace directory itself during initWorkspace,
// but the parent directory must exist first
initLogger.logStep("Preparing remote workspace...");
try {
// Extract parent directory from workspace path
// Example: ~/workspace/project/branch -> ~/workspace/project
const lastSlash = workspacePath.lastIndexOf("/");
const parentDir = lastSlash > 0 ? workspacePath.substring(0, lastSlash) : "~";
// Expand tilde for mkdir command
const expandedParentDir = expandTildeForSSH(parentDir);
const parentDirCommand = `mkdir -p ${expandedParentDir}`;
const mkdirStream = await this.exec(parentDirCommand, {
cwd: "/tmp",
timeout: 10,
abortSignal,
});
const mkdirExitCode = await mkdirStream.exitCode;
if (mkdirExitCode !== 0) {
const stderr = await streamToString(mkdirStream.stderr);
return {
success: false,
error: `Failed to prepare remote workspace: ${stderr}`,
};
}
} catch (error) {
return {
success: false,
error: `Failed to prepare remote workspace: ${getErrorMessage(error)}`,
};
}
initLogger.logStep("Remote workspace prepared");
return {
success: true,
workspacePath,
};
} catch (error) {
return {
success: false,
error: getErrorMessage(error),
};
}
}
async initWorkspace(params: WorkspaceInitParams): Promise<WorkspaceInitResult> {
const { projectPath, branchName, trunkBranch, workspacePath, initLogger, abortSignal, env } =
params;
// Disable git hooks for untrusted projects (prevents post-checkout execution)
const nhp = gitNoHooksPrefix(params.trusted);
try {
// If the workspace directory already exists and contains a git repo (e.g. forked from
// another SSH workspace via worktree add or legacy cp), skip the expensive sync step.
const workspacePathArg = expandTildeForSSH(workspacePath);
let shouldSync = true;
try {
const dirCheck = await execBuffered(this, `test -d ${workspacePathArg}`, {
cwd: "/tmp",
timeout: 10,
abortSignal,
});
if (dirCheck.exitCode === 0) {
const gitCheck = await execBuffered(
this,
`git -C ${workspacePathArg} rev-parse --is-inside-work-tree`,
{
cwd: "/tmp",
timeout: 20,
abortSignal,
}
);
shouldSync = gitCheck.exitCode !== 0;
}
} catch {
// Default to syncing on unexpected errors.
shouldSync = true;
}
if (shouldSync) {
// 1. Sync project to the shared bare base repo with retry for transient SSH failures.
// Errors like "pack-objects died" occur when SSH drops mid-transfer.
initLogger.logStep("Syncing project files to remote...");
const maxSyncAttempts = 3;
for (let attempt = 1; attempt <= maxSyncAttempts; attempt++) {
try {
await this.syncProjectToRemote(projectPath, workspacePath, initLogger, abortSignal);
break;
} catch (error) {
const errorMsg = getErrorMessage(error);
const isRetryable =
errorMsg.includes("pack-objects died") ||
errorMsg.includes("Connection reset") ||
errorMsg.includes("Connection closed") ||
errorMsg.includes("Broken pipe") ||
errorMsg.includes("EPIPE");
if (!isRetryable || attempt === maxSyncAttempts) {
initLogger.logStderr(`Failed to sync project: ${errorMsg}`);
initLogger.logComplete(-1);
return {
success: false,
error: `Failed to sync project: ${errorMsg}`,
};
}
log.info(
`Sync failed (attempt ${attempt}/${maxSyncAttempts}), will retry: ${errorMsg}`
);
initLogger.logStep(
`Sync failed, retrying (attempt ${attempt + 1}/${maxSyncAttempts})...`
);
await new Promise((r) => setTimeout(r, attempt * 1000));
}
}
initLogger.logStep("Files synced successfully");
// 2. Create a worktree from the shared bare base repo for this workspace.
const baseRepoPath = this.getBaseRepoPath(projectPath);
const baseRepoPathArg = expandTildeForSSH(baseRepoPath);
// Fetch latest from origin in the base repo (best-effort) so new branches
// can start from the latest upstream state.
const fetchedOrigin = await this.fetchOriginTrunk(
baseRepoPath,
trunkBranch,
initLogger,
abortSignal,
nhp
);
// Resolve the bundle's staging ref to use as the local fallback start
// point. The staging ref is refs/mux-bundle/<trunk> — but the local
// project's default branch may differ from what was passed as trunkBranch
// (e.g. "master" vs "main"), so probe for the expected ref and fall back
// to whatever is available in refs/mux-bundle/.
const bundleTrunkRef = await this.resolveBundleTrunkRef(
baseRepoPathArg,
trunkBranch,
abortSignal
);
const shouldUseOrigin =
fetchedOrigin &&
bundleTrunkRef != null &&
(await this.canFastForwardToOrigin(
baseRepoPath,
bundleTrunkRef,
trunkBranch,
initLogger,
abortSignal
));
// When origin is reachable, branch from the fresh remote tracking ref.
// Otherwise, use the bundle's staging ref (or HEAD as last resort).
const newBranchBase = shouldUseOrigin
? `origin/${trunkBranch}`
: (bundleTrunkRef ?? "HEAD");
// git worktree add creates the directory and checks out the branch in one step.
// -B creates the branch or resets it to the start point if it already exists
// (e.g. orphaned from a previously deleted workspace). Git still prevents
// checking out a branch that's active in another worktree.
initLogger.logStep(`Creating worktree for branch: ${branchName}`);
const worktreeCmd = `${nhp}git -C ${baseRepoPathArg} worktree add ${workspacePathArg} -B ${shescape.quote(branchName)} ${shescape.quote(newBranchBase)}`;
const worktreeResult = await execBuffered(this, worktreeCmd, {
cwd: "/tmp",
timeout: 300,
abortSignal,
});
if (worktreeResult.exitCode !== 0) {
const errorMsg = `Failed to create worktree: ${worktreeResult.stderr || worktreeResult.stdout}`;
initLogger.logStderr(errorMsg);
initLogger.logComplete(-1);
return { success: false, error: errorMsg };
}
initLogger.logStep("Worktree created successfully");
} else {
initLogger.logStep("Remote workspace already contains a git repo; skipping sync");
// Existing workspace (e.g. forked): fetch origin and checkout as before.
const fetchedOrigin = await this.fetchOriginTrunk(
workspacePath,
trunkBranch,
initLogger,
abortSignal,
nhp
);
const shouldUseOrigin =
fetchedOrigin &&
(await this.canFastForwardToOrigin(
workspacePath,
trunkBranch,
trunkBranch,
initLogger,
abortSignal
));
if (shouldUseOrigin) {
await this.fastForwardToOrigin(workspacePath, trunkBranch, initLogger, abortSignal, nhp);
}
}
// 3. Run .mux/init hook if it exists
// Note: runInitHookOnRuntime calls logComplete() internally
if (shouldSkipInitHook(params, initLogger)) {
initLogger.logComplete(0);
} else {
const hookExists = await checkInitHookExists(projectPath);
if (hookExists) {
initLogger.enterHookPhase?.();
const muxEnv = { ...env, ...getMuxEnv(projectPath, "ssh", branchName) };
// Expand tilde in hook path (quoted paths don't auto-expand on remote)
const hookPath = expandHookPath(`${workspacePath}/.mux/init`);
await runInitHookOnRuntime(
this,
hookPath,
workspacePath,
muxEnv,
initLogger,
abortSignal
);
} else {
// No hook - signal completion immediately
initLogger.logComplete(0);
}
}