rex-worktrees 0.4.5 → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20663,6 +20663,13 @@ var layer7 = /* @__PURE__ */ succeed5(Stdio, /* @__PURE__ */ make29({
20663
20663
  // node_modules/@effect/platform-bun/dist/BunStdio.js
20664
20664
  var layer8 = layer7;
20665
20665
 
20666
+ // node_modules/@effect/platform-bun/dist/BunTerminal.js
20667
+ var exports_BunTerminal = {};
20668
+ __export(exports_BunTerminal, {
20669
+ make: () => make44,
20670
+ layer: () => layer10
20671
+ });
20672
+
20666
20673
  // node_modules/effect/dist/Terminal.js
20667
20674
  var exports_Terminal = {};
20668
20675
  __export(exports_Terminal, {
@@ -33411,6 +33418,7 @@ function defaultShouldQuit(input) {
33411
33418
  }
33412
33419
 
33413
33420
  // node_modules/@effect/platform-bun/dist/BunTerminal.js
33421
+ var make44 = make43;
33414
33422
  var layer10 = layer9;
33415
33423
 
33416
33424
  // node_modules/@effect/platform-bun/dist/BunServices.js
@@ -33622,7 +33630,9 @@ var GitCloneInputSchema = exports_Schema.Struct({
33622
33630
  name: exports_Schema.String,
33623
33631
  branch: exports_Schema.String,
33624
33632
  branchMode: exports_Schema.Literals(["existing", "create"]),
33625
- worktreeName: exports_Schema.optional(exports_Schema.String)
33633
+ worktreeName: exports_Schema.optional(exports_Schema.String),
33634
+ checkout: exports_Schema.optional(exports_Schema.Literals(["primary", "worktree"])),
33635
+ directory: exports_Schema.optional(exports_Schema.String)
33626
33636
  });
33627
33637
  var JjCloneInputSchema = exports_Schema.Struct({
33628
33638
  vcs: exports_Schema.Literal("jj"),
@@ -33632,7 +33642,9 @@ var JjCloneInputSchema = exports_Schema.Struct({
33632
33642
  clientId: exports_Schema.optional(ClientIdSchema),
33633
33643
  name: exports_Schema.String,
33634
33644
  worktreeName: exports_Schema.optional(exports_Schema.String),
33635
- revision: exports_Schema.optional(exports_Schema.String)
33645
+ revision: exports_Schema.optional(exports_Schema.String),
33646
+ checkout: exports_Schema.optional(exports_Schema.Literals(["primary", "worktree"])),
33647
+ directory: exports_Schema.optional(exports_Schema.String)
33636
33648
  });
33637
33649
  var CloneInputSchema = exports_Schema.Union([GitCloneInputSchema, JjCloneInputSchema]);
33638
33650
  var ClonePlanFields = {
@@ -33667,14 +33679,17 @@ var CloneLaunchResultSchema = exports_Schema.Struct({
33667
33679
  pending: exports_Schema.Literal(true),
33668
33680
  warning: exports_Schema.optional(exports_Schema.String)
33669
33681
  });
33670
- var CloneTaskRequestSchema = exports_Schema.Struct({ plan: ClonePlanSchema, sessionId: SessionIdSchema, rexBinDir: exports_Schema.optional(exports_Schema.String), rexLocalEndpoint: exports_Schema.optional(exports_Schema.String) });
33682
+ var RexTaskSettingsSchema = exports_Schema.Struct({ rexBinDir: exports_Schema.optional(exports_Schema.String), rexLocalEndpoint: exports_Schema.optional(exports_Schema.String) });
33683
+ var RexTaskIdentitySchema = exports_Schema.Struct({ REX_SESSION: SessionIdSchema, REX_BLOCK: BlockIdSchema });
33684
+ var CloneTaskRequestSchema = exports_Schema.Struct({ plan: ClonePlanSchema, ...RexTaskSettingsSchema.fields });
33671
33685
  var LaunchInputFields = {
33672
33686
  repo: exports_Schema.String,
33673
33687
  session: SessionSelectionSchema,
33674
33688
  name: exports_Schema.String,
33675
33689
  clientId: exports_Schema.optional(ClientIdSchema),
33676
33690
  additional: exports_Schema.optional(exports_Schema.Boolean),
33677
- split: exports_Schema.optional(exports_Schema.Boolean)
33691
+ split: exports_Schema.optional(exports_Schema.Boolean),
33692
+ directory: exports_Schema.optional(exports_Schema.String)
33678
33693
  };
33679
33694
  var GitLaunchInputSchema = exports_Schema.Struct({
33680
33695
  ...LaunchInputFields,
@@ -33697,7 +33712,7 @@ var LaunchPlanFields = {
33697
33712
  path: exports_Schema.String,
33698
33713
  worktreeRoot: exports_Schema.optional(exports_Schema.String),
33699
33714
  action: exports_Schema.Literals(["focus", "new-tab", "split"]),
33700
- target: exports_Schema.optional(exports_Schema.Struct({ windowId: WindowIdSchema, blockId: BlockIdSchema, label: exports_Schema.String })),
33715
+ target: exports_Schema.optional(exports_Schema.Struct({ windowId: WindowIdSchema, blockId: BlockIdSchema })),
33701
33716
  nameRole: exports_Schema.Literals(["tab", "pane", "none"]),
33702
33717
  name: exports_Schema.optional(exports_Schema.String),
33703
33718
  label: exports_Schema.String,
@@ -33734,11 +33749,10 @@ var LaunchResultSchema = exports_Schema.Struct({
33734
33749
  var TaskRequestFields = {
33735
33750
  repo: exports_Schema.String,
33736
33751
  hostId: ServerHostIdSchema,
33737
- rexBinDir: exports_Schema.optional(exports_Schema.String),
33738
- rexLocalEndpoint: exports_Schema.optional(exports_Schema.String),
33752
+ ...RexTaskSettingsSchema.fields,
33739
33753
  path: exports_Schema.String,
33740
33754
  commonDir: exports_Schema.String,
33741
- sessionId: SessionIdSchema,
33755
+ session: SessionSelectionSchema,
33742
33756
  worktreeRoot: exports_Schema.optional(exports_Schema.String)
33743
33757
  };
33744
33758
  var GitTaskRequestSchema = exports_Schema.Struct({
@@ -33757,7 +33771,7 @@ var JjTaskRequestSchema = exports_Schema.Struct({
33757
33771
  base: exports_Schema.optional(JjRevisionSchema)
33758
33772
  });
33759
33773
  var TaskRequestSchema = exports_Schema.Union([GitTaskRequestSchema, JjTaskRequestSchema]);
33760
- var RequestIdentitySchema = exports_Schema.Struct({ version: exports_Schema.Literal(4), hostId: ServerHostIdSchema });
33774
+ var RequestIdentitySchema = exports_Schema.Struct({ version: exports_Schema.Literal(5), hostId: ServerHostIdSchema });
33761
33775
  var RequestSchema = exports_Schema.Union([
33762
33776
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("discover"), context: exports_Schema.optional(exports_Schema.String) }),
33763
33777
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("sessions") }),
@@ -33773,10 +33787,10 @@ var RequestSchema = exports_Schema.Union([
33773
33787
  var ResponseSchema = exports_Schema.Union([
33774
33788
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("discover"), sessions: exports_Schema.Array(SessionTargetSchema), clients: exports_Schema.Array(ClientTargetSchema), projects: exports_Schema.Array(RepositorySchema), roots: exports_Schema.optional(exports_Schema.Array(exports_Schema.String)), cloneRoot: exports_Schema.String, checkout: exports_Schema.optional(RepositorySchema) }),
33775
33789
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("sessions"), sessions: exports_Schema.Array(SessionTargetSchema), clients: exports_Schema.Array(ClientTargetSchema) }),
33776
- exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("project"), project: RepositorySchema, checkout: RepositorySchema, worktrees: exports_Schema.Array(WorktreeSchema), branches: exports_Schema.Array(exports_Schema.String), revisions: exports_Schema.Array(JjRevisionChoiceSchema) }),
33790
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("project"), project: RepositorySchema, checkout: RepositorySchema, worktrees: exports_Schema.Array(WorktreeSchema), branches: exports_Schema.Array(exports_Schema.String), revisions: exports_Schema.Array(JjRevisionChoiceSchema), worktreeRoot: exports_Schema.optional(exports_Schema.String) }),
33777
33791
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("project-missing"), path: exports_Schema.String }),
33778
33792
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-source"), source: CloneSourceSchema }),
33779
- exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("worktrees"), repository: RepositorySchema, worktrees: exports_Schema.Array(WorktreeSchema), branches: exports_Schema.Array(exports_Schema.String), revisions: exports_Schema.Array(JjRevisionChoiceSchema) }),
33793
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("worktrees"), repository: RepositorySchema, worktrees: exports_Schema.Array(WorktreeSchema), branches: exports_Schema.Array(exports_Schema.String), revisions: exports_Schema.Array(JjRevisionChoiceSchema), worktreeRoot: exports_Schema.optional(exports_Schema.String) }),
33780
33794
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("revision"), revision: JjRevisionSchema }),
33781
33795
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("plan"), plan: LaunchPlanSchema }),
33782
33796
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-plan"), plan: ClonePlanSchema }),
@@ -33788,7 +33802,9 @@ var RexNativeConfigResponseSchema = exports_Schema.fromJsonString(exports_Schema
33788
33802
  var PopupOriginSchema = exports_Schema.Struct({ sessionId: exports_Schema.optional(SessionIdSchema), blockId: exports_Schema.optional(BlockIdSchema), clientId: exports_Schema.optional(ClientIdSchema) });
33789
33803
  var RexIdentitySchema = exports_Schema.Struct({ host_id: ServerHostIdSchema, endpoint: exports_Schema.String, principal: exports_Schema.Struct({ transport: exports_Schema.String }) });
33790
33804
  var RexSessionsSchema = exports_Schema.Struct({ sessions: exports_Schema.Array(exports_Schema.Struct({ session_id: SessionIdSchema, label: exports_Schema.String })) });
33791
- var RexSessionCreatedSchema = exports_Schema.Struct({ session_id: SessionIdSchema });
33805
+ var RexCreatedSchema = exports_Schema.Struct({ window_id: WindowIdSchema, block_ids: exports_Schema.Array(BlockIdSchema) });
33806
+ var RexSplitCreatedSchema = exports_Schema.Struct({ block_ids: exports_Schema.Array(BlockIdSchema) });
33807
+ var RexSessionCreatedSchema = exports_Schema.Struct({ session_id: SessionIdSchema, initial_windows: exports_Schema.Array(RexCreatedSchema) });
33792
33808
  var RexClientsSchema = exports_Schema.Struct({
33793
33809
  clients: exports_Schema.Array(exports_Schema.Struct({
33794
33810
  client_id: ClientIdSchema,
@@ -33796,11 +33812,12 @@ var RexClientsSchema = exports_Schema.Struct({
33796
33812
  connection_state: exports_Schema.optional(exports_Schema.String)
33797
33813
  }))
33798
33814
  });
33799
- var RexWindowsSchema = exports_Schema.Struct({
33800
- windows: exports_Schema.Array(exports_Schema.Struct({
33801
- window_id: WindowIdSchema,
33802
- label: exports_Schema.String,
33803
- layers: exports_Schema.Array(exports_Schema.Struct({ blocks: exports_Schema.optional(exports_Schema.Array(exports_Schema.Struct({ block_id: BlockIdSchema, host_id: ServerHostIdSchema }))) }))
33815
+ var RexBlocksSchema = exports_Schema.Struct({
33816
+ blocks: exports_Schema.Array(exports_Schema.Struct({
33817
+ block_id: BlockIdSchema,
33818
+ host_id: exports_Schema.optional(ServerHostIdSchema),
33819
+ placement: exports_Schema.String,
33820
+ window_id: exports_Schema.optional(exports_Schema.NullOr(WindowIdSchema))
33804
33821
  }))
33805
33822
  });
33806
33823
  var popupSize = { columns: 80, rows: 16 };
@@ -33834,7 +33851,6 @@ var RexViewSchema = exports_Schema.Struct({
33834
33851
  }))
33835
33852
  }))
33836
33853
  });
33837
- var RexCreatedSchema = exports_Schema.Struct({ window_id: exports_Schema.optional(WindowIdSchema), block_ids: exports_Schema.Array(BlockIdSchema) });
33838
33854
  var RexLayerSchema = exports_Schema.Struct({ layer_id: exports_Schema.NullOr(LayerIdSchema), block_ids: exports_Schema.NullOr(exports_Schema.Array(exports_Schema.NullOr(BlockIdSchema))), revision: exports_Schema.Number });
33839
33855
  var RexDirectorySchema = exports_Schema.Struct({ pwd: exports_Schema.optional(exports_Schema.String) });
33840
33856
  var RexRegistrySchema = exports_Schema.Struct({
@@ -33848,13 +33864,12 @@ var RexProcessSchema = exports_Schema.Struct({
33848
33864
  var RexActionsSchema = exports_Schema.Struct({ actions: exports_Schema.Array(exports_Schema.Struct({ name: exports_Schema.String, args: exports_Schema.optional(exports_Schema.Unknown) })) });
33849
33865
  var RexHelperArgsSchema = exports_Schema.Struct({ properties: exports_Schema.Struct({ request: exports_Schema.Struct({ type: exports_Schema.Literal("string") }) }) });
33850
33866
  var RexConfigCheckSchema = exports_Schema.Struct({ path: exports_Schema.String, exists: exports_Schema.Boolean, diagnostics: exports_Schema.Array(exports_Schema.Unknown) });
33851
- var CliBooleanFlagSchema = exports_Schema.Literals(["--additional", "--split", "--no-context", "--managed-popup"]);
33867
+ var CliBooleanFlagSchema = exports_Schema.Literals(["--additional", "--split", "--no-context"]);
33852
33868
  var CliStringFlagSchema = exports_Schema.Literals(["--bin", "--config", "--host", "--repo", "--session", "--name", "--branch", "--revision", "--worktree", "--worktree-name", "--client", "--context", "--origin-session", "--origin-block", "--origin-client"]);
33853
33869
  var CliFlagsSchema = exports_Schema.Struct({
33854
33870
  "--additional": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.Boolean)),
33855
33871
  "--split": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.Boolean)),
33856
33872
  "--no-context": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.Boolean)),
33857
- "--managed-popup": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.Boolean)),
33858
33873
  "--bin": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33859
33874
  "--config": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33860
33875
  "--host": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
@@ -34011,14 +34026,14 @@ var originDefaultHead = exports_Effect.fnUntraced(function* (repoPath) {
34011
34026
  const ref = yield* git(repoPath, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD").pipe(exports_Effect.catch(() => fail17("Cannot determine the existing repository's cached origin default branch")));
34012
34027
  return (yield* git(repoPath, "rev-parse", "--verify", `${ref.trim()}^{commit}`)).trim();
34013
34028
  });
34014
- var cloneRepository = exports_Effect.fnUntraced(function* (url, destination) {
34029
+ var cloneRepository = exports_Effect.fnUntraced(function* (url, destination, branch) {
34015
34030
  const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
34016
34031
  const env = {};
34017
34032
  for (const [key5, value3] of Object.entries(process.env))
34018
34033
  if (!key5.startsWith("GIT_") && value3 !== undefined)
34019
34034
  env[key5] = value3;
34020
34035
  env.GIT_TERMINAL_PROMPT = "1";
34021
- const child = yield* spawner.spawn(exports_ChildProcess.make("git", ["clone", "--origin", "origin", "--", url, destination], {
34036
+ const child = yield* spawner.spawn(exports_ChildProcess.make("git", ["clone", "--origin", "origin", ...branch ? ["--branch", branch] : [], "--", url, destination], {
34022
34037
  env,
34023
34038
  detached: false,
34024
34039
  stdin: "inherit",
@@ -34029,6 +34044,9 @@ var cloneRepository = exports_Effect.fnUntraced(function* (url, destination) {
34029
34044
  if (code !== 0)
34030
34045
  return yield* fail17(`Git clone failed (exit ${code}); destination retained at ${destination}`);
34031
34046
  }, exports_Effect.scoped);
34047
+ var createPrimaryBranch = exports_Effect.fnUntraced(function* (repoPath, branch) {
34048
+ yield* git(repoPath, "switch", "-c", branch);
34049
+ });
34032
34050
  var validCloneBranch = exports_Effect.fnUntraced(function* (branch, worktreeName) {
34033
34051
  if (!branch || branch.startsWith("-") || branch.split("/").some((part) => !part || part === "." || part === "..") || /[\p{ASCII}&&\p{Cc}]/v.test(branch))
34034
34052
  return yield* fail17("Invalid clone branch");
@@ -34592,22 +34610,20 @@ var listSessions = exports_Effect.gen(function* () {
34592
34610
  const result4 = yield* parse3(RexSessionsSchema, yield* rex(["ls", "--json"]));
34593
34611
  return result4.sessions.map((session) => ({ id: session.session_id, label: session.label }));
34594
34612
  });
34595
- var createSession = exports_Effect.fnUntraced(function* (name) {
34596
- const result4 = yield* parse3(RexSessionCreatedSchema, yield* rex(["api", "call", "session.create", JSON.stringify({ label: name })]));
34597
- return result4.session_id;
34598
- });
34599
34613
  var listClients = exports_Effect.gen(function* () {
34600
- const result4 = yield* parse3(RexClientsSchema, yield* rex(["client", "ls", "--json"]));
34614
+ const result4 = yield* parse3(RexClientsSchema, yield* rex(["api", "call", "client.list", JSON.stringify({ kinds: ["app"] })]));
34601
34615
  return result4.clients.filter((client) => client.info?.kind === "app" && client.connection_state === "connected").map((client) => ({ id: client.client_id, label: client.info?.label ?? client.client_id }));
34602
34616
  });
34603
- var windowList = exports_Effect.fnUntraced(function* (sessionId) {
34604
- const result4 = yield* parse3(RexWindowsSchema, yield* rex(["window", "ls", "-s", sessionId, "--json"]));
34605
- return result4.windows;
34617
+ var localBlocks = exports_Effect.fnUntraced(function* (sessionId) {
34618
+ const host = yield* localHost;
34619
+ const result4 = yield* parse3(RexBlocksSchema, yield* rex(["api", "call", "-s", sessionId, "session.list_blocks", JSON.stringify({ session_id: sessionId })]));
34620
+ return result4.blocks.filter((item) => item.host_id === host.id && item.placement === "placed");
34621
+ });
34622
+ var localBlockWindow = exports_Effect.fnUntraced(function* (sessionId, blockId) {
34623
+ return (yield* localBlocks(sessionId)).find((item) => item.block_id === blockId)?.window_id ?? undefined;
34606
34624
  });
34607
34625
  var originDirectory = exports_Effect.fnUntraced(function* (sessionId, blockId) {
34608
- const host = yield* localHost;
34609
- const windows = yield* windowList(sessionId);
34610
- if (!windows.some((window) => window.layers.some((layer12) => layer12.blocks?.some((block) => block.block_id === blockId && block.host_id === host.id))))
34626
+ if (!(yield* localBlockWindow(sessionId, blockId)))
34611
34627
  return;
34612
34628
  const raw = yield* rex(["block", "call", "-s", sessionId, "-b", blockId, "pwd"]);
34613
34629
  const result4 = yield* parse3(RexDirectorySchema, raw);
@@ -34625,46 +34641,85 @@ var commandWithPath = (command) => {
34625
34641
  ];
34626
34642
  return env.length ? ["/usr/bin/env", ...env, ...command] : command;
34627
34643
  };
34628
- var createTab = exports_Effect.fnUntraced(function* (sessionId, name, cwd, command) {
34629
- const result4 = yield* parse3(RexCreatedSchema, yield* rex(["window", "new", "-s", sessionId, name, "-c", cwd, "--shell=none", "--keep-open", "--json", "--", ...commandWithPath(command)]));
34630
- const blockId = result4.block_ids[0];
34631
- if (!blockId)
34632
- return yield* exports_Effect.fail(new AppError({ message: "Rex created a tab without a terminal block" }));
34633
- if (!result4.window_id)
34634
- return yield* exports_Effect.fail(new AppError({ message: "Rex did not return a window ID" }));
34635
- return { windowId: result4.window_id, blockId };
34636
- });
34637
- var createSplit = exports_Effect.fnUntraced(function* (sessionId, windowId, blockId, name, cwd, command) {
34638
- const result4 = yield* parse3(RexCreatedSchema, yield* rex(["split", "-s", sessionId, "-b", blockId, "--split=right", "--label", name, "-c", cwd, "--shell=none", "--keep-open", "--json", "--", ...commandWithPath(command)]));
34639
- const created = result4.block_ids.find((id2) => id2 !== blockId);
34640
- if (!created)
34641
- return yield* exports_Effect.fail(new AppError({ message: "Rex created a split without a new terminal block" }));
34642
- return { windowId: result4.window_id ?? windowId, blockId: created };
34643
- });
34644
- var focus = exports_Effect.fnUntraced(function* (sessionId, windowId, clientId, blockId) {
34644
+ var terminalLayout = (command, cwd, label, onCompletion = false, size8) => ({
34645
+ block: { flavor: "com.superlogical.terminal.shell", label, options: {
34646
+ command: commandWithPath(command),
34647
+ shell: "none",
34648
+ cwd,
34649
+ exit: { on_completion: onCompletion },
34650
+ ...size8 ? { size: size8 } : {}
34651
+ } }
34652
+ });
34653
+ var openTerminal = exports_Effect.fnUntraced(function* (session, name, cwd, command, target) {
34654
+ const layout = terminalLayout(command, cwd, name);
34655
+ let sessionId;
34656
+ let created;
34657
+ if (session.kind === "new") {
34658
+ const result4 = yield* parse3(RexSessionCreatedSchema, yield* rex(["api", "call", "session.create", JSON.stringify({
34659
+ label: session.name,
34660
+ initial_windows: [{ window_label: name, layout }]
34661
+ })]));
34662
+ sessionId = result4.session_id;
34663
+ created = result4.initial_windows[0];
34664
+ } else if (target) {
34665
+ sessionId = session.id;
34666
+ const result4 = yield* parse3(RexSplitCreatedSchema, yield* rex(["api", "call", "-s", sessionId, "session.new_split", JSON.stringify({
34667
+ session_id: sessionId,
34668
+ anchor_id: target.blockId,
34669
+ direction: "horizontal",
34670
+ side: "after",
34671
+ layout,
34672
+ focus: true
34673
+ })]));
34674
+ created = { window_id: target.windowId, block_ids: result4.block_ids };
34675
+ } else {
34676
+ sessionId = session.id;
34677
+ created = yield* parse3(RexCreatedSchema, yield* rex(["api", "call", "-s", sessionId, "session.new_window", JSON.stringify({
34678
+ session_id: sessionId,
34679
+ window_label: name,
34680
+ layout,
34681
+ focus: true
34682
+ })]));
34683
+ }
34684
+ const blockId = created?.block_ids[0];
34685
+ if (!created || !blockId)
34686
+ return yield* exports_Effect.fail(new AppError({ message: "Rex did not return the created window and terminal" }));
34687
+ return { sessionId, windowId: created.window_id, blockId };
34688
+ });
34689
+ var taskContext = exports_Effect.fnUntraced(function* (session, settings, expectedHostId) {
34690
+ const path = yield* exports_Path.Path;
34691
+ if (settings.rexBinDir) {
34692
+ if (!path.isAbsolute(settings.rexBinDir))
34693
+ return yield* exports_Effect.fail(new AppError({ message: "REX_BIN_DIR must be absolute" }));
34694
+ process.env.REX_BIN_DIR = settings.rexBinDir;
34695
+ }
34696
+ if (settings.rexLocalEndpoint)
34697
+ process.env.REX_WORKTREES_LOCAL_ENDPOINT = settings.rexLocalEndpoint;
34698
+ const { REX_SESSION: sessionId, REX_BLOCK: blockId } = yield* exports_Schema.decodeUnknownEffect(RexTaskIdentitySchema)(process.env);
34699
+ if (session.kind === "existing" && session.id !== sessionId)
34700
+ return yield* exports_Effect.fail(new AppError({ message: "Task must run in its requested Rex session and terminal" }));
34701
+ if ((yield* localHost).id !== expectedHostId || !(yield* localBlockWindow(sessionId, blockId)))
34702
+ return yield* exports_Effect.fail(new AppError({ message: "Task must run in a placed terminal on its requested Rex host" }));
34703
+ return { sessionId, blockId };
34704
+ });
34705
+ var focus = exports_Effect.fnUntraced(function* (sessionId, windowId, blockId, clientId) {
34645
34706
  const warnings = [];
34646
- yield* rex(["focus", "-s", sessionId, windowId]).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
34647
- warnings.push(exports_Cause.pretty(exports_Cause.fail(error2)));
34707
+ yield* rex(["api", "call", "-s", sessionId, "session.focus_block", JSON.stringify({ session_id: sessionId, block_id: blockId })]).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
34708
+ warnings.push(`Could not focus Rex pane: ${exports_Cause.pretty(exports_Cause.fail(error2))}`);
34648
34709
  })));
34649
- if (clientId) {
34650
- yield* rex(["-C", clientId, "do", "session.select", `session_id=${sessionId}`, `window_id=${windowId}`]).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
34710
+ if (clientId)
34711
+ yield* rex(["api", "call", "client.perform", JSON.stringify({
34712
+ client_id: clientId,
34713
+ action: "session.select",
34714
+ args: { session_id: sessionId, window_id: windowId }
34715
+ })]).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
34651
34716
  warnings.push(`Could not focus Rex app: ${exports_Cause.pretty(exports_Cause.fail(error2))}`);
34652
34717
  })));
34653
- }
34654
- if (blockId) {
34655
- yield* rex(["focus", "-s", sessionId, "-w", windowId, blockId]).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
34656
- warnings.push(`Could not focus Rex pane: ${exports_Cause.pretty(exports_Cause.fail(error2))}`);
34657
- })));
34658
- }
34659
34718
  return warnings.length ? warnings.join("; ") : undefined;
34660
34719
  });
34661
34720
  var findPane = (node, blockId) => !node ? undefined : node.block_id === blockId ? node : node.split ? findPane(node.split.before, blockId) ?? findPane(node.split.after, blockId) : undefined;
34662
34721
  var openPopup = exports_Effect.fnUntraced(function* (command, sessionId, origin2 = {}) {
34663
- const path = yield* exports_Path.Path;
34664
- const endpoint = (yield* localIdentity).endpoint;
34665
- const program = yield* binary(path);
34666
- const localRex = (args3) => run4(program, ["-S", endpoint, "--autostart=false", ...args3], undefined, nativeEnv());
34667
- const view = yield* parse3(RexViewSchema, yield* localRex(["api", "call", "-s", sessionId, "session.view", JSON.stringify({ session_id: sessionId })]));
34722
+ const view = yield* parse3(RexViewSchema, yield* rex(["api", "call", "-s", sessionId, "session.view", JSON.stringify({ session_id: sessionId })]));
34668
34723
  const source = origin2.blockId ? view.windows.find((window2) => window2.layers.some((layer12) => layer12.blocks.some((block) => block.block_id === origin2.blockId))) : undefined;
34669
34724
  if (origin2.blockId && !source)
34670
34725
  return yield* exports_Effect.fail(new AppError({ message: "Source pane is no longer in the selected Rex session" }));
@@ -34674,9 +34729,9 @@ var openPopup = exports_Effect.fnUntraced(function* (command, sessionId, origin2
34674
34729
  return yield* exports_Effect.fail(new AppError({ message: "No active Rex window for the popup" }));
34675
34730
  }
34676
34731
  const sourceOwner = source?.layers.flatMap((layer12) => layer12.blocks).find((block) => block.block_id === origin2.blockId)?.owner;
34677
- const clients = (yield* parse3(RexClientsSchema, yield* localRex(["client", "ls", "--json"]))).clients.filter((client) => client.info?.kind === "app" && client.connection_state === "connected");
34678
- const clientId = [sourceOwner, origin2.clientId].find((id2) => id2 && clients.some((client) => client.client_id === id2));
34679
- const popupCommand = clientId ? [...command, "--managed-popup", "--origin-client", clientId] : [...command, "--managed-popup"];
34732
+ const clients = yield* listClients;
34733
+ const clientId = [sourceOwner, origin2.clientId].find((id2) => id2 && clients.some((client) => client.id === id2));
34734
+ const popupCommand = clientId ? [...command, "--origin-client", clientId] : command;
34680
34735
  const blocks = window.layers.flatMap((layer12) => layer12.blocks);
34681
34736
  const terminals = blocks.filter((block) => block.flavor === "com.superlogical.terminal.shell");
34682
34737
  const terminal = terminals.find((block) => block.block_id === origin2.blockId) ?? terminals.find((block) => block.block_id === window.focused_block_id) ?? terminals[0];
@@ -34685,7 +34740,7 @@ var openPopup = exports_Effect.fnUntraced(function* (command, sessionId, origin2
34685
34740
  const pane = window.layers.map((layer12) => findPane(layer12.layout, terminal.block_id)).find((node) => node !== undefined);
34686
34741
  if (!pane)
34687
34742
  return yield* exports_Effect.fail(new AppError({ message: "Rex terminal geometry changed before opening the popup" }));
34688
- const size8 = yield* parse3(RexTerminalSizeSchema, yield* localRex(["block", "call", "-s", sessionId, "-b", terminal.block_id, "size"]));
34743
+ const size8 = yield* parse3(RexTerminalSizeSchema, yield* rex(["block", "call", "-s", sessionId, "-b", terminal.block_id, "size"]));
34689
34744
  const zoomed = window.zoomed_block_id === terminal.block_id;
34690
34745
  width2 = Math.min(1, (popupSize.columns + 2) * (zoomed ? 1 : pane.rect[2]) / size8.columns);
34691
34746
  height = Math.min(1, (popupSize.rows + 3) * (zoomed ? 1 : pane.rect[3]) / size8.rows);
@@ -34694,30 +34749,14 @@ var openPopup = exports_Effect.fnUntraced(function* (command, sessionId, origin2
34694
34749
  session_id: sessionId,
34695
34750
  window_id: windowId,
34696
34751
  bounds: [(1 - width2) / 2, (1 - height) / 2, width2, height],
34697
- layout: { block: { flavor: "com.superlogical.terminal.shell", options: { command: commandWithPath(popupCommand), shell: "none", cwd: process.cwd(), size: popupSize, exit: { on_completion: true } } } },
34752
+ layout: terminalLayout(popupCommand, process.cwd(), "Worktrees", true, popupSize),
34698
34753
  focus: true
34699
34754
  };
34700
- const created = yield* parse3(RexLayerSchema, yield* localRex(["api", "call", "-s", sessionId, "session.new_layer", JSON.stringify(args2)]));
34755
+ const created = yield* parse3(RexLayerSchema, yield* rex(["api", "call", "-s", sessionId, "session.new_layer", JSON.stringify(args2)]));
34701
34756
  if (!created.layer_id || !created.block_ids?.some(Boolean))
34702
34757
  return yield* exports_Effect.fail(new AppError({ message: "Rex did not return a floating terminal layer" }));
34703
34758
  return created;
34704
- });
34705
- var closeManagedPopup = exports_Effect.gen(function* () {
34706
- const sessionId = process.env.REX_SESSION === undefined ? undefined : yield* exports_Schema.decodeUnknownEffect(SessionIdSchema)(process.env.REX_SESSION);
34707
- const blockId = process.env.REX_BLOCK === undefined ? undefined : yield* exports_Schema.decodeUnknownEffect(BlockIdSchema)(process.env.REX_BLOCK);
34708
- if (!sessionId || !blockId) {
34709
- return yield* exports_Effect.fail(new AppError({ message: "Cannot close managed Rex popup without its own session and block" }));
34710
- }
34711
- const path = yield* exports_Path.Path;
34712
- const endpoint = (yield* localIdentity).endpoint;
34713
- const program = yield* binary(path);
34714
- const localRex = (args2) => run4(program, ["-S", endpoint, "--autostart=false", ...args2], undefined, nativeEnv());
34715
- const view = yield* parse3(RexViewSchema, yield* localRex(["api", "call", "-s", sessionId, "session.view", JSON.stringify({ session_id: sessionId })]));
34716
- if (!view.windows.some((window) => window.layers.some((layer12) => layer12.blocks.some((block) => block.block_id === blockId)))) {
34717
- return yield* exports_Effect.fail(new AppError({ message: "Managed Rex popup block is no longer in its own session" }));
34718
- }
34719
- yield* localRex(["block", "close", "-s", sessionId, blockId]);
34720
- });
34759
+ }, withLocalIdentity);
34721
34760
 
34722
34761
  // src/config.ts
34723
34762
  var loadConfig = exports_Effect.gen(function* () {
@@ -34785,14 +34824,7 @@ var staleBlock = (error2, sessionId, blockId) => {
34785
34824
  const diagnostic = (error2.stderr.trim() || error2.stdout.trim()).trim();
34786
34825
  return diagnostic === `Error: block target "${blockId}" not found` || diagnostic === `Error: block target "${blockId}" not found: session scope: session "${sessionId}" not found`;
34787
34826
  };
34788
- var liveBlock = exports_Effect.fnUntraced(function* (sessionId, windowId, blockId, hostId, path) {
34789
- const windows = yield* windowList(sessionId);
34790
- const window = windows.find((entry) => entry.window_id === windowId);
34791
- if (!window)
34792
- return false;
34793
- const block = window.layers.flatMap((layer12) => layer12.blocks ?? []).find((entry) => entry.block_id === blockId);
34794
- if (!block || block.host_id !== hostId)
34795
- return false;
34827
+ var liveBlock = exports_Effect.fnUntraced(function* (sessionId, blockId, path) {
34796
34828
  const raw = yield* exports_Effect.catchIf(rex(["block", "call", "-s", sessionId, "-b", blockId, "process"]), (error2) => staleBlock(error2, sessionId, blockId), () => exports_Effect.succeed(""));
34797
34829
  if (!raw)
34798
34830
  return false;
@@ -34806,7 +34838,7 @@ var liveBlock = exports_Effect.fnUntraced(function* (sessionId, windowId, blockI
34806
34838
  if (!pathname)
34807
34839
  return false;
34808
34840
  const cwd = yield* exports_Effect.catchIf(canonical(pathname), (error2) => missing3(error2), () => exports_Effect.succeed(""));
34809
- return cwd === path ? window.label : false;
34841
+ return cwd === path;
34810
34842
  });
34811
34843
  var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34812
34844
  const host = yield* localHost;
@@ -34825,6 +34857,11 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34825
34857
  const repo = yield* repository3(input.repo);
34826
34858
  if (repo.vcs !== input.vcs)
34827
34859
  return yield* fail19("Repository backend changed since selection");
34860
+ const pathService = yield* exports_Path.Path;
34861
+ if (input.directory !== undefined && (!pathService.isAbsolute(input.directory) || pathService.resolve(input.directory) !== input.directory || input.directory === pathService.parse(input.directory).root))
34862
+ return yield* fail19("Worktree directory must be a normalized absolute directory");
34863
+ if (input.directory !== undefined && input.path !== undefined)
34864
+ return yield* fail19("Directory cannot be combined with an existing worktree path");
34828
34865
  let path;
34829
34866
  let checkout;
34830
34867
  let branch = null;
@@ -34838,9 +34875,11 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34838
34875
  return yield* fail19("Select exactly one branch or existing worktree path");
34839
34876
  if (input.path && input.worktreeName !== undefined)
34840
34877
  return yield* fail19("Worktree name only applies to a branch checkout");
34841
- worktreeRoot = input.branch ? yield* resolveWorktreeRoot(repo.path) : undefined;
34878
+ worktreeRoot = input.branch ? input.directory ? pathService.dirname(input.directory) : yield* resolveWorktreeRoot(repo.path) : undefined;
34842
34879
  if (input.branch) {
34843
- const destination = yield* planWorktree(repo.path, input.branch, worktreeRoot, input.worktreeName);
34880
+ const destination = yield* planWorktree(repo.path, input.branch, worktreeRoot, input.directory ? pathService.basename(input.directory) : input.worktreeName);
34881
+ if (input.directory && destination.path !== input.directory)
34882
+ return yield* fail19("Branch is already checked out at a different directory");
34844
34883
  path = destination.path;
34845
34884
  branch = input.branch;
34846
34885
  checkout = destination.existing ? "existing" : (yield* listBranches(repo.path)).includes(branch) ? "attach" : "create";
@@ -34868,7 +34907,9 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34868
34907
  workspaceName = tree.name;
34869
34908
  checkout = "existing";
34870
34909
  } else {
34871
- worktreeRoot = yield* resolveWorktreeRoot(repo.path);
34910
+ if (input.directory && pathService.basename(input.directory) !== input.worktreeName)
34911
+ return yield* fail19("Workspace name must match the directory name");
34912
+ worktreeRoot = input.directory ? pathService.dirname(input.directory) : yield* resolveWorktreeRoot(repo.path);
34872
34913
  const planned = yield* planWorkspace(repo.path, input.worktreeName, input.revision, worktreeRoot);
34873
34914
  path = planned.path;
34874
34915
  workspaceName = planned.workspaceName;
@@ -34877,20 +34918,24 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34877
34918
  }
34878
34919
  }
34879
34920
  let warning;
34880
- const records = yield* associations.pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
34881
- warning = [warning, exports_Cause.pretty(exports_Cause.fail(error2))].filter(Boolean).join("; ");
34882
- return [];
34883
- })));
34884
34921
  if (!clientId && clients.length > 1)
34885
- warning = [warning, "Multiple Rex apps are connected; select the session in the intended app"].filter(Boolean).join("; ");
34922
+ warning = "Multiple Rex apps are connected; select the session in the intended app";
34886
34923
  let target;
34887
- for (const entry of records) {
34888
- if (entry.vcs !== repo.vcs || entry.hostId !== host.id || entry.commonDir !== repo.commonDir || entry.path !== path || input.session.kind !== "existing" || entry.sessionId !== input.session.id)
34889
- continue;
34890
- const label = yield* liveBlock(entry.sessionId, entry.windowId, entry.blockId, host.id, path);
34891
- if (label !== false) {
34892
- target = { windowId: entry.windowId, blockId: entry.blockId, label };
34893
- break;
34924
+ if (input.session.kind === "existing" && (!input.additional || input.split)) {
34925
+ const sessionId = input.session.id;
34926
+ const records = yield* associations.pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
34927
+ warning = [warning, exports_Cause.pretty(exports_Cause.fail(error2))].filter(Boolean).join("; ");
34928
+ return [];
34929
+ })));
34930
+ const candidates = records.filter((entry) => entry.vcs === repo.vcs && entry.hostId === host.id && entry.commonDir === repo.commonDir && entry.path === path && entry.sessionId === sessionId);
34931
+ const blocks = candidates.length ? yield* localBlocks(sessionId) : [];
34932
+ for (const entry of candidates) {
34933
+ if (blocks.find((block) => block.block_id === entry.blockId)?.window_id !== entry.windowId)
34934
+ continue;
34935
+ if (yield* liveBlock(sessionId, entry.blockId, path)) {
34936
+ target = { windowId: entry.windowId, blockId: entry.blockId };
34937
+ break;
34938
+ }
34894
34939
  }
34895
34940
  }
34896
34941
  const action = input.split && target ? "split" : target && !input.additional && !input.split ? "focus" : "new-tab";
@@ -34917,7 +34962,7 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34917
34962
  return {
34918
34963
  ...common,
34919
34964
  vcs: "git",
34920
- input: { ...input, repo: repo.path, ...input.path ? { path } : {} },
34965
+ input: { ...input, repo: repo.path, ...input.path ? { path } : {}, ...input.directory ? { worktreeName: pathService.basename(input.directory) } : {} },
34921
34966
  branch,
34922
34967
  checkout,
34923
34968
  ...gitBase ? { base: gitBase } : {},
@@ -34933,7 +34978,7 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34933
34978
  label: action === "focus" ? "Focus existing tab" : checkout === "create" ? "Create workspace & open" : action === "split" ? "Open pane" : "Open tab"
34934
34979
  };
34935
34980
  });
34936
- var sameLaunchPlan = (a, b) => a.vcs === b.vcs && a.input.vcs === b.input.vcs && a.hostId === b.hostId && a.worktreeRoot === b.worktreeRoot && a.clientId === b.clientId && a.input.repo === b.input.repo && sameSession(a.input.session, b.input.session) && a.input.path === b.input.path && a.input.worktreeName === b.input.worktreeName && a.input.name === b.input.name && a.input.clientId === b.input.clientId && a.input.additional === b.input.additional && a.input.split === b.input.split && a.path === b.path && a.checkout === b.checkout && a.action === b.action && a.nameRole === b.nameRole && a.name === b.name && a.target?.windowId === b.target?.windowId && a.target?.blockId === b.target?.blockId && a.target?.label === b.target?.label && (a.vcs === "git" && b.vcs === "git" && a.input.vcs === "git" && b.input.vcs === "git" ? a.input.branch === b.input.branch && a.branch === b.branch && a.base?.head === b.base?.head && a.base?.branch === b.base?.branch : a.vcs === "jj" && b.vcs === "jj" && a.input.vcs === "jj" && b.input.vcs === "jj" && a.input.revision === b.input.revision && a.workspaceName === b.workspaceName && a.base?.commitId === b.base?.commitId && a.base?.changeId === b.base?.changeId);
34981
+ var sameLaunchPlan = (a, b) => a.vcs === b.vcs && a.input.vcs === b.input.vcs && a.hostId === b.hostId && a.worktreeRoot === b.worktreeRoot && a.clientId === b.clientId && a.input.repo === b.input.repo && sameSession(a.input.session, b.input.session) && a.input.path === b.input.path && a.input.directory === b.input.directory && a.input.worktreeName === b.input.worktreeName && a.input.name === b.input.name && a.input.clientId === b.input.clientId && a.input.additional === b.input.additional && a.input.split === b.input.split && a.path === b.path && a.checkout === b.checkout && a.action === b.action && a.nameRole === b.nameRole && a.name === b.name && a.target?.windowId === b.target?.windowId && a.target?.blockId === b.target?.blockId && (a.vcs === "git" && b.vcs === "git" && a.input.vcs === "git" && b.input.vcs === "git" ? a.input.branch === b.input.branch && a.branch === b.branch && a.base?.head === b.base?.head && a.base?.branch === b.base?.branch : a.vcs === "jj" && b.vcs === "jj" && a.input.vcs === "jj" && b.input.vcs === "jj" && a.input.revision === b.input.revision && a.workspaceName === b.workspaceName && a.base?.commitId === b.base?.commitId && a.base?.changeId === b.base?.changeId);
34937
34982
  var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expectedHostId) {
34938
34983
  const pathService = yield* exports_Path.Path;
34939
34984
  if (!command[0] || !pathService.isAbsolute(command[0]))
@@ -34945,11 +34990,11 @@ var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expe
34945
34990
  const target2 = plan.target;
34946
34991
  if (!target2 || plan.input.session.kind !== "existing")
34947
34992
  return yield* fail19("The reviewed focus target is no longer available");
34948
- const sessionId2 = plan.input.session.id;
34949
- const warning2 = [plan.warning, yield* focus(sessionId2, target2.windowId, plan.clientId, target2.blockId)].filter(Boolean).join("; ") || undefined;
34993
+ const sessionId = plan.input.session.id;
34994
+ const warning2 = [plan.warning, yield* focus(sessionId, target2.windowId, target2.blockId, plan.clientId)].filter(Boolean).join("; ") || undefined;
34950
34995
  const result5 = {
34951
34996
  hostId: plan.hostId,
34952
- sessionId: sessionId2,
34997
+ sessionId,
34953
34998
  windowId: target2.windowId,
34954
34999
  blockId: target2.blockId,
34955
35000
  path: plan.path,
@@ -34962,15 +35007,13 @@ var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expe
34962
35007
  const repo = yield* repository3(plan.input.repo);
34963
35008
  if (repo.vcs !== plan.vcs)
34964
35009
  return yield* fail19("Repository backend changed since review");
34965
- const sessionId = plan.input.session.kind === "existing" ? plan.input.session.id : yield* createSession(plan.input.session.name);
34966
35010
  const common = {
34967
35011
  repo: repo.path,
34968
35012
  path: plan.path,
34969
35013
  commonDir: repo.commonDir,
34970
- sessionId,
35014
+ session: plan.input.session,
34971
35015
  hostId: plan.hostId,
34972
- ...process.env.REX_BIN_DIR ? { rexBinDir: process.env.REX_BIN_DIR } : {},
34973
- ...process.env.REX_WORKTREES_LOCAL_ENDPOINT ? { rexLocalEndpoint: process.env.REX_WORKTREES_LOCAL_ENDPOINT } : {},
35016
+ ...taskSettings(),
34974
35017
  ...plan.worktreeRoot ? { worktreeRoot: plan.worktreeRoot } : {}
34975
35018
  };
34976
35019
  const request3 = plan.vcs === "git" ? {
@@ -34992,13 +35035,13 @@ var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expe
34992
35035
  const name = plan.name;
34993
35036
  if (!name)
34994
35037
  return yield* fail19("The reviewed Rex tab name is no longer available");
34995
- const created = plan.action === "split" ? target ? yield* createSplit(sessionId, target.windowId, target.blockId, name, plan.path, argv) : yield* fail19("The reviewed split target is no longer available") : yield* createTab(sessionId, name, plan.checkout === "existing" ? plan.path : repo.path, argv);
34996
- const warning = [plan.warning, yield* focus(sessionId, created.windowId, plan.clientId, created.blockId)].filter(Boolean).join("; ") || undefined;
35038
+ if (plan.action === "split" && !target)
35039
+ return yield* fail19("The reviewed split target is no longer available");
35040
+ const created = yield* openTerminal(plan.input.session, name, plan.checkout === "existing" ? plan.path : repo.path, argv, plan.action === "split" ? target : undefined);
35041
+ const warning = [plan.warning, yield* focus(created.sessionId, created.windowId, created.blockId, plan.clientId)].filter(Boolean).join("; ") || undefined;
34997
35042
  const result4 = {
34998
35043
  hostId: plan.hostId,
34999
- sessionId,
35000
- windowId: created.windowId,
35001
- blockId: created.blockId,
35044
+ ...created,
35002
35045
  path: plan.path,
35003
35046
  pending: true,
35004
35047
  action: plan.action,
@@ -35023,25 +35066,20 @@ var shell = exports_Effect.fnUntraced(function* (cwd) {
35023
35066
  if (code !== 0)
35024
35067
  return yield* fail19(`Shell exited with status ${code}`);
35025
35068
  }, exports_Effect.scoped);
35069
+ var taskSettings = () => ({
35070
+ ...process.env.REX_BIN_DIR ? { rexBinDir: process.env.REX_BIN_DIR } : {},
35071
+ ...process.env.REX_WORKTREES_LOCAL_ENDPOINT ? { rexLocalEndpoint: process.env.REX_WORKTREES_LOCAL_ENDPOINT } : {}
35072
+ });
35073
+ var associateTask = exports_Effect.fnUntraced(function* (association) {
35074
+ const windowId = yield* localBlockWindow(association.sessionId, association.blockId);
35075
+ if (!windowId)
35076
+ return yield* fail19("Rex task terminal is no longer placed on its requested host");
35077
+ yield* saveAssociation({ ...association, windowId });
35078
+ }, (effect2) => effect2.pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => console.error(`Checkout is available; association not saved: ${exports_Cause.pretty(exports_Cause.fail(error2))}`)))));
35026
35079
  var task = exports_Effect.fnUntraced(function* (request3) {
35027
- if (request3.rexBinDir) {
35028
- const path2 = yield* exports_Path.Path;
35029
- if (!path2.isAbsolute(request3.rexBinDir))
35030
- return yield* fail19("REX_BIN_DIR must be an absolute directory");
35031
- process.env.REX_BIN_DIR = request3.rexBinDir;
35032
- }
35033
- if (request3.rexLocalEndpoint)
35034
- process.env.REX_WORKTREES_LOCAL_ENDPOINT = request3.rexLocalEndpoint;
35035
- const host = yield* localHost;
35036
- if (host.id !== request3.hostId)
35037
- return yield* fail19(`Wrong Rex task host: expected ${request3.hostId}, got ${host.id}`);
35080
+ const { sessionId, blockId } = yield* taskContext(request3.session, request3, request3.hostId);
35038
35081
  if (request3.vcs === "git" && !request3.branch && request3.worktreeName !== undefined)
35039
35082
  return yield* fail19("Worktree name only applies to a branch checkout");
35040
- if (process.env.REX_SESSION !== request3.sessionId || !process.env.REX_BLOCK)
35041
- return yield* fail19("Task must run in its requested Rex session and terminal");
35042
- const blockId = yield* exports_Schema.decodeUnknownEffect(BlockIdSchema)(process.env.REX_BLOCK);
35043
- if (!(yield* listSessions).some((item) => item.id === request3.sessionId))
35044
- return yield* fail19("Requested Rex session no longer exists");
35045
35083
  const current = yield* repository3(request3.repo);
35046
35084
  if (current.vcs !== request3.vcs || current.commonDir !== request3.commonDir || current.path !== request3.repo)
35047
35085
  return yield* fail19("Repository identity changed since launch");
@@ -35061,7 +35099,7 @@ var task = exports_Effect.fnUntraced(function* (request3) {
35061
35099
  if (request3.base)
35062
35100
  return yield* fail19("Existing JJ workspace cannot change its base revision");
35063
35101
  path = yield* canonical(request3.path);
35064
- const tree = (yield* listWorkspaces(request3.repo)).find((entry2) => entry2.path === path && entry2.name === request3.workspaceName && entry2.present);
35102
+ const tree = (yield* listWorkspaces(request3.repo)).find((entry) => entry.path === path && entry.name === request3.workspaceName && entry.present);
35065
35103
  if (!tree)
35066
35104
  return yield* fail19("Selected JJ workspace no longer belongs to repository");
35067
35105
  }
@@ -35088,17 +35126,7 @@ var task = exports_Effect.fnUntraced(function* (request3) {
35088
35126
  }
35089
35127
  if (path !== request3.path)
35090
35128
  return yield* fail19(`Worktree path changed; checkout remains at ${path}`);
35091
- const windows = yield* windowList(request3.sessionId).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
35092
- console.error(`Worktree ${path} is available; cannot inspect Rex terminal for association: ${exports_Cause.pretty(exports_Cause.fail(error2))}`);
35093
- return [];
35094
- })));
35095
- const entry = windows.find((window) => window.layers.some((layer12) => layer12.blocks?.some((block) => block.block_id === blockId && block.host_id === host.id)));
35096
- if (entry) {
35097
- yield* saveAssociation({ vcs: request3.vcs, hostId: host.id, commonDir: current.commonDir, path, sessionId: request3.sessionId, windowId: entry.window_id, blockId }).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
35098
- console.error(`Worktree ${path} is available; association not saved: ${exports_Cause.pretty(exports_Cause.fail(error2))}`);
35099
- })));
35100
- } else
35101
- console.error(`Worktree ${path} is available; Rex block could not be associated, select this worktree by path next time.`);
35129
+ yield* associateTask({ vcs: request3.vcs, hostId: request3.hostId, commonDir: current.commonDir, path, sessionId, blockId });
35102
35130
  yield* shell(path);
35103
35131
  });
35104
35132
  var cloneDestination = exports_Effect.fnUntraced(function* (destination, url, vcs = "git", sourceHostId) {
@@ -35145,12 +35173,26 @@ var checkCloneParent = exports_Effect.fnUntraced(function* (destination) {
35145
35173
  catch: (cause) => new AppError({ message: `Cannot create clone destination ${destination}: ${ancestor} is not writable; choose another destination or fix its permissions`, cause })
35146
35174
  });
35147
35175
  });
35176
+ var validateCloneDestination = exports_Effect.fnUntraced(function* (input) {
35177
+ const path = yield* exports_Path.Path;
35178
+ if (input.directory !== undefined) {
35179
+ if (!path.isAbsolute(input.directory) || path.resolve(input.directory) !== input.directory || input.directory === path.parse(input.directory).root)
35180
+ return yield* fail19("Worktree directory must be a normalized absolute directory");
35181
+ if (input.checkout !== "worktree")
35182
+ return yield* fail19("Worktree directory requires a worktree checkout");
35183
+ }
35184
+ if (input.checkout === "primary" && input.worktreeName !== undefined)
35185
+ return yield* fail19("Primary checkout cannot have a worktree name");
35186
+ if (input.checkout === "worktree" && input.vcs === "jj" && !input.directory && !input.worktreeName)
35187
+ return yield* fail19("JJ worktree checkout requires a workspace name or directory");
35188
+ });
35148
35189
  var planClone = exports_Effect.fnUntraced(function* (input, expectedHostId) {
35149
35190
  const host = yield* localHost;
35150
35191
  if (expectedHostId && host.id !== expectedHostId)
35151
35192
  return yield* fail19("Wrong Rex clone host");
35152
35193
  if (input.vcs !== input.source.vcs)
35153
35194
  return yield* fail19("Clone source backend does not match request");
35195
+ yield* validateCloneDestination(input);
35154
35196
  yield* exports_Schema.decodeUnknownEffect(SessionSelectionSchema)(input.session);
35155
35197
  if (input.session.kind === "existing") {
35156
35198
  const sessionId = input.session.id;
@@ -35174,6 +35216,8 @@ var planClone = exports_Effect.fnUntraced(function* (input, expectedHostId) {
35174
35216
  if (commonDir === undefined)
35175
35217
  yield* checkCloneParent(input.repo);
35176
35218
  const existing = commonDir !== undefined;
35219
+ if (existing && input.checkout === "primary" && input.vcs === "git" && (input.branchMode !== "existing" || (yield* repositoryHead(input.repo)).branch !== input.branch))
35220
+ return yield* fail19("Existing primary checkout is not on the requested branch");
35177
35221
  let gitBase;
35178
35222
  let base;
35179
35223
  if (input.vcs === "git") {
@@ -35192,9 +35236,14 @@ var planClone = exports_Effect.fnUntraced(function* (input, expectedHostId) {
35192
35236
  }
35193
35237
  if (input.vcs === "jj" && existing && !base)
35194
35238
  base = yield* resolveRevision(input.repo, "@-");
35239
+ if (input.vcs === "jj" && existing && input.checkout === "primary" && base) {
35240
+ const current = yield* resolveRevision(input.repo, "@-");
35241
+ if (current.commitId !== base.commitId || current.changeId !== base.changeId)
35242
+ return yield* fail19("Existing primary workspace is not based on the requested revision");
35243
+ }
35195
35244
  const clientId = input.clientId ?? (clients.length === 1 ? clients[0]?.id : undefined);
35196
35245
  const warning = !clientId && clients.length > 1 ? "Multiple Rex apps are connected; select the intended app" : undefined;
35197
- const snapshotDetail = input.vcs === "jj" && (input.worktreeName || existing) ? `JJ ${input.worktreeName ? "workspace creation" : "new change"} snapshots the destination workspace at ${input.repo}; its working-copy commit and colocated Git index intent-to-add entries may change.` : undefined;
35246
+ const snapshotDetail = input.vcs === "jj" && input.checkout !== "primary" && (input.directory || input.worktreeName || existing) ? `JJ ${input.directory || input.worktreeName ? "workspace creation" : "new change"} snapshots the destination workspace at ${input.repo}; its working-copy commit and colocated Git index intent-to-add entries may change.` : undefined;
35198
35247
  const common = {
35199
35248
  hostId: host.id,
35200
35249
  ...clientId ? { clientId } : {},
@@ -35219,7 +35268,7 @@ var planClone = exports_Effect.fnUntraced(function* (input, expectedHostId) {
35219
35268
  ...base ? { base } : {}
35220
35269
  };
35221
35270
  });
35222
- var sameClonePlan = (a, b) => a.vcs === b.vcs && a.input.vcs === b.input.vcs && a.hostId === b.hostId && a.clientId === b.clientId && a.repo === b.repo && a.existing === b.existing && a.commonDir === b.commonDir && a.input.repo === b.input.repo && sameSession(a.input.session, b.input.session) && a.input.clientId === b.input.clientId && a.input.name === b.input.name && a.input.worktreeName === b.input.worktreeName && a.input.source.url === b.input.source.url && a.input.source.sourceHostId === b.input.source.sourceHostId && (a.vcs === "git" && b.vcs === "git" && a.input.vcs === "git" && b.input.vcs === "git" ? a.base === b.base && a.input.branch === b.input.branch && a.input.branchMode === b.input.branchMode && a.input.source.branch === b.input.source.branch && a.input.source.branches.length === b.input.source.branches.length && a.input.source.branches.every((branch, index2) => branch === b.input.source.branches[index2]) : a.vcs === "jj" && b.vcs === "jj" && a.input.vcs === "jj" && b.input.vcs === "jj" && a.base?.commitId === b.base?.commitId && a.base?.changeId === b.base?.changeId && a.input.revision === b.input.revision && a.input.source.revision?.commitId === b.input.source.revision?.commitId && a.input.source.revision?.changeId === b.input.source.revision?.changeId && a.input.source.revisions.length === b.input.source.revisions.length && a.input.source.revisions.every((choice, index2) => choice.expression === b.input.source.revisions[index2]?.expression && choice.revision.commitId === b.input.source.revisions[index2]?.revision.commitId && choice.revision.changeId === b.input.source.revisions[index2]?.revision.changeId));
35271
+ var sameClonePlan = (a, b) => a.vcs === b.vcs && a.input.vcs === b.input.vcs && a.hostId === b.hostId && a.clientId === b.clientId && a.repo === b.repo && a.existing === b.existing && a.commonDir === b.commonDir && a.input.repo === b.input.repo && sameSession(a.input.session, b.input.session) && a.input.clientId === b.input.clientId && a.input.name === b.input.name && a.input.worktreeName === b.input.worktreeName && a.input.directory === b.input.directory && a.input.checkout === b.input.checkout && a.input.source.url === b.input.source.url && a.input.source.sourceHostId === b.input.source.sourceHostId && (a.vcs === "git" && b.vcs === "git" && a.input.vcs === "git" && b.input.vcs === "git" ? a.base === b.base && a.input.branch === b.input.branch && a.input.branchMode === b.input.branchMode && a.input.source.branch === b.input.source.branch && a.input.source.branches.length === b.input.source.branches.length && a.input.source.branches.every((branch, index2) => branch === b.input.source.branches[index2]) : a.vcs === "jj" && b.vcs === "jj" && a.input.vcs === "jj" && b.input.vcs === "jj" && a.base?.commitId === b.base?.commitId && a.base?.changeId === b.base?.changeId && a.input.revision === b.input.revision && a.input.source.revision?.commitId === b.input.source.revision?.commitId && a.input.source.revision?.changeId === b.input.source.revision?.changeId && a.input.source.revisions.length === b.input.source.revisions.length && a.input.source.revisions.every((choice, index2) => choice.expression === b.input.source.revisions[index2]?.expression && choice.revision.commitId === b.input.source.revisions[index2]?.revision.commitId && choice.revision.changeId === b.input.source.revisions[index2]?.revision.changeId));
35223
35272
  var launchClone = exports_Effect.fnUntraced(function* (input, command, reviewed, expectedHostId) {
35224
35273
  const path = yield* exports_Path.Path;
35225
35274
  if (!command[0] || !path.isAbsolute(command[0]))
@@ -35230,18 +35279,16 @@ var launchClone = exports_Effect.fnUntraced(function* (input, command, reviewed,
35230
35279
  const home = process.env.HOME;
35231
35280
  if (!home || !path.isAbsolute(home))
35232
35281
  return yield* fail19("Target HOME must be an absolute directory");
35233
- const request3 = {
35234
- plan,
35235
- sessionId: plan.input.session.kind === "existing" ? plan.input.session.id : yield* createSession(plan.input.session.name),
35236
- ...process.env.REX_BIN_DIR ? { rexBinDir: process.env.REX_BIN_DIR } : {},
35237
- ...process.env.REX_WORKTREES_LOCAL_ENDPOINT ? { rexLocalEndpoint: process.env.REX_WORKTREES_LOCAL_ENDPOINT } : {}
35238
- };
35239
- const created = yield* createTab(request3.sessionId, input.name, home, [...command, "clone-task", JSON.stringify(request3)]);
35240
- const warning = [plan.warning, yield* focus(request3.sessionId, created.windowId, plan.clientId, created.blockId)].filter(Boolean).join("; ") || undefined;
35241
- const result4 = { hostId: plan.hostId, sessionId: request3.sessionId, windowId: created.windowId, blockId: created.blockId, repo: plan.repo, pending: true, ...warning ? { warning } : {} };
35282
+ const request3 = { plan, ...taskSettings() };
35283
+ const created = yield* openTerminal(plan.input.session, input.name, home, [...command, "clone-task", JSON.stringify(request3)]);
35284
+ const warning = [plan.warning, yield* focus(created.sessionId, created.windowId, created.blockId, plan.clientId)].filter(Boolean).join("; ") || undefined;
35285
+ const result4 = { hostId: plan.hostId, ...created, repo: plan.repo, pending: true, ...warning ? { warning } : {} };
35242
35286
  return result4;
35243
35287
  });
35244
35288
  var prepareCloneCheckout = exports_Effect.fnUntraced(function* (plan) {
35289
+ yield* validateCloneDestination(plan.input);
35290
+ if (plan.repo !== plan.input.repo)
35291
+ return yield* fail19("Clone destination changed since review");
35245
35292
  if (plan.vcs === "git")
35246
35293
  yield* validCloneBranch(plan.input.branch, plan.input.worktreeName);
35247
35294
  const url = yield* exports_Effect.try({
@@ -35273,7 +35320,7 @@ var prepareCloneCheckout = exports_Effect.fnUntraced(function* (plan) {
35273
35320
  if ((yield* fs.realPath(parent)) !== parent || (yield* fs.realPath(plan.repo)) !== plan.repo)
35274
35321
  return yield* fail19(`Clone path changed; reserved destination retained at ${plan.repo}`);
35275
35322
  if (plan.vcs === "git")
35276
- yield* cloneRepository(url, plan.repo);
35323
+ yield* cloneRepository(url, plan.repo, plan.input.checkout === "primary" && plan.input.branchMode === "existing" ? plan.input.branch : undefined);
35277
35324
  else
35278
35325
  yield* cloneRepository2(url, plan.repo);
35279
35326
  }
@@ -35286,11 +35333,18 @@ var prepareCloneCheckout = exports_Effect.fnUntraced(function* (plan) {
35286
35333
  if (plan.vcs === "jj") {
35287
35334
  const base = plan.base ?? (yield* resolveRevision(repo.path, "@-"));
35288
35335
  let cwd2;
35289
- if (plan.input.worktreeName) {
35290
- const planned = yield* planWorkspace(repo.path, plan.input.worktreeName, base.commitId, yield* resolveWorktreeRoot(repo.path));
35291
- if (planned.base.commitId !== base.commitId || planned.base.changeId !== base.changeId)
35292
- return yield* fail19(`JJ clone base is unavailable; clone retained at ${plan.repo}`);
35293
- const created = yield* createWorkspace(repo.path, planned.workspaceName, base, yield* resolveWorktreeRoot(repo.path));
35336
+ const workspaceName = plan.input.directory ? pathService.basename(plan.input.directory) : plan.input.worktreeName;
35337
+ const worktreeRoot2 = plan.input.directory ? pathService.dirname(plan.input.directory) : workspaceName ? yield* resolveWorktreeRoot(repo.path) : undefined;
35338
+ if (plan.input.checkout === "primary" && plan.existing) {
35339
+ const current = yield* resolveRevision(repo.path, "@-");
35340
+ if (current.commitId !== base.commitId || current.changeId !== base.changeId)
35341
+ return yield* fail19("Existing primary workspace changed since review");
35342
+ cwd2 = repo.path;
35343
+ } else if (workspaceName) {
35344
+ const planned = yield* planWorkspace(repo.path, workspaceName, base.commitId, worktreeRoot2);
35345
+ if (planned.base.commitId !== base.commitId || planned.base.changeId !== base.changeId || plan.input.directory && planned.path !== plan.input.directory)
35346
+ return yield* fail19(`JJ clone base or directory is unavailable; clone retained at ${plan.repo}`);
35347
+ const created = yield* createWorkspace(repo.path, planned.workspaceName, base, worktreeRoot2);
35294
35348
  if (!created.path || !created.present || created.path !== planned.path)
35295
35349
  return yield* fail19(`JJ workspace registration changed; clone retained at ${plan.repo}`);
35296
35350
  cwd2 = created.path;
@@ -35307,16 +35361,32 @@ var prepareCloneCheckout = exports_Effect.fnUntraced(function* (plan) {
35307
35361
  const local = yield* listBranches(repo.path);
35308
35362
  const remote = yield* remoteBranches(repo.path);
35309
35363
  const { branch, branchMode } = plan.input;
35364
+ if (plan.input.checkout === "primary") {
35365
+ if (plan.existing) {
35366
+ if (branchMode !== "existing" || (yield* repositoryHead(repo.path)).branch !== branch)
35367
+ return yield* fail19("Existing primary checkout is not on the requested branch");
35368
+ } else if (branchMode === "create") {
35369
+ if (local.includes(branch) || remote.includes(branch))
35370
+ return yield* fail19(`Branch ${branch} already exists; clone retained at ${plan.repo}`);
35371
+ yield* createPrimaryBranch(repo.path, branch);
35372
+ } else if ((yield* repositoryHead(repo.path)).branch !== branch) {
35373
+ return yield* fail19(`Cloned primary checkout is not on ${branch}; clone retained at ${plan.repo}`);
35374
+ }
35375
+ return { repo, cwd: yield* fs.realPath(repo.path) };
35376
+ }
35377
+ const worktreeRoot = plan.input.directory ? pathService.dirname(plan.input.directory) : yield* resolveWorktreeRoot(repo.path);
35378
+ const worktreeName = plan.input.directory ? pathService.basename(plan.input.directory) : plan.input.worktreeName;
35310
35379
  let cwd;
35311
35380
  if (branchMode === "existing") {
35312
35381
  if (!local.includes(branch) && !remote.includes(branch))
35313
35382
  return yield* fail19(`Branch ${branch} was not pushed to origin; clone retained at ${plan.repo}`);
35314
- const worktreeRoot = yield* resolveWorktreeRoot(repo.path);
35383
+ const planned = yield* planWorktree(repo.path, branch, worktreeRoot, worktreeName);
35384
+ if (plan.input.directory && planned.path !== plan.input.directory)
35385
+ return yield* fail19("Branch is already checked out at a different directory");
35315
35386
  if (local.includes(branch)) {
35316
- const planned = yield* planWorktree(repo.path, branch, worktreeRoot, plan.input.worktreeName);
35317
- cwd = planned.existing ? planned.path : (yield* createWorktree(repo.path, branch, { attachOnly: true, worktreeRoot, worktreeName: plan.input.worktreeName })).path;
35387
+ cwd = planned.existing ? planned.path : (yield* createWorktree(repo.path, branch, { attachOnly: true, worktreeRoot, worktreeName })).path;
35318
35388
  } else {
35319
- cwd = (yield* createWorktree(repo.path, branch, { startPoint: yield* remoteBranchHead(repo.path, branch), worktreeRoot, worktreeName: plan.input.worktreeName })).path;
35389
+ cwd = (yield* createWorktree(repo.path, branch, { startPoint: yield* remoteBranchHead(repo.path, branch), worktreeRoot, worktreeName })).path;
35320
35390
  }
35321
35391
  } else {
35322
35392
  if (local.includes(branch) || remote.includes(branch))
@@ -35324,39 +35394,28 @@ var prepareCloneCheckout = exports_Effect.fnUntraced(function* (plan) {
35324
35394
  const base = plan.existing ? plan.base : (yield* repositoryHead(repo.path)).head;
35325
35395
  if (!base)
35326
35396
  return yield* fail19("Origin default branch changed since review");
35327
- cwd = (yield* createWorktree(repo.path, branch, { startPoint: base, worktreeRoot: yield* resolveWorktreeRoot(repo.path), worktreeName: plan.input.worktreeName })).path;
35397
+ cwd = (yield* createWorktree(repo.path, branch, { startPoint: base, worktreeRoot, worktreeName })).path;
35328
35398
  }
35329
35399
  return { repo, cwd: yield* fs.realPath(cwd) };
35330
35400
  });
35331
35401
  var cloneTask = exports_Effect.fnUntraced(function* (request3) {
35332
- if (request3.rexBinDir) {
35333
- const path = yield* exports_Path.Path;
35334
- if (!path.isAbsolute(request3.rexBinDir))
35335
- return yield* fail19("REX_BIN_DIR must be absolute");
35336
- process.env.REX_BIN_DIR = request3.rexBinDir;
35337
- }
35338
- if (request3.rexLocalEndpoint)
35339
- process.env.REX_WORKTREES_LOCAL_ENDPOINT = request3.rexLocalEndpoint;
35340
35402
  const { plan } = request3;
35341
- if (process.env.REX_SESSION !== request3.sessionId || !process.env.REX_BLOCK)
35342
- return yield* fail19("Clone task must run in its requested Rex terminal");
35343
- const blockId = yield* exports_Schema.decodeUnknownEffect(BlockIdSchema)(process.env.REX_BLOCK);
35344
- if (!(yield* listSessions).some((item) => item.id === request3.sessionId))
35345
- return yield* fail19("Requested Rex session no longer exists");
35403
+ const { sessionId, blockId } = yield* taskContext(plan.input.session, request3, plan.hostId);
35346
35404
  if (!sameClonePlan(plan, yield* planClone(plan.input, plan.hostId)))
35347
35405
  return yield* fail19("Clone target changed since launch; destination left untouched");
35348
35406
  const { repo, cwd } = yield* prepareCloneCheckout(plan);
35349
35407
  yield* rememberCloneRoot((yield* exports_Path.Path).dirname(repo.path)).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => console.error(`Checkout ${cwd} is available; clone parent not remembered: ${exports_Cause.pretty(exports_Cause.fail(error2))}`))));
35350
- const windows = yield* windowList(request3.sessionId).pipe(exports_Effect.catch(() => exports_Effect.succeed([])));
35351
- const window = windows.find((entry) => entry.layers.some((layer12) => layer12.blocks?.some((block) => block.block_id === blockId && block.host_id === plan.hostId)));
35352
- if (window)
35353
- yield* saveAssociation({ vcs: repo.vcs, hostId: plan.hostId, commonDir: repo.commonDir, path: cwd, sessionId: request3.sessionId, windowId: window.window_id, blockId }).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => console.error(`Checkout ${cwd} is available; association not saved: ${exports_Cause.pretty(exports_Cause.fail(error2))}`))));
35354
- else
35355
- console.error(`Checkout ${cwd} is available; Rex block could not be associated`);
35408
+ yield* associateTask({ vcs: repo.vcs, hostId: plan.hostId, commonDir: repo.commonDir, path: cwd, sessionId, blockId });
35356
35409
  yield* shell(cwd);
35357
35410
  });
35358
35411
 
35359
35412
  // src/host.ts
35413
+ var checkoutInventory = (repo) => exports_Effect.all({
35414
+ worktrees: repo.vcs === "git" ? listWorktrees(repo.path) : listWorkspaces(repo.path),
35415
+ branches: repo.vcs === "git" ? listBranches(repo.path) : exports_Effect.succeed([]),
35416
+ revisions: repo.vcs === "jj" ? listRevisions(repo.path) : exports_Effect.succeed([]),
35417
+ worktreeRoot: resolveWorktreeRoot(repo.path)
35418
+ }, { concurrency: 4 });
35360
35419
  var dispatchHost = exports_Effect.fnUntraced(function* (request3, command) {
35361
35420
  const host = yield* localHost;
35362
35421
  if (host.id !== request3.hostId)
@@ -35365,7 +35424,7 @@ var dispatchHost = exports_Effect.fnUntraced(function* (request3, command) {
35365
35424
  const paths = request3.kind === "sessions" ? [] : request3.kind === "discover" ? request3.context ? [request3.context] : [] : request3.kind === "project" ? [request3.path] : request3.kind === "clone-plan" || request3.kind === "clone-launch" ? [request3.input.repo] : request3.kind === "plan" || request3.kind === "launch" ? [request3.input.repo, ...request3.input.path ? [request3.input.path] : []] : [request3.repo];
35366
35425
  if (paths.some((value3) => !path.isAbsolute(value3)))
35367
35426
  return yield* exports_Effect.fail(new AppError({ message: "Destination repository and worktree paths must be absolute" }));
35368
- const identity3 = { version: 4, hostId: host.id };
35427
+ const identity3 = { version: 5, hostId: host.id };
35369
35428
  let result4;
35370
35429
  switch (request3.kind) {
35371
35430
  case "sessions": {
@@ -35403,11 +35462,7 @@ var dispatchHost = exports_Effect.fnUntraced(function* (request3, command) {
35403
35462
  }
35404
35463
  const checkout = yield* repository3(request3.path);
35405
35464
  const canonical2 = yield* project3(request3.path);
35406
- const inventory2 = yield* exports_Effect.all({
35407
- worktrees: canonical2.vcs === "git" ? listWorktrees(canonical2.path) : listWorkspaces(canonical2.path),
35408
- branches: canonical2.vcs === "git" ? listBranches(canonical2.path) : exports_Effect.succeed([]),
35409
- revisions: canonical2.vcs === "jj" ? listRevisions(canonical2.path) : exports_Effect.succeed([])
35410
- }, { concurrency: 4 });
35465
+ const inventory2 = yield* checkoutInventory(canonical2);
35411
35466
  result4 = {
35412
35467
  ...identity3,
35413
35468
  kind: "project",
@@ -35428,11 +35483,7 @@ var dispatchHost = exports_Effect.fnUntraced(function* (request3, command) {
35428
35483
  }
35429
35484
  case "worktrees": {
35430
35485
  const repo = yield* repository3(request3.repo);
35431
- const inventory2 = yield* exports_Effect.all({
35432
- worktrees: repo.vcs === "git" ? listWorktrees(repo.path) : listWorkspaces(repo.path),
35433
- branches: repo.vcs === "git" ? listBranches(repo.path) : exports_Effect.succeed([]),
35434
- revisions: repo.vcs === "jj" ? listRevisions(repo.path) : exports_Effect.succeed([])
35435
- }, { concurrency: 4 });
35486
+ const inventory2 = yield* checkoutInventory(repo);
35436
35487
  result4 = {
35437
35488
  ...identity3,
35438
35489
  kind: "worktrees",
@@ -35470,23 +35521,20 @@ var hostRequest = exports_Effect.fnUntraced(function* (raw, command) {
35470
35521
 
35471
35522
  // src/client.ts
35472
35523
  var fail20 = (message) => exports_Effect.fail(new AppError({ message }));
35473
- var listMachines = exports_Effect.gen(function* () {
35474
- const registry = yield* machinesRegistry;
35475
- const machines = [
35476
- { key: "local", label: registry.home.this_machine && registry.home.label || "This machine", local: true, selector: process.env.REX_WORKTREES_LOCAL_ENDPOINT ?? "local" },
35477
- ...registry.hosts.map(({ host }) => ({ key: host.id, label: host.label, local: false, selector: host.label }))
35478
- ];
35479
- return machines;
35480
- });
35524
+ var machinesIn = (registry) => [
35525
+ { key: "local", label: registry.home.this_machine && registry.home.label || "This machine", local: true, selector: process.env.REX_WORKTREES_LOCAL_ENDPOINT ?? "local" },
35526
+ ...registry.hosts.map(({ host }) => ({ key: host.id, label: host.label, local: false, selector: host.label }))
35527
+ ];
35528
+ var listMachines = exports_Effect.map(machinesRegistry, machinesIn);
35481
35529
  var connectMachine = exports_Effect.fnUntraced(function* (machine) {
35482
- const choices = yield* listMachines;
35483
- const current = choices.find((choice) => choice.key === machine.key && choice.local === machine.local);
35530
+ const registry = yield* machinesRegistry;
35531
+ const current = machinesIn(registry).find((choice) => choice.key === machine.key && choice.local === machine.local);
35484
35532
  if (!current)
35485
35533
  return yield* fail20(`Rex machine ${machine.label} is no longer registered; choose another machine`);
35486
35534
  if (current.local)
35487
35535
  return { ...current, hostId: (yield* localHost).id };
35488
35536
  const identity3 = yield* remoteIdentity(current.selector);
35489
- const registered = (yield* machinesRegistry).hosts.find((entry) => entry.host.id === current.key);
35537
+ const registered = registry.hosts.find((entry) => entry.host.id === current.key);
35490
35538
  if (!registered?.host.endpoints.includes(identity3.endpoint)) {
35491
35539
  return yield* fail20(`Rex machine ${current.label} resolved to an unexpected server; refusing to route remotely`);
35492
35540
  }
@@ -35500,9 +35548,9 @@ var connectMachine = exports_Effect.fnUntraced(function* (machine) {
35500
35548
  return { ...current, hostId: identity3.host_id };
35501
35549
  });
35502
35550
  var connectedRequest = exports_Effect.fnUntraced(function* (host, command, body) {
35503
- const encoded = { version: 4, hostId: host.hostId, ...body };
35551
+ const encoded = { version: 5, hostId: host.hostId, ...body };
35504
35552
  const response = host.local ? yield* dispatchHost(encoded, command) : yield* exports_Schema.decodeUnknownEffect(RexWorktreesResponseSchema)(yield* remoteRex(host.selector, ["do", "worktrees_request", "--args", JSON.stringify({ request: JSON.stringify(encoded) }), "--json"]));
35505
- if (response.hostId !== host.hostId || response.version !== 4 || response.kind !== body.kind && !(body.kind === "project" && response.kind === "project-missing" && response.path === body.path))
35553
+ if (response.hostId !== host.hostId || response.version !== 5 || response.kind !== body.kind && !(body.kind === "project" && response.kind === "project-missing" && response.path === body.path))
35506
35554
  return yield* fail20(`Unexpected Rex host/protocol response from ${host.label}; update rex-worktrees on that machine, run setup, and reload its Rex config`);
35507
35555
  return response;
35508
35556
  });
@@ -35542,13 +35590,13 @@ var inspectProject = exports_Effect.fnUntraced(function* (host, command, path) {
35542
35590
  return yield* fail20(`Project directory does not exist: ${result4.path}`);
35543
35591
  if (result4.kind !== "project")
35544
35592
  return yield* fail20("Unexpected project response");
35545
- return { project: result4.project, checkout: result4.checkout, worktrees: result4.worktrees, branches: result4.branches, revisions: result4.revisions };
35593
+ return { project: result4.project, checkout: result4.checkout, worktrees: result4.worktrees, branches: result4.branches, revisions: result4.revisions, worktreeRoot: result4.worktreeRoot };
35546
35594
  });
35547
35595
  var inspectWorktrees = exports_Effect.fnUntraced(function* (host, command, repo) {
35548
35596
  const result4 = yield* request3(host, command, { kind: "worktrees", repo });
35549
35597
  if (result4.kind !== "worktrees")
35550
35598
  return yield* fail20("Unexpected worktree response");
35551
- return { repository: result4.repository, worktrees: result4.worktrees, branches: result4.branches, revisions: result4.revisions };
35599
+ return { repository: result4.repository, worktrees: result4.worktrees, branches: result4.branches, revisions: result4.revisions, worktreeRoot: result4.worktreeRoot };
35552
35600
  });
35553
35601
  var inspectRevision = exports_Effect.fnUntraced(function* (host, command, repo, revision) {
35554
35602
  const result4 = yield* request3(host, command, { kind: "revision", repo, revision });
@@ -35627,13 +35675,16 @@ function M.setup(opts)
35627
35675
  if type(config.projects) == "table" and next(config.projects) == nil then config.projects = nil end
35628
35676
  local settings = rex.json.encode({ config = config, directory = config_dir })
35629
35677
 
35678
+ local function exec_options(stdin)
35679
+ local options = { stdin = stdin, timeout = 20, env = { REX_WORKTREES_CONFIG = settings } }
35680
+ if rex_bin_dir then options.env.REX_BIN_DIR = rex_bin_dir end
35681
+ if installed_path_env ~= false then options.env.PATH = installed_path_env end
35682
+ options.env.REX_WORKTREES_LOCAL_ENDPOINT = os.getenv("REX_WORKTREES_LOCAL_ENDPOINT")
35683
+ return options
35684
+ end
35685
+
35630
35686
  local function worktrees_request(request)
35631
- local exec_opts = { stdin = request, timeout = 20, env = {} }
35632
- exec_opts.env.REX_WORKTREES_CONFIG = settings
35633
- if rex_bin_dir then exec_opts.env.REX_BIN_DIR = rex_bin_dir end
35634
- if installed_path_env ~= false then exec_opts.env.PATH = installed_path_env end
35635
- if os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") then exec_opts.env.REX_WORKTREES_LOCAL_ENDPOINT = os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") end
35636
- local result, run_err = rex.exec({ bin, "host-request" }, exec_opts)
35687
+ local result, run_err = rex.exec({ bin, "host-request" }, exec_options(request))
35637
35688
  if not result then error(run_err, 0) end
35638
35689
  if not result.ok then
35639
35690
  error("rex-worktrees host-request failed (exit " .. tostring(result.code)
@@ -35687,12 +35738,7 @@ function M.setup(opts)
35687
35738
  table.insert(command, "--origin-client")
35688
35739
  table.insert(command, ctx.client_id)
35689
35740
  end
35690
- local exec_opts = { timeout = 20, env = {} }
35691
- exec_opts.env.REX_WORKTREES_CONFIG = settings
35692
- if rex_bin_dir then exec_opts.env.REX_BIN_DIR = rex_bin_dir end
35693
- if installed_path_env ~= false then exec_opts.env.PATH = installed_path_env end
35694
- if os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") then exec_opts.env.REX_WORKTREES_LOCAL_ENDPOINT = os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") end
35695
- local result, run_err = rex.exec(command, exec_opts)
35741
+ local result, run_err = rex.exec(command, exec_options())
35696
35742
  if not result then error(run_err, 0) end
35697
35743
  if not result.ok then
35698
35744
  error("rex-worktrees launch-popup failed: " ..
@@ -38556,10 +38602,10 @@ var pad = (text, width2) => text + " ".repeat(Math.max(0, width2 - Bun.stringWid
38556
38602
  var formRows = [
38557
38603
  { id: "project", label: "Project", value: "\u2014", disabled: true },
38558
38604
  { id: "machine", label: "Machine", value: "\u2014", disabled: true },
38559
- { id: "destination", label: "Checkout", value: "\u2014", disabled: true },
38605
+ { id: "session", label: "Session", value: "\u2014", disabled: true },
38606
+ { id: "destination", label: "Worktree", value: "\u2014", disabled: true },
38560
38607
  { id: "branch", label: "Branch", value: "\u2014", disabled: true },
38561
38608
  { id: "checkoutName", label: "Directory", value: "\u2014", disabled: true },
38562
- { id: "session", label: "Session", value: "\u2014", disabled: true },
38563
38609
  { id: "mode", label: "Mode", value: "\u2014", disabled: true }
38564
38610
  ];
38565
38611
  var choiceCount = popupSize.rows - formRows.length - 6;
@@ -38668,7 +38714,18 @@ var acknowledge = (title, lines2, tone, view = { rows: [], submitLabel: "Close"
38668
38714
  })).pipe(exports_Effect.catch(() => exports_Effect.void));
38669
38715
  var problem = (error2) => error2 instanceof AppError ? error2.message : exports_Cause.pretty(exports_Cause.fail(error2));
38670
38716
  var selected = (value3, current, title, description) => ({ value: value3, selected: current, title, description });
38671
- var generatedName = (draft) => draft.worktreeName ?? (draft.clone?.vcs === "jj" ? draft.projectChoice?.name : draft.destination?.label) ?? draft.projectChoice?.name ?? "Worktree";
38717
+ var directoryFor = (draft) => {
38718
+ if (draft.destination?.path)
38719
+ return draft.destination.path;
38720
+ if (draft.clone && !draft.isCreating)
38721
+ return draft.clone.repo;
38722
+ if (draft.directory)
38723
+ return draft.directory;
38724
+ const repo = draft.clone?.repo ?? draft.project?.path;
38725
+ const name = draft.worktreeName ?? draft.destination?.branch;
38726
+ return repo && name ? `${(draft.worktreeRoot ?? `${repo}.worktrees`).replace(/\/$/, "")}/${name}` : undefined;
38727
+ };
38728
+ var generatedName = (draft) => draft.clone && !draft.isCreating ? draft.projectChoice?.name ?? "Project" : draft.worktreeName ?? draft.destination?.label ?? draft.projectChoice?.name ?? "Worktree";
38672
38729
  var inputFor = (draft) => {
38673
38730
  if (!draft.host || !draft.project || !draft.projectChoice || !draft.destination || !draft.session)
38674
38731
  return;
@@ -38680,9 +38737,20 @@ var inputFor = (draft) => {
38680
38737
  additional: draft.mode === "new-tab",
38681
38738
  split: draft.mode === "split"
38682
38739
  };
38740
+ if (draft.destination.path)
38741
+ return { ...common, vcs: draft.project.vcs, path: draft.destination.path };
38742
+ const directory = directoryFor(draft);
38743
+ if (!directory)
38744
+ return;
38683
38745
  if (draft.project.vcs === "jj")
38684
- return draft.destination.path ? { ...common, vcs: "jj", path: draft.destination.path } : draft.worktreeName && draft.destination.revision ? { ...common, vcs: "jj", worktreeName: draft.worktreeName, revision: draft.destination.revision } : undefined;
38685
- return draft.destination.branch ? { ...common, vcs: "git", branch: draft.destination.branch, ...draft.worktreeName ? { worktreeName: draft.worktreeName } : {} } : { ...common, vcs: "git", path: draft.destination.path };
38746
+ return draft.worktreeName && draft.destination.revision ? { ...common, vcs: "jj", worktreeName: draft.worktreeName, revision: draft.destination.revision, directory } : undefined;
38747
+ return draft.destination.branch ? {
38748
+ ...common,
38749
+ vcs: "git",
38750
+ branch: draft.destination.branch,
38751
+ directory,
38752
+ ...draft.worktreeName ? { worktreeName: draft.worktreeName } : {}
38753
+ } : undefined;
38686
38754
  };
38687
38755
  var changeProjectChoice = (draft, projectChoice) => ({
38688
38756
  ...draft,
@@ -38691,20 +38759,30 @@ var changeProjectChoice = (draft, projectChoice) => ({
38691
38759
  clone: undefined,
38692
38760
  destination: undefined,
38693
38761
  worktreeName: undefined,
38762
+ directory: undefined,
38763
+ worktreeRoot: undefined,
38764
+ isCreating: false,
38694
38765
  sourcePath: undefined
38695
38766
  });
38696
- var changeProject = (draft, candidate) => ({
38697
- ...draft,
38698
- project: candidate,
38699
- clone: undefined,
38700
- destination: draft.project?.vcs === candidate.vcs && draft.project.commonDir === candidate.commonDir ? draft.destination : undefined,
38701
- worktreeName: draft.project?.vcs === candidate.vcs && draft.project.commonDir === candidate.commonDir ? draft.worktreeName : undefined,
38702
- sourcePath: candidate.vcs === "jj" && draft.project?.vcs === "jj" && draft.project.commonDir === candidate.commonDir ? draft.sourcePath : undefined
38703
- });
38767
+ var changeProject = (draft, candidate) => {
38768
+ const same = draft.project?.vcs === candidate.vcs && draft.project.commonDir === candidate.commonDir;
38769
+ return {
38770
+ ...draft,
38771
+ project: candidate,
38772
+ clone: undefined,
38773
+ destination: same ? draft.destination : undefined,
38774
+ worktreeName: same ? draft.worktreeName : undefined,
38775
+ directory: same ? draft.directory : undefined,
38776
+ isCreating: same && draft.isCreating,
38777
+ sourcePath: candidate.vcs === "jj" && same ? draft.sourcePath : undefined
38778
+ };
38779
+ };
38704
38780
  var changeDestination = (draft, candidate, worktreeName) => ({
38705
38781
  ...draft,
38706
38782
  destination: candidate,
38707
- worktreeName: candidate.path ? undefined : worktreeName
38783
+ worktreeName: candidate.path ? undefined : worktreeName,
38784
+ directory: candidate.path ? undefined : draft.directory,
38785
+ isCreating: candidate.path ? false : draft.isCreating
38708
38786
  });
38709
38787
  var selectWorktree = (draft, tree) => {
38710
38788
  if (!tree.path || tree.vcs === "jj" && !tree.present)
@@ -38712,6 +38790,7 @@ var selectWorktree = (draft, tree) => {
38712
38790
  return {
38713
38791
  ...changeDestination(draft, {
38714
38792
  path: tree.path,
38793
+ worktree: tree,
38715
38794
  label: tree.vcs === "jj" ? tree.name : tree.path.split("/").filter(Boolean).at(-1) ?? tree.path
38716
38795
  }),
38717
38796
  ...tree.vcs === "jj" ? {
@@ -38720,15 +38799,14 @@ var selectWorktree = (draft, tree) => {
38720
38799
  } : {}
38721
38800
  };
38722
38801
  };
38723
- var typeWorktreeName = (draft, name, mainline) => ({
38724
- ...draft,
38725
- worktreeName: name,
38726
- destination: draft.destination && !draft.destination.path ? draft.destination : draft.project?.vcs === "jj" && !draft.clone && mainline ? { revision: mainline.revision.commitId, label: mainline.label } : undefined
38727
- });
38728
38802
  var selectRevision = (draft, choice) => changeDestination(draft, { revision: choice.revision.commitId, label: choice.label }, draft.worktreeName);
38729
38803
  var cloneInputFor = (draft) => {
38730
38804
  if (!draft.host || !draft.clone || !draft.session || !draft.clone.repo.startsWith("/"))
38731
38805
  return;
38806
+ const directory = draft.isCreating ? directoryFor(draft) : undefined;
38807
+ const checkout = draft.isCreating ? "worktree" : "primary";
38808
+ if (draft.isCreating && (!directory || draft.clone.vcs === "git" && draft.destination?.branch === draft.clone.branch))
38809
+ return;
38732
38810
  if (draft.clone.vcs === "jj") {
38733
38811
  const revision = draft.clone.revision?.commitId === draft.destination?.revision ? draft.clone.revision : draft.clone.revisions.find((choice) => choice.revision.commitId === draft.destination?.revision)?.revision;
38734
38812
  return {
@@ -38743,8 +38821,10 @@ var cloneInputFor = (draft) => {
38743
38821
  repo: draft.clone.repo,
38744
38822
  session: draft.session,
38745
38823
  clientId: draft.clientId,
38824
+ checkout,
38825
+ directory,
38746
38826
  name: generatedName(draft),
38747
- ...draft.worktreeName ? { worktreeName: draft.worktreeName } : {},
38827
+ ...draft.isCreating && draft.worktreeName ? { worktreeName: draft.worktreeName } : {},
38748
38828
  ...draft.destination?.revision ? { revision: draft.destination.revision } : {}
38749
38829
  };
38750
38830
  }
@@ -38762,25 +38842,28 @@ var cloneInputFor = (draft) => {
38762
38842
  repo: draft.clone.repo,
38763
38843
  session: draft.session,
38764
38844
  clientId: draft.clientId,
38845
+ checkout,
38846
+ directory,
38765
38847
  name: generatedName(draft),
38766
38848
  branch: draft.destination.branch,
38767
38849
  branchMode: draft.clone.branches.includes(draft.destination.branch) ? "existing" : "create",
38768
- ...draft.worktreeName ? { worktreeName: draft.worktreeName } : {}
38850
+ ...draft.isCreating && draft.worktreeName ? { worktreeName: draft.worktreeName } : {}
38769
38851
  };
38770
38852
  };
38771
38853
  var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effect.scoped(exports_Effect.suspend(() => {
38772
38854
  let launchAcknowledged = false;
38773
38855
  return exports_Effect.gen(function* () {
38774
38856
  const terminal = yield* exports_Terminal.Terminal;
38857
+ const path = yield* exports_Path.Path;
38775
38858
  yield* exports_Effect.acquireRelease(terminal.display("\x1B[?1049h\x1B[?25l"), () => terminal.display("\x1B[?25h\x1B[?1049l").pipe(exports_Effect.orDie));
38776
38859
  let machines = [];
38777
38860
  let draft = { mode: "auto" };
38778
38861
  let sessions = [];
38779
38862
  let focused = "project";
38863
+ let isBranchEditPending = false;
38780
38864
  let error2;
38781
38865
  let blocked = false;
38782
38866
  let cloneRoot = "";
38783
- let cloneRoots = [];
38784
38867
  let contextPath;
38785
38868
  let activeView;
38786
38869
  const resizeEvents = exports_Effect.gen(function* () {
@@ -38792,7 +38875,7 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38792
38875
  const chooseField = exports_Effect.fnUntraced(function* (view, initialFocus) {
38793
38876
  let detailOffset = 0;
38794
38877
  let visibleRows = popupSize.rows;
38795
- const fields = [...formRows.filter((slot) => view.rows.some((row) => row.id === slot.id)).map((row) => row.id), "submit", "cancel"];
38878
+ const fields = [...formRows.filter((slot) => view.rows.some((row) => row.id === slot.id && !row.disabled && !row.isReadOnly)).map((row) => row.id), "submit", "cancel"];
38796
38879
  const initial = Math.max(0, fields.indexOf(initialFocus));
38797
38880
  const prompt = exports_Prompt.Custom(initial, yield* resizeEvents, {
38798
38881
  render: (index2, action) => action._tag === "Submit" ? exports_Effect.succeed("") : exports_Effect.gen(function* () {
@@ -38818,7 +38901,7 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38818
38901
  return exports_Effect.succeed(view.submitDisabled ? { _tag: "Beep" } : { _tag: "Submit", value: "submit" });
38819
38902
  if (key5.name === "enter" || key5.name === "return") {
38820
38903
  const selected2 = fields[index2];
38821
- return exports_Effect.succeed(selected2 === "submit" && view.submitDisabled || view.rows.some((row) => row.id === selected2 && row.disabled) ? { _tag: "Beep" } : { _tag: "Submit", value: selected2 });
38904
+ return exports_Effect.succeed(selected2 === "submit" && view.submitDisabled ? { _tag: "Beep" } : { _tag: "Submit", value: selected2 });
38822
38905
  }
38823
38906
  const backward = key5.name === "up" || key5.name === "k" && !key5.ctrl || key5.name === "backtab" || key5.name === "tab" && key5.shift;
38824
38907
  const forward = key5.name === "down" || key5.name === "j" && !key5.ctrl || key5.name === "tab";
@@ -38902,59 +38985,48 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38902
38985
  projectChoice: choice,
38903
38986
  host,
38904
38987
  project: undefined,
38988
+ sourcePath: undefined,
38905
38989
  clone: { ...source, repo },
38906
38990
  destination: source.vcs === "git" && source.branch ? { branch: source.branch, label: source.branch } : undefined,
38907
- worktreeName: undefined
38991
+ worktreeName: undefined,
38992
+ directory: undefined,
38993
+ worktreeRoot: undefined,
38994
+ isCreating: false
38908
38995
  };
38909
38996
  });
38910
- const cloneDestination2 = exports_Effect.fnUntraced(function* (choice, host) {
38911
- let repo = clonePath(choice);
38912
- if (!repo) {
38913
- const picked = yield* inputChoice({
38914
- message: "Project name is not a safe clone directory; type an absolute clone destination",
38915
- choices: []
38916
- });
38917
- repo = picked.kind === "selected" ? picked.value : picked.text.trim();
38918
- }
38919
- if (!repo.startsWith("/"))
38920
- return yield* exports_Effect.fail(new AppError({ message: "Clone destination must be an absolute path on this machine" }));
38921
- yield* proposeClone(choice, host, repo);
38922
- });
38923
38997
  const bindProject = exports_Effect.fnUntraced(function* (choice, host, available) {
38924
38998
  const source = choice.source;
38925
- let path = source?.machineKey === host.key && source.hostId === host.hostId ? source.checkoutPath ?? source.repository.path : undefined;
38926
- if (!path && choice.path?.startsWith("/"))
38927
- path = choice.path;
38928
- if (source && (source.machineKey !== host.key || source.hostId !== host.hostId)) {
38929
- if (path)
38930
- yield* proposeClone(choice, host, path);
38931
- else
38932
- yield* cloneDestination2(choice, host);
38933
- return;
38934
- }
38935
- if (!path) {
38936
- const directory = yield* inputChoice({
38937
- message: `Project directory on ${host.label} (existing checkout; absolute path)`,
38938
- choices: available.map((repo) => ({ value: repo.path, title: repo.name, description: repo.path }))
38939
- });
38940
- path = directory.kind === "selected" ? directory.value : directory.text.trim();
38999
+ const sameHost = source?.machineKey === host.key && source.hostId === host.hostId;
39000
+ const matches = available.filter((repo) => repo.name === choice.name && (!source || repo.vcs === source.repository.vcs));
39001
+ let directory = sameHost ? source.checkoutPath ?? source.repository.path : choice.path;
39002
+ if (!directory && matches.length === 1)
39003
+ directory = matches[0].path;
39004
+ if (!directory && matches.length > 1)
39005
+ return yield* exports_Effect.fail(new AppError({ message: `Multiple projects named ${choice.name} on this machine; select its exact project directory` }));
39006
+ directory ??= source ? clonePath(choice) : undefined;
39007
+ if (!directory) {
39008
+ if (source) {
39009
+ yield* proposeClone(choice, host, "");
39010
+ return;
39011
+ }
39012
+ return yield* exports_Effect.fail(new AppError({ message: "Select a known project or enter its absolute directory on this machine" }));
38941
39013
  }
38942
- if (!path.startsWith("/"))
39014
+ if (!path.isAbsolute(directory))
38943
39015
  return yield* exports_Effect.fail(new AppError({ message: "Project directory must be an absolute path on this machine" }));
38944
- const inspected = yield* exports_Effect.result(inspectProject(host, command, path));
39016
+ const inspected = yield* exports_Effect.result(inspectProject(host, command, directory));
38945
39017
  if (exports_Result.isFailure(inspected)) {
38946
- if (choice.source && inspected.failure instanceof AppError && inspected.failure.message.startsWith("Project directory does not exist:")) {
38947
- yield* proposeClone(choice, host, path);
39018
+ if (source && inspected.failure instanceof AppError && inspected.failure.message.startsWith("Project directory does not exist:")) {
39019
+ yield* proposeClone(choice, host, directory);
38948
39020
  return;
38949
39021
  }
38950
39022
  return yield* exports_Effect.fail(inspected.failure);
38951
39023
  }
38952
- if (source?.machineKey === host.key && source.hostId === host.hostId && (inspected.success.project.vcs !== source.repository.vcs || inspected.success.project.commonDir !== source.repository.commonDir))
39024
+ if (sameHost && (inspected.success.project.vcs !== source.repository.vcs || inspected.success.project.commonDir !== source.repository.commonDir))
38953
39025
  return yield* exports_Effect.fail(new AppError({ message: "Project directory changed; select the exact project directory again" }));
38954
39026
  return inspected.success;
38955
39027
  });
38956
39028
  const useProject = (found) => {
38957
- draft = changeProject(draft, found.project);
39029
+ draft = { ...changeProject(draft, found.project), worktreeRoot: found.worktreeRoot };
38958
39030
  if (found.checkout.vcs === "jj" && !draft.sourcePath)
38959
39031
  draft = { ...draft, sourcePath: found.checkout.path };
38960
39032
  if (!draft.destination) {
@@ -38969,7 +39041,6 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38969
39041
  draft = { machine, projectChoice: draft.projectChoice, mode: draft.mode };
38970
39042
  sessions = [];
38971
39043
  cloneRoot = "";
38972
- cloneRoots = [];
38973
39044
  error2 = undefined;
38974
39045
  const discoveredContext = machine.local ? contextPath : undefined;
38975
39046
  contextPath = undefined;
@@ -38989,7 +39060,6 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38989
39060
  else
38990
39061
  draft = { ...draft, host };
38991
39062
  cloneRoot = found.cloneRoot;
38992
- cloneRoots = found.roots;
38993
39063
  projects = [
38994
39064
  ...projects.filter((item) => item.source?.machineKey !== machine.key || item.source.hostId !== host.hostId),
38995
39065
  ...found.projects.map((repo) => known(host, repo, found.checkout))
@@ -39021,6 +39091,10 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39021
39091
  error2 = undefined;
39022
39092
  });
39023
39093
  const formView = (initializing = false) => {
39094
+ const jj2 = (draft.clone?.vcs ?? draft.project?.vcs) === "jj";
39095
+ const tree = draft.destination?.path ? draft.destination.worktree : undefined;
39096
+ const ready = !!draft.host && !!(draft.project || draft.clone);
39097
+ const directory = directoryFor(draft);
39024
39098
  const rows2 = [
39025
39099
  { id: "project", label: "Project", value: draft.projectChoice?.name ?? "Choose a project" },
39026
39100
  {
@@ -39029,50 +39103,50 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39029
39103
  value: draft.machine?.label ?? "Choose Rex host",
39030
39104
  detail: draft.host ? `Host ID: ${draft.host.hostId}` : draft.machine?.selector
39031
39105
  },
39032
- {
39033
- id: "destination",
39034
- label: draft.clone ? "Clone to" : draft.project?.vcs === "jj" ? "Workspace" : "Checkout",
39035
- value: draft.clone?.repo ?? (draft.project?.vcs === "jj" && !draft.destination?.path ? draft.worktreeName : undefined) ?? draft.destination?.label ?? (draft.project?.vcs === "jj" ? "Choose workspace or type new name" : "Choose checkout or type branch"),
39036
- detail: draft.clone?.repo ?? draft.destination?.path,
39037
- disabled: !draft.host || !(draft.project || draft.clone)
39038
- },
39039
39106
  {
39040
39107
  id: "session",
39041
39108
  label: "Session",
39042
39109
  value: draft.session?.kind === "new" ? `New: ${draft.session.name}` : sessions.find((s) => s.id === (draft.session?.kind === "existing" ? draft.session.id : undefined))?.label ?? (draft.session?.kind === "existing" ? draft.session.id : "Choose or type new session"),
39043
39110
  detail: draft.session?.kind === "existing" ? draft.session.id : draft.session?.kind === "new" ? "Create on submit" : undefined,
39044
39111
  disabled: !draft.host
39045
- }
39046
- ];
39047
- if (draft.project?.vcs === "jj" && !draft.destination?.path || draft.clone?.vcs === "jj")
39048
- rows2.push({
39112
+ },
39113
+ {
39114
+ id: "destination",
39115
+ label: jj2 ? "Workspace" : "Worktree",
39116
+ value: draft.clone && !draft.isCreating ? "Project checkout (after clone)" : draft.isCreating ? jj2 ? "Create new workspace\u2026" : "Create new worktree\u2026" : draft.destination?.label ?? (jj2 ? "Choose a workspace" : "Choose a worktree"),
39117
+ detail: tree ? "Branch and Directory describe this worktree; select another worktree to change them." : draft.isCreating ? jj2 ? "Choose the starting revision and directory for the new workspace." : "Choose an unused branch or a new branch name, then its directory." : undefined,
39118
+ disabled: !ready
39119
+ },
39120
+ {
39049
39121
  id: "branch",
39050
- label: "Start from",
39051
- value: draft.destination?.revision ? draft.destination.label : draft.clone ? "Cloned default" : "Select or type revision",
39052
- disabled: !draft.host || !!draft.project && !draft.worktreeName
39053
- });
39054
- if (draft.clone?.vcs === "git")
39055
- rows2.push({ id: "branch", label: "Branch", value: draft.destination?.branch ?? "Select or type branch", disabled: !draft.host });
39056
- if (draft.clone || draft.project?.vcs === "git" && draft.destination?.branch && !draft.destination.path)
39057
- rows2.push({
39122
+ label: tree?.vcs === "jj" ? "Revision" : jj2 ? "Start from" : "Branch",
39123
+ value: tree?.vcs === "jj" ? `${tree.changeId.slice(0, 12)} \xB7 ${tree.head.slice(0, 12)}` : tree?.vcs === "git" ? tree.branch ?? `Detached HEAD \xB7 ${tree.head.slice(0, 12)}` : jj2 ? draft.destination?.revision ? draft.destination.label : draft.clone ? "Cloned default" : "Choose a starting revision" : draft.destination?.branch ?? "Select or type branch",
39124
+ detail: tree ? undefined : jj2 ? "Revision for the new workspace; the source workspace is not moved." : "Select an unused existing branch, or type the name of a new branch.",
39125
+ isReadOnly: !!tree,
39126
+ disabled: !ready || !tree && !draft.clone && !draft.isCreating
39127
+ },
39128
+ {
39058
39129
  id: "checkoutName",
39059
- label: draft.clone?.vcs === "jj" ? "Workspace" : "Directory",
39060
- value: draft.worktreeName ?? (draft.clone?.vcs === "jj" ? "Use cloned default workspace" : "Default (derived from branch)"),
39061
- disabled: !draft.host
39062
- });
39063
- if (!draft.clone)
39064
- rows2.push({
39130
+ label: "Directory",
39131
+ value: directory || (draft.clone ? "Choose an absolute directory" : "Choose a branch first"),
39132
+ detail: directory,
39133
+ isReadOnly: !!tree,
39134
+ disabled: !ready || !draft.clone && !directory
39135
+ },
39136
+ {
39065
39137
  id: "mode",
39066
39138
  label: "Mode",
39067
- value: draft.mode === "auto" ? "Reuse matching tab, otherwise new tab" : draft.mode === "new-tab" ? "Always new tab" : "Split matching tab, otherwise new tab",
39139
+ value: draft.clone ? "New tab (cloning)" : draft.mode === "auto" ? "Reuse matching tab, otherwise new tab" : draft.mode === "new-tab" ? "Always new tab" : "Split matching tab, otherwise new tab",
39140
+ isReadOnly: !!draft.clone,
39068
39141
  disabled: !draft.host
39069
- });
39142
+ }
39143
+ ];
39070
39144
  return {
39071
39145
  rows: rows2.map((row) => ({ ...row, disabled: initializing || row.disabled })),
39072
- submitLabel: draft.clone ? "Clone & Open" : draft.destination?.path ? "Open checkout" : draft.project?.vcs === "jj" ? "Create workspace & open" : "Create checkout & open",
39146
+ submitLabel: draft.clone ? "Clone & open" : tree ? jj2 ? "Open workspace" : "Open worktree" : jj2 ? "Create workspace & open" : "Create worktree & open",
39073
39147
  submitDisabled: initializing || blocked || !draft.host || !(cloneInputFor(draft) || inputFor(draft)),
39074
- notice: draft.clone ? "Only pushed history transfers" : undefined,
39075
- error: initializing ? undefined : error2 ?? (!draft.projectChoice ? "Select a project" : !draft.machine ? "Select a Rex machine" : !draft.host ? "Connect to the selected machine and install its worktrees helper if missing" : !(draft.project || draft.clone) ? "Select the exact project directory on this machine" : !draft.destination && draft.project?.vcs !== "jj" && draft.clone?.vcs !== "jj" ? "Select a branch" : draft.project?.vcs === "jj" && (!draft.worktreeName && !draft.destination?.path || !!draft.worktreeName && !draft.destination?.revision) ? "Choose an existing workspace or a new workspace name and starting revision" : !draft.session ? "Choose an existing Rex session or type a new name" : undefined)
39148
+ notice: draft.clone ? `This project will be cloned onto this machine: ${draft.clone.repo || "choose its Directory"}. Only pushed history transfers.` : undefined,
39149
+ error: initializing ? undefined : error2 ?? (!draft.projectChoice ? "Select a project" : !draft.machine ? "Select a Rex machine" : !draft.host ? "Connect to the selected machine and install its worktrees helper if missing" : !ready ? "Select the exact project directory on this machine" : !draft.destination && !draft.clone ? "Choose an existing worktree or Create new worktree\u2026" : !jj2 && !tree && !draft.destination?.branch ? "Choose a branch" : jj2 && draft.isCreating && !draft.destination?.revision && !draft.clone ? "Choose a starting revision" : !directory ? "Choose an absolute directory" : !draft.session ? "Choose an existing Rex session or type a new name" : undefined)
39076
39150
  };
39077
39151
  };
39078
39152
  const initialView = { ...formView(true), notice: "Discovering projects and Rex sessions\u2026" };
@@ -39094,7 +39168,8 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39094
39168
  while (true) {
39095
39169
  const view = formView();
39096
39170
  activeView = view;
39097
- const action = yield* chooseField(view, focused).pipe(exports_Effect.catchTag("QuitError", () => exports_Effect.succeed("cancel")));
39171
+ const action = isBranchEditPending ? "branch" : yield* chooseField(view, focused).pipe(exports_Effect.catchTag("QuitError", () => exports_Effect.succeed("cancel")));
39172
+ isBranchEditPending = false;
39098
39173
  focused = action;
39099
39174
  if (action === "cancel")
39100
39175
  return;
@@ -39109,8 +39184,8 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39109
39184
  continue;
39110
39185
  }
39111
39186
  const clonePlan = current2.success;
39112
- if (clonePlan.repo !== cloneInput.repo || clonePlan.hostId !== draft.host.hostId) {
39113
- error2 = clonePlan.hostId !== draft.host.hostId ? "Rex target changed; select the machine again" : `Clone destination changed; edit the destination: ${clonePlan.repo}`;
39187
+ if (clonePlan.repo !== cloneInput.repo || clonePlan.hostId !== draft.host.hostId || clonePlan.input.checkout !== cloneInput.checkout || clonePlan.input.directory !== cloneInput.directory) {
39188
+ error2 = clonePlan.hostId !== draft.host.hostId ? "Rex target changed; select the machine again" : clonePlan.repo !== cloneInput.repo ? `Clone destination changed; edit the destination: ${clonePlan.repo}` : "Clone helper changed the checkout request; update its plugin and select the machine again";
39114
39189
  blocked = true;
39115
39190
  continue;
39116
39191
  }
@@ -39142,8 +39217,8 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39142
39217
  continue;
39143
39218
  }
39144
39219
  const plan = current.success;
39145
- if (plan.hostId !== draft.host.hostId || input.path && plan.path !== input.path) {
39146
- error2 = plan.hostId !== draft.host.hostId ? "Rex target changed; select the machine again" : `Destination changed; select the checkout again: ${plan.path}`;
39220
+ if (plan.hostId !== draft.host.hostId || input.path && plan.path !== input.path || input.directory && plan.path !== input.directory) {
39221
+ error2 = plan.hostId !== draft.host.hostId ? "Rex target changed; select the machine again" : `Destination changed; select the worktree again: ${plan.path}`;
39147
39222
  blocked = true;
39148
39223
  continue;
39149
39224
  }
@@ -39208,84 +39283,73 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39208
39283
  } else if (action === "destination") {
39209
39284
  if (!draft.host || !(draft.project || draft.clone))
39210
39285
  return yield* exports_Effect.fail(new AppError({ message: "Select a project and machine before choosing a worktree" }));
39211
- if (draft.clone) {
39212
- const clone = draft.clone;
39213
- const picked = yield* inputChoice({
39214
- message: "Clone to (absolute destination path on selected machine)",
39215
- choices: [
39216
- { value: clone.repo, title: "Current clone destination", description: clone.repo },
39217
- ...cloneRoots.map((root) => ({
39218
- value: `${root.replace(/\/$/, "")}/${draft.projectChoice?.name ?? "project"}`,
39219
- title: "Configured root suggestion",
39220
- description: `${root.replace(/\/$/, "")}/${draft.projectChoice?.name ?? "project"}`
39221
- }))
39222
- ]
39223
- });
39224
- const repo = (picked.kind === "selected" ? picked.value : picked.text).trim();
39225
- if (!repo.startsWith("/"))
39226
- return yield* exports_Effect.fail(new AppError({ message: "Clone destination must be an absolute path on this machine" }));
39227
- draft = { ...draft, clone: { ...clone, repo } };
39228
- } else {
39229
- const found = yield* inspectWorktrees(draft.host, command, draft.project.vcs === "jj" ? draft.sourcePath ?? draft.project.path : draft.project.path);
39230
- const trees = found.worktrees.filter((tree) => tree.vcs === "jj" || !tree.bare && !tree.prunable);
39231
- const git2 = draft.project.vcs === "git";
39232
- const picked = yield* inputChoice({
39233
- message: git2 ? "Checkout (select exact worktree or branch, or type new branch)" : "Workspace (select existing, Clone this project, or type new workspace name)",
39234
- choices: [
39235
- ...trees.map((tree) => ({
39236
- value: tree,
39237
- title: tree.vcs === "jj" ? tree.name : tree.path.split("/").filter(Boolean).at(-1) ?? tree.path,
39238
- description: tree.vcs === "jj" ? tree.present && tree.path ? `${tree.changeId.slice(0, 12)} \xB7 ${tree.path}` : `Unavailable \xB7 ${tree.path ?? "location unknown"}` : `${tree.branch ?? "Detached HEAD"} \xB7 ${tree.path}`
39239
- })),
39240
- ...git2 ? found.branches.map((branch) => ({
39241
- value: { kind: "branch", value: branch },
39242
- title: `Branch: ${branch}`,
39243
- description: trees.find((tree) => tree.vcs === "git" && tree.branch === branch)?.path ?? "Free branch \u2014 attach new checkout"
39244
- })) : [],
39245
- ...draft.projectChoice?.source ? [{
39246
- value: "clone",
39247
- title: "Clone this project\u2026",
39248
- description: clonePath(draft.projectChoice) ? `Propose ${clonePath(draft.projectChoice)} \xB7 only pushed history transfers` : "Choose an absolute clone destination \xB7 only pushed history transfers"
39249
- }] : []
39250
- ]
39286
+ const jj2 = (draft.clone?.vcs ?? draft.project?.vcs) === "jj";
39287
+ const found = draft.clone ? undefined : yield* inspectWorktrees(draft.host, command, jj2 ? draft.sourcePath ?? draft.project.path : draft.project.path);
39288
+ const trees = found?.worktrees.filter((tree) => tree.vcs === "jj" || !tree.bare && !tree.prunable) ?? [];
39289
+ const choices = trees.map((tree) => ({
39290
+ value: tree,
39291
+ selected: tree.path === draft.destination?.path,
39292
+ title: tree.vcs === "jj" ? `${tree.present ? "" : "Unavailable: "}${tree.name}` : path.basename(tree.path),
39293
+ description: tree.vcs === "jj" ? tree.present && tree.path ? `${tree.changeId.slice(0, 12)} \xB7 ${tree.path}` : `Unavailable \xB7 ${tree.path ?? "location unknown"}` : `${tree.branch ?? "Detached HEAD"} \xB7 ${tree.path}`
39294
+ }));
39295
+ if (draft.clone)
39296
+ choices.push({
39297
+ value: "primary",
39298
+ selected: !draft.isCreating,
39299
+ title: "Project checkout (after clone)",
39300
+ description: draft.clone.repo
39251
39301
  });
39252
- if (picked.kind === "selected") {
39253
- if (picked.value === "clone")
39254
- yield* cloneDestination2(draft.projectChoice, draft.host);
39255
- else if ("kind" in picked.value) {
39256
- const branch = picked.value.value;
39257
- const existing = trees.find((tree) => tree.vcs === "git" && tree.branch === branch);
39258
- draft = existing ? selectWorktree(draft, existing) : changeDestination(draft, { branch, label: branch }, draft.worktreeName);
39259
- } else {
39260
- draft = selectWorktree(draft, picked.value);
39261
- }
39262
- } else {
39263
- const name = picked.text.trim();
39264
- if (!name || name.startsWith("-") && git2 || /[\p{ASCII}&&\p{Cc}]/v.test(name) || !git2 && (name.startsWith("/") || name.split(/[\\/]/).some((part) => !part || part === "." || part === "..")))
39265
- return yield* exports_Effect.fail(new AppError({ message: git2 ? "Branch name must be a valid Git branch" : "Invalid workspace name" }));
39266
- if (git2) {
39267
- const existing = trees.find((tree) => tree.vcs === "git" && tree.branch === name);
39268
- draft = existing ? selectWorktree(draft, existing) : changeDestination(draft, { branch: name, label: name }, draft.worktreeName);
39269
- } else
39270
- draft = typeWorktreeName(draft, name, found.revisions.find((choice) => choice.expression === "trunk()"));
39271
- }
39272
- }
39302
+ choices.push({
39303
+ value: "create",
39304
+ selected: !!draft.isCreating,
39305
+ title: jj2 ? "Create new workspace\u2026" : "Create new worktree\u2026",
39306
+ description: jj2 ? "Choose starting revision and directory" : "Choose branch and directory"
39307
+ });
39308
+ const picked = yield* choose(jj2 ? "Workspace (select existing or create new)" : "Worktree (select existing or create new)", choices);
39309
+ if (picked === "primary") {
39310
+ const clone = draft.clone;
39311
+ draft = {
39312
+ ...draft,
39313
+ isCreating: false,
39314
+ directory: undefined,
39315
+ worktreeName: undefined,
39316
+ destination: clone.vcs === "git" && clone.branch ? { branch: clone.branch, label: clone.branch } : undefined
39317
+ };
39318
+ } else if (picked === "create") {
39319
+ let name = "workspace";
39320
+ if (jj2)
39321
+ for (let suffix = 2;trees.some((tree) => tree.vcs === "jj" && tree.name === name); suffix++)
39322
+ name = `workspace-${suffix}`;
39323
+ const mainline = (draft.clone?.vcs === "jj" ? draft.clone.revisions : found?.revisions)?.find((choice) => choice.expression === "trunk()");
39324
+ draft = {
39325
+ ...draft,
39326
+ isCreating: true,
39327
+ directory: undefined,
39328
+ worktreeName: jj2 ? name : undefined,
39329
+ worktreeRoot: found ? found.worktreeRoot : draft.worktreeRoot,
39330
+ destination: jj2 && mainline ? { revision: mainline.revision.commitId, label: mainline.label } : { label: jj2 ? "Create new workspace\u2026" : "Create new worktree\u2026" }
39331
+ };
39332
+ isBranchEditPending = !jj2;
39333
+ } else
39334
+ draft = selectWorktree(draft, picked);
39273
39335
  } else if (action === "checkoutName") {
39336
+ const proposed = draft.clone && !draft.isCreating && draft.projectChoice ? clonePath(draft.projectChoice) : directoryFor({ ...draft, directory: undefined });
39274
39337
  const picked = yield* inputChoice({
39275
- message: draft.clone?.vcs === "jj" ? "Optional separate workspace name" : "Optional custom checkout directory name",
39276
- choices: [
39277
- { value: null, title: "Use default", description: "No separate custom name" },
39278
- ...draft.worktreeName ? [{ value: draft.worktreeName, title: "Current custom name" }] : []
39279
- ]
39338
+ message: "Directory (absolute path on selected machine)",
39339
+ choices: proposed ? [{ value: proposed, title: "Use proposed directory", description: proposed }] : []
39280
39340
  });
39281
- if (picked.kind === "selected" && picked.value === null)
39282
- draft = { ...draft, worktreeName: undefined };
39283
- else {
39284
- const name = (picked.kind === "selected" ? picked.value : picked.text).trim();
39285
- if (!name || /[\p{ASCII}&&\p{Cc}]/v.test(name) || name.split(/[\\/]/).some((part) => !part || part === "." || part === ".."))
39286
- return yield* exports_Effect.fail(new AppError({ message: "Invalid custom checkout name" }));
39287
- draft = { ...draft, worktreeName: name };
39288
- }
39341
+ const text = (picked.kind === "selected" ? picked.value : picked.text).trim();
39342
+ if (!path.isAbsolute(text) || /[\p{ASCII}&&\p{Cc}]/v.test(text) || path.dirname(path.resolve(text)) === path.resolve(text))
39343
+ return yield* exports_Effect.fail(new AppError({ message: "Directory must be an absolute non-root path on this machine" }));
39344
+ const directory = path.resolve(text);
39345
+ if (draft.clone && !draft.isCreating)
39346
+ draft = { ...draft, clone: { ...draft.clone, repo: directory } };
39347
+ else
39348
+ draft = {
39349
+ ...draft,
39350
+ directory,
39351
+ ...(draft.clone?.vcs ?? draft.project?.vcs) === "jj" ? { worktreeName: path.basename(directory) } : {}
39352
+ };
39289
39353
  } else if (action === "branch") {
39290
39354
  if (!draft.host || !(draft.project || draft.clone))
39291
39355
  return yield* exports_Effect.fail(new AppError({ message: "Select a project and machine before choosing a base or branch" }));
@@ -39335,18 +39399,28 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39335
39399
  if (jjClone)
39336
39400
  draft = { ...draft, clone: { ...jjClone, revision: choice.revision } };
39337
39401
  }
39338
- } else if (draft.clone?.vcs === "git") {
39402
+ } else {
39403
+ const clone = draft.clone?.vcs === "git" ? draft.clone : undefined;
39404
+ const found = clone ? undefined : yield* inspectWorktrees(draft.host, command, draft.project.path);
39405
+ const occupied = new Set;
39406
+ for (const tree of found?.worktrees ?? [])
39407
+ if (tree.vcs === "git" && tree.branch)
39408
+ occupied.add(tree.branch);
39409
+ if (clone && draft.isCreating && clone.branch)
39410
+ occupied.add(clone.branch);
39339
39411
  const picked = yield* inputChoice({
39340
- message: "Branch (select source branch or type new branch; only pushed history transfers)",
39341
- choices: draft.clone.branches.map((branch2) => ({
39412
+ message: "Branch (select unused or type new name)",
39413
+ choices: (clone?.branches ?? found?.branches ?? []).filter((branch2) => !occupied.has(branch2)).map((branch2) => ({
39342
39414
  value: branch2,
39343
39415
  title: branch2,
39344
- description: "Use this branch from the cloned origin"
39416
+ description: clone ? "Published branch" : "Existing branch \xB7 new worktree"
39345
39417
  }))
39346
39418
  });
39347
39419
  const branch = picked.kind === "selected" ? picked.value : picked.text.trim();
39348
39420
  if (!branch || branch.startsWith("-") || /[\p{ASCII}&&\p{Cc}]/v.test(branch))
39349
39421
  return yield* exports_Effect.fail(new AppError({ message: "Branch name must be a valid Git branch" }));
39422
+ if (occupied.has(branch))
39423
+ return yield* exports_Effect.fail(new AppError({ message: `Branch ${branch} is already checked out; select its existing worktree instead` }));
39350
39424
  draft = { ...draft, destination: { branch, label: branch } };
39351
39425
  }
39352
39426
  } else if (action === "session") {
@@ -39379,7 +39453,7 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39379
39453
  }
39380
39454
  }
39381
39455
  }).pipe(exports_Effect.catchCause((cause) => exports_Cause.hasInterrupts(cause) || launchAcknowledged ? exports_Effect.failCause(cause) : acknowledge("Could not open worktrees", [exports_Cause.pretty(cause)], "error").pipe(exports_Effect.andThen(exports_Effect.failCause(cause)))), exports_Effect.provideServiceEffect(exports_Terminal.Terminal, exports_Effect.gen(function* () {
39382
- const terminal = yield* exports_Terminal.Terminal;
39456
+ const terminal = yield* exports_BunTerminal.make(({ key: key5 }) => key5.ctrl && (key5.name === "c" || key5.name === "d"));
39383
39457
  const input = yield* terminal.readInput;
39384
39458
  return { ...terminal, readInput: exports_Effect.succeed(input) };
39385
39459
  })));
@@ -39455,7 +39529,7 @@ Run rex config reload to activate.`}`);
39455
39529
  }
39456
39530
  if (verb === "popup") {
39457
39531
  const flags = yield* parseFlags(args2);
39458
- if (Object.keys(flags).some((key5) => !["--host", "--context", "--origin-session", "--origin-block", "--origin-client", "--no-context", "--managed-popup"].includes(key5))) {
39532
+ if (Object.keys(flags).some((key5) => !["--host", "--context", "--origin-session", "--origin-block", "--origin-client", "--no-context"].includes(key5))) {
39459
39533
  return yield* exports_Effect.fail(new AppError({ message: "Invalid popup flags" }));
39460
39534
  }
39461
39535
  if (flags["--context"] && flags["--no-context"])
@@ -39472,8 +39546,6 @@ Run rex config reload to activate.`}`);
39472
39546
  };
39473
39547
  const context3 = typeof flags["--context"] === "string" ? exports_Effect.succeed(resolve6(flags["--context"])) : flags["--no-context"] ? exports_Effect.succeed(undefined) : args2.length && sessionId && blockId ? originDirectory(sessionId, blockId) : exports_Effect.succeed(process.cwd());
39474
39548
  yield* popup(executable, context3, origin2, flags["--host"]);
39475
- if (flags["--managed-popup"])
39476
- yield* closeManagedPopup;
39477
39549
  return;
39478
39550
  }
39479
39551
  if (verb === "launch-popup") {
@@ -39511,7 +39583,7 @@ Run rex config reload to activate.`}`);
39511
39583
  return;
39512
39584
  }
39513
39585
  if (verb === "open") {
39514
- if (args2.some((arg) => ["--context", "--origin-session", "--origin-block", "--origin-client", "--no-context", "--managed-popup"].includes(arg))) {
39586
+ if (args2.some((arg) => ["--context", "--origin-session", "--origin-block", "--origin-client", "--no-context"].includes(arg))) {
39515
39587
  return yield* exports_Effect.fail(new AppError({ message: "Context flags are only supported by popup" }));
39516
39588
  }
39517
39589
  const flags = yield* parseFlags(args2);