rex-worktrees 0.2.0 → 0.3.1

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.
@@ -33541,6 +33541,13 @@ var AssociationSchema = exports_Schema.Struct({
33541
33541
  blockId: BlockIdSchema
33542
33542
  });
33543
33543
  var SessionTargetSchema = exports_Schema.Struct({ id: SessionIdSchema, label: exports_Schema.String });
33544
+ var SessionSelectionSchema = exports_Schema.Union([
33545
+ exports_Schema.Struct({ kind: exports_Schema.Literal("existing"), id: SessionIdSchema }),
33546
+ exports_Schema.Struct({
33547
+ kind: exports_Schema.Literal("new"),
33548
+ name: exports_Schema.String.pipe(exports_Schema.check(exports_Schema.isMaxLength(128), exports_Schema.isPattern(/^(?=.*\S)(?!.*[\p{ASCII}&&\p{Cc}]).*$/v)))
33549
+ })
33550
+ ]);
33544
33551
  var ClientTargetSchema = exports_Schema.Struct({ id: ClientIdSchema, label: exports_Schema.String });
33545
33552
  var MachineSchema = exports_Schema.Struct({ key: exports_Schema.Union([exports_Schema.Literal("local"), RegisteredHostIdSchema]), label: exports_Schema.String, local: exports_Schema.Boolean, selector: exports_Schema.String });
33546
33553
  var DestinationHostSchema = exports_Schema.Struct({ ...MachineSchema.fields, hostId: ServerHostIdSchema });
@@ -33563,7 +33570,7 @@ var GitCloneInputSchema = exports_Schema.Struct({
33563
33570
  vcs: exports_Schema.Literal("git"),
33564
33571
  source: GitCloneSourceSchema,
33565
33572
  repo: exports_Schema.String,
33566
- sessionId: SessionIdSchema,
33573
+ session: SessionSelectionSchema,
33567
33574
  clientId: exports_Schema.optional(ClientIdSchema),
33568
33575
  name: exports_Schema.String,
33569
33576
  branch: exports_Schema.String,
@@ -33574,7 +33581,7 @@ var JjCloneInputSchema = exports_Schema.Struct({
33574
33581
  vcs: exports_Schema.Literal("jj"),
33575
33582
  source: JjCloneSourceSchema,
33576
33583
  repo: exports_Schema.String,
33577
- sessionId: SessionIdSchema,
33584
+ session: SessionSelectionSchema,
33578
33585
  clientId: exports_Schema.optional(ClientIdSchema),
33579
33586
  name: exports_Schema.String,
33580
33587
  worktreeName: exports_Schema.optional(exports_Schema.String),
@@ -33583,7 +33590,6 @@ var JjCloneInputSchema = exports_Schema.Struct({
33583
33590
  var CloneInputSchema = exports_Schema.Union([GitCloneInputSchema, JjCloneInputSchema]);
33584
33591
  var ClonePlanFields = {
33585
33592
  hostId: ServerHostIdSchema,
33586
- sessionId: SessionIdSchema,
33587
33593
  clientId: exports_Schema.optional(ClientIdSchema),
33588
33594
  repo: exports_Schema.String,
33589
33595
  existing: exports_Schema.Boolean,
@@ -33614,10 +33620,10 @@ var CloneLaunchResultSchema = exports_Schema.Struct({
33614
33620
  pending: exports_Schema.Literal(true),
33615
33621
  warning: exports_Schema.optional(exports_Schema.String)
33616
33622
  });
33617
- var CloneTaskRequestSchema = exports_Schema.Struct({ plan: ClonePlanSchema, rexBinDir: exports_Schema.optional(exports_Schema.String), rexLocalEndpoint: exports_Schema.optional(exports_Schema.String) });
33623
+ var CloneTaskRequestSchema = exports_Schema.Struct({ plan: ClonePlanSchema, sessionId: SessionIdSchema, rexBinDir: exports_Schema.optional(exports_Schema.String), rexLocalEndpoint: exports_Schema.optional(exports_Schema.String) });
33618
33624
  var LaunchInputFields = {
33619
33625
  repo: exports_Schema.String,
33620
- sessionId: SessionIdSchema,
33626
+ session: SessionSelectionSchema,
33621
33627
  name: exports_Schema.String,
33622
33628
  clientId: exports_Schema.optional(ClientIdSchema),
33623
33629
  additional: exports_Schema.optional(exports_Schema.Boolean),
@@ -33640,7 +33646,6 @@ var JjLaunchInputSchema = exports_Schema.Struct({
33640
33646
  var LaunchInputSchema = exports_Schema.Union([GitLaunchInputSchema, JjLaunchInputSchema]);
33641
33647
  var LaunchPlanFields = {
33642
33648
  hostId: ServerHostIdSchema,
33643
- sessionId: SessionIdSchema,
33644
33649
  clientId: exports_Schema.optional(ClientIdSchema),
33645
33650
  path: exports_Schema.String,
33646
33651
  worktreeRoot: exports_Schema.optional(exports_Schema.String),
@@ -33705,26 +33710,24 @@ var JjTaskRequestSchema = exports_Schema.Struct({
33705
33710
  base: exports_Schema.optional(JjRevisionSchema)
33706
33711
  });
33707
33712
  var TaskRequestSchema = exports_Schema.Union([GitTaskRequestSchema, JjTaskRequestSchema]);
33708
- var RequestIdentitySchema = exports_Schema.Struct({ version: exports_Schema.Literal(3), hostId: ServerHostIdSchema });
33713
+ var RequestIdentitySchema = exports_Schema.Struct({ version: exports_Schema.Literal(4), hostId: ServerHostIdSchema });
33709
33714
  var RequestSchema = exports_Schema.Union([
33710
33715
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("discover"), context: exports_Schema.optional(exports_Schema.String) }),
33711
33716
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-source"), repo: exports_Schema.String }),
33712
33717
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("project"), path: exports_Schema.String }),
33713
33718
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("worktrees"), repo: exports_Schema.String }),
33714
33719
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("revision"), repo: exports_Schema.String, revision: exports_Schema.String }),
33715
- exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("branch"), repo: exports_Schema.String, branch: exports_Schema.String, worktreeName: exports_Schema.optional(exports_Schema.String) }),
33716
33720
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("plan"), input: LaunchInputSchema }),
33717
33721
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-plan"), input: CloneInputSchema }),
33718
33722
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-launch"), input: CloneInputSchema, reviewed: ClonePlanSchema }),
33719
33723
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("launch"), input: LaunchInputSchema, reviewed: LaunchPlanSchema })
33720
33724
  ]);
33721
33725
  var ResponseSchema = exports_Schema.Union([
33722
- 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)), checkout: exports_Schema.optional(RepositorySchema) }),
33726
+ 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) }),
33723
33727
  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) }),
33724
33728
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("project-missing"), path: exports_Schema.String }),
33725
33729
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-source"), source: CloneSourceSchema }),
33726
33730
  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) }),
33727
- exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("branch"), path: exports_Schema.String, branch: exports_Schema.String, existing: exports_Schema.Boolean }),
33728
33731
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("revision"), revision: JjRevisionSchema }),
33729
33732
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("plan"), plan: LaunchPlanSchema }),
33730
33733
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-plan"), plan: ClonePlanSchema }),
@@ -33737,25 +33740,33 @@ var PopupSizeSchema = exports_Schema.Struct({ columns: exports_Schema.Number, ro
33737
33740
  var PopupBoundsSchema = exports_Schema.Tuple([exports_Schema.Number, exports_Schema.Number, exports_Schema.Number, exports_Schema.Number]);
33738
33741
  var RexIdentitySchema = exports_Schema.Struct({ host_id: ServerHostIdSchema, endpoint: exports_Schema.String, principal: exports_Schema.Struct({ transport: exports_Schema.String }) });
33739
33742
  var RexSessionsSchema = exports_Schema.Struct({ sessions: exports_Schema.Array(exports_Schema.Struct({ session_id: SessionIdSchema, label: exports_Schema.String })) });
33740
- var RexClientsSchema = exports_Schema.Struct({ clients: exports_Schema.Array(exports_Schema.Struct({
33741
- client_id: ClientIdSchema,
33742
- info: exports_Schema.optional(exports_Schema.Struct({ kind: exports_Schema.String, label: exports_Schema.optional(exports_Schema.String) })),
33743
- connection_state: exports_Schema.optional(exports_Schema.String)
33744
- })) });
33745
- var RexWindowsSchema = exports_Schema.Struct({ windows: exports_Schema.Array(exports_Schema.Struct({
33746
- window_id: WindowIdSchema,
33747
- label: exports_Schema.String,
33748
- layers: exports_Schema.Array(exports_Schema.Struct({ blocks: exports_Schema.optional(exports_Schema.Array(exports_Schema.Struct({ block_id: BlockIdSchema, host_id: ServerHostIdSchema }))) }))
33749
- })) });
33750
- var RexViewSchema = exports_Schema.Struct({ active_window_id: exports_Schema.NullOr(WindowIdSchema), windows: exports_Schema.Array(exports_Schema.Struct({
33751
- window_id: WindowIdSchema,
33752
- layers: exports_Schema.Array(exports_Schema.Struct({
33753
- layer_id: exports_Schema.NullOr(LayerIdSchema),
33754
- kind: exports_Schema.String,
33755
- bounds: exports_Schema.optional(exports_Schema.NullOr(PopupBoundsSchema)),
33756
- blocks: exports_Schema.Array(exports_Schema.Struct({ block_id: BlockIdSchema, owner: exports_Schema.optional(exports_Schema.NullOr(ClientIdSchema)) }))
33743
+ var RexSessionCreatedSchema = exports_Schema.Struct({ session_id: SessionIdSchema });
33744
+ var RexClientsSchema = exports_Schema.Struct({
33745
+ clients: exports_Schema.Array(exports_Schema.Struct({
33746
+ client_id: ClientIdSchema,
33747
+ info: exports_Schema.optional(exports_Schema.Struct({ kind: exports_Schema.String, label: exports_Schema.optional(exports_Schema.String) })),
33748
+ connection_state: exports_Schema.optional(exports_Schema.String)
33749
+ }))
33750
+ });
33751
+ var RexWindowsSchema = exports_Schema.Struct({
33752
+ windows: exports_Schema.Array(exports_Schema.Struct({
33753
+ window_id: WindowIdSchema,
33754
+ label: exports_Schema.String,
33755
+ layers: exports_Schema.Array(exports_Schema.Struct({ blocks: exports_Schema.optional(exports_Schema.Array(exports_Schema.Struct({ block_id: BlockIdSchema, host_id: ServerHostIdSchema }))) }))
33757
33756
  }))
33758
- })) });
33757
+ });
33758
+ var RexViewSchema = exports_Schema.Struct({
33759
+ active_window_id: exports_Schema.NullOr(WindowIdSchema),
33760
+ windows: exports_Schema.Array(exports_Schema.Struct({
33761
+ window_id: WindowIdSchema,
33762
+ layers: exports_Schema.Array(exports_Schema.Struct({
33763
+ layer_id: exports_Schema.NullOr(LayerIdSchema),
33764
+ kind: exports_Schema.String,
33765
+ bounds: exports_Schema.optional(exports_Schema.NullOr(PopupBoundsSchema)),
33766
+ blocks: exports_Schema.Array(exports_Schema.Struct({ block_id: BlockIdSchema, owner: exports_Schema.optional(exports_Schema.NullOr(ClientIdSchema)) }))
33767
+ }))
33768
+ }))
33769
+ });
33759
33770
  var RexResizedSchema = exports_Schema.Struct({ revision: exports_Schema.Number });
33760
33771
  var RexTerminalSizeSchema = exports_Schema.Struct({ ...PopupSizeSchema.fields, owner: exports_Schema.NullOr(ClientIdSchema) });
33761
33772
  var RexCreatedSchema = exports_Schema.Struct({ window_id: exports_Schema.optional(WindowIdSchema), block_ids: exports_Schema.Array(BlockIdSchema) });
@@ -34377,6 +34388,70 @@ var discoverProjects = exports_Effect.fnUntraced(function* (roots, explicitProje
34377
34388
  return found;
34378
34389
  });
34379
34390
 
34391
+ // src/state.ts
34392
+ import { randomUUID } from "crypto";
34393
+ import { homedir } from "os";
34394
+ var cloneRootFile = exports_Effect.fnUntraced(function* (stateRoot) {
34395
+ const path = yield* exports_Path.Path;
34396
+ const root = stateRoot ?? (process.env.XDG_STATE_HOME || path.join(homedir(), ".local", "state"));
34397
+ if (!path.isAbsolute(root))
34398
+ return yield* new AppError({ message: "State home must be absolute" });
34399
+ return path.join(root, "rex-worktrees", "clone-root.json");
34400
+ });
34401
+ var CloneRootSchema = exports_Schema.Struct({ cloneRoot: exports_Schema.String });
34402
+ var rememberedCloneRoot = exports_Effect.fnUntraced(function* (stateRoot) {
34403
+ const fs = yield* exports_FileSystem.FileSystem;
34404
+ const path = yield* exports_Path.Path;
34405
+ const filename = yield* cloneRootFile(stateRoot);
34406
+ const raw = yield* fs.readFileString(filename).pipe(exports_Effect.catchIf((error2) => exports_PlatformError.isPlatformError(error2) && error2.reason._tag === "NotFound", () => exports_Effect.succeed(undefined)));
34407
+ if (raw === undefined)
34408
+ return;
34409
+ const record2 = yield* exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(CloneRootSchema))(raw).pipe(exports_Effect.catch(() => exports_Effect.succeed(undefined)));
34410
+ return record2 && path.isAbsolute(record2.cloneRoot) && path.resolve(record2.cloneRoot) === record2.cloneRoot ? record2.cloneRoot : undefined;
34411
+ });
34412
+ var rememberCloneRoot = exports_Effect.fnUntraced(function* (parent, stateRoot) {
34413
+ const fs = yield* exports_FileSystem.FileSystem;
34414
+ const path = yield* exports_Path.Path;
34415
+ if (!path.isAbsolute(parent) || path.resolve(parent) !== parent)
34416
+ return yield* new AppError({ message: "Clone parent must be normalized and absolute" });
34417
+ const filename = yield* cloneRootFile(stateRoot);
34418
+ yield* fs.makeDirectory(path.dirname(filename), { recursive: true, mode: 448 });
34419
+ const temporary = `${filename}.${randomUUID()}.tmp`;
34420
+ yield* fs.writeFileString(temporary, JSON.stringify({ cloneRoot: parent }), { flag: "wx", mode: 384 });
34421
+ yield* fs.rename(temporary, filename).pipe(exports_Effect.ensuring(fs.remove(temporary, { force: true }).pipe(exports_Effect.ignore)));
34422
+ });
34423
+ var saveAssociation = exports_Effect.fnUntraced(function* (association) {
34424
+ const fs = yield* exports_FileSystem.FileSystem;
34425
+ const path = yield* exports_Path.Path;
34426
+ const root = process.env.XDG_STATE_HOME || path.join(homedir(), ".local", "state");
34427
+ const directory = path.join(root, "rex-worktrees", "associations");
34428
+ yield* fs.makeDirectory(directory, { recursive: true, mode: 448 });
34429
+ const id2 = randomUUID();
34430
+ const temporary = path.join(directory, `${id2}.tmp`);
34431
+ const destination = path.join(directory, `${id2}.json`);
34432
+ yield* fs.writeFileString(temporary, JSON.stringify(association), { flag: "wx", mode: 384 });
34433
+ yield* fs.rename(temporary, destination).pipe(exports_Effect.ensuring(fs.remove(temporary, { force: true }).pipe(exports_Effect.ignore)));
34434
+ });
34435
+ var associations = exports_Effect.gen(function* () {
34436
+ const fs = yield* exports_FileSystem.FileSystem;
34437
+ const path = yield* exports_Path.Path;
34438
+ const directory = path.join(process.env.XDG_STATE_HOME || path.join(homedir(), ".local", "state"), "rex-worktrees", "associations");
34439
+ const result4 = [];
34440
+ if (!(yield* fs.exists(directory)))
34441
+ return result4;
34442
+ for (const name of yield* fs.readDirectory(directory)) {
34443
+ if (!name.endsWith(".json"))
34444
+ continue;
34445
+ const raw = yield* exports_Effect.catchIf(fs.readFileString(path.join(directory, name)), (error2) => exports_PlatformError.isPlatformError(error2) && error2.reason._tag === "NotFound", () => exports_Effect.succeed(undefined));
34446
+ if (raw === undefined)
34447
+ continue;
34448
+ const record2 = yield* exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(AssociationSchema))(raw).pipe(exports_Effect.catch(() => exports_Effect.succeed(undefined)));
34449
+ if (record2)
34450
+ result4.push(record2);
34451
+ }
34452
+ return result4;
34453
+ });
34454
+
34380
34455
  // src/config.ts
34381
34456
  var loadConfig = exports_Effect.gen(function* () {
34382
34457
  const fs = yield* exports_FileSystem.FileSystem;
@@ -34402,6 +34477,21 @@ var loadConfig = exports_Effect.gen(function* () {
34402
34477
  };
34403
34478
  return config;
34404
34479
  });
34480
+ var resolveCloneRoot = exports_Effect.fnUntraced(function* (roots, projects, stateRoot) {
34481
+ const path = yield* exports_Path.Path;
34482
+ if (roots[0])
34483
+ return roots[0];
34484
+ const remembered = yield* rememberedCloneRoot(stateRoot);
34485
+ if (remembered)
34486
+ return remembered;
34487
+ const parents = new Set(projects.map((project4) => path.dirname(project4.path)));
34488
+ if (parents.size === 1)
34489
+ return [...parents][0];
34490
+ const home = process.env.HOME;
34491
+ if (!home || !path.isAbsolute(home))
34492
+ return yield* new AppError({ message: "Target HOME must be an absolute directory" });
34493
+ return home;
34494
+ });
34405
34495
  var resolveWorktreeRoot = exports_Effect.fnUntraced(function* (repoPath) {
34406
34496
  const config = yield* loadConfig;
34407
34497
  const target = yield* project3(repoPath);
@@ -34490,6 +34580,10 @@ var listSessions = exports_Effect.gen(function* () {
34490
34580
  const result4 = yield* parse3(RexSessionsSchema, yield* rex(["ls", "--json"]));
34491
34581
  return result4.sessions.map((session) => ({ id: session.session_id, label: session.label }));
34492
34582
  });
34583
+ var createSession = exports_Effect.fnUntraced(function* (name) {
34584
+ const result4 = yield* parse3(RexSessionCreatedSchema, yield* rex(["api", "call", "session.create", JSON.stringify({ label: name })]));
34585
+ return result4.session_id;
34586
+ });
34493
34587
  var listClients = exports_Effect.gen(function* () {
34494
34588
  const result4 = yield* parse3(RexClientsSchema, yield* rex(["client", "ls", "--json"]));
34495
34589
  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 }));
@@ -34505,8 +34599,9 @@ var originDirectory = exports_Effect.fnUntraced(function* (sessionId, blockId) {
34505
34599
  return;
34506
34600
  const raw = yield* rex(["block", "call", "-s", sessionId, "-b", blockId, "pwd"]);
34507
34601
  const result4 = yield* parse3(RexDirectorySchema, raw);
34508
- if (result4.pwd)
34509
- return localDirectoryUri(result4.pwd);
34602
+ const directory = result4.pwd ? localDirectoryUri(result4.pwd) : undefined;
34603
+ if (directory !== undefined)
34604
+ return directory;
34510
34605
  const processInfo = yield* parse3(RexProcessSchema, yield* rex(["block", "call", "-s", sessionId, "-b", blockId, "process"]));
34511
34606
  const cwd = processInfo.foreground?.cwd;
34512
34607
  return cwd?.startsWith("/") && !cwd.includes("\x00") ? cwd : undefined;
@@ -34673,43 +34768,11 @@ var closeManagedPopup = exports_Effect.gen(function* () {
34673
34768
  yield* localRex(["block", "close", "-s", sessionId, blockId]);
34674
34769
  });
34675
34770
 
34676
- // src/state.ts
34677
- import { randomUUID } from "crypto";
34678
- import { homedir } from "os";
34679
- var saveAssociation = exports_Effect.fnUntraced(function* (association) {
34680
- const fs = yield* exports_FileSystem.FileSystem;
34681
- const path = yield* exports_Path.Path;
34682
- const root = process.env.XDG_STATE_HOME || path.join(homedir(), ".local", "state");
34683
- const directory = path.join(root, "rex-worktrees", "associations");
34684
- yield* fs.makeDirectory(directory, { recursive: true, mode: 448 });
34685
- const id2 = randomUUID();
34686
- const temporary = path.join(directory, `${id2}.tmp`);
34687
- const destination = path.join(directory, `${id2}.json`);
34688
- yield* fs.writeFileString(temporary, JSON.stringify(association), { flag: "wx", mode: 384 });
34689
- yield* fs.rename(temporary, destination).pipe(exports_Effect.ensuring(fs.remove(temporary, { force: true }).pipe(exports_Effect.ignore)));
34690
- });
34691
- var associations = exports_Effect.gen(function* () {
34692
- const fs = yield* exports_FileSystem.FileSystem;
34693
- const path = yield* exports_Path.Path;
34694
- const directory = path.join(process.env.XDG_STATE_HOME || path.join(homedir(), ".local", "state"), "rex-worktrees", "associations");
34695
- const result4 = [];
34696
- if (!(yield* fs.exists(directory)))
34697
- return result4;
34698
- for (const name of yield* fs.readDirectory(directory)) {
34699
- if (!name.endsWith(".json"))
34700
- continue;
34701
- const raw = yield* exports_Effect.catchIf(fs.readFileString(path.join(directory, name)), (error2) => exports_PlatformError.isPlatformError(error2) && error2.reason._tag === "NotFound", () => exports_Effect.succeed(undefined));
34702
- if (raw === undefined)
34703
- continue;
34704
- const record2 = yield* exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(AssociationSchema))(raw).pipe(exports_Effect.catch(() => exports_Effect.succeed(undefined)));
34705
- if (record2)
34706
- result4.push(record2);
34707
- }
34708
- return result4;
34709
- });
34710
-
34711
34771
  // src/worktrees.ts
34772
+ import { constants as constants2 } from "fs";
34773
+ import { access as access3 } from "fs/promises";
34712
34774
  var fail19 = (message) => exports_Effect.fail(new AppError({ message }));
34775
+ var sameSession = (a, b) => a.kind === b.kind && (a.kind === "existing" && b.kind === "existing" ? a.id === b.id : a.kind === "new" && b.kind === "new" && a.name === b.name);
34713
34776
  var canonical = exports_Effect.fnUntraced(function* (path) {
34714
34777
  const fs = yield* exports_FileSystem.FileSystem;
34715
34778
  return yield* fs.realPath(path);
@@ -34748,8 +34811,12 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34748
34811
  const host = yield* localHost;
34749
34812
  if (expectedHostId && host.id !== expectedHostId)
34750
34813
  return yield* fail19(`Wrong Rex host: expected ${expectedHostId}, got ${host.id}`);
34751
- if (!(yield* listSessions).some((item) => item.id === input.sessionId))
34752
- return yield* fail19(`Rex session ${input.sessionId} does not exist locally`);
34814
+ yield* exports_Schema.decodeUnknownEffect(SessionSelectionSchema)(input.session);
34815
+ if (input.session.kind === "existing") {
34816
+ const sessionId = input.session.id;
34817
+ if (!(yield* listSessions).some((item) => item.id === sessionId))
34818
+ return yield* fail19(`Rex session ${sessionId} does not exist locally`);
34819
+ }
34753
34820
  const clients = yield* listClients;
34754
34821
  if (input.clientId && !clients.some((item) => item.id === input.clientId))
34755
34822
  return yield* fail19(`Rex app client ${input.clientId} is not connected locally`);
@@ -34817,7 +34884,7 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34817
34884
  warning = [warning, "Multiple Rex apps are connected; select the session in the intended app"].filter(Boolean).join("; ");
34818
34885
  let target;
34819
34886
  for (const entry of records) {
34820
- if (entry.vcs !== repo.vcs || entry.hostId !== host.id || entry.commonDir !== repo.commonDir || entry.path !== path || entry.sessionId !== input.sessionId)
34887
+ 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)
34821
34888
  continue;
34822
34889
  const label = yield* liveBlock(entry.sessionId, entry.windowId, entry.blockId, host.id, path);
34823
34890
  if (label !== false) {
@@ -34835,7 +34902,6 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34835
34902
  detail = [detail, `Creating a JJ workspace snapshots ${repo.path}; its working-copy commit and colocated Git index intent-to-add entries may change.`].filter(Boolean).join(" ");
34836
34903
  const common = {
34837
34904
  hostId: host.id,
34838
- sessionId: input.sessionId,
34839
34905
  ...clientId ? { clientId } : {},
34840
34906
  path,
34841
34907
  ...worktreeRoot ? { worktreeRoot } : {},
@@ -34866,7 +34932,7 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34866
34932
  label: action === "focus" ? "Focus existing tab" : checkout === "create" ? "Create workspace & open" : action === "split" ? "Open pane" : "Open tab"
34867
34933
  };
34868
34934
  });
34869
- var sameLaunchPlan = (a, b) => a.vcs === b.vcs && a.input.vcs === b.input.vcs && a.hostId === b.hostId && a.worktreeRoot === b.worktreeRoot && a.sessionId === b.sessionId && a.clientId === b.clientId && a.input.repo === b.input.repo && a.input.sessionId === b.input.sessionId && 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);
34935
+ 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);
34870
34936
  var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expectedHostId) {
34871
34937
  const pathService = yield* exports_Path.Path;
34872
34938
  if (!command[0] || !pathService.isAbsolute(command[0]))
@@ -34876,12 +34942,13 @@ var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expe
34876
34942
  return yield* fail19("Launch plan changed since review; inspect the destination before submitting again");
34877
34943
  if (plan.action === "focus") {
34878
34944
  const target2 = plan.target;
34879
- if (!target2)
34945
+ if (!target2 || plan.input.session.kind !== "existing")
34880
34946
  return yield* fail19("The reviewed focus target is no longer available");
34881
- const warning2 = [plan.warning, yield* focus(plan.sessionId, target2.windowId, plan.clientId, target2.blockId)].filter(Boolean).join("; ") || undefined;
34947
+ const sessionId2 = plan.input.session.id;
34948
+ const warning2 = [plan.warning, yield* focus(sessionId2, target2.windowId, plan.clientId, target2.blockId)].filter(Boolean).join("; ") || undefined;
34882
34949
  const result5 = {
34883
34950
  hostId: plan.hostId,
34884
- sessionId: plan.sessionId,
34951
+ sessionId: sessionId2,
34885
34952
  windowId: target2.windowId,
34886
34953
  blockId: target2.blockId,
34887
34954
  path: plan.path,
@@ -34894,11 +34961,12 @@ var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expe
34894
34961
  const repo = yield* repository3(plan.input.repo);
34895
34962
  if (repo.vcs !== plan.vcs)
34896
34963
  return yield* fail19("Repository backend changed since review");
34964
+ const sessionId = plan.input.session.kind === "existing" ? plan.input.session.id : yield* createSession(plan.input.session.name);
34897
34965
  const common = {
34898
34966
  repo: repo.path,
34899
34967
  path: plan.path,
34900
34968
  commonDir: repo.commonDir,
34901
- sessionId: plan.sessionId,
34969
+ sessionId,
34902
34970
  hostId: plan.hostId,
34903
34971
  ...process.env.REX_BIN_DIR ? { rexBinDir: process.env.REX_BIN_DIR } : {},
34904
34972
  ...process.env.REX_WORKTREES_LOCAL_ENDPOINT ? { rexLocalEndpoint: process.env.REX_WORKTREES_LOCAL_ENDPOINT } : {},
@@ -34923,11 +34991,11 @@ var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expe
34923
34991
  const name = plan.name;
34924
34992
  if (!name)
34925
34993
  return yield* fail19("The reviewed Rex tab name is no longer available");
34926
- const created = plan.action === "split" ? target ? yield* createSplit(plan.sessionId, target.windowId, target.blockId, name, plan.path, argv) : yield* fail19("The reviewed split target is no longer available") : yield* createTab(plan.sessionId, name, plan.checkout === "existing" ? plan.path : repo.path, argv);
34927
- const warning = [plan.warning, yield* focus(plan.sessionId, created.windowId, plan.clientId, created.blockId)].filter(Boolean).join("; ") || undefined;
34994
+ 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);
34995
+ const warning = [plan.warning, yield* focus(sessionId, created.windowId, plan.clientId, created.blockId)].filter(Boolean).join("; ") || undefined;
34928
34996
  const result4 = {
34929
34997
  hostId: plan.hostId,
34930
- sessionId: plan.sessionId,
34998
+ sessionId,
34931
34999
  windowId: created.windowId,
34932
35000
  blockId: created.blockId,
34933
35001
  path: plan.path,
@@ -35064,14 +35132,29 @@ var cloneDestination = exports_Effect.fnUntraced(function* (destination, url, vc
35064
35132
  }
35065
35133
  return;
35066
35134
  });
35135
+ var checkCloneParent = exports_Effect.fnUntraced(function* (destination) {
35136
+ const fs = yield* exports_FileSystem.FileSystem;
35137
+ const path = yield* exports_Path.Path;
35138
+ let ancestor = path.dirname(destination);
35139
+ while (!(yield* fs.lstat(ancestor).pipe(exports_Effect.map(() => true), exports_Effect.catchIf(missing3, () => exports_Effect.succeed(false)))))
35140
+ ancestor = path.dirname(ancestor);
35141
+ yield* exports_Effect.tryPromise({
35142
+ try: () => access3(ancestor, constants2.W_OK | constants2.X_OK),
35143
+ catch: (cause) => new AppError({ message: `Cannot create clone destination ${destination}: ${ancestor} is not writable; choose another destination or fix its permissions`, cause })
35144
+ });
35145
+ });
35067
35146
  var planClone = exports_Effect.fnUntraced(function* (input, expectedHostId) {
35068
35147
  const host = yield* localHost;
35069
35148
  if (expectedHostId && host.id !== expectedHostId)
35070
35149
  return yield* fail19("Wrong Rex clone host");
35071
35150
  if (input.vcs !== input.source.vcs)
35072
35151
  return yield* fail19("Clone source backend does not match request");
35073
- if (!(yield* listSessions).some((item) => item.id === input.sessionId))
35074
- return yield* fail19("Requested Rex session does not exist");
35152
+ yield* exports_Schema.decodeUnknownEffect(SessionSelectionSchema)(input.session);
35153
+ if (input.session.kind === "existing") {
35154
+ const sessionId = input.session.id;
35155
+ if (!(yield* listSessions).some((item) => item.id === sessionId))
35156
+ return yield* fail19("Requested Rex session does not exist");
35157
+ }
35075
35158
  const clients = yield* listClients;
35076
35159
  if (input.clientId && !clients.some((item) => item.id === input.clientId))
35077
35160
  return yield* fail19("Requested Rex app client is not connected");
@@ -35086,6 +35169,8 @@ var planClone = exports_Effect.fnUntraced(function* (input, expectedHostId) {
35086
35169
  catch: () => new AppError({ message: "Clone source URL is unsafe or local to another Rex host" })
35087
35170
  });
35088
35171
  const commonDir = yield* cloneDestination(input.repo, url, input.vcs, host.id);
35172
+ if (commonDir === undefined)
35173
+ yield* checkCloneParent(input.repo);
35089
35174
  const existing = commonDir !== undefined;
35090
35175
  let gitBase;
35091
35176
  let base;
@@ -35110,7 +35195,6 @@ var planClone = exports_Effect.fnUntraced(function* (input, expectedHostId) {
35110
35195
  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;
35111
35196
  const common = {
35112
35197
  hostId: host.id,
35113
- sessionId: input.sessionId,
35114
35198
  ...clientId ? { clientId } : {},
35115
35199
  repo: input.repo,
35116
35200
  existing,
@@ -35133,7 +35217,7 @@ var planClone = exports_Effect.fnUntraced(function* (input, expectedHostId) {
35133
35217
  ...base ? { base } : {}
35134
35218
  };
35135
35219
  });
35136
- var sameClonePlan = (a, b) => a.vcs === b.vcs && a.input.vcs === b.input.vcs && a.hostId === b.hostId && a.sessionId === b.sessionId && a.clientId === b.clientId && a.repo === b.repo && a.existing === b.existing && a.commonDir === b.commonDir && a.input.repo === b.input.repo && a.input.sessionId === b.input.sessionId && 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));
35220
+ 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));
35137
35221
  var launchClone = exports_Effect.fnUntraced(function* (input, command, reviewed, expectedHostId) {
35138
35222
  const path = yield* exports_Path.Path;
35139
35223
  if (!command[0] || !path.isAbsolute(command[0]))
@@ -35141,17 +35225,18 @@ var launchClone = exports_Effect.fnUntraced(function* (input, command, reviewed,
35141
35225
  const plan = yield* planClone(input, expectedHostId);
35142
35226
  if (reviewed && !sameClonePlan(reviewed, plan))
35143
35227
  return yield* fail19("Clone plan changed since review; inspect before submitting again");
35228
+ const home = process.env.HOME;
35229
+ if (!home || !path.isAbsolute(home))
35230
+ return yield* fail19("Target HOME must be an absolute directory");
35144
35231
  const request3 = {
35145
35232
  plan,
35233
+ sessionId: plan.input.session.kind === "existing" ? plan.input.session.id : yield* createSession(plan.input.session.name),
35146
35234
  ...process.env.REX_BIN_DIR ? { rexBinDir: process.env.REX_BIN_DIR } : {},
35147
35235
  ...process.env.REX_WORKTREES_LOCAL_ENDPOINT ? { rexLocalEndpoint: process.env.REX_WORKTREES_LOCAL_ENDPOINT } : {}
35148
35236
  };
35149
- const home = process.env.HOME;
35150
- if (!home || !path.isAbsolute(home))
35151
- return yield* fail19("Target HOME must be an absolute directory");
35152
- const created = yield* createTab(plan.sessionId, input.name, home, [...command, "clone-task", JSON.stringify(request3)]);
35153
- const warning = [plan.warning, yield* focus(plan.sessionId, created.windowId, plan.clientId, created.blockId)].filter(Boolean).join("; ") || undefined;
35154
- const result4 = { hostId: plan.hostId, sessionId: plan.sessionId, windowId: created.windowId, blockId: created.blockId, repo: plan.repo, pending: true, ...warning ? { warning } : {} };
35237
+ const created = yield* createTab(request3.sessionId, input.name, home, [...command, "clone-task", JSON.stringify(request3)]);
35238
+ const warning = [plan.warning, yield* focus(request3.sessionId, created.windowId, plan.clientId, created.blockId)].filter(Boolean).join("; ") || undefined;
35239
+ const result4 = { hostId: plan.hostId, sessionId: request3.sessionId, windowId: created.windowId, blockId: created.blockId, repo: plan.repo, pending: true, ...warning ? { warning } : {} };
35155
35240
  return result4;
35156
35241
  });
35157
35242
  var prepareCloneCheckout = exports_Effect.fnUntraced(function* (plan) {
@@ -35251,16 +35336,19 @@ var cloneTask = exports_Effect.fnUntraced(function* (request3) {
35251
35336
  if (request3.rexLocalEndpoint)
35252
35337
  process.env.REX_WORKTREES_LOCAL_ENDPOINT = request3.rexLocalEndpoint;
35253
35338
  const { plan } = request3;
35254
- if (process.env.REX_SESSION !== plan.sessionId || !process.env.REX_BLOCK)
35339
+ if (process.env.REX_SESSION !== request3.sessionId || !process.env.REX_BLOCK)
35255
35340
  return yield* fail19("Clone task must run in its requested Rex terminal");
35256
35341
  const blockId = yield* exports_Schema.decodeUnknownEffect(BlockIdSchema)(process.env.REX_BLOCK);
35342
+ if (!(yield* listSessions).some((item) => item.id === request3.sessionId))
35343
+ return yield* fail19("Requested Rex session no longer exists");
35257
35344
  if (!sameClonePlan(plan, yield* planClone(plan.input, plan.hostId)))
35258
35345
  return yield* fail19("Clone target changed since launch; destination left untouched");
35259
35346
  const { repo, cwd } = yield* prepareCloneCheckout(plan);
35260
- const windows = yield* windowList(plan.sessionId).pipe(exports_Effect.catch(() => exports_Effect.succeed([])));
35347
+ 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))}`))));
35348
+ const windows = yield* windowList(request3.sessionId).pipe(exports_Effect.catch(() => exports_Effect.succeed([])));
35261
35349
  const window = windows.find((entry) => entry.layers.some((layer12) => layer12.blocks?.some((block) => block.block_id === blockId && block.host_id === plan.hostId)));
35262
35350
  if (window)
35263
- yield* saveAssociation({ vcs: repo.vcs, hostId: plan.hostId, commonDir: repo.commonDir, path: cwd, sessionId: plan.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))}`))));
35351
+ 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))}`))));
35264
35352
  else
35265
35353
  console.error(`Checkout ${cwd} is available; Rex block could not be associated`);
35266
35354
  yield* shell(cwd);
@@ -35275,7 +35363,7 @@ var dispatchHost = exports_Effect.fnUntraced(function* (request3, command) {
35275
35363
  const paths = 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];
35276
35364
  if (paths.some((value3) => !path.isAbsolute(value3)))
35277
35365
  return yield* exports_Effect.fail(new AppError({ message: "Destination repository and worktree paths must be absolute" }));
35278
- const identity3 = { version: 3, hostId: host.id };
35366
+ const identity3 = { version: 4, hostId: host.id };
35279
35367
  let result4;
35280
35368
  switch (request3.kind) {
35281
35369
  case "discover": {
@@ -35287,7 +35375,16 @@ var dispatchHost = exports_Effect.fnUntraced(function* (request3, command) {
35287
35375
  clients: listClients,
35288
35376
  projects: discoverProjects(config.roots, config.projects, request3.context)
35289
35377
  }, { concurrency: 4 });
35290
- result4 = { ...identity3, kind: "discover", sessions, clients, projects, roots: config.roots, ...checkout ? { checkout } : {} };
35378
+ result4 = {
35379
+ ...identity3,
35380
+ kind: "discover",
35381
+ sessions,
35382
+ clients,
35383
+ projects,
35384
+ roots: config.roots,
35385
+ cloneRoot: yield* resolveCloneRoot(config.roots, projects),
35386
+ ...checkout ? { checkout } : {}
35387
+ };
35291
35388
  break;
35292
35389
  }
35293
35390
  case "project": {
@@ -35312,7 +35409,11 @@ var dispatchHost = exports_Effect.fnUntraced(function* (request3, command) {
35312
35409
  }
35313
35410
  case "clone-source": {
35314
35411
  const repo = yield* repository3(request3.repo);
35315
- result4 = { ...identity3, kind: "clone-source", source: repo.vcs === "git" ? yield* cloneSource(repo.path, host.id) : yield* cloneSource2(repo.path, host.id) };
35412
+ result4 = {
35413
+ ...identity3,
35414
+ kind: "clone-source",
35415
+ source: repo.vcs === "git" ? yield* cloneSource(repo.path, host.id) : yield* cloneSource2(repo.path, host.id)
35416
+ };
35316
35417
  break;
35317
35418
  }
35318
35419
  case "worktrees": {
@@ -35334,14 +35435,6 @@ var dispatchHost = exports_Effect.fnUntraced(function* (request3, command) {
35334
35435
  result4 = { ...identity3, kind: "revision", revision: yield* resolveRevision(repo.path, request3.revision) };
35335
35436
  break;
35336
35437
  }
35337
- case "branch": {
35338
- const repo = yield* repository3(request3.repo);
35339
- if (repo.vcs !== "git")
35340
- return yield* exports_Effect.fail(new AppError({ message: "Branch checkout requires a Git repository" }));
35341
- const planned = yield* planWorktree(repo.path, request3.branch, yield* resolveWorktreeRoot(repo.path), request3.worktreeName);
35342
- result4 = { ...identity3, kind: "branch", path: planned.path, branch: planned.branch, existing: planned.existing };
35343
- break;
35344
- }
35345
35438
  case "plan":
35346
35439
  result4 = { ...identity3, kind: "plan", plan: yield* planLaunch(request3.input, host.id) };
35347
35440
  break;
@@ -35394,7 +35487,7 @@ var connectMachine = exports_Effect.fnUntraced(function* (machine) {
35394
35487
  return { ...current, hostId: identity3.host_id };
35395
35488
  });
35396
35489
  var request3 = exports_Effect.fnUntraced(function* (host, command, body) {
35397
- const encoded = { version: 3, hostId: host.hostId, ...body };
35490
+ const encoded = { version: 4, hostId: host.hostId, ...body };
35398
35491
  let response;
35399
35492
  if (host.local) {
35400
35493
  response = yield* dispatchHost(encoded, command);
@@ -35405,7 +35498,7 @@ var request3 = exports_Effect.fnUntraced(function* (host, command, body) {
35405
35498
  const raw = yield* remoteRex(current.selector, ["do", "worktrees_request", "--args", JSON.stringify({ request: JSON.stringify(encoded) }), "--json"]);
35406
35499
  response = yield* exports_Schema.decodeUnknownEffect(RexWorktreesResponseSchema)(raw);
35407
35500
  }
35408
- if (response.hostId !== host.hostId || response.version !== 3 || response.kind !== body.kind && !(body.kind === "project" && response.kind === "project-missing" && response.path === body.path))
35501
+ if (response.hostId !== host.hostId || response.version !== 4 || response.kind !== body.kind && !(body.kind === "project" && response.kind === "project-missing" && response.path === body.path))
35409
35502
  return yield* fail20(`Unexpected Rex host/protocol response from ${host.label}; update rex-worktrees on that machine, run setup, and reload its Rex config`);
35410
35503
  return response;
35411
35504
  });
@@ -35413,7 +35506,7 @@ var discover = exports_Effect.fnUntraced(function* (host, command, context3) {
35413
35506
  const result4 = yield* request3(host, command, { kind: "discover", ...host.local && context3 ? { context: context3 } : {} });
35414
35507
  if (result4.kind !== "discover")
35415
35508
  return yield* fail20("Unexpected discovery response");
35416
- return { sessions: result4.sessions, clients: result4.clients, projects: result4.projects, roots: result4.roots ?? [], ...result4.checkout ? { checkout: result4.checkout } : {} };
35509
+ return { sessions: result4.sessions, clients: result4.clients, projects: result4.projects, roots: result4.roots ?? [], cloneRoot: result4.cloneRoot, ...result4.checkout ? { checkout: result4.checkout } : {} };
35417
35510
  });
35418
35511
  var inspectProject = exports_Effect.fnUntraced(function* (host, command, path) {
35419
35512
  const result4 = yield* request3(host, command, { kind: "project", path });
@@ -35435,12 +35528,6 @@ var inspectRevision = exports_Effect.fnUntraced(function* (host, command, repo,
35435
35528
  return yield* fail20("Unexpected revision response");
35436
35529
  return result4.revision;
35437
35530
  });
35438
- var inspectBranch = exports_Effect.fnUntraced(function* (host, command, repo, branch, worktreeName) {
35439
- const result4 = yield* request3(host, command, { kind: "branch", repo, branch, ...worktreeName !== undefined ? { worktreeName } : {} });
35440
- if (result4.kind !== "branch")
35441
- return yield* fail20("Unexpected branch response");
35442
- return { path: result4.path, branch: result4.branch, existing: result4.existing };
35443
- });
35444
35531
  var review = exports_Effect.fnUntraced(function* (host, command, input) {
35445
35532
  const result4 = yield* request3(host, command, { kind: "plan", input });
35446
35533
  if (result4.kind !== "plan")
@@ -38377,7 +38464,7 @@ var renderFormFrame = (view, focused, editing, columns, rows2, colors2 = !proces
38377
38464
  const heading = `${color("REX", "cyan", colors2)} ${color("/ WORKTREES", "bold", colors2)}`;
38378
38465
  add4(heading);
38379
38466
  screen.push(line("\u251C", "\u2524"));
38380
- const budget = Math.max(0, rows2 - (editing ? rows2 >= 20 ? 11 : 9 : 7));
38467
+ const budget = Math.max(0, rows2 - (editing ? rows2 >= 20 ? 10 : 8 : 7));
38381
38468
  const body = [];
38382
38469
  const addBody = (text) => body.push(border(fit(text, inside)));
38383
38470
  const addWrapped = (text, tone, limit = budget) => {
@@ -38395,7 +38482,7 @@ var renderFormFrame = (view, focused, editing, columns, rows2, colors2 = !proces
38395
38482
  const room = Math.max(1, inside - 19);
38396
38483
  const indicator = active ? color("\u203A", "cyan", colors2) : " ";
38397
38484
  addBody(`${indicator} ${color(label, row.disabled ? "muted" : active ? "cyan" : "bold", colors2)} ${color(fit(value3, room), row.disabled ? "muted" : active ? "bold" : "muted", colors2)}`);
38398
- if (!editing && !view.error && active && row.detail && body.length < budget - 3)
38485
+ if (!editing && row.detail && (row.id === "destination" && row.detail.startsWith("/") || !view.error && active) && body.length < budget - 3)
38399
38486
  addWrapped(row.detail, "muted", budget - 3);
38400
38487
  }
38401
38488
  if (view.error) {
@@ -38411,13 +38498,13 @@ var renderFormFrame = (view, focused, editing, columns, rows2, colors2 = !proces
38411
38498
  while (body.length < budget)
38412
38499
  addBody("");
38413
38500
  screen.push(...body.slice(0, budget));
38414
- if (!editing)
38501
+ if (!editing) {
38415
38502
  screen.push(line("\u251C", "\u2524"));
38416
- const submit2 = focused === "submit" ? color("\u203A", "cyan", colors2) : " ";
38417
- const cancel = focused === "cancel" ? color("\u203A", "cyan", colors2) : " ";
38418
- add4(`${submit2} ${color(fit(safeDisplayText(view.submitLabel), Math.max(1, inside - 19)), view.submitDisabled ? "muted" : "cyan", colors2)} ${cancel} ${color("Cancel", focused === "cancel" ? "cyan" : "muted", colors2)}`);
38419
- if (!editing)
38503
+ const submit2 = focused === "submit" ? color("\u203A", "cyan", colors2) : " ";
38504
+ const cancel = focused === "cancel" ? color("\u203A", "cyan", colors2) : " ";
38505
+ add4(`${submit2} ${color(fit(safeDisplayText(view.submitLabel), Math.max(1, inside - 19)), view.submitDisabled ? "muted" : "cyan", colors2)} ${cancel} ${color("Cancel", focused === "cancel" ? "cyan" : "muted", colors2)}`);
38420
38506
  add4(color(" \u2191\u2193 / jk move \xB7 Tab next \xB7 Enter select \xB7 Ctrl+S submit \xB7 Esc close", "muted", colors2));
38507
+ }
38421
38508
  screen.push(line("\u2514", "\u2518"));
38422
38509
  return screen.join(`\r
38423
38510
  `) + (editing ? `\r
@@ -38519,11 +38606,11 @@ var problem = (error2) => error2 instanceof AppError ? error2.message : exports_
38519
38606
  var selected = (value3, current, title, description) => ({ value: value3, selected: current, title, description });
38520
38607
  var generatedName = (draft) => draft.worktreeName ?? (draft.clone?.vcs === "jj" ? draft.projectChoice?.name : draft.destination?.label) ?? draft.projectChoice?.name ?? "Worktree";
38521
38608
  var inputFor = (draft) => {
38522
- if (!draft.host || !draft.project || !draft.projectChoice || !draft.destination || !draft.sessionId)
38609
+ if (!draft.host || !draft.project || !draft.projectChoice || !draft.destination || !draft.session)
38523
38610
  return;
38524
38611
  const common = {
38525
38612
  repo: draft.project.vcs === "jj" ? draft.sourcePath ?? draft.project.path : draft.project.path,
38526
- sessionId: draft.sessionId,
38613
+ session: draft.session,
38527
38614
  name: generatedName(draft),
38528
38615
  clientId: draft.clientId,
38529
38616
  additional: draft.mode === "new-tab",
@@ -38560,7 +38647,10 @@ var selectWorktree = (draft, tree) => {
38560
38647
  if (!tree.path || tree.vcs === "jj" && !tree.present)
38561
38648
  throw new AppError({ message: `Workspace ${tree.vcs === "jj" ? tree.name : tree.path} is unavailable; inspect its registered location before opening` });
38562
38649
  return {
38563
- ...changeDestination(draft, { path: tree.path, label: tree.vcs === "jj" ? tree.name : tree.path.split("/").filter(Boolean).at(-1) ?? tree.path }),
38650
+ ...changeDestination(draft, {
38651
+ path: tree.path,
38652
+ label: tree.vcs === "jj" ? tree.name : tree.path.split("/").filter(Boolean).at(-1) ?? tree.path
38653
+ }),
38564
38654
  ...tree.vcs === "jj" ? {
38565
38655
  sourcePath: tree.path,
38566
38656
  projectChoice: draft.projectChoice?.source && draft.projectChoice.source.hostId === draft.host?.hostId ? { ...draft.projectChoice, source: { ...draft.projectChoice.source, checkoutPath: tree.path } } : draft.projectChoice
@@ -38572,10 +38662,9 @@ var typeWorktreeName = (draft, name, mainline) => ({
38572
38662
  worktreeName: name,
38573
38663
  destination: draft.destination && !draft.destination.path ? draft.destination : draft.project?.vcs === "jj" && !draft.clone && mainline ? { revision: mainline.revision.commitId, label: mainline.label } : undefined
38574
38664
  });
38575
- var resolveBranch = (draft, branch, path, existing) => existing ? changeDestination(draft, { path, label: path.split("/").filter(Boolean).at(-1) ?? path }) : changeDestination(draft, { branch, label: branch }, draft.worktreeName ?? branch);
38576
38665
  var selectRevision = (draft, choice) => changeDestination(draft, { revision: choice.revision.commitId, label: choice.label }, draft.worktreeName);
38577
38666
  var cloneInputFor = (draft) => {
38578
- if (!draft.host || !draft.clone || !draft.sessionId || !draft.clone.repo.startsWith("/"))
38667
+ if (!draft.host || !draft.clone || !draft.session || !draft.clone.repo.startsWith("/"))
38579
38668
  return;
38580
38669
  if (draft.clone.vcs === "jj")
38581
38670
  return {
@@ -38588,7 +38677,7 @@ var cloneInputFor = (draft) => {
38588
38677
  ...draft.clone.revision ? { revision: draft.clone.revision } : {}
38589
38678
  },
38590
38679
  repo: draft.clone.repo,
38591
- sessionId: draft.sessionId,
38680
+ session: draft.session,
38592
38681
  clientId: draft.clientId,
38593
38682
  name: generatedName(draft),
38594
38683
  ...draft.worktreeName ? { worktreeName: draft.worktreeName } : {},
@@ -38606,7 +38695,7 @@ var cloneInputFor = (draft) => {
38606
38695
  branch: draft.clone.branch
38607
38696
  },
38608
38697
  repo: draft.clone.repo,
38609
- sessionId: draft.sessionId,
38698
+ session: draft.session,
38610
38699
  clientId: draft.clientId,
38611
38700
  name: generatedName(draft),
38612
38701
  branch: draft.destination.branch,
@@ -38626,8 +38715,8 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38626
38715
  let error2;
38627
38716
  let plan;
38628
38717
  let clonePlan;
38718
+ let cloneRoot = "";
38629
38719
  let cloneRoots = [];
38630
- let submitAfterEdit = false;
38631
38720
  let contextPath;
38632
38721
  const resizePopup = yield* makePopupSizer;
38633
38722
  let activeView;
@@ -38705,14 +38794,7 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38705
38794
  return `\x1B[H\x1B[2J${renderFormFrame(view, focused, true, columns, rows2)}${editor}`;
38706
38795
  }),
38707
38796
  clear: () => exports_Effect.succeed(""),
38708
- process: (event, state) => {
38709
- if (event._tag === "Event")
38710
- return exports_Effect.succeed({ _tag: "NextFrame", state });
38711
- const action = advanceInputChoice(state, event.input, options.choices, options.selectionOnly);
38712
- if (event.input.key.ctrl && event.input.key.name === "s" && action._tag === "Submit" && action.value)
38713
- submitAfterEdit = true;
38714
- return exports_Effect.succeed(action);
38715
- }
38797
+ process: (event, state) => exports_Effect.succeed(event._tag === "Event" ? { _tag: "NextFrame", state } : advanceInputChoice(state, event.input, options.choices, options.selectionOnly))
38716
38798
  }));
38717
38799
  return result4 === null ? yield* exports_Effect.fail(new exports_Terminal.QuitError({})) : result4;
38718
38800
  }, exports_Effect.scoped);
@@ -38738,31 +38820,7 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38738
38820
  error2 = undefined;
38739
38821
  }
38740
38822
  });
38741
- const refresh = exports_Effect.gen(function* () {
38742
- plan = undefined;
38743
- clonePlan = undefined;
38744
- if (!draft.host)
38745
- return;
38746
- const cloneInput = cloneInputFor(draft);
38747
- if (cloneInput) {
38748
- const result5 = yield* exports_Effect.result(reviewClone(draft.host, command, cloneInput));
38749
- if (exports_Result.isSuccess(result5)) {
38750
- clonePlan = result5.success;
38751
- error2 = undefined;
38752
- } else
38753
- error2 = problem(result5.failure);
38754
- return;
38755
- }
38756
- const input = inputFor(draft);
38757
- if (!input)
38758
- return;
38759
- const result4 = yield* exports_Effect.result(review(draft.host, command, input));
38760
- if (exports_Result.isSuccess(result4)) {
38761
- plan = result4.success;
38762
- error2 = undefined;
38763
- } else
38764
- error2 = problem(result4.failure);
38765
- });
38823
+ const clonePath = (choice) => choice.name && choice.name !== "." && choice.name !== ".." && !/[/\\\p{Cc}\u202a-\u202e\u2066-\u2069]/u.test(choice.name) ? `${cloneRoot.replace(/\/$/, "")}/${choice.name}` : undefined;
38766
38824
  const known = (host, repository4, checkout) => ({
38767
38825
  name: repository4.name,
38768
38826
  source: {
@@ -38794,17 +38852,16 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38794
38852
  };
38795
38853
  });
38796
38854
  const cloneDestination2 = exports_Effect.fnUntraced(function* (choice, host) {
38797
- const picked = yield* inputChoice({
38798
- message: `Clone destination on ${host.label} (absolute path; only pushed history transfers)`,
38799
- choices: cloneRoots.map((root) => ({
38800
- value: `${root.replace(/\/$/, "")}/${choice.name}`,
38801
- title: choice.name,
38802
- description: `${root.replace(/\/$/, "")}/${choice.name} \xB7 configured root suggestion`
38803
- }))
38804
- });
38805
- const repo = picked.kind === "selected" ? picked.value : picked.text.trim();
38855
+ let repo = clonePath(choice);
38856
+ if (!repo) {
38857
+ const picked = yield* inputChoice({
38858
+ message: "Project name is not a safe clone directory; type an absolute clone destination",
38859
+ choices: []
38860
+ });
38861
+ repo = picked.kind === "selected" ? picked.value : picked.text.trim();
38862
+ }
38806
38863
  if (!repo.startsWith("/"))
38807
- return yield* exports_Effect.fail(new AppError({ message: "Clone destination must be an absolute path on the selected machine" }));
38864
+ return yield* exports_Effect.fail(new AppError({ message: "Clone destination must be an absolute path on this machine" }));
38808
38865
  yield* proposeClone(choice, host, repo);
38809
38866
  });
38810
38867
  const bindProject = exports_Effect.fnUntraced(function* (choice, host, available) {
@@ -38812,17 +38869,17 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38812
38869
  let path = source?.machineKey === host.key && source.hostId === host.hostId ? source.checkoutPath ?? source.repository.path : undefined;
38813
38870
  if (!path && choice.path?.startsWith("/"))
38814
38871
  path = choice.path;
38872
+ if (source && (source.machineKey !== host.key || source.hostId !== host.hostId)) {
38873
+ if (path)
38874
+ yield* proposeClone(choice, host, path);
38875
+ else
38876
+ yield* cloneDestination2(choice, host);
38877
+ return;
38878
+ }
38815
38879
  if (!path) {
38816
38880
  const directory = yield* inputChoice({
38817
- message: `Project directory on ${host.label} (existing checkout or missing clone destination; absolute path)`,
38818
- choices: [
38819
- ...available.map((repo) => ({ value: repo.path, title: repo.name, description: repo.path })),
38820
- ...cloneRoots.map((root) => ({
38821
- value: `${root.replace(/\/$/, "")}/${choice.name}`,
38822
- title: choice.name,
38823
- description: `${root.replace(/\/$/, "")}/${choice.name} \xB7 configured root suggestion`
38824
- }))
38825
- ]
38881
+ message: `Project directory on ${host.label} (existing checkout; absolute path)`,
38882
+ choices: available.map((repo) => ({ value: repo.path, title: repo.name, description: repo.path }))
38826
38883
  });
38827
38884
  path = directory.kind === "selected" ? directory.value : directory.text.trim();
38828
38885
  }
@@ -38851,6 +38908,7 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38851
38908
  sessions = [];
38852
38909
  plan = undefined;
38853
38910
  clonePlan = undefined;
38911
+ cloneRoot = "";
38854
38912
  cloneRoots = [];
38855
38913
  error2 = problem(connected.failure);
38856
38914
  return;
@@ -38868,11 +38926,13 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38868
38926
  sessions = [];
38869
38927
  plan = undefined;
38870
38928
  clonePlan = undefined;
38929
+ cloneRoot = "";
38871
38930
  cloneRoots = [];
38872
38931
  error2 = problem(discovered.failure);
38873
38932
  return;
38874
38933
  }
38875
38934
  const found = discovered.success;
38935
+ cloneRoot = found.cloneRoot;
38876
38936
  cloneRoots = found.roots;
38877
38937
  projects = [
38878
38938
  ...projects.filter((item) => item.source?.machineKey !== machine.key || item.source.hostId !== connected.success.hostId),
@@ -38881,7 +38941,7 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38881
38941
  sessions = found.sessions;
38882
38942
  draft = {
38883
38943
  ...draft,
38884
- sessionId: sessions.some((item) => item.id === draft.sessionId) ? draft.sessionId : connected.success.local && origin2.sessionId && sessions.some((item) => item.id === origin2.sessionId) ? origin2.sessionId : sessions.length === 1 ? sessions[0]?.id : undefined,
38944
+ session: draft.session?.kind === "new" ? draft.session : sessions.some((item) => item.id === (draft.session?.kind === "existing" ? draft.session.id : undefined)) ? draft.session : connected.success.local && origin2.sessionId && sessions.some((item) => item.id === origin2.sessionId) ? { kind: "existing", id: origin2.sessionId } : sessions.length === 1 ? { kind: "existing", id: sessions[0].id } : undefined,
38885
38945
  clientId: focusClient(found.clients)
38886
38946
  };
38887
38947
  if (!draft.projectChoice && found.checkout && discoveredContext) {
@@ -38910,10 +38970,15 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38910
38970
  draft = changeProject(draft, inspected.success.project);
38911
38971
  if (inspected.success.checkout.vcs === "jj" && !draft.sourcePath)
38912
38972
  draft = { ...draft, sourcePath: inspected.success.checkout.path };
38973
+ if (!draft.destination) {
38974
+ const checkoutPath = inspected.success.checkout.path;
38975
+ const tree = inspected.success.worktrees.find((item) => item.path === checkoutPath && (item.vcs === "jj" ? item.present : !item.bare && !item.prunable));
38976
+ if (tree)
38977
+ draft = selectWorktree(draft, tree);
38978
+ }
38913
38979
  }
38914
38980
  }
38915
38981
  error2 = undefined;
38916
- yield* refresh;
38917
38982
  });
38918
38983
  const formView = (initializing = false) => {
38919
38984
  const rows2 = [
@@ -38926,31 +38991,57 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38926
38991
  },
38927
38992
  {
38928
38993
  id: "destination",
38929
- label: draft.project?.vcs === "jj" || draft.clone?.vcs === "jj" ? "Workspace" : "Worktree",
38930
- value: draft.clone ? draft.worktreeName ?? (draft.clone.vcs === "jj" ? "Use cloned default workspace" : "Use branch checkout after clone") : draft.worktreeName ?? draft.destination?.label ?? "Choose checkout or type new directory name",
38994
+ label: draft.clone ? "Clone to" : draft.project?.vcs === "jj" ? "Workspace" : "Checkout",
38995
+ 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"),
38996
+ detail: draft.clone?.repo ?? draft.destination?.path,
38931
38997
  disabled: !draft.host || !(draft.project || draft.clone)
38932
38998
  },
38933
- {
38934
- id: "branch",
38935
- label: draft.project?.vcs === "jj" || draft.clone?.vcs === "jj" ? "Start from" : "Branch",
38936
- value: draft.project?.vcs === "jj" || draft.clone?.vcs === "jj" ? draft.destination?.revision ? draft.destination.label : draft.clone ? "Cloned default" : "Select or type a revision" : draft.destination?.branch ?? (draft.destination?.path && plan?.vcs === "git" ? plan.branch ?? "Existing checkout" : "Select or type branch"),
38937
- disabled: !draft.host || !(draft.project || draft.clone) || (draft.project?.vcs === "jj" ? !draft.worktreeName : draft.clone?.vcs === "jj" ? false : !(draft.clone || draft.worktreeName || draft.destination?.path))
38938
- },
38939
38999
  {
38940
39000
  id: "session",
38941
39001
  label: "Session",
38942
- value: sessions.find((s) => s.id === draft.sessionId)?.label ?? draft.sessionId ?? "Choose exact session",
38943
- detail: draft.sessionId,
39002
+ 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"),
39003
+ detail: draft.session?.kind === "existing" ? draft.session.id : draft.session?.kind === "new" ? "Create on confirmation" : undefined,
38944
39004
  disabled: !draft.host
38945
- },
38946
- { id: "mode", label: "Mode", value: draft.clone ? "New tab (clone task)" : draft.mode === "auto" ? "Reuse matching tab, otherwise new tab" : draft.mode === "new-tab" ? "Always new tab" : "Split matching tab, otherwise new tab", disabled: !draft.host || !!draft.clone }
39005
+ }
38947
39006
  ];
39007
+ if (draft.project?.vcs === "jj" && !draft.destination?.path || draft.clone?.vcs === "jj")
39008
+ rows2.push({
39009
+ id: "branch",
39010
+ label: "Start from",
39011
+ value: draft.destination?.revision ? draft.destination.label : draft.clone ? "Cloned default" : "Select or type revision",
39012
+ disabled: !draft.host || !!draft.project && !draft.worktreeName
39013
+ });
39014
+ if (draft.clone?.vcs === "git")
39015
+ rows2.push({ id: "branch", label: "Branch", value: draft.destination?.branch ?? "Select or type branch", disabled: !draft.host });
39016
+ if (draft.clone || draft.project?.vcs === "git" && draft.destination?.branch && !draft.destination.path)
39017
+ rows2.push({
39018
+ id: "checkoutName",
39019
+ label: draft.clone?.vcs === "jj" ? "Workspace" : "Directory",
39020
+ value: draft.worktreeName ?? (draft.clone?.vcs === "jj" ? "Use cloned default workspace" : "Default (derived from branch)"),
39021
+ disabled: !draft.host
39022
+ });
39023
+ if (!draft.clone)
39024
+ rows2.push({
39025
+ id: "mode",
39026
+ label: "Mode",
39027
+ value: draft.mode === "auto" ? "Reuse matching tab, otherwise new tab" : draft.mode === "new-tab" ? "Always new tab" : "Split matching tab, otherwise new tab",
39028
+ disabled: !draft.host
39029
+ });
39030
+ const safeOpen = !draft.clone && !!draft.destination?.path && draft.session?.kind === "existing";
38948
39031
  return {
38949
- rows: rows2.filter((row) => !(row.id === "branch" && draft.project?.vcs === "jj" && !draft.clone && !!draft.destination?.path)).map((row) => ({ ...row, disabled: initializing || row.disabled })),
38950
- submitLabel: clonePlan?.label ?? plan?.label ?? (draft.clone ? "Clone & Open" : "Open worktree"),
38951
- submitDisabled: initializing || !draft.host || !(clonePlan || plan),
38952
- notice: [clonePlan?.detail, clonePlan?.warning, plan?.detail, plan?.warning].filter(Boolean).join(" \xB7 ") || undefined,
38953
- 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.sessionId ? "Select an exact Rex session" : undefined),
39032
+ rows: rows2.map((row) => ({ ...row, disabled: initializing || row.disabled })),
39033
+ submitLabel: clonePlan?.label ?? plan?.label ?? (draft.clone ? "Review clone" : safeOpen ? "Open checkout" : "Review & open"),
39034
+ submitDisabled: initializing || !draft.host || !(cloneInputFor(draft) || inputFor(draft)),
39035
+ notice: [
39036
+ clonePlan || plan ? "Review this action; submit again to launch" : draft.clone ? "Only pushed history transfers" : undefined,
39037
+ plan ? `Destination: ${plan.path}` : undefined,
39038
+ clonePlan?.detail,
39039
+ clonePlan?.vcs === "jj" ? `Start from: ${draft.destination?.revision ? `${draft.destination.label} (${draft.destination.revision})` : "cloned default"}` : undefined,
39040
+ clonePlan?.warning,
39041
+ plan?.detail,
39042
+ plan?.warning
39043
+ ].filter(Boolean).join(" \xB7 ") || undefined,
39044
+ 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),
38954
39045
  fitWarning: activeView?.fitWarning
38955
39046
  };
38956
39047
  };
@@ -38969,27 +39060,27 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
38969
39060
  const initialAction = yield* exports_Effect.raceFirst(initialize, chooseField(initialView, "project").pipe(exports_Effect.catchTag("QuitError", () => exports_Effect.succeed("cancel"))));
38970
39061
  if (initialAction === "cancel")
38971
39062
  return;
38972
- let queuedSubmit = false;
38973
39063
  while (true) {
38974
39064
  const view = formView();
38975
39065
  activeView = view;
38976
- const action = queuedSubmit ? "submit" : yield* chooseField(view, focused).pipe(exports_Effect.catchTag("QuitError", () => exports_Effect.succeed("cancel")));
38977
- queuedSubmit = false;
39066
+ const action = yield* chooseField(view, focused).pipe(exports_Effect.catchTag("QuitError", () => exports_Effect.succeed("cancel")));
38978
39067
  focused = action;
38979
39068
  if (action === "cancel")
38980
39069
  return;
38981
39070
  if (action === "submit") {
38982
39071
  const cloneInput = cloneInputFor(draft);
38983
- if (draft.host && cloneInput && clonePlan) {
39072
+ if (!draft.host || !(cloneInput || inputFor(draft)))
39073
+ continue;
39074
+ if (cloneInput) {
38984
39075
  const current2 = yield* exports_Effect.result(reviewClone(draft.host, command, cloneInput));
38985
39076
  if (exports_Result.isFailure(current2)) {
38986
39077
  error2 = problem(current2.failure);
38987
39078
  clonePlan = undefined;
38988
39079
  continue;
38989
39080
  }
38990
- if (!sameClonePlan(current2.success, clonePlan)) {
39081
+ if (!clonePlan || !sameClonePlan(current2.success, clonePlan)) {
39082
+ error2 = clonePlan ? "Clone destination or Rex target changed; review the updated URL and destination before submitting again" : undefined;
38991
39083
  clonePlan = current2.success;
38992
- error2 = "Clone destination or Rex target changed; review the updated URL and destination before submitting again";
38993
39084
  continue;
38994
39085
  }
38995
39086
  const launched2 = yield* exports_Effect.result(submitClone(draft.host, command, cloneInput, clonePlan));
@@ -39012,7 +39103,7 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39012
39103
  return;
39013
39104
  }
39014
39105
  const input = inputFor(draft);
39015
- if (!draft.host || !input || !plan)
39106
+ if (!input)
39016
39107
  continue;
39017
39108
  const current = yield* exports_Effect.result(review(draft.host, command, input));
39018
39109
  if (exports_Result.isFailure(current)) {
@@ -39020,11 +39111,19 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39020
39111
  plan = undefined;
39021
39112
  continue;
39022
39113
  }
39023
- if (!sameLaunchPlan(current.success, plan)) {
39024
- plan = current.success;
39114
+ if (plan && !sameLaunchPlan(current.success, plan)) {
39025
39115
  error2 = "Destination or Rex target changed; review the updated action before submitting again";
39116
+ plan = current.success;
39026
39117
  continue;
39027
39118
  }
39119
+ if (!plan) {
39120
+ const safeOpen = !!draft.destination?.path && draft.session?.kind === "existing" && current.success.checkout === "existing" && current.success.path === draft.destination.path && safeDisplayText(draft.destination.path) === draft.destination.path && !current.success.detail && !current.success.warning && !view.fitWarning && naturalFormRows(view, yield* terminal.columns) + 1 <= (yield* terminal.rows);
39121
+ plan = current.success;
39122
+ if (!safeOpen) {
39123
+ error2 = undefined;
39124
+ continue;
39125
+ }
39126
+ }
39028
39127
  const launched = yield* exports_Effect.result(submit(draft.host, command, input, plan));
39029
39128
  if (exports_Result.isFailure(launched)) {
39030
39129
  launchAcknowledged = true;
@@ -39047,7 +39146,7 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39047
39146
  }
39048
39147
  if (view.rows.find((row) => row.id === action)?.disabled)
39049
39148
  continue;
39050
- const hadCloneReview = !!clonePlan;
39149
+ error2 = undefined;
39051
39150
  const editing = yield* exports_Effect.result(exports_Effect.gen(function* () {
39052
39151
  if (action === "machine") {
39053
39152
  yield* loadMachines;
@@ -39081,14 +39180,17 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39081
39180
  draft = changeProject(draft, inspected.project);
39082
39181
  if (inspected.checkout.vcs === "jj")
39083
39182
  draft = { ...draft, sourcePath: inspected.checkout.path };
39183
+ const tree = inspected.worktrees.find((item) => item.path === inspected.checkout.path && (item.vcs === "jj" ? item.present : !item.bare && !item.prunable));
39184
+ if (tree)
39185
+ draft = selectWorktree(draft, tree);
39084
39186
  }
39085
39187
  projects = [
39086
39188
  ...projects.filter((item) => item.source?.machineKey !== host.key || item.source.hostId !== host.hostId),
39087
39189
  ...found.projects.map((repo) => known(host, repo, found.checkout))
39088
39190
  ];
39089
39191
  sessions = found.sessions;
39090
- if (!sessions.some((item) => item.id === draft.sessionId))
39091
- draft = { ...draft, sessionId: sessions.length === 1 ? sessions[0]?.id : undefined };
39192
+ if (draft.session?.kind === "existing" && !sessions.some((item) => item.id === (draft.session?.kind === "existing" ? draft.session.id : undefined)))
39193
+ draft = { ...draft, session: sessions.length === 1 ? { kind: "existing", id: sessions[0].id } : undefined };
39092
39194
  draft = { ...draft, clientId: focusClient(found.clients) };
39093
39195
  } else
39094
39196
  draft = changeProjectChoice(draft, choice);
@@ -39098,7 +39200,7 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39098
39200
  if (draft.clone) {
39099
39201
  const clone = draft.clone;
39100
39202
  const picked = yield* inputChoice({
39101
- message: clone.vcs === "jj" ? "Clone destination: absolute path or optional separate workspace name (none to clear)" : "Clone destination: type absolute path; type checkout name for optional separate worktree",
39203
+ message: "Clone to (absolute destination path on selected machine)",
39102
39204
  choices: [
39103
39205
  { value: clone.repo, title: "Current clone destination", description: clone.repo },
39104
39206
  ...cloneRoots.map((root) => ({
@@ -39108,57 +39210,73 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39108
39210
  }))
39109
39211
  ]
39110
39212
  });
39111
- if (picked.kind === "selected" || picked.text.startsWith("/")) {
39112
- const repo = picked.kind === "selected" ? picked.value : picked.text.trim();
39113
- draft = { ...draft, clone: { ...clone, repo } };
39114
- } else {
39115
- const name = picked.text.trim();
39116
- if (name === "none")
39117
- draft = { ...draft, worktreeName: undefined };
39118
- else {
39119
- if (!name || /[\p{ASCII}&&\p{Cc}]/v.test(name) || name.split(/[\\/]/).some((part) => !part || part === "." || part === ".."))
39120
- return yield* exports_Effect.fail(new AppError({ message: "Type an absolute clone destination or valid checkout name (none to clear)" }));
39121
- draft = { ...draft, worktreeName: name };
39122
- }
39123
- }
39213
+ const repo = (picked.kind === "selected" ? picked.value : picked.text).trim();
39214
+ if (!repo.startsWith("/"))
39215
+ return yield* exports_Effect.fail(new AppError({ message: "Clone destination must be an absolute path on this machine" }));
39216
+ draft = { ...draft, clone: { ...clone, repo } };
39124
39217
  } else {
39125
39218
  const found = yield* inspectWorktrees(draft.host, command, draft.project.vcs === "jj" ? draft.sourcePath ?? draft.project.path : draft.project.path);
39126
39219
  const trees = found.worktrees.filter((tree) => tree.vcs === "jj" || !tree.bare && !tree.prunable);
39220
+ const git2 = draft.project.vcs === "git";
39127
39221
  const picked = yield* inputChoice({
39128
- message: draft.project.vcs === "jj" ? "Workspace (select existing, Clone this project, or type new workspace name)" : "Worktree (select checkout, Clone this project, or type new directory name)",
39222
+ message: git2 ? "Checkout (select exact worktree or branch, or type new branch)" : "Workspace (select existing, Clone this project, or type new workspace name)",
39129
39223
  choices: [
39130
39224
  ...trees.map((tree) => ({
39131
39225
  value: tree,
39132
39226
  title: tree.vcs === "jj" ? tree.name : tree.path.split("/").filter(Boolean).at(-1) ?? tree.path,
39133
39227
  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}`
39134
39228
  })),
39229
+ ...git2 ? found.branches.map((branch) => ({
39230
+ value: { kind: "branch", value: branch },
39231
+ title: `Branch: ${branch}`,
39232
+ description: trees.find((tree) => tree.vcs === "git" && tree.branch === branch)?.path ?? "Free branch \u2014 attach new checkout"
39233
+ })) : [],
39135
39234
  ...draft.projectChoice?.source ? [{
39136
39235
  value: "clone",
39137
39236
  title: "Clone this project\u2026",
39138
- description: "Choose a new absolute destination; only published history transfers"
39237
+ description: clonePath(draft.projectChoice) ? `Propose ${clonePath(draft.projectChoice)} \xB7 only pushed history transfers` : "Choose an absolute clone destination \xB7 only pushed history transfers"
39139
39238
  }] : []
39140
39239
  ]
39141
39240
  });
39142
39241
  if (picked.kind === "selected") {
39143
39242
  if (picked.value === "clone")
39144
39243
  yield* cloneDestination2(draft.projectChoice, draft.host);
39145
- else {
39244
+ else if ("kind" in picked.value) {
39245
+ const branch = picked.value.value;
39246
+ const existing = trees.find((tree) => tree.vcs === "git" && tree.branch === branch);
39247
+ draft = existing ? selectWorktree(draft, existing) : changeDestination(draft, { branch, label: branch }, draft.worktreeName);
39248
+ } else {
39146
39249
  if (picked.value.vcs === "jj" && (!picked.value.present || !picked.value.path))
39147
39250
  return yield* exports_Effect.fail(new AppError({ message: `Workspace ${picked.value.name} is unavailable; inspect its registered location before opening` }));
39148
39251
  draft = selectWorktree(draft, picked.value);
39149
39252
  }
39150
39253
  } else {
39151
39254
  const name = picked.text.trim();
39152
- if (!name || name.startsWith("/") || /[\p{ASCII}&&\p{Cc}]/v.test(name) || name.split(/[\\/]/).some((part) => !part || part === "." || part === ".."))
39153
- return yield* exports_Effect.fail(new AppError({ message: "Invalid workspace or worktree name" }));
39154
- const candidate = typeWorktreeName(draft, name, draft.project.vcs === "jj" ? found.revisions.find((choice) => choice.expression === "trunk()") : undefined);
39155
- if (draft.project.vcs === "git" && candidate.destination?.branch) {
39156
- const inspected = yield* inspectBranch(draft.host, command, draft.project.path, candidate.destination.branch, name);
39157
- draft = resolveBranch(candidate, inspected.branch, inspected.path, inspected.existing);
39255
+ if (!name || name.startsWith("-") && git2 || /[\p{ASCII}&&\p{Cc}]/v.test(name) || !git2 && (name.startsWith("/") || name.split(/[\\/]/).some((part) => !part || part === "." || part === "..")))
39256
+ return yield* exports_Effect.fail(new AppError({ message: git2 ? "Branch name must be a valid Git branch" : "Invalid workspace name" }));
39257
+ if (git2) {
39258
+ const existing = trees.find((tree) => tree.vcs === "git" && tree.branch === name);
39259
+ draft = existing ? selectWorktree(draft, existing) : changeDestination(draft, { branch: name, label: name }, draft.worktreeName);
39158
39260
  } else
39159
- draft = candidate;
39261
+ draft = typeWorktreeName(draft, name, found.revisions.find((choice) => choice.expression === "trunk()"));
39160
39262
  }
39161
39263
  }
39264
+ } else if (action === "checkoutName") {
39265
+ const picked = yield* inputChoice({
39266
+ message: draft.clone?.vcs === "jj" ? "Optional separate workspace name" : "Optional custom checkout directory name",
39267
+ choices: [
39268
+ { value: null, title: "Use default", description: "No separate custom name" },
39269
+ ...draft.worktreeName ? [{ value: draft.worktreeName, title: "Current custom name" }] : []
39270
+ ]
39271
+ });
39272
+ if (picked.kind === "selected" && picked.value === null)
39273
+ draft = { ...draft, worktreeName: undefined };
39274
+ else {
39275
+ const name = (picked.kind === "selected" ? picked.value : picked.text).trim();
39276
+ if (!name || /[\p{ASCII}&&\p{Cc}]/v.test(name) || name.split(/[\\/]/).some((part) => !part || part === "." || part === ".."))
39277
+ return yield* exports_Effect.fail(new AppError({ message: "Invalid custom checkout name" }));
39278
+ draft = { ...draft, worktreeName: name };
39279
+ }
39162
39280
  } else if (action === "branch") {
39163
39281
  if (!draft.host || !(draft.project || draft.clone))
39164
39282
  return yield* exports_Effect.fail(new AppError({ message: "Select a project and machine before choosing a base or branch" }));
@@ -39221,50 +39339,35 @@ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effec
39221
39339
  if (!branch || branch.startsWith("-") || /[\p{ASCII}&&\p{Cc}]/v.test(branch))
39222
39340
  return yield* exports_Effect.fail(new AppError({ message: "Branch name must be a valid Git branch" }));
39223
39341
  draft = { ...draft, destination: { branch, label: branch } };
39224
- } else {
39225
- const found = yield* inspectWorktrees(draft.host, command, draft.project.path);
39226
- const picked = yield* inputChoice({
39227
- message: "Branch (select existing or type new branch)",
39228
- choices: found.branches.map((branch2) => ({
39229
- value: branch2,
39230
- title: branch2,
39231
- description: found.worktrees.find((tree) => tree.vcs === "git" && tree.branch === branch2)?.path ?? "Free branch \u2014 attach new checkout"
39232
- }))
39233
- });
39234
- const branch = picked.kind === "selected" ? picked.value : picked.text;
39235
- if (!branch.trim())
39236
- return yield* exports_Effect.fail(new AppError({ message: "Branch name is required" }));
39237
- const inspected = yield* inspectBranch(draft.host, command, draft.project.path, branch, draft.worktreeName);
39238
- draft = resolveBranch(draft, inspected.branch, inspected.path, inspected.existing);
39239
39342
  }
39240
39343
  } else if (action === "session") {
39241
39344
  if (!draft.host)
39242
39345
  return yield* exports_Effect.fail(new AppError({ message: "Select a machine before choosing a session" }));
39243
39346
  const found = yield* discover(draft.host, command);
39244
39347
  sessions = found.sessions;
39245
- if (!sessions.length)
39246
- return yield* exports_Effect.fail(new AppError({ message: "No Rex sessions available on selected machine" }));
39247
39348
  draft = { ...draft, clientId: focusClient(found.clients) };
39248
- draft = { ...draft, sessionId: yield* choose("Exact Rex session", sessions.map((item) => selected(item.id, item.id === draft.sessionId, item.label, item.id))) };
39349
+ const picked = yield* inputChoice({
39350
+ message: "Session (select existing or type new name)",
39351
+ choices: sessions.map((item) => ({ value: item.id, title: item.label, description: item.id }))
39352
+ });
39353
+ draft = { ...draft, session: picked.kind === "selected" ? { kind: "existing", id: picked.value } : { kind: "new", name: picked.text } };
39249
39354
  } else if (action === "mode") {
39250
- draft = { ...draft, mode: yield* choose("Open mode", [
39251
- selected("auto", draft.mode === "auto", "Reuse matching tab", "Focus existing task, otherwise open new tab"),
39252
- selected("new-tab", draft.mode === "new-tab", "Always new tab"),
39253
- selected("split", draft.mode === "split", "Split matching task", "Opens new tab when no live target exists")
39254
- ]) };
39355
+ draft = {
39356
+ ...draft,
39357
+ mode: yield* choose("Open mode", [
39358
+ selected("auto", draft.mode === "auto", "Reuse matching tab", "Focus existing task, otherwise open new tab"),
39359
+ selected("new-tab", draft.mode === "new-tab", "Always new tab"),
39360
+ selected("split", draft.mode === "split", "Split matching task", "Opens new tab when no live target exists")
39361
+ ])
39362
+ };
39255
39363
  }
39256
39364
  }));
39257
39365
  if (exports_Result.isFailure(editing)) {
39258
- submitAfterEdit = false;
39259
39366
  if (!exports_Terminal.isQuitError(editing.failure))
39260
39367
  error2 = problem(editing.failure);
39261
39368
  } else {
39262
- if (draft.host) {
39263
- error2 = undefined;
39264
- yield* refresh;
39265
- }
39266
- queuedSubmit = submitAfterEdit && !formView().submitDisabled && (!draft.clone || hadCloneReview);
39267
- submitAfterEdit = false;
39369
+ plan = undefined;
39370
+ clonePlan = undefined;
39268
39371
  }
39269
39372
  }
39270
39373
  }).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)))));
@@ -39423,7 +39526,7 @@ Run rex config reload to activate.`}`);
39423
39526
  input = {
39424
39527
  vcs,
39425
39528
  repo: repoPath,
39426
- sessionId: flags["--session"],
39529
+ session: { kind: "existing", id: flags["--session"] },
39427
39530
  name: flags["--name"],
39428
39531
  branch: flags["--branch"],
39429
39532
  worktreeName: flags["--worktree-name"],
@@ -39438,7 +39541,7 @@ Run rex config reload to activate.`}`);
39438
39541
  input = {
39439
39542
  vcs,
39440
39543
  repo: repoPath,
39441
- sessionId: flags["--session"],
39544
+ session: { kind: "existing", id: flags["--session"] },
39442
39545
  name: flags["--name"],
39443
39546
  worktreeName: flags["--worktree-name"],
39444
39547
  revision: flags["--revision"],