@moberg_hr/work-tree 1.5.1 → 1.8.0

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.
package/dist/bin.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/bin.ts
4
- import fs44 from "fs";
5
- import path43 from "path";
4
+ import fs45 from "fs";
5
+ import path44 from "path";
6
6
  import chalk27 from "chalk";
7
7
 
8
8
  // src/cli.ts
@@ -323,26 +323,110 @@ async function fetchRemoteAsync(cwd) {
323
323
  git(["remote", "set-head", "origin", "--auto"], cwd);
324
324
  }
325
325
  }
326
- function rebaseOntoMain(branch, cwd) {
327
- const defaultBranch = getDefaultBranch(cwd) ?? "main";
328
- git(["fetch", "--quiet"], cwd);
329
- const base = remoteBranchExists(defaultBranch, cwd) ? `origin/${defaultBranch}` : defaultBranch;
330
- const result = git(["rebase", base, branch], cwd);
331
- if (result.exitCode !== 0) {
332
- git(["rebase", "--abort"], cwd);
333
- return result.stderr || "Rebase failed";
326
+ function gitAsync(args, cwd) {
327
+ debug("gitAsync", args.join(" "), `cwd=${cwd}`);
328
+ return new Promise((resolve) => {
329
+ execFile(
330
+ "git",
331
+ args,
332
+ { cwd, encoding: "utf-8", timeout: 6e4, windowsHide: true },
333
+ (err, stdout, stderr) => {
334
+ const r = {
335
+ stdout: (stdout ?? "").toString().trim(),
336
+ stderr: (stderr ?? "").toString().trim(),
337
+ exitCode: err ? err.code ?? 1 : 0
338
+ };
339
+ if (typeof r.exitCode !== "number") r.exitCode = 1;
340
+ if (r.exitCode !== 0) {
341
+ debug("gitAsync failed", { args, exitCode: r.exitCode, stderr: r.stderr });
342
+ }
343
+ resolve(r);
344
+ }
345
+ );
346
+ });
347
+ }
348
+ async function getDefaultBranchAsync(cwd) {
349
+ const result = await gitAsync(["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
350
+ if (result.exitCode === 0 && result.stdout) {
351
+ return result.stdout.replace(/^refs\/remotes\/origin\//, "");
334
352
  }
335
353
  return null;
336
354
  }
337
- function countConflicts(branch, cwd) {
338
- const defaultBranch = getDefaultBranch(cwd) ?? "main";
339
- const base = remoteBranchExists(defaultBranch, cwd) ? `origin/${defaultBranch}` : defaultBranch;
340
- const mergeBase = git(["merge-base", base, branch], cwd);
355
+ async function refExistsAsync(ref, cwd) {
356
+ return (await gitAsync(["rev-parse", "--verify", ref], cwd)).exitCode === 0;
357
+ }
358
+ async function checkSquashMergedAsync(branch, baseRef, cwd) {
359
+ const mb = await gitAsync(["merge-base", baseRef, branch], cwd);
360
+ if (mb.exitCode !== 0) return false;
361
+ const tree = await gitAsync(["rev-parse", `${branch}^{tree}`], cwd);
362
+ if (tree.exitCode !== 0) return false;
363
+ const dangling = await gitAsync(["commit-tree", tree.stdout, "-p", mb.stdout, "-m", ""], cwd);
364
+ if (dangling.exitCode !== 0) return false;
365
+ const cherry = await gitAsync(["cherry", baseRef, dangling.stdout], cwd);
366
+ if (cherry.exitCode !== 0) return false;
367
+ return cherry.stdout.startsWith("-");
368
+ }
369
+ async function checkMergeStatusAsync(branch, baseRef, cwd) {
370
+ const branchInBase = await gitAsync(["merge-base", "--is-ancestor", branch, baseRef], cwd);
371
+ if (branchInBase.exitCode !== 0) {
372
+ if (await checkSquashMergedAsync(branch, baseRef, cwd)) return "squash-merged";
373
+ return "unrelated";
374
+ }
375
+ const baseInBranch = await gitAsync(["merge-base", "--is-ancestor", baseRef, branch], cwd);
376
+ if (baseInBranch.exitCode === 0) return "merged";
377
+ const tip = await gitAsync(["rev-parse", branch], cwd);
378
+ if (tip.exitCode !== 0) return "unrelated";
379
+ const mainLine = await gitAsync(["rev-list", "--first-parent", "-n", "500", baseRef], cwd);
380
+ if (mainLine.exitCode === 0 && mainLine.stdout.includes(tip.stdout)) {
381
+ return "stale";
382
+ }
383
+ return "merged";
384
+ }
385
+ async function isBranchMergedAsync(branch, cwd, baseBranch) {
386
+ const defaultBranch = await getDefaultBranchAsync(cwd);
387
+ const bases = baseBranch ? [baseBranch] : [defaultBranch, "main", "master"].filter(
388
+ (b) => b !== null
389
+ );
390
+ const uniqueBases = [...new Set(bases)];
391
+ for (const base of uniqueBases) {
392
+ if (await refExistsAsync(`origin/${base}`, cwd)) {
393
+ const baseRef = `origin/${base}`;
394
+ const status = await checkMergeStatusAsync(branch, baseRef, cwd);
395
+ if (status === "merged") return { merged: true, into: baseRef, confidence: "merged" };
396
+ if (status === "squash-merged")
397
+ return { merged: true, into: baseRef, confidence: "squash-merged" };
398
+ if (status === "stale") return { merged: false, into: null, confidence: null };
399
+ }
400
+ if (await refExistsAsync(base, cwd)) {
401
+ const status = await checkMergeStatusAsync(branch, base, cwd);
402
+ if (status === "merged") return { merged: true, into: base, confidence: "merged" };
403
+ if (status === "squash-merged")
404
+ return { merged: true, into: base, confidence: "squash-merged" };
405
+ if (status === "stale") return { merged: false, into: null, confidence: null };
406
+ }
407
+ }
408
+ return { merged: false, into: null, confidence: null };
409
+ }
410
+ async function countConflictsAsync(branch, cwd) {
411
+ const defaultBranch = await getDefaultBranchAsync(cwd) ?? "main";
412
+ const base = await refExistsAsync(`origin/${defaultBranch}`, cwd) ? `origin/${defaultBranch}` : defaultBranch;
413
+ const mergeBase = await gitAsync(["merge-base", base, branch], cwd);
341
414
  if (mergeBase.exitCode !== 0) return 0;
342
- const result = git(["merge-tree", mergeBase.stdout, base, branch], cwd);
415
+ const result = await gitAsync(["merge-tree", mergeBase.stdout, base, branch], cwd);
343
416
  const conflicts = (result.stdout.match(/^<<<<<<< /gm) || []).length;
344
417
  return conflicts;
345
418
  }
419
+ async function rebaseOntoMainAsync(branch, cwd) {
420
+ const defaultBranch = await getDefaultBranchAsync(cwd) ?? "main";
421
+ await gitAsync(["fetch", "--quiet"], cwd);
422
+ const base = await refExistsAsync(`origin/${defaultBranch}`, cwd) ? `origin/${defaultBranch}` : defaultBranch;
423
+ const result = await gitAsync(["rebase", base, branch], cwd);
424
+ if (result.exitCode !== 0) {
425
+ await gitAsync(["rebase", "--abort"], cwd);
426
+ return result.stderr || "Rebase failed";
427
+ }
428
+ return null;
429
+ }
346
430
  function getUnpushedCommits(cwd) {
347
431
  const branch = getCurrentBranch(cwd);
348
432
  if (!branch) return "";
@@ -1575,11 +1659,12 @@ async function upsertSession(target, isGroup, branch, paths, jiraKey, baseBranch
1575
1659
  saveHistory(sessions);
1576
1660
  });
1577
1661
  }
1578
- async function upsertSessionWithPort(target, isGroup, branch, paths, config, jiraKey, baseBranch) {
1662
+ async function upsertSessionWithPort(target, isGroup, branch, paths, config, jiraKey, baseBranch, baseBranches) {
1579
1663
  return withHistoryLock(async () => {
1580
1664
  const sessions = loadHistory();
1581
1665
  const existing = findSession(sessions, target, branch);
1582
1666
  const now = (/* @__PURE__ */ new Date()).toISOString();
1667
+ const hasPerRepo = baseBranches && Object.keys(baseBranches).length > 0;
1583
1668
  let port = existing?.port;
1584
1669
  if (port === void 0) {
1585
1670
  const seedKey = sessionKey(target, branch);
@@ -1594,6 +1679,7 @@ async function upsertSessionWithPort(target, isGroup, branch, paths, config, jir
1594
1679
  existing.lastAccessedAt = now;
1595
1680
  if (jiraKey) existing.jiraKey = jiraKey;
1596
1681
  if (baseBranch && !existing.baseBranch) existing.baseBranch = baseBranch;
1682
+ if (hasPerRepo && !existing.baseBranches) existing.baseBranches = baseBranches;
1597
1683
  if (port !== void 0) existing.port = port;
1598
1684
  } else {
1599
1685
  const session = {
@@ -1606,6 +1692,7 @@ async function upsertSessionWithPort(target, isGroup, branch, paths, config, jir
1606
1692
  };
1607
1693
  if (jiraKey) session.jiraKey = jiraKey;
1608
1694
  if (baseBranch) session.baseBranch = baseBranch;
1695
+ if (hasPerRepo) session.baseBranches = baseBranches;
1609
1696
  if (port !== void 0) session.port = port;
1610
1697
  sessions.push(session);
1611
1698
  }
@@ -1721,6 +1808,62 @@ function copyConfigFiles(repoPath, worktreePath, patterns) {
1721
1808
  }
1722
1809
  }
1723
1810
 
1811
+ // src/core/base-spec.ts
1812
+ var BaseSpecError = class extends Error {
1813
+ constructor(message) {
1814
+ super(message);
1815
+ this.name = "BaseSpecError";
1816
+ }
1817
+ };
1818
+ function parseBaseSpec(raw) {
1819
+ const spec = { perRepo: {} };
1820
+ if (raw === void 0) return spec;
1821
+ const values = Array.isArray(raw) ? raw : [raw];
1822
+ for (const value of values) {
1823
+ const v = value.trim();
1824
+ if (!v) continue;
1825
+ const eq = v.indexOf("=");
1826
+ if (eq === -1) {
1827
+ if (spec.default !== void 0 && spec.default !== v) {
1828
+ throw new BaseSpecError(
1829
+ `Conflicting default --base values: '${spec.default}' and '${v}'`
1830
+ );
1831
+ }
1832
+ spec.default = v;
1833
+ } else {
1834
+ const alias = v.slice(0, eq).trim();
1835
+ const branch = v.slice(eq + 1).trim();
1836
+ if (!alias || !branch) {
1837
+ throw new BaseSpecError(
1838
+ `Invalid --base '${value}'. Use 'alias=branch' or a bare 'branch'.`
1839
+ );
1840
+ }
1841
+ const prior = spec.perRepo[alias];
1842
+ if (prior !== void 0 && prior !== branch) {
1843
+ throw new BaseSpecError(
1844
+ `Conflicting --base for '${alias}': '${prior}' and '${branch}'`
1845
+ );
1846
+ }
1847
+ spec.perRepo[alias] = branch;
1848
+ }
1849
+ }
1850
+ return spec;
1851
+ }
1852
+ function baseForAlias(spec, alias) {
1853
+ return spec.perRepo[alias] ?? spec.default;
1854
+ }
1855
+ function isEmptyBaseSpec(spec) {
1856
+ return spec.default === void 0 && Object.keys(spec.perRepo).length === 0;
1857
+ }
1858
+ function baseSpecOverrideAliases(spec) {
1859
+ return Object.keys(spec.perRepo);
1860
+ }
1861
+ function toBaseSpec(base) {
1862
+ if (base === void 0) return { perRepo: {} };
1863
+ if (typeof base === "string") return { default: base, perRepo: {} };
1864
+ return base;
1865
+ }
1866
+
1724
1867
  // src/core/worktree.ts
1725
1868
  function createSingleWorktree(repoPath, worktreePath, branchName, config, baseBranch) {
1726
1869
  debug("createSingleWorktree", { repoPath, worktreePath, branchName, baseBranch });
@@ -1926,8 +2069,9 @@ function removeSingleWorktree(repoPath, worktreePath, branchName, force) {
1926
2069
  return false;
1927
2070
  }
1928
2071
  }
1929
- async function setupWorktree(targetName, branchName, config, baseBranch, jiraKey) {
1930
- debug("setupWorktree", { targetName, branchName, baseBranch, jiraKey });
2072
+ async function setupWorktree(targetName, branchName, config, base, jiraKey) {
2073
+ const spec = toBaseSpec(base);
2074
+ debug("setupWorktree", { targetName, branchName, spec, jiraKey });
1931
2075
  const target = resolveProjectTarget(targetName, config);
1932
2076
  if (!target) {
1933
2077
  debug("setupWorktree: target not found", targetName);
@@ -1935,27 +2079,38 @@ async function setupWorktree(targetName, branchName, config, baseBranch, jiraKey
1935
2079
  }
1936
2080
  const workTreeDirName = branchName.replace(/\//g, "-");
1937
2081
  if (target.isGroup) {
1938
- return setupGroupWorktree(target.name, target.repoAliases, branchName, workTreeDirName, config, baseBranch, jiraKey);
2082
+ return setupGroupWorktree(target.name, target.repoAliases, branchName, workTreeDirName, config, spec, jiraKey);
1939
2083
  } else {
1940
- return setupSingleWorktree(targetName, branchName, workTreeDirName, config, baseBranch, jiraKey);
2084
+ return setupSingleWorktree(targetName, branchName, workTreeDirName, config, spec, jiraKey);
1941
2085
  }
1942
2086
  }
1943
- async function setupGroupWorktree(groupName, repoAliases, branchName, workTreeDirName, config, baseBranch, jiraKey) {
2087
+ async function setupGroupWorktree(groupName, repoAliases, branchName, workTreeDirName, config, spec, jiraKey) {
1944
2088
  const groupWorktreePath = path12.join(config.worktreesRoot, groupName, workTreeDirName);
1945
- if (baseBranch) {
2089
+ if (!isEmptyBaseSpec(spec)) {
2090
+ const unknownAliases = baseSpecOverrideAliases(spec).filter(
2091
+ (a) => !repoAliases.includes(a)
2092
+ );
2093
+ if (unknownAliases.length > 0) {
2094
+ console.error(
2095
+ `--base names repo(s) not in group '${groupName}': ${unknownAliases.join(", ")}. Group repos: ${repoAliases.join(", ")}`
2096
+ );
2097
+ return null;
2098
+ }
1946
2099
  const missingBase = [];
1947
2100
  const branchExists = [];
1948
2101
  for (const alias of repoAliases) {
1949
2102
  const repoPath = config.repos[alias];
1950
- if (!localBranchExists(baseBranch, repoPath) && !remoteBranchExists(baseBranch, repoPath)) {
1951
- missingBase.push(alias);
2103
+ const repoBase = baseForAlias(spec, alias);
2104
+ if (!repoBase) continue;
2105
+ if (!localBranchExists(repoBase, repoPath) && !remoteBranchExists(repoBase, repoPath)) {
2106
+ missingBase.push(`${alias} (${repoBase})`);
1952
2107
  }
1953
2108
  if (localBranchExists(branchName, repoPath) || remoteBranchExists(branchName, repoPath)) {
1954
2109
  branchExists.push(alias);
1955
2110
  }
1956
2111
  }
1957
2112
  if (missingBase.length > 0) {
1958
- console.error(`Base branch '${baseBranch}' not found in: ${missingBase.join(", ")}`);
2113
+ console.error(`Base branch not found in: ${missingBase.join(", ")}`);
1959
2114
  return null;
1960
2115
  }
1961
2116
  if (branchExists.length > 0) {
@@ -1968,14 +2123,17 @@ async function setupGroupWorktree(groupName, repoAliases, branchName, workTreeDi
1968
2123
  console.log("");
1969
2124
  fs13.mkdirSync(groupWorktreePath, { recursive: true });
1970
2125
  const createdWorktrees = [];
2126
+ const baseBranches = {};
1971
2127
  for (const alias of repoAliases) {
1972
2128
  const repoPath = config.repos[alias];
1973
2129
  const repoName = path12.basename(repoPath);
1974
2130
  const subWorktreePath = path12.join(groupWorktreePath, repoName);
2131
+ const repoBase = baseForAlias(spec, alias);
1975
2132
  console.log(chalk5.cyan(`[${alias}] (${repoName}):`));
1976
- const success = createSingleWorktree(repoPath, subWorktreePath, branchName, config, baseBranch);
2133
+ const success = createSingleWorktree(repoPath, subWorktreePath, branchName, config, repoBase);
1977
2134
  if (success) {
1978
2135
  createdWorktrees.push({ repoPath, worktreePath: subWorktreePath });
2136
+ if (repoBase) baseBranches[subWorktreePath] = repoBase;
1979
2137
  } else {
1980
2138
  console.log("");
1981
2139
  console.log(chalk5.yellow("Rolling back created worktrees due to failure..."));
@@ -2005,6 +2163,8 @@ async function setupGroupWorktree(groupName, repoAliases, branchName, workTreeDi
2005
2163
  console.log(chalk5.yellow(`Run 'work config regengroup ${groupName}' to generate it.`));
2006
2164
  }
2007
2165
  const allPaths = createdWorktrees.map((wt) => wt.worktreePath);
2166
+ const distinctBases = [...new Set(Object.values(baseBranches))];
2167
+ const representativeBase = spec.default ?? (distinctBases.length === 1 ? distinctBases[0] : void 0);
2008
2168
  const { port } = await upsertSessionWithPort(
2009
2169
  groupName,
2010
2170
  true,
@@ -2012,17 +2172,26 @@ async function setupGroupWorktree(groupName, repoAliases, branchName, workTreeDi
2012
2172
  allPaths,
2013
2173
  config,
2014
2174
  jiraKey,
2015
- baseBranch
2175
+ representativeBase,
2176
+ baseBranches
2016
2177
  );
2017
2178
  console.log("");
2018
2179
  console.log(`Branch: ${branchName}`);
2019
2180
  if (port !== void 0) console.log(chalk5.gray(`Dev-server port: ${port}`));
2020
2181
  return { launchDir: groupWorktreePath, paths: allPaths, isGroup: true, port };
2021
2182
  }
2022
- async function setupSingleWorktree(targetName, branchName, workTreeDirName, config, baseBranch, jiraKey) {
2183
+ async function setupSingleWorktree(targetName, branchName, workTreeDirName, config, spec, jiraKey) {
2023
2184
  const repoPath = config.repos[targetName];
2024
2185
  const repoName = path12.basename(repoPath);
2025
2186
  let workTreePath = path12.join(config.worktreesRoot, repoName, workTreeDirName);
2187
+ const unknownAliases = baseSpecOverrideAliases(spec).filter((a) => a !== targetName);
2188
+ if (unknownAliases.length > 0) {
2189
+ console.error(
2190
+ `--base names repo(s) other than '${targetName}': ${unknownAliases.join(", ")}`
2191
+ );
2192
+ return null;
2193
+ }
2194
+ const baseBranch = baseForAlias(spec, targetName);
2026
2195
  if (!fs13.existsSync(repoPath)) {
2027
2196
  console.error(`Repository path does not exist: ${repoPath}`);
2028
2197
  return null;
@@ -2049,7 +2218,8 @@ async function setupSingleWorktree(targetName, branchName, workTreeDirName, conf
2049
2218
  [workTreePath],
2050
2219
  config,
2051
2220
  jiraKey,
2052
- baseBranch
2221
+ baseBranch,
2222
+ baseBranch ? { [workTreePath]: baseBranch } : void 0
2053
2223
  );
2054
2224
  console.log(`Branch: ${branchName}`);
2055
2225
  if (port !== void 0) console.log(chalk5.gray(`Dev-server port: ${port}`));
@@ -2121,7 +2291,7 @@ var treeCommand = {
2121
2291
  type: "boolean",
2122
2292
  default: false
2123
2293
  }).option("base", {
2124
- describe: "Create the new branch from this base branch instead of HEAD",
2294
+ describe: "Base branch to fork from instead of HEAD. Repeatable. Use a bare branch (--base dev) for all repos, or alias=branch (--base backend=dev --base frontend=feat/x) for per-repo bases in a group.",
2125
2295
  type: "string"
2126
2296
  }).option("prompt", {
2127
2297
  describe: "Initial prompt to send to the AI tool on startup",
@@ -2146,7 +2316,17 @@ var treeCommand = {
2146
2316
  const open = argv.open;
2147
2317
  const unsafe = argv.unsafe;
2148
2318
  const setupOnly = argv["setup-only"];
2149
- const baseBranch = argv.base;
2319
+ let baseSpec;
2320
+ try {
2321
+ baseSpec = parseBaseSpec(argv.base);
2322
+ } catch (err) {
2323
+ if (err instanceof BaseSpecError) {
2324
+ console.error(err.message);
2325
+ process.exitCode = 1;
2326
+ return;
2327
+ }
2328
+ throw err;
2329
+ }
2150
2330
  const jiraKey = argv["jira-key"];
2151
2331
  const promptFile = argv["prompt-file"];
2152
2332
  let initialPrompt = argv.prompt;
@@ -2184,12 +2364,10 @@ var treeCommand = {
2184
2364
  process.exitCode = 1;
2185
2365
  return;
2186
2366
  }
2187
- if (baseBranch && !branchName) {
2367
+ if (!isEmptyBaseSpec(baseSpec) && !branchName) {
2188
2368
  console.error("--base requires a branch name");
2189
2369
  console.log(
2190
- chalk6.yellow(
2191
- `Usage: work tree ${targetName} <branch> --base ${baseBranch}`
2192
- )
2370
+ chalk6.yellow(`Usage: work tree ${targetName} <branch> --base <base>`)
2193
2371
  );
2194
2372
  process.exitCode = 1;
2195
2373
  return;
@@ -2237,7 +2415,7 @@ var treeCommand = {
2237
2415
  }
2238
2416
  return;
2239
2417
  }
2240
- const result = await setupWorktree(targetName, branchName, config, baseBranch, jiraKey);
2418
+ const result = await setupWorktree(targetName, branchName, config, baseSpec, jiraKey);
2241
2419
  if (!result) {
2242
2420
  process.exitCode = 1;
2243
2421
  return;
@@ -3126,7 +3304,7 @@ import { render } from "ink";
3126
3304
 
3127
3305
  // src/tui-ink/App.tsx
3128
3306
  import { useState, useEffect, useRef, useCallback, useMemo } from "react";
3129
- import { Box as Box4 } from "ink";
3307
+ import { Box as Box5 } from "ink";
3130
3308
  import fs23 from "fs";
3131
3309
  import os6 from "os";
3132
3310
  import path20 from "path";
@@ -3443,7 +3621,7 @@ var PtySession = class {
3443
3621
  cwd;
3444
3622
  outputHandler;
3445
3623
  _exited = false;
3446
- _idle = true;
3624
+ _status = "idle";
3447
3625
  _outputBuffer = "";
3448
3626
  _loggedOutput = false;
3449
3627
  onExit;
@@ -3513,13 +3691,18 @@ var PtySession = class {
3513
3691
  get exited() {
3514
3692
  return this._exited;
3515
3693
  }
3694
+ /** True when the session is not actively working (idle or needs input). */
3516
3695
  get idle() {
3517
- return this._idle;
3696
+ return this._status !== "running";
3697
+ }
3698
+ /** Live status: 'running', 'idle' (turn finished) or 'attention' (needs input). */
3699
+ get status() {
3700
+ return this._status;
3518
3701
  }
3519
- /** Called by the dashboard when a hook event indicates idle state change. */
3520
- setIdle(idle) {
3521
- if (this._exited || this._idle === idle) return;
3522
- this._idle = idle;
3702
+ /** Called by the dashboard when a hook event indicates a state change. */
3703
+ setStatus(status) {
3704
+ if (this._exited || this._status === status) return;
3705
+ this._status = status;
3523
3706
  this.onStatusChange?.();
3524
3707
  }
3525
3708
  write(data) {
@@ -3986,7 +4169,7 @@ function renderBufferLines(buffer, cols, rows, scrollBack = 0) {
3986
4169
  // src/tui-ink/Sidebar.tsx
3987
4170
  import React from "react";
3988
4171
  import { Box, Text } from "ink";
3989
- import { jsx, jsxs } from "react/jsx-runtime";
4172
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3990
4173
  function buildSessionRows(sessions, statusMap) {
3991
4174
  if (sessions.length === 0) return [];
3992
4175
  const rows = [];
@@ -3995,7 +4178,7 @@ function buildSessionRows(sessions, statusMap) {
3995
4178
  for (const s of sessions) {
3996
4179
  const key = `${s.target}:${s.branch}`;
3997
4180
  const status = statusMap?.get(key);
3998
- if (status === "running" || status === "idle") {
4181
+ if (status !== void 0 && status !== "stopped") {
3999
4182
  active.push(s);
4000
4183
  } else {
4001
4184
  inactive.push(s);
@@ -4119,6 +4302,47 @@ function cursorToRow(rows, cursor) {
4119
4302
  function sessionKey2(s) {
4120
4303
  return `${s.target}:${s.branch}`;
4121
4304
  }
4305
+ function computeScrollOffset(rows, cursor, contentHeight) {
4306
+ let cursorRowIdx = 0;
4307
+ let selectableCount = 0;
4308
+ for (let i = 0; i < rows.length; i++) {
4309
+ if (rows[i].type !== "header") {
4310
+ if (selectableCount === cursor) {
4311
+ cursorRowIdx = i;
4312
+ break;
4313
+ }
4314
+ selectableCount++;
4315
+ }
4316
+ }
4317
+ if (rows.length > contentHeight && cursorRowIdx >= contentHeight - 1) {
4318
+ return Math.min(
4319
+ cursorRowIdx - contentHeight + 2,
4320
+ rows.length - contentHeight
4321
+ );
4322
+ }
4323
+ return 0;
4324
+ }
4325
+ function InputText({ value, pos, budget }) {
4326
+ let v = value;
4327
+ let p = pos;
4328
+ if (budget !== void 0 && value.length + 1 > budget) {
4329
+ const windowLen = Math.max(1, budget - 1);
4330
+ const start = Math.max(0, p - windowLen);
4331
+ v = value.slice(start, start + windowLen);
4332
+ p = pos - start;
4333
+ }
4334
+ if (p >= v.length) {
4335
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
4336
+ /* @__PURE__ */ jsx(Text, { children: v }),
4337
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "\u2588" })
4338
+ ] });
4339
+ }
4340
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
4341
+ /* @__PURE__ */ jsx(Text, { children: v.slice(0, p) }),
4342
+ /* @__PURE__ */ jsx(Text, { inverse: true, children: v[p] }),
4343
+ /* @__PURE__ */ jsx(Text, { children: v.slice(p + 1) })
4344
+ ] });
4345
+ }
4122
4346
  function truncate(str, max) {
4123
4347
  if (max <= 1) return "";
4124
4348
  return str.length > max ? str.slice(0, max - 1) + "\u2026" : str;
@@ -4163,8 +4387,8 @@ function SessionRow({
4163
4387
  active,
4164
4388
  width
4165
4389
  }) {
4166
- const dotChar = status === "idle" ? "\u25C6" : status === "running" ? "\u25CF" : "\u25CB";
4167
- const dotColor = status === "idle" ? "yellow" : status === "running" ? "green" : "gray";
4390
+ const dotChar = status === "attention" ? "\u25C6" : status === "idle" ? "\u25C7" : status === "running" ? "\u25CF" : "\u25CB";
4391
+ const dotColor = status === "attention" ? "yellow" : status === "idle" ? "cyan" : status === "running" ? "green" : "gray";
4168
4392
  const agoStr = timeAgo(effectiveLastAccessedAt(s));
4169
4393
  const mergedLen = merged ? 8 : 0;
4170
4394
  const conflictLen = conflicts > 0 ? 2 + String(conflicts).length : 0;
@@ -4209,11 +4433,8 @@ function ProjectRow({
4209
4433
  /* @__PURE__ */ jsx(Text, { color: "magenta", children: truncate(name, width - 15) }),
4210
4434
  /* @__PURE__ */ jsx(Text, { children: " " }),
4211
4435
  /* @__PURE__ */ jsx(Text, { color: "cyan", children: "branch:" }),
4212
- /* @__PURE__ */ jsxs(Text, { children: [
4213
- " ",
4214
- branchInput.value
4215
- ] }),
4216
- /* @__PURE__ */ jsx(Text, { dimColor: true, children: "\u2588" })
4436
+ /* @__PURE__ */ jsx(Text, { children: " " }),
4437
+ /* @__PURE__ */ jsx(InputText, { value: branchInput.value, pos: branchInput.pos })
4217
4438
  ] });
4218
4439
  }
4219
4440
  return /* @__PURE__ */ jsxs(Box, { width, children: [
@@ -4271,26 +4492,7 @@ function BorderedPane({
4271
4492
  }) {
4272
4493
  const innerWidth = width - 2;
4273
4494
  const contentHeight = height - 2;
4274
- let cursorRowIdx = 0;
4275
- let selectableCount = 0;
4276
- for (let i = 0; i < sidebarRows.length; i++) {
4277
- if (sidebarRows[i].type !== "header") {
4278
- if (selectableCount === cursor) {
4279
- cursorRowIdx = i;
4280
- break;
4281
- }
4282
- selectableCount++;
4283
- }
4284
- }
4285
- let scrollOffset = 0;
4286
- if (sidebarRows.length > contentHeight) {
4287
- if (cursorRowIdx >= contentHeight - 1) {
4288
- scrollOffset = Math.min(
4289
- cursorRowIdx - contentHeight + 2,
4290
- sidebarRows.length - contentHeight
4291
- );
4292
- }
4293
- }
4495
+ const scrollOffset = computeScrollOffset(sidebarRows, cursor, contentHeight);
4294
4496
  const rendered = [];
4295
4497
  let selectableIdx = 0;
4296
4498
  for (let i = 0; i < scrollOffset; i++) {
@@ -4311,7 +4513,14 @@ function BorderedPane({
4311
4513
  rendered.push(renderRow(row, rowIdx, sel));
4312
4514
  }
4313
4515
  }
4314
- const topBorder = title ? "\u250C\u2500 " + title + " " + "\u2500".repeat(Math.max(0, innerWidth - title.length - 3)) + "\u2510" : "\u250C" + "\u2500".repeat(innerWidth) + "\u2510";
4516
+ const hiddenAbove = scrollOffset;
4517
+ const hiddenBelow = Math.max(0, sidebarRows.length - (scrollOffset + contentHeight));
4518
+ const upText = hiddenAbove > 0 ? ` \u2191${hiddenAbove} ` : "";
4519
+ const downText = hiddenBelow > 0 ? ` \u2193${hiddenBelow} ` : "";
4520
+ const titlePart = title ? "\u2500 " + title + " " : "";
4521
+ const topFill = Math.max(0, innerWidth - titlePart.length - upText.length);
4522
+ const topBorder = "\u250C" + titlePart + "\u2500".repeat(topFill) + upText + "\u2510";
4523
+ const bottomBorder = "\u2514" + "\u2500".repeat(Math.max(0, innerWidth - downText.length)) + downText + "\u2518";
4315
4524
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", width, children: [
4316
4525
  /* @__PURE__ */ jsx(Text, { color: borderColor, children: topBorder }),
4317
4526
  rendered.map((row, i) => /* @__PURE__ */ jsxs(Box, { children: [
@@ -4319,12 +4528,13 @@ function BorderedPane({
4319
4528
  row,
4320
4529
  /* @__PURE__ */ jsx(Text, { color: borderColor, children: "\u2502" })
4321
4530
  ] }, i)),
4322
- /* @__PURE__ */ jsx(Text, { color: borderColor, children: "\u2514" + "\u2500".repeat(innerWidth) + "\u2518" })
4531
+ /* @__PURE__ */ jsx(Text, { color: borderColor, children: bottomBorder })
4323
4532
  ] });
4324
4533
  }
4325
- function Sidebar({ sidebarRows, cursor, focused, statusMap, conflictCounts, mergedSet, prMap, activeKey, width, height, branchInput }) {
4534
+ var Sidebar = React.memo(function Sidebar2({ sidebarRows, cursor, focused, statusMap, conflictCounts, mergedSet, prMap, activeKey, width, height, branchInput, filter }) {
4326
4535
  const borderColor = focused ? "cyan" : "gray";
4327
4536
  const innerWidth = width - 2;
4537
+ const title = filter ? `Worktrees /${filter.value}${filter.editing ? "\u2588" : ""}` : "Worktrees";
4328
4538
  return /* @__PURE__ */ jsx(
4329
4539
  BorderedPane,
4330
4540
  {
@@ -4332,7 +4542,7 @@ function Sidebar({ sidebarRows, cursor, focused, statusMap, conflictCounts, merg
4332
4542
  cursor,
4333
4543
  focused,
4334
4544
  borderColor,
4335
- title: "Worktrees",
4545
+ title,
4336
4546
  width,
4337
4547
  height,
4338
4548
  renderRow: (row, i, sel) => {
@@ -4373,7 +4583,7 @@ function Sidebar({ sidebarRows, cursor, focused, statusMap, conflictCounts, merg
4373
4583
  }
4374
4584
  }
4375
4585
  );
4376
- }
4586
+ });
4377
4587
  function statusColor(status) {
4378
4588
  const lower = status.toLowerCase();
4379
4589
  if (lower.includes("progress") || lower.includes("review")) return "cyan";
@@ -4398,7 +4608,7 @@ function JiraListRow({
4398
4608
  /* @__PURE__ */ jsx(Text, { children: truncate(issue.summary, summaryBudget) })
4399
4609
  ] });
4400
4610
  }
4401
- function PrPane({ prRows, cursor, focused, localBranches, width, height }) {
4611
+ var PrPane = React.memo(function PrPane2({ prRows, cursor, focused, localBranches, width, height }) {
4402
4612
  const borderColor = focused ? "cyan" : "gray";
4403
4613
  const innerWidth = width - 2;
4404
4614
  return /* @__PURE__ */ jsx(
@@ -4429,7 +4639,7 @@ function PrPane({ prRows, cursor, focused, localBranches, width, height }) {
4429
4639
  }
4430
4640
  }
4431
4641
  );
4432
- }
4642
+ });
4433
4643
  function TaskListRow({
4434
4644
  task,
4435
4645
  selected,
@@ -4451,22 +4661,21 @@ function TaskListRow({
4451
4661
  /* @__PURE__ */ jsx(Text, { dimColor: true, children: idStr })
4452
4662
  ] });
4453
4663
  }
4454
- function TaskInputRow({ value, width }) {
4664
+ function TaskInputRow({ value, pos, width }) {
4455
4665
  const budget = Math.max(4, width - 8);
4456
4666
  return /* @__PURE__ */ jsxs(Box, { width, children: [
4457
4667
  /* @__PURE__ */ jsx(Text, { children: " " }),
4458
4668
  /* @__PURE__ */ jsx(Text, { color: "cyan", children: "+ " }),
4459
- /* @__PURE__ */ jsx(Text, { children: truncate(value, budget) }),
4460
- /* @__PURE__ */ jsx(Text, { dimColor: true, children: "\u2588" })
4669
+ /* @__PURE__ */ jsx(InputText, { value, pos, budget })
4461
4670
  ] });
4462
4671
  }
4463
- function TaskPane({ taskRows, cursor, focused, width, height, taskInput }) {
4672
+ var TaskPane = React.memo(function TaskPane2({ taskRows, cursor, focused, width, height, taskInput }) {
4464
4673
  const borderColor = focused ? "cyan" : "gray";
4465
4674
  const innerWidth = width - 2;
4466
4675
  const contentHeight = height - 2;
4467
4676
  if (taskInput !== null && taskInput !== void 0) {
4468
4677
  const rendered = [];
4469
- rendered.push(/* @__PURE__ */ jsx(TaskInputRow, { value: taskInput, width: innerWidth }, "input"));
4678
+ rendered.push(/* @__PURE__ */ jsx(TaskInputRow, { value: taskInput.value, pos: taskInput.pos, width: innerWidth }, "input"));
4470
4679
  let selectableIdx = 0;
4471
4680
  for (let i = 0; i < contentHeight - 1 && i < taskRows.length; i++) {
4472
4681
  const row = taskRows[i];
@@ -4521,8 +4730,8 @@ function TaskPane({ taskRows, cursor, focused, width, height, taskInput }) {
4521
4730
  }
4522
4731
  }
4523
4732
  );
4524
- }
4525
- function JiraPane({ jiraRows, cursor, focused, width, height }) {
4733
+ });
4734
+ var JiraPane = React.memo(function JiraPane2({ jiraRows, cursor, focused, width, height }) {
4526
4735
  const borderColor = focused ? "cyan" : "gray";
4527
4736
  const innerWidth = width - 2;
4528
4737
  return /* @__PURE__ */ jsx(
@@ -4552,12 +4761,13 @@ function JiraPane({ jiraRows, cursor, focused, width, height }) {
4552
4761
  }
4553
4762
  }
4554
4763
  );
4555
- }
4764
+ });
4556
4765
 
4557
4766
  // src/tui-ink/TerminalPane.tsx
4767
+ import React2 from "react";
4558
4768
  import { Box as Box2, Text as Text2 } from "ink";
4559
4769
  import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
4560
- function TerminalPane({ lines, width, height, focused, placeholder, title }) {
4770
+ var TerminalPane = React2.memo(function TerminalPane2({ lines, width, height, focused, placeholder, title, scrollback }) {
4561
4771
  const borderColor = focused ? "cyan" : "gray";
4562
4772
  const innerWidth = width - 2;
4563
4773
  const contentHeight = height - 2;
@@ -4583,8 +4793,10 @@ function TerminalPane({ lines, width, height, focused, placeholder, title }) {
4583
4793
  }
4584
4794
  }
4585
4795
  }
4796
+ const scrolledTitle = scrollback && scrollback > 0 ? `${title ?? "Terminal"} \u2500 \u2191${scrollback} paused (pgdn/type to resume)` : title;
4797
+ const topBorder = scrolledTitle ? "\u250C\u2500 " + scrolledTitle + " " + "\u2500".repeat(Math.max(0, innerWidth - scrolledTitle.length - 3)) + "\u2510" : "\u250C" + "\u2500".repeat(innerWidth) + "\u2510";
4586
4798
  return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", width, children: [
4587
- /* @__PURE__ */ jsx2(Text2, { color: borderColor, children: title ? "\u250C\u2500 " + title + " " + "\u2500".repeat(Math.max(0, innerWidth - title.length - 3)) + "\u2510" : "\u250C" + "\u2500".repeat(innerWidth) + "\u2510" }),
4799
+ /* @__PURE__ */ jsx2(Text2, { color: scrollback && scrollback > 0 ? "yellow" : borderColor, children: topBorder }),
4588
4800
  content.map((row, i) => /* @__PURE__ */ jsxs2(Box2, { children: [
4589
4801
  /* @__PURE__ */ jsx2(Text2, { color: borderColor, children: "\u2502" }),
4590
4802
  /* @__PURE__ */ jsx2(Box2, { width: innerWidth, children: row }),
@@ -4592,19 +4804,20 @@ function TerminalPane({ lines, width, height, focused, placeholder, title }) {
4592
4804
  ] }, i)),
4593
4805
  /* @__PURE__ */ jsx2(Text2, { color: borderColor, children: "\u2514" + "\u2500".repeat(innerWidth) + "\u2518" })
4594
4806
  ] });
4595
- }
4807
+ });
4596
4808
 
4597
4809
  // src/tui-ink/StatusBar.tsx
4810
+ import React3 from "react";
4598
4811
  import { Box as Box3, Text as Text3 } from "ink";
4599
- import { Fragment, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
4812
+ import { Fragment as Fragment2, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
4600
4813
  var PANE_HINTS = {
4601
- sessions: " tab pane j/k nav enter start n new d remove . editor u rebase g sync G sync all q quit ",
4602
- tasks: " tab pane j/k nav enter toggle a add e edit w worktree d remove g sync G sync all q quit ",
4603
- prs: " tab pane j/k nav enter checkout g sync G sync all q quit ",
4604
- jira: " tab pane j/k nav enter worktree o open g sync G sync all q quit ",
4605
- terminal: " tab pane ctrl+] detach "
4814
+ sessions: " tab pane j/k nav / filter enter start n new d remove u rebase g sync ? help q quit ",
4815
+ tasks: " tab pane j/k nav enter toggle a add e edit w worktree d remove ? help q quit ",
4816
+ prs: " tab pane j/k nav enter checkout o open g sync ? help q quit ",
4817
+ jira: " tab pane j/k nav enter worktree o open g sync ? help q quit ",
4818
+ terminal: " tab pane ctrl+] detach pgup/pgdn scroll "
4606
4819
  };
4607
- function StatusBar({ message, pane, syncing }) {
4820
+ var StatusBar = React3.memo(function StatusBar2({ message, pane, syncing }) {
4608
4821
  if (message) {
4609
4822
  return /* @__PURE__ */ jsxs3(Box3, { children: [
4610
4823
  /* @__PURE__ */ jsxs3(Text3, { color: "yellow", children: [
@@ -4617,21 +4830,217 @@ function StatusBar({ message, pane, syncing }) {
4617
4830
  }
4618
4831
  return /* @__PURE__ */ jsxs3(Box3, { children: [
4619
4832
  /* @__PURE__ */ jsx3(Text3, { dimColor: true, children: PANE_HINTS[pane] }),
4620
- pane === "sessions" && /* @__PURE__ */ jsxs3(Fragment, { children: [
4833
+ pane === "sessions" && /* @__PURE__ */ jsxs3(Fragment2, { children: [
4621
4834
  /* @__PURE__ */ jsx3(Text3, { dimColor: true, children: "[" }),
4622
4835
  /* @__PURE__ */ jsx3(Text3, { color: "green", children: "\u25CF" }),
4623
4836
  /* @__PURE__ */ jsx3(Text3, { dimColor: true, children: " working " }),
4624
4837
  /* @__PURE__ */ jsx3(Text3, { color: "yellow", children: "\u25C6" }),
4625
4838
  /* @__PURE__ */ jsx3(Text3, { dimColor: true, children: " needs input " }),
4839
+ /* @__PURE__ */ jsx3(Text3, { color: "cyan", children: "\u25C7" }),
4840
+ /* @__PURE__ */ jsx3(Text3, { dimColor: true, children: " done " }),
4626
4841
  /* @__PURE__ */ jsx3(Text3, { dimColor: true, children: "\u25CB stopped]" })
4627
4842
  ] }),
4628
4843
  syncing && /* @__PURE__ */ jsx3(Box3, { flexGrow: 1 }),
4629
4844
  syncing && /* @__PURE__ */ jsx3(Text3, { color: "cyan", children: " syncing" })
4630
4845
  ] });
4846
+ });
4847
+
4848
+ // src/tui-ink/HelpOverlay.tsx
4849
+ import React4 from "react";
4850
+ import { Box as Box4, Text as Text4 } from "ink";
4851
+ import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
4852
+ var HELP = [
4853
+ { type: "section", label: "Navigation" },
4854
+ { type: "key", keys: "tab", desc: "cycle pane focus" },
4855
+ { type: "key", keys: "j/k or \u2191/\u2193", desc: "move cursor" },
4856
+ { type: "key", keys: "ctrl+d / ctrl+u", desc: "half-page down / up" },
4857
+ { type: "key", keys: "pgup / pgdn", desc: "page up / down" },
4858
+ { type: "key", keys: "mouse", desc: "wheel scrolls, click focuses + selects" },
4859
+ { type: "blank" },
4860
+ { type: "section", label: "Worktrees pane" },
4861
+ { type: "key", keys: "enter", desc: "start / show session" },
4862
+ { type: "key", keys: "/", desc: "filter sessions (enter keeps, esc clears)" },
4863
+ { type: "key", keys: "n", desc: "new worktree" },
4864
+ { type: "key", keys: "d", desc: "remove worktree (press d again to confirm)" },
4865
+ { type: "key", keys: ".", desc: "open in editor" },
4866
+ { type: "key", keys: "u", desc: "rebase onto main" },
4867
+ { type: "blank" },
4868
+ { type: "section", label: "Pull Requests / Jira panes" },
4869
+ { type: "key", keys: "enter", desc: "checkout PR / create worktree for issue" },
4870
+ { type: "key", keys: "o", desc: "open in browser" },
4871
+ { type: "blank" },
4872
+ { type: "section", label: "Tasks pane" },
4873
+ { type: "key", keys: "enter or x", desc: "toggle done" },
4874
+ { type: "key", keys: "a / e / d", desc: "add / edit / remove task" },
4875
+ { type: "key", keys: "w", desc: "create worktree from task" },
4876
+ { type: "blank" },
4877
+ { type: "section", label: "Terminal" },
4878
+ { type: "key", keys: "ctrl+]", desc: "detach back to sidebar" },
4879
+ { type: "key", keys: "pgup / pgdn", desc: "scroll history (typing resumes live)" },
4880
+ { type: "blank" },
4881
+ { type: "section", label: "Global" },
4882
+ { type: "key", keys: "g / G", desc: "sync focused pane / sync everything" },
4883
+ { type: "key", keys: "r", desc: "refresh all panes" },
4884
+ { type: "key", keys: "?", desc: "toggle this help" },
4885
+ { type: "key", keys: "q or ctrl+c", desc: "quit" }
4886
+ ];
4887
+ var HelpOverlay = React4.memo(function HelpOverlay2({ width, height }) {
4888
+ const innerWidth = width - 2;
4889
+ const contentHeight = height - 2;
4890
+ const title = "Help \u2014 press ? or esc to close";
4891
+ const topBorder = "\u250C\u2500 " + title + " " + "\u2500".repeat(Math.max(0, innerWidth - title.length - 3)) + "\u2510";
4892
+ const rows = [];
4893
+ for (let i = 0; i < contentHeight; i++) {
4894
+ const line = HELP[i];
4895
+ if (!line || line.type === "blank") {
4896
+ rows.push(/* @__PURE__ */ jsx4(Text4, { children: " ".repeat(innerWidth) }, i));
4897
+ continue;
4898
+ }
4899
+ if (line.type === "section") {
4900
+ rows.push(
4901
+ /* @__PURE__ */ jsx4(Box4, { width: innerWidth, children: /* @__PURE__ */ jsx4(Text4, { color: "yellow", bold: true, children: " " + line.label }) }, i)
4902
+ );
4903
+ continue;
4904
+ }
4905
+ rows.push(
4906
+ /* @__PURE__ */ jsxs4(Box4, { width: innerWidth, children: [
4907
+ /* @__PURE__ */ jsx4(Text4, { color: "cyan", children: " " + line.keys.padEnd(18) }),
4908
+ /* @__PURE__ */ jsx4(Text4, { children: line.desc })
4909
+ ] }, i)
4910
+ );
4911
+ }
4912
+ return /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", width, children: [
4913
+ /* @__PURE__ */ jsx4(Text4, { color: "cyan", children: topBorder }),
4914
+ rows.map((row, i) => /* @__PURE__ */ jsxs4(Box4, { children: [
4915
+ /* @__PURE__ */ jsx4(Text4, { color: "cyan", children: "\u2502" }),
4916
+ row,
4917
+ /* @__PURE__ */ jsx4(Text4, { color: "cyan", children: "\u2502" })
4918
+ ] }, i)),
4919
+ /* @__PURE__ */ jsx4(Text4, { color: "cyan", children: "\u2514" + "\u2500".repeat(innerWidth) + "\u2518" })
4920
+ ] });
4921
+ });
4922
+
4923
+ // src/tui-ink/line-editor.ts
4924
+ var KEYS = {
4925
+ UP: "\x1B[A",
4926
+ DOWN: "\x1B[B",
4927
+ RIGHT: "\x1B[C",
4928
+ LEFT: "\x1B[D",
4929
+ HOME: "\x1B[H",
4930
+ END: "\x1B[F",
4931
+ HOME_ALT: "\x1B[1~",
4932
+ END_ALT: "\x1B[4~",
4933
+ PAGE_UP: "\x1B[5~",
4934
+ PAGE_DOWN: "\x1B[6~",
4935
+ DELETE: "\x1B[3~",
4936
+ ESC: "\x1B",
4937
+ ENTER: "\r",
4938
+ BACKSPACE: "\x7F",
4939
+ BACKSPACE_ALT: "\b",
4940
+ CTRL_C: "",
4941
+ CTRL_D: "",
4942
+ CTRL_U: "",
4943
+ TAB: " "
4944
+ };
4945
+ function splitInputChunks(data) {
4946
+ const tokens = [];
4947
+ let i = 0;
4948
+ let run2 = "";
4949
+ const flushRun = () => {
4950
+ if (run2) {
4951
+ tokens.push(run2);
4952
+ run2 = "";
4953
+ }
4954
+ };
4955
+ while (i < data.length) {
4956
+ const ch = data[i];
4957
+ if (ch === "\x1B") {
4958
+ flushRun();
4959
+ const next = data[i + 1];
4960
+ if (next === "[") {
4961
+ let j = i + 2;
4962
+ while (j < data.length) {
4963
+ const code2 = data.charCodeAt(j);
4964
+ if (code2 >= 64 && code2 <= 126) break;
4965
+ j++;
4966
+ }
4967
+ tokens.push(data.slice(i, Math.min(j + 1, data.length)));
4968
+ i = j + 1;
4969
+ continue;
4970
+ }
4971
+ if (next === "O" && i + 2 < data.length) {
4972
+ tokens.push(data.slice(i, i + 3));
4973
+ i += 3;
4974
+ continue;
4975
+ }
4976
+ tokens.push("\x1B");
4977
+ i++;
4978
+ continue;
4979
+ }
4980
+ const code = data.charCodeAt(i);
4981
+ if (code < 32 || code === 127) {
4982
+ flushRun();
4983
+ tokens.push(ch);
4984
+ i++;
4985
+ continue;
4986
+ }
4987
+ run2 += ch;
4988
+ i++;
4989
+ }
4990
+ flushRun();
4991
+ return tokens;
4992
+ }
4993
+ function sanitizePaste(text) {
4994
+ const firstLine = text.split(/\r|\n/, 1)[0] ?? "";
4995
+ return firstLine.replace(/[\u0000-\u001f\u007f]/g, "");
4996
+ }
4997
+ function editLine(state, token) {
4998
+ const { value, pos } = state;
4999
+ switch (token) {
5000
+ case KEYS.ESC:
5001
+ case KEYS.CTRL_C:
5002
+ return { state, action: "cancel" };
5003
+ case KEYS.ENTER:
5004
+ return { state, action: "submit" };
5005
+ case KEYS.BACKSPACE:
5006
+ case KEYS.BACKSPACE_ALT:
5007
+ if (pos === 0) return { state, action: null };
5008
+ return {
5009
+ state: { value: value.slice(0, pos - 1) + value.slice(pos), pos: pos - 1 },
5010
+ action: null
5011
+ };
5012
+ case KEYS.DELETE:
5013
+ if (pos >= value.length) return { state, action: null };
5014
+ return {
5015
+ state: { value: value.slice(0, pos) + value.slice(pos + 1), pos },
5016
+ action: null
5017
+ };
5018
+ case KEYS.LEFT:
5019
+ return { state: { value, pos: Math.max(0, pos - 1) }, action: null };
5020
+ case KEYS.RIGHT:
5021
+ return { state: { value, pos: Math.min(value.length, pos + 1) }, action: null };
5022
+ case KEYS.HOME:
5023
+ case KEYS.HOME_ALT:
5024
+ return { state: { value, pos: 0 }, action: null };
5025
+ case KEYS.END:
5026
+ case KEYS.END_ALT:
5027
+ return { state: { value, pos: value.length }, action: null };
5028
+ case KEYS.CTRL_U:
5029
+ return { state: { value: value.slice(pos), pos: 0 }, action: null };
5030
+ }
5031
+ if (token.startsWith("\x1B") || token.charCodeAt(0) < 32 || token === "\x7F") {
5032
+ return { state, action: null };
5033
+ }
5034
+ const insert = sanitizePaste(token);
5035
+ if (!insert) return { state, action: null };
5036
+ return {
5037
+ state: { value: value.slice(0, pos) + insert + value.slice(pos), pos: pos + insert.length },
5038
+ action: null
5039
+ };
4631
5040
  }
4632
5041
 
4633
5042
  // src/tui-ink/App.tsx
4634
- import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
5043
+ import { jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
4635
5044
  var DETACH_KEY = "";
4636
5045
  var TAB_KEY = " ";
4637
5046
  var RENDER_INTERVAL_MS = 50;
@@ -4639,7 +5048,7 @@ var MOUSE_SGR_RE = /\x1b\[<(\d+);(\d+);(\d+)[Mm]/;
4639
5048
  function hasClaudeConversation(dir) {
4640
5049
  try {
4641
5050
  const resolved = path20.resolve(dir);
4642
- const projectDir = resolved.replace(/[/\\:]/g, "-");
5051
+ const projectDir = resolved.replace(/[^a-zA-Z0-9-]/g, "-");
4643
5052
  const claudeProjectPath = path20.join(os6.homedir(), ".claude", "projects", projectDir);
4644
5053
  if (!fs23.existsSync(claudeProjectPath)) return false;
4645
5054
  const files = fs23.readdirSync(claudeProjectPath);
@@ -4734,20 +5143,35 @@ function App({ unsafe, onExit }) {
4734
5143
  const [pendingJiraIssue, setPendingJiraIssue] = useState(null);
4735
5144
  const [pendingTask, setPendingTask] = useState(null);
4736
5145
  const [savedSessionCursor, setSavedSessionCursor] = useState(0);
5146
+ const [showHelp2, setShowHelp] = useState(false);
5147
+ const [filter, setFilter] = useState(null);
5148
+ const [pendingRemoveKey, setPendingRemoveKey] = useState(null);
5149
+ const [termScroll, setTermScroll] = useState(0);
5150
+ const setScrollBack = useCallback((n) => {
5151
+ termScrollBack.current = n;
5152
+ setTermScroll(n);
5153
+ }, []);
4737
5154
  const localBranches = useMemo(() => new Set(sessions.map((s) => s.branch)), [sessions]);
4738
5155
  const projectRows = useMemo(() => buildProjectRows(projects), [projects]);
4739
5156
  const prRows = useMemo(() => buildPrRows(prMap), [prMap]);
4740
5157
  const jiraRows = useMemo(() => buildJiraRows(jiraIssues), [jiraIssues]);
4741
5158
  const taskRows = useMemo(() => buildTaskRows(tasks), [tasks]);
5159
+ const filteredSessions = useMemo(() => {
5160
+ const q = filter?.value.trim().toLowerCase();
5161
+ if (!q) return sessions;
5162
+ return sessions.filter(
5163
+ (s) => s.branch.toLowerCase().includes(q) || s.target.toLowerCase().includes(q)
5164
+ );
5165
+ }, [sessions, filter]);
4742
5166
  const ptySessions = useRef(/* @__PURE__ */ new Map());
4743
5167
  const sessionRows = useMemo(() => {
4744
5168
  const sMap = /* @__PURE__ */ new Map();
4745
5169
  for (const [key, pty2] of ptySessions.current) {
4746
5170
  if (pty2.exited) continue;
4747
- sMap.set(key, pty2.idle ? "idle" : "running");
5171
+ sMap.set(key, pty2.status);
4748
5172
  }
4749
- return buildSessionRows(sessions, sMap);
4750
- }, [sessions, statusVersion]);
5173
+ return buildSessionRows(filteredSessions, sMap);
5174
+ }, [filteredSessions, statusVersion]);
4751
5175
  const topRows = topPaneMode === 0 /* SESSIONS */ ? sessionRows : projectRows;
4752
5176
  const renderPending = useRef(false);
4753
5177
  const focusRef = useRef(focus);
@@ -4787,6 +5211,13 @@ function App({ unsafe, onExit }) {
4787
5211
  prRowsRef.current = prRows;
4788
5212
  const acliAvailableRef = useRef(acliAvailable);
4789
5213
  acliAvailableRef.current = acliAvailable;
5214
+ const showHelpRef = useRef(showHelp2);
5215
+ showHelpRef.current = showHelp2;
5216
+ const filterRef = useRef(filter);
5217
+ filterRef.current = filter;
5218
+ const pendingRemoveRef = useRef(pendingRemoveKey);
5219
+ pendingRemoveRef.current = pendingRemoveKey;
5220
+ const rebasingRef = useRef(false);
4790
5221
  const hookServerRef = useRef(null);
4791
5222
  const notifiedSessionsRef = useRef(/* @__PURE__ */ new Set());
4792
5223
  const [dims, setDims] = useState(() => ({
@@ -4803,16 +5234,21 @@ function App({ unsafe, onExit }) {
4803
5234
  const taskPaneHeight = Math.max(5, Math.floor(contentHeight * 0.2));
4804
5235
  const prPaneHeight = Math.max(5, Math.floor((contentHeight - jiraPaneHeight - taskPaneHeight) * 0.45));
4805
5236
  const sessionPaneHeight = contentHeight - prPaneHeight - taskPaneHeight - jiraPaneHeight;
5237
+ const layoutRef = useRef({ sidebarWidth, termInner, contentHeight, sessionPaneHeight, prPaneHeight, jiraPaneHeight, taskPaneHeight });
5238
+ layoutRef.current = { sidebarWidth, termInner, contentHeight, sessionPaneHeight, prPaneHeight, jiraPaneHeight, taskPaneHeight };
4806
5239
  useEffect(() => {
5240
+ let attentionCount = 0;
4807
5241
  let idleCount = 0;
4808
5242
  let runningCount = 0;
4809
5243
  for (const pty2 of ptySessions.current.values()) {
4810
5244
  if (pty2.exited) continue;
4811
- if (pty2.idle) idleCount++;
5245
+ if (pty2.status === "attention") attentionCount++;
5246
+ else if (pty2.status === "idle") idleCount++;
4812
5247
  else runningCount++;
4813
5248
  }
4814
5249
  const parts = [];
4815
- if (idleCount > 0) parts.push(`\u{1F7E1} ${idleCount}`);
5250
+ if (attentionCount > 0) parts.push(`\u{1F7E1} ${attentionCount}`);
5251
+ if (idleCount > 0) parts.push(`\u{1F535} ${idleCount}`);
4816
5252
  if (runningCount > 0) parts.push(`\u{1F7E2} ${runningCount}`);
4817
5253
  const title = parts.length > 0 ? parts.join(" ") : "work dash";
4818
5254
  process.stdout.write(`\x1B]0;${title}\x07`);
@@ -4820,23 +5256,21 @@ function App({ unsafe, onExit }) {
4820
5256
  const computeGeneration = useRef(0);
4821
5257
  const computeConflictsAndMerged = useCallback((sessionList) => {
4822
5258
  const generation = ++computeGeneration.current;
4823
- const tick = () => new Promise((r) => setTimeout(r, 0));
4824
5259
  (async () => {
4825
5260
  const counts = /* @__PURE__ */ new Map();
4826
5261
  const merged = /* @__PURE__ */ new Set();
4827
5262
  for (const s of sessionList) {
4828
5263
  if (computeGeneration.current !== generation) return;
4829
- await tick();
4830
5264
  const existing = s.paths.find((p) => fs23.existsSync(p));
4831
5265
  if (!existing || !s.branch) continue;
4832
5266
  const key = sessionKey2(s);
4833
5267
  try {
4834
- const c = countConflicts(s.branch, existing);
5268
+ const c = await countConflictsAsync(s.branch, existing);
4835
5269
  if (c > 0) counts.set(key, c);
4836
5270
  } catch {
4837
5271
  }
4838
5272
  try {
4839
- const { merged: isMerged } = isBranchMerged(s.branch, existing);
5273
+ const { merged: isMerged } = await isBranchMergedAsync(s.branch, existing);
4840
5274
  if (isMerged) merged.add(key);
4841
5275
  } catch {
4842
5276
  }
@@ -4848,10 +5282,10 @@ function App({ unsafe, onExit }) {
4848
5282
  })();
4849
5283
  }, []);
4850
5284
  const refreshPrs = useCallback(() => {
4851
- if (!ghAvailable || !config || prFetching.current) return;
5285
+ if (!ghAvailable || !config || prFetching.current) return Promise.resolve();
4852
5286
  prFetching.current = true;
4853
5287
  setMessage("Loading PRs...");
4854
- fetchAllPullRequests(config.repos).then((prs) => {
5288
+ return fetchAllPullRequests(config.repos).then((prs) => {
4855
5289
  setPrMap(prs);
4856
5290
  setMessage("");
4857
5291
  }).catch(() => {
@@ -4860,9 +5294,9 @@ function App({ unsafe, onExit }) {
4860
5294
  });
4861
5295
  }, [ghAvailable, config]);
4862
5296
  const refreshJira = useCallback(() => {
4863
- if (!acliAvailable || jiraFetching.current) return;
5297
+ if (!acliAvailable || jiraFetching.current) return Promise.resolve();
4864
5298
  jiraFetching.current = true;
4865
- fetchMyJiraIssues().then((issues) => setJiraIssues(issues)).catch(() => {
5299
+ return fetchMyJiraIssues().then((issues) => setJiraIssues(issues)).catch(() => {
4866
5300
  }).finally(() => {
4867
5301
  jiraFetching.current = false;
4868
5302
  });
@@ -4875,11 +5309,11 @@ function App({ unsafe, onExit }) {
4875
5309
  setSessions(updated);
4876
5310
  computeConflictsAndMerged(updated);
4877
5311
  }, [computeConflictsAndMerged]);
4878
- const buildStatusMap = useCallback(() => {
5312
+ const statusMap = useMemo(() => {
4879
5313
  const map = /* @__PURE__ */ new Map();
4880
5314
  for (const [key, pty2] of ptySessions.current) {
4881
5315
  if (pty2.exited) continue;
4882
- map.set(key, pty2.idle ? "idle" : "running");
5316
+ map.set(key, pty2.status);
4883
5317
  }
4884
5318
  return map;
4885
5319
  }, [statusVersion]);
@@ -4889,6 +5323,8 @@ function App({ unsafe, onExit }) {
4889
5323
  setTimeout(() => {
4890
5324
  renderPending.current = false;
4891
5325
  try {
5326
+ const activeKey2 = activeKeyRef.current;
5327
+ if (!activeKey2 || ptySessions.current.get(activeKey2) !== pty2) return;
4892
5328
  if (termScrollBack.current > 0) return;
4893
5329
  const lines = renderBufferLines(pty2.terminal.buffer.active, termInner, contentHeight - 2);
4894
5330
  setTermLines(lines);
@@ -4905,6 +5341,16 @@ function App({ unsafe, onExit }) {
4905
5341
  } catch {
4906
5342
  }
4907
5343
  }, [termInner, contentHeight]);
5344
+ const scrollTerminal = useCallback((linesUp) => {
5345
+ const pty2 = activeKeyRef.current ? ptySessions.current.get(activeKeyRef.current) : void 0;
5346
+ if (!pty2 || pty2.exited) return;
5347
+ const maxScroll = pty2.terminal.buffer.active.baseY;
5348
+ const next = Math.max(0, Math.min(maxScroll, termScrollBack.current + linesUp));
5349
+ if (next !== termScrollBack.current) {
5350
+ setScrollBack(next);
5351
+ renderTermAtScroll();
5352
+ }
5353
+ }, [setScrollBack, renderTermAtScroll]);
4908
5354
  const findPtyByCwd = useCallback((cwd) => {
4909
5355
  const normalized = path20.resolve(cwd).toLowerCase();
4910
5356
  for (const pty2 of ptySessions.current.values()) {
@@ -4971,10 +5417,12 @@ function App({ unsafe, onExit }) {
4971
5417
  callback: (cwd, event) => {
4972
5418
  const pty2 = findPtyByCwd(cwd);
4973
5419
  if (!pty2) return;
4974
- if (event === "stop" || event === "notification") {
4975
- pty2.setIdle(true);
5420
+ if (event === "notification") {
5421
+ pty2.setStatus("attention");
5422
+ } else if (event === "stop") {
5423
+ pty2.setStatus("idle");
4976
5424
  } else if (event === "prompt_submit") {
4977
- pty2.setIdle(false);
5425
+ pty2.setStatus("running");
4978
5426
  }
4979
5427
  const dedupKey = ptyDedupKey(pty2);
4980
5428
  const kind = notifyKindForEvent(
@@ -5035,7 +5483,7 @@ function App({ unsafe, onExit }) {
5035
5483
  const switchDisplay = useCallback((s) => {
5036
5484
  const k = sessionKey2(s);
5037
5485
  if (activeKeyRef.current === k) return;
5038
- termScrollBack.current = 0;
5486
+ setScrollBack(0);
5039
5487
  if (activeKeyRef.current) {
5040
5488
  ptySessions.current.get(activeKeyRef.current)?.setOutputHandler(void 0);
5041
5489
  }
@@ -5086,6 +5534,7 @@ function App({ unsafe, onExit }) {
5086
5534
  if (activeKeyRef.current && activeKeyRef.current !== key) {
5087
5535
  ptySessions.current.get(activeKeyRef.current)?.setOutputHandler(void 0);
5088
5536
  }
5537
+ setScrollBack(0);
5089
5538
  setActiveKey(key);
5090
5539
  setFocus(4 /* TERMINAL */);
5091
5540
  pty2.resize(termInner, contentHeight - 2);
@@ -5276,8 +5725,8 @@ function App({ unsafe, onExit }) {
5276
5725
  connectPty(key, setupPty);
5277
5726
  }, [unsafe, termInner, contentHeight, refreshSessions, connectPty, registerPty, savedSessionCursor, config]);
5278
5727
  useEffect(() => {
5279
- const handler = (data) => {
5280
- const key = data.toString("utf8");
5728
+ const handleKey = (key) => {
5729
+ const layout = layoutRef.current;
5281
5730
  const mouseMatch = MOUSE_SGR_RE.exec(key);
5282
5731
  if (mouseMatch) {
5283
5732
  const button = parseInt(mouseMatch[1], 10);
@@ -5285,48 +5734,52 @@ function App({ unsafe, onExit }) {
5285
5734
  const row = parseInt(mouseMatch[3], 10);
5286
5735
  if (button === 64 || button === 65) {
5287
5736
  const delta = button === 64 ? -1 : 1;
5288
- if (col <= sidebarWidth) {
5289
- if (row <= sessionPaneHeight) {
5737
+ if (col <= layout.sidebarWidth) {
5738
+ if (row <= layout.sessionPaneHeight) {
5290
5739
  moveSessionCursor(delta);
5291
- } else if (row <= sessionPaneHeight + prPaneHeight) {
5740
+ } else if (row <= layout.sessionPaneHeight + layout.prPaneHeight) {
5292
5741
  movePrCursor(delta);
5293
- } else if (jiraPaneHeight > 0 && row <= sessionPaneHeight + prPaneHeight + jiraPaneHeight) {
5742
+ } else if (layout.jiraPaneHeight > 0 && row <= layout.sessionPaneHeight + layout.prPaneHeight + layout.jiraPaneHeight) {
5294
5743
  moveJiraCursor(delta);
5295
5744
  } else {
5296
5745
  moveTaskCursor(delta);
5297
5746
  }
5298
5747
  } else {
5299
- const pty2 = activeKeyRef.current ? ptySessions.current.get(activeKeyRef.current) : void 0;
5300
- if (pty2 && !pty2.exited) {
5301
- const maxScroll = pty2.terminal.buffer.active.baseY;
5302
- const newScroll = Math.max(0, Math.min(maxScroll, termScrollBack.current - delta * 3));
5303
- if (newScroll !== termScrollBack.current) {
5304
- termScrollBack.current = newScroll;
5305
- renderTermAtScroll();
5306
- }
5307
- }
5748
+ scrollTerminal(-delta * 3);
5308
5749
  }
5309
5750
  return;
5310
5751
  }
5311
5752
  if (button === 0) {
5312
- if (col <= sidebarWidth) {
5313
- if (row <= sessionPaneHeight) {
5753
+ if (col <= layout.sidebarWidth) {
5754
+ if (row <= layout.sessionPaneHeight) {
5314
5755
  setFocus(0 /* SESSIONS */);
5315
5756
  const visualIdx = row - 2;
5316
- if (visualIdx >= 0) setSessionCursor(visualRowToCursor(topRowsRef.current, visualIdx));
5317
- } else if (row <= sessionPaneHeight + prPaneHeight) {
5757
+ if (visualIdx >= 0) {
5758
+ const offset = computeScrollOffset(topRowsRef.current, sessionCursorRef.current, layout.sessionPaneHeight - 2);
5759
+ setSessionCursor(visualRowToCursor(topRowsRef.current, visualIdx + offset));
5760
+ }
5761
+ } else if (row <= layout.sessionPaneHeight + layout.prPaneHeight) {
5318
5762
  setFocus(2 /* PRS */);
5319
- const visualIdx = row - sessionPaneHeight - 2;
5320
- if (visualIdx >= 0) setPrCursor(visualRowToCursor(prRowsRef.current, visualIdx));
5321
- } else if (jiraPaneHeight > 0 && row <= sessionPaneHeight + prPaneHeight + jiraPaneHeight) {
5763
+ const visualIdx = row - layout.sessionPaneHeight - 2;
5764
+ if (visualIdx >= 0) {
5765
+ const offset = computeScrollOffset(prRowsRef.current, prCursorRef.current, layout.prPaneHeight - 2);
5766
+ setPrCursor(visualRowToCursor(prRowsRef.current, visualIdx + offset));
5767
+ }
5768
+ } else if (layout.jiraPaneHeight > 0 && row <= layout.sessionPaneHeight + layout.prPaneHeight + layout.jiraPaneHeight) {
5322
5769
  setFocus(3 /* JIRA */);
5323
- const visualIdx = row - sessionPaneHeight - prPaneHeight - 2;
5324
- if (visualIdx >= 0) setJiraCursor(visualRowToCursor(jiraRowsRef.current, visualIdx));
5770
+ const visualIdx = row - layout.sessionPaneHeight - layout.prPaneHeight - 2;
5771
+ if (visualIdx >= 0) {
5772
+ const offset = computeScrollOffset(jiraRowsRef.current, jiraCursorRef.current, layout.jiraPaneHeight - 2);
5773
+ setJiraCursor(visualRowToCursor(jiraRowsRef.current, visualIdx + offset));
5774
+ }
5325
5775
  } else {
5326
5776
  setFocus(1 /* TASKS */);
5327
- const taskStart = sessionPaneHeight + prPaneHeight + jiraPaneHeight;
5777
+ const taskStart = layout.sessionPaneHeight + layout.prPaneHeight + layout.jiraPaneHeight;
5328
5778
  const visualIdx = row - taskStart - 2;
5329
- if (visualIdx >= 0) setTaskCursor(visualRowToCursor(taskRowsRef.current, visualIdx));
5779
+ if (visualIdx >= 0) {
5780
+ const offset = computeScrollOffset(taskRowsRef.current, taskCursorRef.current, layout.taskPaneHeight - 2);
5781
+ setTaskCursor(visualRowToCursor(taskRowsRef.current, visualIdx + offset));
5782
+ }
5330
5783
  }
5331
5784
  } else {
5332
5785
  const activePty = activeKeyRef.current ? ptySessions.current.get(activeKeyRef.current) : void 0;
@@ -5337,18 +5790,25 @@ function App({ unsafe, onExit }) {
5337
5790
  }
5338
5791
  return;
5339
5792
  }
5793
+ if (showHelpRef.current) {
5794
+ if (key === "?" || key === KEYS.ESC || key === "q" || key === KEYS.CTRL_C) {
5795
+ setShowHelp(false);
5796
+ }
5797
+ return;
5798
+ }
5340
5799
  if (branchInputRef.current) {
5341
- if (key === "\x1B" || key === "") {
5800
+ const { projectName, isGroup, value, pos } = branchInputRef.current;
5801
+ const { state, action } = editLine({ value, pos }, key);
5802
+ if (action === "cancel") {
5342
5803
  setBranchInput(null);
5343
5804
  setTopPaneMode(1 /* PROJECTS */);
5344
5805
  setMessage("Esc to go back");
5345
5806
  return;
5346
5807
  }
5347
- if (key === "\r") {
5348
- const { projectName, value, isGroup } = branchInputRef.current;
5808
+ if (action === "submit") {
5349
5809
  setBranchInput(null);
5350
- if (value.trim()) {
5351
- handleCreateWorktree(projectName, value.trim());
5810
+ if (state.value.trim()) {
5811
+ handleCreateWorktree(projectName, state.value.trim());
5352
5812
  } else if (!isGroup) {
5353
5813
  handleLaunchBaseRepo(projectName);
5354
5814
  } else {
@@ -5356,12 +5816,36 @@ function App({ unsafe, onExit }) {
5356
5816
  }
5357
5817
  return;
5358
5818
  }
5359
- if (key === "\x7F" || key === "\b") {
5360
- setBranchInput((prev) => prev ? { ...prev, value: prev.value.slice(0, -1) } : null);
5819
+ setBranchInput({ projectName, isGroup, ...state });
5820
+ return;
5821
+ }
5822
+ if (filterRef.current?.editing) {
5823
+ if (key === KEYS.UP) {
5824
+ moveSessionCursor(-1);
5361
5825
  return;
5362
5826
  }
5363
- if (key.charCodeAt(0) < 32) return;
5364
- setBranchInput((prev) => prev ? { ...prev, value: prev.value + key } : null);
5827
+ if (key === KEYS.DOWN) {
5828
+ moveSessionCursor(1);
5829
+ return;
5830
+ }
5831
+ const current = filterRef.current.value;
5832
+ const { state, action } = editLine({ value: current, pos: current.length }, key);
5833
+ if (action === "cancel") {
5834
+ setFilter(null);
5835
+ setSessionCursor(0);
5836
+ setMessage("");
5837
+ return;
5838
+ }
5839
+ if (action === "submit" || key === TAB_KEY) {
5840
+ const value = current.trim();
5841
+ setFilter(value ? { value, editing: false } : null);
5842
+ setMessage(value ? `Filtering: ${value} (esc clears)` : "");
5843
+ return;
5844
+ }
5845
+ if (state.value !== current) {
5846
+ setFilter({ value: state.value, editing: true });
5847
+ setSessionCursor(0);
5848
+ }
5365
5849
  return;
5366
5850
  }
5367
5851
  if (key === TAB_KEY) {
@@ -5394,11 +5878,24 @@ function App({ unsafe, onExit }) {
5394
5878
  setMessage("");
5395
5879
  return;
5396
5880
  }
5397
- termScrollBack.current = 0;
5881
+ if (key === KEYS.PAGE_UP) {
5882
+ scrollTerminal(Math.max(1, layout.contentHeight - 3));
5883
+ return;
5884
+ }
5885
+ if (key === KEYS.PAGE_DOWN) {
5886
+ scrollTerminal(-Math.max(1, layout.contentHeight - 3));
5887
+ return;
5888
+ }
5889
+ if (termScrollBack.current > 0) setScrollBack(0);
5398
5890
  ptySessions.current.get(activeKeyRef.current)?.write(key);
5399
5891
  return;
5400
5892
  }
5401
5893
  setMessage("");
5894
+ if (pendingRemoveRef.current && key !== "d") setPendingRemoveKey(null);
5895
+ if (key === "?") {
5896
+ setShowHelp(true);
5897
+ return;
5898
+ }
5402
5899
  if (key === "G") {
5403
5900
  if (syncing) return;
5404
5901
  setSyncing(true);
@@ -5413,8 +5910,7 @@ function App({ unsafe, onExit }) {
5413
5910
  );
5414
5911
  }
5415
5912
  refreshSessions();
5416
- refreshPrs();
5417
- refreshJira();
5913
+ await Promise.all([refreshPrs(), refreshJira()]);
5418
5914
  refreshTasks();
5419
5915
  computeConflictsAndMerged(sessionsRef.current);
5420
5916
  setSyncing(false);
@@ -5422,6 +5918,33 @@ function App({ unsafe, onExit }) {
5422
5918
  })();
5423
5919
  return;
5424
5920
  }
5921
+ if (taskInputRef.current === null) {
5922
+ const pageJump = (dir, full) => {
5923
+ const heightFor = focusRef.current === 2 /* PRS */ ? layout.prPaneHeight : focusRef.current === 3 /* JIRA */ ? layout.jiraPaneHeight : focusRef.current === 1 /* TASKS */ ? layout.taskPaneHeight : layout.sessionPaneHeight;
5924
+ const page = Math.max(1, full ? heightFor - 2 : Math.floor((heightFor - 2) / 2));
5925
+ const delta = page * dir;
5926
+ if (focusRef.current === 2 /* PRS */) movePrCursor(delta);
5927
+ else if (focusRef.current === 3 /* JIRA */) moveJiraCursor(delta);
5928
+ else if (focusRef.current === 1 /* TASKS */) moveTaskCursor(delta);
5929
+ else moveSessionCursor(delta);
5930
+ };
5931
+ if (key === KEYS.PAGE_UP) {
5932
+ pageJump(-1, true);
5933
+ return;
5934
+ }
5935
+ if (key === KEYS.PAGE_DOWN) {
5936
+ pageJump(1, true);
5937
+ return;
5938
+ }
5939
+ if (key === KEYS.CTRL_U) {
5940
+ pageJump(-1, false);
5941
+ return;
5942
+ }
5943
+ if (key === KEYS.CTRL_D) {
5944
+ pageJump(1, false);
5945
+ return;
5946
+ }
5947
+ }
5425
5948
  if (topPaneModeRef.current === 1 /* PROJECTS */) {
5426
5949
  if (key === "\x1B" || key === "" || key === "q") {
5427
5950
  setTopPaneMode(0 /* SESSIONS */);
@@ -5466,7 +5989,7 @@ function App({ unsafe, onExit }) {
5466
5989
  handleCreateWorktree(row.name, branch);
5467
5990
  } else {
5468
5991
  setTopPaneMode(2 /* BRANCH_INPUT */);
5469
- setBranchInput({ projectName: row.name, value: "", isGroup: row.isGroup });
5992
+ setBranchInput({ projectName: row.name, value: "", pos: 0, isGroup: row.isGroup });
5470
5993
  setMessage(row.isGroup ? "Type branch name, Enter to create, Esc to cancel" : "Type branch name (empty for base repo), Enter to create, Esc to cancel");
5471
5994
  }
5472
5995
  }
@@ -5476,14 +5999,15 @@ function App({ unsafe, onExit }) {
5476
5999
  }
5477
6000
  if (focusRef.current === 1 /* TASKS */) {
5478
6001
  if (taskInputRef.current !== null) {
5479
- if (key === "\x1B" || key === "") {
6002
+ const { state, action } = editLine(taskInputRef.current, key);
6003
+ if (action === "cancel") {
5480
6004
  setTaskInput(null);
5481
6005
  setTaskEditId(null);
5482
6006
  setMessage("");
5483
6007
  return;
5484
6008
  }
5485
- if (key === "\r") {
5486
- const text = taskInputRef.current.trim();
6009
+ if (action === "submit") {
6010
+ const text = taskInputRef.current.value.trim();
5487
6011
  const editId = taskEditIdRef.current;
5488
6012
  setTaskInput(null);
5489
6013
  setTaskEditId(null);
@@ -5498,12 +6022,7 @@ function App({ unsafe, onExit }) {
5498
6022
  }
5499
6023
  return;
5500
6024
  }
5501
- if (key === "\x7F" || key === "\b") {
5502
- setTaskInput((prev) => prev !== null ? prev.slice(0, -1) : null);
5503
- return;
5504
- }
5505
- if (key.charCodeAt(0) < 32) return;
5506
- setTaskInput((prev) => prev !== null ? prev + key : null);
6025
+ setTaskInput(state);
5507
6026
  return;
5508
6027
  }
5509
6028
  if (key === "\x1B[A" || key === "k") {
@@ -5523,7 +6042,7 @@ function App({ unsafe, onExit }) {
5523
6042
  return;
5524
6043
  }
5525
6044
  if (key === "a") {
5526
- setTaskInput("");
6045
+ setTaskInput({ value: "", pos: 0 });
5527
6046
  setMessage("Type task, Enter to add, Esc to cancel");
5528
6047
  return;
5529
6048
  }
@@ -5531,7 +6050,7 @@ function App({ unsafe, onExit }) {
5531
6050
  const row = cursorToRow(taskRowsRef.current, taskCursorRef.current);
5532
6051
  if (row?.type === "task") {
5533
6052
  setTaskEditId(row.task.id);
5534
- setTaskInput(row.task.text);
6053
+ setTaskInput({ value: row.task.text, pos: row.task.text.length });
5535
6054
  setMessage("Edit task, Enter to save, Esc to cancel");
5536
6055
  }
5537
6056
  return;
@@ -5687,6 +6206,16 @@ function App({ unsafe, onExit }) {
5687
6206
  onExit();
5688
6207
  return;
5689
6208
  }
6209
+ if (key === KEYS.ESC && filterRef.current) {
6210
+ setFilter(null);
6211
+ setSessionCursor(0);
6212
+ return;
6213
+ }
6214
+ if (key === "/" && topPaneModeRef.current === 0 /* SESSIONS */) {
6215
+ setFilter({ value: filterRef.current?.value ?? "", editing: true });
6216
+ setMessage("Type to filter, Enter to keep, Esc to clear");
6217
+ return;
6218
+ }
5690
6219
  if (key === "\x1B[A" || key === "k") {
5691
6220
  moveSessionCursor(-1);
5692
6221
  return;
@@ -5707,6 +6236,12 @@ function App({ unsafe, onExit }) {
5707
6236
  if (row?.type !== "session") return;
5708
6237
  const s = row.session;
5709
6238
  const k = sessionKey2(s);
6239
+ if (pendingRemoveRef.current !== k) {
6240
+ setPendingRemoveKey(k);
6241
+ setMessage(`Remove ${s.target}/${s.branch}? Press d again to confirm, any other key cancels`);
6242
+ return;
6243
+ }
6244
+ setPendingRemoveKey(null);
5710
6245
  const pty2 = ptySessions.current.get(k);
5711
6246
  if (pty2) {
5712
6247
  notifiedSessionsRef.current.delete(ptyDedupKey(pty2));
@@ -5763,14 +6298,22 @@ function App({ unsafe, onExit }) {
5763
6298
  setMessage("Session path no longer exists");
5764
6299
  return;
5765
6300
  }
5766
- setMessage(`Rebasing ${s.branch}...`);
5767
- const err = rebaseOntoMain(s.branch, existing);
5768
- if (err) {
5769
- setMessage(`Rebase failed: ${err}`);
5770
- } else {
5771
- setMessage(`Rebased ${s.branch} onto main`);
5772
- computeConflictsAndMerged(sessionsRef.current);
6301
+ if (rebasingRef.current) {
6302
+ setMessage("A rebase is already running");
6303
+ return;
5773
6304
  }
6305
+ rebasingRef.current = true;
6306
+ setMessage(`Rebasing ${s.branch}...`);
6307
+ void rebaseOntoMainAsync(s.branch, existing).then((err) => {
6308
+ if (err) {
6309
+ setMessage(`Rebase failed: ${err}`);
6310
+ } else {
6311
+ setMessage(`Rebased ${s.branch} onto main`);
6312
+ computeConflictsAndMerged(sessionsRef.current);
6313
+ }
6314
+ }).catch((e) => setMessage(`Rebase failed: ${e.message}`)).finally(() => {
6315
+ rebasingRef.current = false;
6316
+ });
5774
6317
  return;
5775
6318
  }
5776
6319
  if (key === "g") {
@@ -5787,7 +6330,7 @@ function App({ unsafe, onExit }) {
5787
6330
  );
5788
6331
  }
5789
6332
  refreshSessions();
5790
- refreshPrs();
6333
+ await refreshPrs();
5791
6334
  computeConflictsAndMerged(sessionsRef.current);
5792
6335
  setSyncing(false);
5793
6336
  setMessage("Sessions synced");
@@ -5796,18 +6339,23 @@ function App({ unsafe, onExit }) {
5796
6339
  }
5797
6340
  if (key === "r") {
5798
6341
  refreshSessions();
5799
- refreshPrs();
5800
- refreshJira();
6342
+ void refreshPrs();
6343
+ void refreshJira();
5801
6344
  refreshTasks();
5802
6345
  if (!ghAvailable) setMessage("Refreshed");
5803
6346
  return;
5804
6347
  }
5805
6348
  };
6349
+ const handler = (data) => {
6350
+ for (const key of splitInputChunks(data.toString("utf8"))) {
6351
+ handleKey(key);
6352
+ }
6353
+ };
5806
6354
  process.stdin.on("data", handler);
5807
6355
  return () => {
5808
6356
  process.stdin.removeListener("data", handler);
5809
6357
  };
5810
- }, [onExit, activateSession, refreshSessions, refreshPrs, refreshJira, refreshTasks, moveSessionCursor, movePrCursor, moveJiraCursor, moveTaskCursor, syncSessionCursorToActive, handleCreateWorktree, savedSessionCursor, config, computeConflictsAndMerged, syncing, ghAvailable, prMap]);
6358
+ }, [onExit, activateSession, refreshSessions, refreshPrs, refreshJira, refreshTasks, moveSessionCursor, movePrCursor, moveJiraCursor, moveTaskCursor, syncSessionCursorToActive, handleCreateWorktree, handleLaunchBaseRepo, savedSessionCursor, config, computeConflictsAndMerged, syncing, ghAvailable, prMap, scrollTerminal, setScrollBack]);
5811
6359
  useEffect(() => {
5812
6360
  const handler = () => {
5813
6361
  const newCols = process.stdout.columns || 80;
@@ -5819,6 +6367,10 @@ function App({ unsafe, onExit }) {
5819
6367
  const newTermInner = newCols - Math.min(60, Math.floor(newCols * 0.525)) - 2;
5820
6368
  const newContentHeight = newRows - 3;
5821
6369
  pty2.resize(newTermInner, newContentHeight);
6370
+ try {
6371
+ setTermLines(renderBufferLines(pty2.terminal.buffer.active, newTermInner, newContentHeight, termScrollBack.current));
6372
+ } catch {
6373
+ }
5822
6374
  }
5823
6375
  }
5824
6376
  };
@@ -5838,12 +6390,11 @@ function App({ unsafe, onExit }) {
5838
6390
  }, 5 * 60 * 1e3);
5839
6391
  return () => clearInterval(interval);
5840
6392
  }, []);
5841
- const statusMap = buildStatusMap();
5842
6393
  const placeholder = !activeKey ? "Select a session and press Enter" : "Press Enter to start session";
5843
- return /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", width: cols, height: rows, children: [
5844
- /* @__PURE__ */ jsxs4(Box4, { flexDirection: "row", height: contentHeight, children: [
5845
- /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", width: sidebarWidth, children: [
5846
- /* @__PURE__ */ jsx4(
6394
+ return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", width: cols, height: rows, children: [
6395
+ showHelp2 ? /* @__PURE__ */ jsx5(HelpOverlay, { width: cols, height: contentHeight }) : /* @__PURE__ */ jsxs5(Box5, { flexDirection: "row", height: contentHeight, children: [
6396
+ /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", width: sidebarWidth, children: [
6397
+ /* @__PURE__ */ jsx5(
5847
6398
  Sidebar,
5848
6399
  {
5849
6400
  sidebarRows: topRows,
@@ -5856,10 +6407,11 @@ function App({ unsafe, onExit }) {
5856
6407
  activeKey,
5857
6408
  width: sidebarWidth,
5858
6409
  height: sessionPaneHeight,
5859
- branchInput
6410
+ branchInput,
6411
+ filter
5860
6412
  }
5861
6413
  ),
5862
- /* @__PURE__ */ jsx4(
6414
+ /* @__PURE__ */ jsx5(
5863
6415
  PrPane,
5864
6416
  {
5865
6417
  prRows,
@@ -5870,7 +6422,7 @@ function App({ unsafe, onExit }) {
5870
6422
  height: prPaneHeight
5871
6423
  }
5872
6424
  ),
5873
- jiraPaneHeight > 0 && /* @__PURE__ */ jsx4(
6425
+ jiraPaneHeight > 0 && /* @__PURE__ */ jsx5(
5874
6426
  JiraPane,
5875
6427
  {
5876
6428
  jiraRows,
@@ -5880,7 +6432,7 @@ function App({ unsafe, onExit }) {
5880
6432
  height: jiraPaneHeight
5881
6433
  }
5882
6434
  ),
5883
- /* @__PURE__ */ jsx4(
6435
+ /* @__PURE__ */ jsx5(
5884
6436
  TaskPane,
5885
6437
  {
5886
6438
  taskRows,
@@ -5892,7 +6444,7 @@ function App({ unsafe, onExit }) {
5892
6444
  }
5893
6445
  )
5894
6446
  ] }),
5895
- /* @__PURE__ */ jsx4(
6447
+ /* @__PURE__ */ jsx5(
5896
6448
  TerminalPane,
5897
6449
  {
5898
6450
  lines: termLines,
@@ -5900,16 +6452,17 @@ function App({ unsafe, onExit }) {
5900
6452
  height: contentHeight,
5901
6453
  focused: focus === 4 /* TERMINAL */,
5902
6454
  placeholder,
5903
- title: "Terminal"
6455
+ title: "Terminal",
6456
+ scrollback: termScroll
5904
6457
  }
5905
6458
  )
5906
6459
  ] }),
5907
- /* @__PURE__ */ jsx4(StatusBar, { message, pane: focus === 4 /* TERMINAL */ ? "terminal" : focus === 2 /* PRS */ ? "prs" : focus === 3 /* JIRA */ ? "jira" : focus === 1 /* TASKS */ ? "tasks" : "sessions", syncing })
6460
+ /* @__PURE__ */ jsx5(StatusBar, { message, pane: focus === 4 /* TERMINAL */ ? "terminal" : focus === 2 /* PRS */ ? "prs" : focus === 3 /* JIRA */ ? "jira" : focus === 1 /* TASKS */ ? "tasks" : "sessions", syncing })
5908
6461
  ] });
5909
6462
  }
5910
6463
 
5911
6464
  // src/tui-ink/index.tsx
5912
- import { jsx as jsx5 } from "react/jsx-runtime";
6465
+ import { jsx as jsx6 } from "react/jsx-runtime";
5913
6466
  function crashLog(label2, err) {
5914
6467
  try {
5915
6468
  const msg = err instanceof Error ? err.stack || err.message : String(err);
@@ -5928,11 +6481,11 @@ async function startDashboard(unsafe) {
5928
6481
  process.stdin.setRawMode(true);
5929
6482
  process.stdin.resume();
5930
6483
  const restore = () => {
5931
- process.stdout.write("\x1B]0;\x07\x1B[?25h\x1B[?1049l");
6484
+ process.stdout.write("\x1B]0;\x07\x1B[?1000l\x1B[?1006l\x1B[?25h\x1B[?1049l");
5932
6485
  };
5933
6486
  try {
5934
6487
  const { waitUntilExit, unmount } = render(
5935
- /* @__PURE__ */ jsx5(App, { unsafe, onExit: () => {
6488
+ /* @__PURE__ */ jsx6(App, { unsafe, onExit: () => {
5936
6489
  unmount();
5937
6490
  restore();
5938
6491
  process.exit(0);
@@ -6337,9 +6890,9 @@ var hydrateCommand = {
6337
6890
  };
6338
6891
 
6339
6892
  // src/commands/diff.ts
6340
- import fs35 from "fs";
6893
+ import fs36 from "fs";
6341
6894
  import os9 from "os";
6342
- import path32 from "path";
6895
+ import path33 from "path";
6343
6896
  import { spawn as childSpawn } from "child_process";
6344
6897
  import chalk21 from "chalk";
6345
6898
 
@@ -7041,11 +7594,12 @@ function resolveBase(scope, argv) {
7041
7594
  }
7042
7595
  return { base: "HEAD", source: "default" };
7043
7596
  }
7044
- function buildRepoSpecs(scope, base) {
7597
+ function buildRepoSpecs(scope, base, perRepoBase) {
7045
7598
  return scope.repos.map((r) => {
7046
- let diffArg = base;
7047
- if (base !== "HEAD") {
7048
- const mb = git(["merge-base", base, "HEAD"], r.root);
7599
+ const repoBase = perRepoBase?.[r.root] ?? base;
7600
+ let diffArg = repoBase;
7601
+ if (repoBase !== "HEAD") {
7602
+ const mb = git(["merge-base", repoBase, "HEAD"], r.root);
7049
7603
  if (mb.exitCode === 0 && mb.stdout) diffArg = mb.stdout;
7050
7604
  }
7051
7605
  return { name: r.name, root: r.root, diffArg };
@@ -7062,6 +7616,17 @@ function resolveRepoDiff(root, base, sessionBaseBranch) {
7062
7616
  if (mb.exitCode === 0 && mb.stdout) diffArg = mb.stdout;
7063
7617
  return { resolvedBase: parent, diffArg };
7064
7618
  }
7619
+ function sessionBaseForPath(root) {
7620
+ const norm = normPath(root);
7621
+ for (const s of loadHistory()) {
7622
+ for (const p of s.paths) {
7623
+ if (normPath(p) === norm) {
7624
+ return s.baseBranches?.[p] ?? s.baseBranch;
7625
+ }
7626
+ }
7627
+ }
7628
+ return void 0;
7629
+ }
7065
7630
 
7066
7631
  // src/core/comment-server.ts
7067
7632
  import { Hono as Hono2 } from "hono";
@@ -7149,9 +7714,56 @@ import { Hono } from "hono";
7149
7714
  import { serve } from "@hono/node-server";
7150
7715
  import { streamSSE } from "hono/streaming";
7151
7716
 
7152
- // src/core/fs-watcher.ts
7717
+ // src/core/file-context.ts
7153
7718
  import fs31 from "fs";
7154
7719
  import path28 from "path";
7720
+ import spawn10 from "cross-spawn";
7721
+ function readContextLines(opts) {
7722
+ const { root, relPath, ref } = opts;
7723
+ if (!relPath || !isInsideRoot(root, relPath)) return null;
7724
+ const start = Math.max(1, Math.floor(opts.start));
7725
+ const end = Math.max(start, Math.floor(opts.end));
7726
+ const content = !ref || ref === "working" ? readWorkingTree(root, relPath) : readAtRef(root, ref, relPath);
7727
+ if (content === null) return null;
7728
+ const all = content.split(/\r?\n/);
7729
+ if (all.length > 0 && all[all.length - 1] === "") all.pop();
7730
+ const totalLines = all.length;
7731
+ const slice = all.slice(start - 1, end);
7732
+ return {
7733
+ lines: slice,
7734
+ start,
7735
+ totalLines,
7736
+ eof: end >= totalLines
7737
+ };
7738
+ }
7739
+ function readWorkingTree(root, relPath) {
7740
+ try {
7741
+ const absPath = path28.join(root, relPath);
7742
+ const realRoot2 = fs31.realpathSync(path28.resolve(root));
7743
+ const realPath = fs31.realpathSync(absPath);
7744
+ const sep = path28.sep;
7745
+ if (realPath !== realRoot2 && !realPath.startsWith(realRoot2 + sep)) {
7746
+ return null;
7747
+ }
7748
+ return fs31.readFileSync(absPath, "utf-8");
7749
+ } catch {
7750
+ return null;
7751
+ }
7752
+ }
7753
+ function readAtRef(root, ref, relPath) {
7754
+ const r = spawn10.sync("git", ["show", `${ref}:${relPath}`], {
7755
+ cwd: root,
7756
+ encoding: "utf-8",
7757
+ maxBuffer: 64 * 1024 * 1024,
7758
+ windowsHide: true
7759
+ });
7760
+ if (r.status === 0 && typeof r.stdout === "string") return r.stdout;
7761
+ return null;
7762
+ }
7763
+
7764
+ // src/core/fs-watcher.ts
7765
+ import fs32 from "fs";
7766
+ import path29 from "path";
7155
7767
  import chalk19 from "chalk";
7156
7768
  import chokidar from "chokidar";
7157
7769
  var IGNORED_DIRS = /* @__PURE__ */ new Set([
@@ -7177,7 +7789,7 @@ var IGNORED_DIRS = /* @__PURE__ */ new Set([
7177
7789
  ]);
7178
7790
  function isIgnoredWatchPath(roots, filePath) {
7179
7791
  for (const root of roots) {
7180
- const rel = path28.relative(root, filePath).replace(/\\/g, "/");
7792
+ const rel = path29.relative(root, filePath).replace(/\\/g, "/");
7181
7793
  if (rel === "" || rel.startsWith("../")) continue;
7182
7794
  if (rel.split("/").some((seg) => IGNORED_DIRS.has(seg))) return true;
7183
7795
  }
@@ -7201,8 +7813,8 @@ function createFsWatcher(opts) {
7201
7813
  };
7202
7814
  if (SUPPORTS_RECURSIVE_WATCH) {
7203
7815
  const watchers = opts.roots.map((root) => {
7204
- const w = fs31.watch(root, { recursive: true }, (_event, filename) => {
7205
- if (filename && isIgnoredWatchPath([root], path28.join(root, filename.toString()))) {
7816
+ const w = fs32.watch(root, { recursive: true }, (_event, filename) => {
7817
+ if (filename && isIgnoredWatchPath([root], path29.join(root, filename.toString()))) {
7206
7818
  return;
7207
7819
  }
7208
7820
  fire();
@@ -7240,30 +7852,30 @@ function createFsWatcher(opts) {
7240
7852
  }
7241
7853
 
7242
7854
  // src/core/web-static.ts
7243
- import fs32 from "fs";
7244
- import path29 from "path";
7855
+ import fs33 from "fs";
7856
+ import path30 from "path";
7245
7857
  import { fileURLToPath } from "url";
7246
7858
  function resolveWebRoot() {
7247
- const entryDir = path29.dirname(process.argv[1] ?? "");
7248
- const moduleDir = path29.dirname(fileURLToPath(import.meta.url));
7859
+ const entryDir = path30.dirname(process.argv[1] ?? "");
7860
+ const moduleDir = path30.dirname(fileURLToPath(import.meta.url));
7249
7861
  const candidates = [
7250
- path29.join(entryDir, "web"),
7862
+ path30.join(entryDir, "web"),
7251
7863
  // bundled: this module is inlined into dist/<bin>.js, so dist/web is a
7252
7864
  // sibling of the bundle. Works even when argv[1] is an npm bin symlink
7253
7865
  // (which is not realpath'd, so the entryDir candidate above misses).
7254
- path29.join(moduleDir, "web"),
7866
+ path30.join(moduleDir, "web"),
7255
7867
  // dev/tsx fallback: walk up from src/core to repo root then into dist/web.
7256
- path29.resolve(moduleDir, "../../dist/web")
7868
+ path30.resolve(moduleDir, "../../dist/web")
7257
7869
  ];
7258
7870
  for (const c of candidates) {
7259
- if (fs32.existsSync(path29.join(c, "index.html"))) return c;
7871
+ if (fs33.existsSync(path30.join(c, "index.html"))) return c;
7260
7872
  }
7261
7873
  return null;
7262
7874
  }
7263
7875
 
7264
7876
  // src/core/spa-handler.ts
7265
- import fs33 from "fs";
7266
- import path30 from "path";
7877
+ import fs34 from "fs";
7878
+ import path31 from "path";
7267
7879
  var MIME = {
7268
7880
  ".html": "text/html; charset=utf-8",
7269
7881
  ".js": "application/javascript; charset=utf-8",
@@ -7277,18 +7889,18 @@ var MIME = {
7277
7889
  function readFile(root, relPath) {
7278
7890
  const clean = relPath.split("?")[0];
7279
7891
  const requested = clean === "/" ? "/index.html" : clean;
7280
- const filePath = path30.join(root, requested);
7281
- const norm = path30.normalize(filePath);
7282
- if (!norm.startsWith(path30.normalize(root))) return null;
7892
+ const filePath = path31.join(root, requested);
7893
+ const norm = path31.normalize(filePath);
7894
+ if (!norm.startsWith(path31.normalize(root))) return null;
7283
7895
  let stat;
7284
7896
  try {
7285
- stat = fs33.statSync(norm);
7897
+ stat = fs34.statSync(norm);
7286
7898
  } catch {
7287
7899
  return null;
7288
7900
  }
7289
7901
  if (!stat.isFile()) return null;
7290
- const ext = path30.extname(norm).toLowerCase();
7291
- return { body: fs33.readFileSync(norm), ext };
7902
+ const ext = path31.extname(norm).toLowerCase();
7903
+ return { body: fs34.readFileSync(norm), ext };
7292
7904
  }
7293
7905
  function serveSpa(c, webRoot) {
7294
7906
  const url = new URL(c.req.url);
@@ -7344,7 +7956,11 @@ async function startDiffServer(opts) {
7344
7956
  const base = c.req.query("base") === "branch" ? "branch" : "uncommitted";
7345
7957
  try {
7346
7958
  const resolved = opts.repos.map(
7347
- (r) => base === "uncommitted" ? { resolvedBase: "HEAD", diffArg: r.diffArg } : resolveRepoDiff(r.root, "branch", opts.sessionBaseBranch)
7959
+ (r) => base === "uncommitted" ? { resolvedBase: "HEAD", diffArg: r.diffArg } : resolveRepoDiff(
7960
+ r.root,
7961
+ "branch",
7962
+ opts.sessionBaseBranches?.[r.root] ?? opts.sessionBaseBranch
7963
+ )
7348
7964
  );
7349
7965
  const repos = opts.repos.map((r, i) => ({
7350
7966
  name: r.name,
@@ -7358,6 +7974,21 @@ async function startDiffServer(opts) {
7358
7974
  return c.json({ error: err.message }, 500);
7359
7975
  }
7360
7976
  });
7977
+ app.get("/api/file-lines", (c) => {
7978
+ const repoName = c.req.query("repo") ?? "";
7979
+ const relPath = c.req.query("path") ?? "";
7980
+ const start = Number(c.req.query("start"));
7981
+ const end = Number(c.req.query("end"));
7982
+ const ref = c.req.query("ref") || void 0;
7983
+ if (!relPath || !Number.isInteger(start) || !Number.isInteger(end)) {
7984
+ return c.json({ error: "bad path/start/end" }, 400);
7985
+ }
7986
+ const root = opts.repos.length === 1 ? opts.repos[0].root : opts.repos.find((r) => r.name === repoName)?.root;
7987
+ if (!root) return c.json({ error: "unknown repo" }, 404);
7988
+ const result = readContextLines({ root, relPath, start, end, ref });
7989
+ if (!result) return c.json({ error: "cannot read file" }, 400);
7990
+ return c.json(result);
7991
+ });
7361
7992
  app.get(
7362
7993
  "/events",
7363
7994
  (c) => streamSSE(c, async (stream) => {
@@ -7520,6 +8151,7 @@ async function startCommentServer(opts) {
7520
8151
  repos: opts.repos,
7521
8152
  scopeLabel: opts.scopeLabel,
7522
8153
  sessionBaseBranch: opts.sessionBaseBranch,
8154
+ sessionBaseBranches: opts.sessionBaseBranches,
7523
8155
  watchDebounceMs: opts.watchDebounceMs,
7524
8156
  attachRoutes
7525
8157
  });
@@ -7561,8 +8193,8 @@ function diffReviewSnapshot(snapshot, seen) {
7561
8193
  }
7562
8194
 
7563
8195
  // src/core/static-renderer.ts
7564
- import fs34 from "fs";
7565
- import path31 from "path";
8196
+ import fs35 from "fs";
8197
+ import path32 from "path";
7566
8198
  function buildDiff(specs, resolvedBase) {
7567
8199
  return {
7568
8200
  repos: specs.map((r) => ({
@@ -7578,8 +8210,8 @@ function renderStatic(opts) {
7578
8210
  if (!webRoot) {
7579
8211
  throw new Error("Could not find dist/web/. Run `npm run build` first.");
7580
8212
  }
7581
- const shellPath = path31.join(webRoot, "index.html");
7582
- let shell = fs34.readFileSync(shellPath, "utf-8");
8213
+ const shellPath = path32.join(webRoot, "index.html");
8214
+ let shell = fs35.readFileSync(shellPath, "utf-8");
7583
8215
  const uncommitted = buildDiff(opts.uncommitted, "HEAD");
7584
8216
  const branch = opts.branch ? buildDiff(opts.branch.specs, opts.branch.resolvedBase) : void 0;
7585
8217
  const initialBase = opts.initialBase ?? "uncommitted";
@@ -7628,10 +8260,10 @@ function escapeForScriptTag(json) {
7628
8260
  }
7629
8261
  function readAsset(webRoot, urlPath) {
7630
8262
  const clean = urlPath.split("?")[0].replace(/^\//, "");
7631
- const full = path31.join(webRoot, clean);
7632
- if (!path31.normalize(full).startsWith(path31.normalize(webRoot))) return null;
8263
+ const full = path32.join(webRoot, clean);
8264
+ if (!path32.normalize(full).startsWith(path32.normalize(webRoot))) return null;
7633
8265
  try {
7634
- return fs34.readFileSync(full, "utf-8");
8266
+ return fs35.readFileSync(full, "utf-8");
7635
8267
  } catch {
7636
8268
  return null;
7637
8269
  }
@@ -7672,22 +8304,22 @@ async function runStop(repoSpecs) {
7672
8304
  }
7673
8305
  }
7674
8306
  function webUrlFilePath() {
7675
- return path32.join(os9.homedir(), ".work", "web.url");
8307
+ return path33.join(os9.homedir(), ".work", "web.url");
7676
8308
  }
7677
8309
  function resolveWorkBinPath(selfArgv1) {
7678
8310
  let real = selfArgv1;
7679
8311
  try {
7680
- real = fs35.realpathSync(selfArgv1);
8312
+ real = fs36.realpathSync(selfArgv1);
7681
8313
  } catch {
7682
8314
  }
7683
8315
  if (real.endsWith("wd-bin.js")) {
7684
- return path32.join(path32.dirname(real), "bin.js");
8316
+ return path33.join(path33.dirname(real), "bin.js");
7685
8317
  }
7686
8318
  return real;
7687
8319
  }
7688
8320
  function readWebUrl() {
7689
8321
  try {
7690
- const v = fs35.readFileSync(webUrlFilePath(), "utf-8").trim();
8322
+ const v = fs36.readFileSync(webUrlFilePath(), "utf-8").trim();
7691
8323
  return v || null;
7692
8324
  } catch {
7693
8325
  return null;
@@ -7697,8 +8329,8 @@ async function ensureWorkWebRunning() {
7697
8329
  const existing = readWebUrl();
7698
8330
  if (existing) return existing;
7699
8331
  const workBin = resolveWorkBinPath(process.argv[1]);
7700
- const out = fs35.openSync(
7701
- path32.join(os9.homedir(), ".work", "web-autostart.log"),
8332
+ const out = fs36.openSync(
8333
+ path33.join(os9.homedir(), ".work", "web-autostart.log"),
7702
8334
  "a"
7703
8335
  );
7704
8336
  const child = childSpawn(
@@ -7713,7 +8345,7 @@ async function ensureWorkWebRunning() {
7713
8345
  }
7714
8346
  );
7715
8347
  child.unref();
7716
- fs35.closeSync(out);
8348
+ fs36.closeSync(out);
7717
8349
  const url = await waitForUrlFile(webUrlFilePath(), 5e3);
7718
8350
  return url;
7719
8351
  }
@@ -7757,9 +8389,10 @@ async function runLauncher(ctx) {
7757
8389
  function runStatic(ctx, initialBranch) {
7758
8390
  const uncommitted = buildRepoSpecs(ctx.scope, "HEAD");
7759
8391
  const primaryRoot = ctx.scope.repos.find((r) => r.name === ctx.scope.activeRepoName)?.root ?? ctx.scope.repos[0].root;
7760
- const parent = ctx.scope.session?.baseBranch ?? findAnyParentBranch(primaryRoot);
8392
+ const perRepoBase = ctx.scope.session?.baseBranches;
8393
+ const parent = perRepoBase?.[primaryRoot] ?? ctx.scope.session?.baseBranch ?? findAnyParentBranch(primaryRoot);
7761
8394
  const branch = parent === null ? void 0 : {
7762
- specs: buildRepoSpecs(ctx.scope, parent),
8395
+ specs: buildRepoSpecs(ctx.scope, parent, perRepoBase),
7763
8396
  resolvedBase: parent
7764
8397
  };
7765
8398
  const uncommittedTotal = uncommitted.reduce(
@@ -7781,7 +8414,7 @@ function runStatic(ctx, initialBranch) {
7781
8414
  initialBase: initialBranch && branch ? "branch" : "uncommitted"
7782
8415
  });
7783
8416
  const filePath = `${ctx.scopeStem}.html`;
7784
- fs35.writeFileSync(filePath, html, "utf-8");
8417
+ fs36.writeFileSync(filePath, html, "utf-8");
7785
8418
  info(chalk21.gray(`Wrote ${filePath}`));
7786
8419
  openUrl(`file:///${filePath.replace(/\\/g, "/")}`);
7787
8420
  }
@@ -7790,7 +8423,7 @@ function waitForUrlFile(filePath, timeoutMs) {
7790
8423
  const start = Date.now();
7791
8424
  const tick = () => {
7792
8425
  try {
7793
- const v = fs35.readFileSync(filePath, "utf-8").trim();
8426
+ const v = fs36.readFileSync(filePath, "utf-8").trim();
7794
8427
  if (v) return resolve(v);
7795
8428
  } catch {
7796
8429
  }
@@ -7930,6 +8563,7 @@ summary-id: ${info3.summary.id}` : ""}
7930
8563
  repos: ctx.repoSpecs,
7931
8564
  scopeLabel: ctx.scopeLabel,
7932
8565
  sessionBaseBranch: ctx.scope.session?.baseBranch,
8566
+ sessionBaseBranches: ctx.scope.session?.baseBranches,
7933
8567
  onComment,
7934
8568
  onCommentDeleted,
7935
8569
  onSubmitReviewStart,
@@ -8036,21 +8670,21 @@ var diffCommand = {
8036
8670
  };
8037
8671
 
8038
8672
  // src/commands/web.ts
8039
- import fs40 from "fs";
8673
+ import fs41 from "fs";
8040
8674
  import os13 from "os";
8041
- import path41 from "path";
8675
+ import path42 from "path";
8042
8676
  import chalk23 from "chalk";
8043
8677
 
8044
8678
  // src/core/web-server.ts
8045
- import fs39 from "fs";
8679
+ import fs40 from "fs";
8046
8680
  import os12 from "os";
8047
- import path40 from "path";
8681
+ import path41 from "path";
8048
8682
  import chalk22 from "chalk";
8049
8683
  import { Hono as Hono3 } from "hono";
8050
8684
  import { streamSSE as streamSSE3 } from "hono/streaming";
8051
8685
 
8052
8686
  // src/core/web-state.ts
8053
- import path33 from "path";
8687
+ import path34 from "path";
8054
8688
  import crypto4 from "crypto";
8055
8689
  import chokidar2 from "chokidar";
8056
8690
  function sessionIdFor(s) {
@@ -8071,7 +8705,7 @@ function subscribeSession(sessionId, onChange) {
8071
8705
  const watcher = chokidar2.watch(roots, {
8072
8706
  ignored: (filePath) => {
8073
8707
  for (const r of roots) {
8074
- const rel = path33.relative(r, filePath).replace(/\\/g, "/");
8708
+ const rel = path34.relative(r, filePath).replace(/\\/g, "/");
8075
8709
  if (rel === ".git" || rel.startsWith(".git/")) return true;
8076
8710
  }
8077
8711
  return false;
@@ -8185,24 +8819,24 @@ function disposeAllPtys() {
8185
8819
  }
8186
8820
 
8187
8821
  // src/core/comment-file-store.ts
8188
- import fs36 from "fs";
8189
- import path34 from "path";
8822
+ import fs37 from "fs";
8823
+ import path35 from "path";
8190
8824
  import os10 from "os";
8191
8825
  function commentsDir() {
8192
- return path34.join(os10.homedir(), ".work", "comments");
8826
+ return path35.join(os10.homedir(), ".work", "comments");
8193
8827
  }
8194
8828
  function ensureDir() {
8195
- fs36.mkdirSync(commentsDir(), { recursive: true });
8829
+ fs37.mkdirSync(commentsDir(), { recursive: true });
8196
8830
  }
8197
8831
  function commentsFileFor(sessionId) {
8198
- return path34.join(commentsDir(), `${sessionId}.json`);
8832
+ return path35.join(commentsDir(), `${sessionId}.json`);
8199
8833
  }
8200
8834
  function pathFor(sessionId) {
8201
8835
  return commentsFileFor(sessionId);
8202
8836
  }
8203
8837
  function readDisk(sessionId) {
8204
8838
  try {
8205
- const raw = fs36.readFileSync(pathFor(sessionId), "utf-8");
8839
+ const raw = fs37.readFileSync(pathFor(sessionId), "utf-8");
8206
8840
  const parsed = JSON.parse(raw);
8207
8841
  return Array.isArray(parsed) ? parsed : [];
8208
8842
  } catch {
@@ -8274,29 +8908,29 @@ function clearCommentStoreCache() {
8274
8908
  }
8275
8909
 
8276
8910
  // src/core/pending-delivery.ts
8277
- import fs37 from "fs";
8278
- import path35 from "path";
8911
+ import fs38 from "fs";
8912
+ import path36 from "path";
8279
8913
  function pathFor2(sessionId) {
8280
8914
  return {
8281
8915
  comments: commentsFileFor(sessionId),
8282
- delivered: path35.join(commentsDir(), `${sessionId}.delivered.json`)
8916
+ delivered: path36.join(commentsDir(), `${sessionId}.delivered.json`)
8283
8917
  };
8284
8918
  }
8285
8919
  function readJson(filePath, fallback) {
8286
8920
  try {
8287
- return JSON.parse(fs37.readFileSync(filePath, "utf8"));
8921
+ return JSON.parse(fs38.readFileSync(filePath, "utf8"));
8288
8922
  } catch {
8289
8923
  return fallback;
8290
8924
  }
8291
8925
  }
8292
8926
  function writeAtomic2(filePath, content) {
8293
- fs37.mkdirSync(path35.dirname(filePath), { recursive: true });
8927
+ fs38.mkdirSync(path36.dirname(filePath), { recursive: true });
8294
8928
  const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
8295
- fs37.writeFileSync(tmp, content, "utf-8");
8296
- fs37.renameSync(tmp, filePath);
8929
+ fs38.writeFileSync(tmp, content, "utf-8");
8930
+ fs38.renameSync(tmp, filePath);
8297
8931
  }
8298
8932
  function normalize(p) {
8299
- return path35.resolve(p).replace(/\\/g, "/").toLowerCase();
8933
+ return path36.resolve(p).replace(/\\/g, "/").toLowerCase();
8300
8934
  }
8301
8935
  function findSessionForCwd(cwd) {
8302
8936
  const norm = normalize(cwd);
@@ -8327,7 +8961,7 @@ function readPendingForSession(sessionId) {
8327
8961
  return comments.filter(isPendingFor(delivered));
8328
8962
  }
8329
8963
  function scopeStoreIdsForPaths(paths) {
8330
- const resolved = paths.map((p) => path35.resolve(p));
8964
+ const resolved = paths.map((p) => path36.resolve(p));
8331
8965
  const ids = /* @__PURE__ */ new Set();
8332
8966
  ids.add(`scope-${scopeHashFor(resolved)}`);
8333
8967
  for (const p of resolved) ids.add(`scope-${scopeHashFor([p])}`);
@@ -8650,8 +9284,8 @@ function mountPanesRoutes(app, opts) {
8650
9284
  }
8651
9285
 
8652
9286
  // src/core/worktree-routes.ts
8653
- import path36 from "path";
8654
- import { spawn as spawn10 } from "child_process";
9287
+ import path37 from "path";
9288
+ import { spawn as spawn11 } from "child_process";
8655
9289
  import { zValidator as zValidator4 } from "@hono/zod-validator";
8656
9290
  import { z as z3 } from "zod";
8657
9291
  function mountWorktreeRoutes(app, opts) {
@@ -8774,10 +9408,10 @@ function mountWorktreeRoutes(app, opts) {
8774
9408
  const id = c.req.param("id");
8775
9409
  const session = findSession2(id);
8776
9410
  if (!session) return c.json({ error: "unknown session" }, 404);
8777
- const target = session.isGroup ? path36.dirname(session.paths[0]) : session.paths[0];
9411
+ const target = session.isGroup ? path37.dirname(session.paths[0]) : session.paths[0];
8778
9412
  try {
8779
9413
  const cmd = process.platform === "win32" ? "code.cmd" : "code";
8780
- const child = spawn10(cmd, [target], {
9414
+ const child = spawn11(cmd, [target], {
8781
9415
  detached: true,
8782
9416
  stdio: "ignore",
8783
9417
  shell: false
@@ -8794,27 +9428,27 @@ function mountWorktreeRoutes(app, opts) {
8794
9428
  import { zValidator as zValidator5 } from "@hono/zod-validator";
8795
9429
  import { z as z4 } from "zod";
8796
9430
  import { EventEmitter } from "events";
8797
- import path39 from "path";
8798
- import spawn12 from "cross-spawn";
9431
+ import path40 from "path";
9432
+ import spawn13 from "cross-spawn";
8799
9433
 
8800
9434
  // src/core/checkpoint.ts
8801
- import fs38 from "fs";
9435
+ import fs39 from "fs";
8802
9436
  import os11 from "os";
8803
- import path37 from "path";
8804
- import spawn11 from "cross-spawn";
9437
+ import path38 from "path";
9438
+ import spawn12 from "cross-spawn";
8805
9439
  function manifestPath(scopeHash) {
8806
- const dir = path37.join(os11.homedir(), ".work", "diffs");
8807
- fs38.mkdirSync(dir, { recursive: true });
8808
- return path37.join(dir, `${scopeHash}.checkpoints.json`);
9440
+ const dir = path38.join(os11.homedir(), ".work", "diffs");
9441
+ fs39.mkdirSync(dir, { recursive: true });
9442
+ return path38.join(dir, `${scopeHash}.checkpoints.json`);
8809
9443
  }
8810
9444
  function emptyManifest(scopeHash) {
8811
9445
  return { version: 1, scopeHash, entries: [] };
8812
9446
  }
8813
9447
  function loadManifest(scopeHash) {
8814
9448
  const file = manifestPath(scopeHash);
8815
- if (!fs38.existsSync(file)) return emptyManifest(scopeHash);
9449
+ if (!fs39.existsSync(file)) return emptyManifest(scopeHash);
8816
9450
  try {
8817
- const raw = fs38.readFileSync(file, "utf-8");
9451
+ const raw = fs39.readFileSync(file, "utf-8");
8818
9452
  const parsed = JSON.parse(raw);
8819
9453
  if (parsed.version !== 1 || !Array.isArray(parsed.entries)) {
8820
9454
  return emptyManifest(scopeHash);
@@ -8843,7 +9477,7 @@ function snapshotRepo(repoRoot, scopeHash, id, includeWorkingTree = true) {
8843
9477
  GIT_COMMITTER_EMAIL: "wd@local",
8844
9478
  GIT_COMMITTER_DATE: "2000-01-01T00:00:00Z"
8845
9479
  };
8846
- const commit = spawn11.sync("git", commitArgs, {
9480
+ const commit = spawn12.sync("git", commitArgs, {
8847
9481
  cwd: repoRoot,
8848
9482
  encoding: "utf-8",
8849
9483
  env: commitEnv,
@@ -8852,7 +9486,7 @@ function snapshotRepo(repoRoot, scopeHash, id, includeWorkingTree = true) {
8852
9486
  if (commit.status !== 0 || !commit.stdout) return null;
8853
9487
  const commitSha = commit.stdout.trim();
8854
9488
  const refName = `refs/wd/${scopeHash}/${id}`;
8855
- const updateRef = spawn11.sync("git", ["update-ref", refName, commitSha], {
9489
+ const updateRef = spawn12.sync("git", ["update-ref", refName, commitSha], {
8856
9490
  cwd: repoRoot,
8857
9491
  encoding: "utf-8",
8858
9492
  windowsHide: true
@@ -8879,7 +9513,7 @@ async function takeCheckpoint(scopeHash, repos, opts = {}) {
8879
9513
  const rollbackRefs = () => {
8880
9514
  const refName = `refs/wd/${scopeHash}/${nextId}`;
8881
9515
  for (const repo of repos) {
8882
- spawn11.sync("git", ["update-ref", "-d", refName], {
9516
+ spawn12.sync("git", ["update-ref", "-d", refName], {
8883
9517
  cwd: repo.root,
8884
9518
  encoding: "utf-8",
8885
9519
  windowsHide: true
@@ -8894,7 +9528,7 @@ async function takeCheckpoint(scopeHash, repos, opts = {}) {
8894
9528
  const prev = manifest.entries[manifest.entries.length - 1];
8895
9529
  const treeOf = (root, commitSha) => {
8896
9530
  if (!commitSha) return null;
8897
- const r = spawn11.sync(
9531
+ const r = spawn12.sync(
8898
9532
  "git",
8899
9533
  ["rev-parse", `${commitSha}^{tree}`],
8900
9534
  { cwd: root, encoding: "utf-8", windowsHide: true }
@@ -8929,7 +9563,7 @@ function clearCheckpoints(scopeHash, repoRoots) {
8929
9563
  for (const root of repoRoots) {
8930
9564
  for (const entry of manifest.entries) {
8931
9565
  const refName = `refs/wd/${scopeHash}/${entry.id}`;
8932
- spawn11.sync("git", ["update-ref", "-d", refName], {
9566
+ spawn12.sync("git", ["update-ref", "-d", refName], {
8933
9567
  cwd: root,
8934
9568
  encoding: "utf-8",
8935
9569
  windowsHide: true
@@ -8937,16 +9571,16 @@ function clearCheckpoints(scopeHash, repoRoots) {
8937
9571
  }
8938
9572
  }
8939
9573
  const file = manifestPath(scopeHash);
8940
- if (fs38.existsSync(file)) {
9574
+ if (fs39.existsSync(file)) {
8941
9575
  try {
8942
- fs38.unlinkSync(file);
9576
+ fs39.unlinkSync(file);
8943
9577
  } catch {
8944
9578
  }
8945
9579
  }
8946
9580
  }
8947
9581
 
8948
9582
  // src/core/scope-manager.ts
8949
- import path38 from "path";
9583
+ import path39 from "path";
8950
9584
  import crypto5 from "crypto";
8951
9585
  var scopes = /* @__PURE__ */ new Map();
8952
9586
  function hashFor(paths) {
@@ -8963,7 +9597,7 @@ var ScopePathRejectedError = class extends Error {
8963
9597
  }
8964
9598
  };
8965
9599
  function normaliseForCompare(p) {
8966
- return path38.resolve(p).replace(/\\/g, "/").toLowerCase();
9600
+ return path39.resolve(p).replace(/\\/g, "/").toLowerCase();
8967
9601
  }
8968
9602
  function rejectedPaths(normalised) {
8969
9603
  const config = loadConfig();
@@ -8981,7 +9615,7 @@ function rejectedPaths(normalised) {
8981
9615
  });
8982
9616
  }
8983
9617
  function registerScope(paths, label2) {
8984
- const normalised = paths.map((p) => path38.resolve(p));
9618
+ const normalised = paths.map((p) => path39.resolve(p));
8985
9619
  const rejected = rejectedPaths(normalised);
8986
9620
  if (rejected.length > 0) throw new ScopePathRejectedError(rejected);
8987
9621
  const hash = hashFor(normalised);
@@ -8995,7 +9629,7 @@ function registerScope(paths, label2) {
8995
9629
  const scope = {
8996
9630
  hash,
8997
9631
  paths: normalised,
8998
- label: label2 ?? path38.basename(normalised[0]),
9632
+ label: label2 ?? path39.basename(normalised[0]),
8999
9633
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
9000
9634
  ended: false
9001
9635
  };
@@ -9068,7 +9702,7 @@ function mountScopeRoutes(app, opts) {
9068
9702
  function workingTreeFingerprint(paths) {
9069
9703
  const parts = [];
9070
9704
  for (const p of paths) {
9071
- const r = spawn12.sync(
9705
+ const r = spawn13.sync(
9072
9706
  "git",
9073
9707
  ["status", "--porcelain", "--no-renames", "-z"],
9074
9708
  { cwd: p, encoding: "utf-8", windowsHide: true }
@@ -9192,7 +9826,7 @@ function mountScopeRoutes(app, opts) {
9192
9826
  const fromSha = fromEntry.repos[p] ?? "HEAD";
9193
9827
  const toSha = toEntry === void 0 ? "working" : toEntry.repos[p] ?? "HEAD";
9194
9828
  return {
9195
- name: path39.basename(p),
9829
+ name: path40.basename(p),
9196
9830
  root: p,
9197
9831
  files: computeRangeDiff({ root: p, fromRef: fromSha, toRef: toSha })
9198
9832
  };
@@ -9206,9 +9840,11 @@ function mountScopeRoutes(app, opts) {
9206
9840
  repos: repos2
9207
9841
  });
9208
9842
  }
9209
- const resolved = scope.paths.map((p) => resolveRepoDiff(p, base));
9843
+ const resolved = scope.paths.map(
9844
+ (p) => resolveRepoDiff(p, base, sessionBaseForPath(p))
9845
+ );
9210
9846
  const repos = scope.paths.map((p, i) => ({
9211
- name: path39.basename(p),
9847
+ name: path40.basename(p),
9212
9848
  root: p,
9213
9849
  resolvedBase: resolved[i].resolvedBase,
9214
9850
  files: computeDiff({ root: p, diffArg: resolved[i].diffArg })
@@ -9227,6 +9863,23 @@ function mountScopeRoutes(app, opts) {
9227
9863
  return c.json({ error: err.message }, 500);
9228
9864
  }
9229
9865
  });
9866
+ app.get("/api/scopes/:hash/file-lines", (c) => {
9867
+ const scope = getScope(c.req.param("hash"));
9868
+ if (!scope) return c.json({ error: "unknown scope" }, 404);
9869
+ const repoName = c.req.query("repo") ?? "";
9870
+ const relPath = c.req.query("path") ?? "";
9871
+ const start = Number(c.req.query("start"));
9872
+ const end = Number(c.req.query("end"));
9873
+ const ref = c.req.query("ref") || void 0;
9874
+ if (!relPath || !Number.isInteger(start) || !Number.isInteger(end)) {
9875
+ return c.json({ error: "bad path/start/end" }, 400);
9876
+ }
9877
+ const root = scope.paths.length === 1 ? scope.paths[0] : scope.paths.find((p) => path40.basename(p) === repoName);
9878
+ if (!root) return c.json({ error: "unknown repo" }, 404);
9879
+ const result = readContextLines({ root, relPath, start, end, ref });
9880
+ if (!result) return c.json({ error: "cannot read file" }, 400);
9881
+ return c.json(result);
9882
+ });
9230
9883
  app.get("/api/scopes/:hash/checkpoints", (c) => {
9231
9884
  const scope = getScope(c.req.param("hash"));
9232
9885
  if (!scope) return c.json({ error: "unknown scope" }, 404);
@@ -9455,9 +10108,11 @@ function sessionToWire(s) {
9455
10108
  };
9456
10109
  }
9457
10110
  function computeSessionDiff(s, base) {
9458
- const resolved = s.paths.map((p) => resolveRepoDiff(p, base, s.baseBranch));
10111
+ const resolved = s.paths.map(
10112
+ (p) => resolveRepoDiff(p, base, s.baseBranches?.[p] ?? s.baseBranch)
10113
+ );
9459
10114
  const repos = s.paths.map((p, i) => ({
9460
- name: path40.basename(p),
10115
+ name: path41.basename(p),
9461
10116
  root: p,
9462
10117
  resolvedBase: resolved[i].resolvedBase,
9463
10118
  files: computeDiff({ root: p, diffArg: resolved[i].diffArg })
@@ -9477,17 +10132,17 @@ async function startWebServer(opts = {}) {
9477
10132
  for (const cb of sseListeners) cb({ event, data });
9478
10133
  };
9479
10134
  const home = os12.homedir();
9480
- const historyPath = path40.join(home, ".work", "history.json");
10135
+ const historyPath = path41.join(home, ".work", "history.json");
9481
10136
  const onHistoryChange = () => broadcast("sessions-changed", { ts: Date.now() });
9482
- fs39.watchFile(historyPath, { interval: 1e3 }, onHistoryChange);
9483
- const tasksPath = path40.join(home, ".work", "tasks.json");
10137
+ fs40.watchFile(historyPath, { interval: 1e3 }, onHistoryChange);
10138
+ const tasksPath = path41.join(home, ".work", "tasks.json");
9484
10139
  const onTasksChange = () => broadcast("tasks-changed", { ts: Date.now() });
9485
- fs39.watchFile(tasksPath, { interval: 1e3 }, onTasksChange);
10140
+ fs40.watchFile(tasksPath, { interval: 1e3 }, onTasksChange);
9486
10141
  const projectsRoot = claudeProjectsRoot();
9487
10142
  let activityWatcher = null;
9488
10143
  if (!lean) {
9489
10144
  try {
9490
- if (fs39.existsSync(projectsRoot)) {
10145
+ if (fs40.existsSync(projectsRoot)) {
9491
10146
  activityWatcher = createFsWatcher({
9492
10147
  roots: [projectsRoot],
9493
10148
  debounceMs: 250,
@@ -9562,8 +10217,8 @@ async function startWebServer(opts = {}) {
9562
10217
  url: handle.url,
9563
10218
  port: handle.port,
9564
10219
  stop: async () => {
9565
- fs39.unwatchFile(historyPath, onHistoryChange);
9566
- fs39.unwatchFile(tasksPath, onTasksChange);
10220
+ fs40.unwatchFile(historyPath, onHistoryChange);
10221
+ fs40.unwatchFile(tasksPath, onTasksChange);
9567
10222
  if (decayTick) clearInterval(decayTick);
9568
10223
  activityWatcher?.stop();
9569
10224
  disposeAllWatchers();
@@ -9625,10 +10280,10 @@ function info2(message) {
9625
10280
  process.stderr.write(message + "\n");
9626
10281
  }
9627
10282
  function urlFilePath() {
9628
- return path41.join(os13.homedir(), ".work", "web.url");
10283
+ return path42.join(os13.homedir(), ".work", "web.url");
9629
10284
  }
9630
10285
  function pidFilePath() {
9631
- return path41.join(os13.homedir(), ".work", "web.pid");
10286
+ return path42.join(os13.homedir(), ".work", "web.pid");
9632
10287
  }
9633
10288
  function isPidAlive(pid) {
9634
10289
  try {
@@ -9640,7 +10295,7 @@ function isPidAlive(pid) {
9640
10295
  }
9641
10296
  function readPid() {
9642
10297
  try {
9643
- const raw = fs40.readFileSync(pidFilePath(), "utf-8").trim();
10298
+ const raw = fs41.readFileSync(pidFilePath(), "utf-8").trim();
9644
10299
  const n = Number(raw);
9645
10300
  return Number.isFinite(n) && n > 0 ? n : null;
9646
10301
  } catch {
@@ -9649,7 +10304,7 @@ function readPid() {
9649
10304
  }
9650
10305
  function readUrl() {
9651
10306
  try {
9652
- const v = fs40.readFileSync(urlFilePath(), "utf-8").trim();
10307
+ const v = fs41.readFileSync(urlFilePath(), "utf-8").trim();
9653
10308
  return v || null;
9654
10309
  } catch {
9655
10310
  return null;
@@ -9675,11 +10330,11 @@ function stopExisting() {
9675
10330
  if (!isPidAlive(pid)) {
9676
10331
  info2(chalk23.gray(`Stale PID ${pid} \u2014 cleaning up.`));
9677
10332
  try {
9678
- fs40.unlinkSync(pidFilePath());
10333
+ fs41.unlinkSync(pidFilePath());
9679
10334
  } catch {
9680
10335
  }
9681
10336
  try {
9682
- fs40.unlinkSync(urlFilePath());
10337
+ fs41.unlinkSync(urlFilePath());
9683
10338
  } catch {
9684
10339
  }
9685
10340
  return false;
@@ -9688,11 +10343,11 @@ function stopExisting() {
9688
10343
  process.kill(pid);
9689
10344
  info2(chalk23.gray(`Stopped work web (PID ${pid}).`));
9690
10345
  try {
9691
- fs40.unlinkSync(pidFilePath());
10346
+ fs41.unlinkSync(pidFilePath());
9692
10347
  } catch {
9693
10348
  }
9694
10349
  try {
9695
- fs40.unlinkSync(urlFilePath());
10350
+ fs41.unlinkSync(urlFilePath());
9696
10351
  } catch {
9697
10352
  }
9698
10353
  return true;
@@ -9743,19 +10398,19 @@ var webCommand = {
9743
10398
  process.exit(1);
9744
10399
  }
9745
10400
  try {
9746
- fs40.unlinkSync(pidFilePath());
10401
+ fs41.unlinkSync(pidFilePath());
9747
10402
  } catch {
9748
10403
  }
9749
10404
  try {
9750
- fs40.unlinkSync(urlFilePath());
10405
+ fs41.unlinkSync(urlFilePath());
9751
10406
  } catch {
9752
10407
  }
9753
10408
  const lean = !!argv.lean || process.env.WORK_WEB_LEAN === "1";
9754
10409
  const handle = await startWebServer({ lean });
9755
10410
  try {
9756
- fs40.mkdirSync(path41.dirname(urlFilePath()), { recursive: true });
9757
- fs40.writeFileSync(urlFilePath(), handle.url);
9758
- fs40.writeFileSync(pidFilePath(), String(process.pid));
10411
+ fs41.mkdirSync(path42.dirname(urlFilePath()), { recursive: true });
10412
+ fs41.writeFileSync(urlFilePath(), handle.url);
10413
+ fs41.writeFileSync(pidFilePath(), String(process.pid));
9759
10414
  } catch {
9760
10415
  }
9761
10416
  info2(
@@ -9785,11 +10440,11 @@ var webCommand = {
9785
10440
  const shutdown = () => {
9786
10441
  info2(chalk23.gray("\nStopping work web."));
9787
10442
  try {
9788
- fs40.unlinkSync(urlFilePath());
10443
+ fs41.unlinkSync(urlFilePath());
9789
10444
  } catch {
9790
10445
  }
9791
10446
  try {
9792
- fs40.unlinkSync(pidFilePath());
10447
+ fs41.unlinkSync(pidFilePath());
9793
10448
  } catch {
9794
10449
  }
9795
10450
  if (!lean) {
@@ -9809,11 +10464,11 @@ var webCommand = {
9809
10464
  process.on("SIGTERM", shutdown);
9810
10465
  process.on("exit", () => {
9811
10466
  try {
9812
- fs40.unlinkSync(pidFilePath());
10467
+ fs41.unlinkSync(pidFilePath());
9813
10468
  } catch {
9814
10469
  }
9815
10470
  try {
9816
- fs40.unlinkSync(urlFilePath());
10471
+ fs41.unlinkSync(urlFilePath());
9817
10472
  } catch {
9818
10473
  }
9819
10474
  });
@@ -9888,7 +10543,7 @@ var hookCommand = {
9888
10543
 
9889
10544
  // src/commands/run.ts
9890
10545
  import chalk24 from "chalk";
9891
- import spawn13 from "cross-spawn";
10546
+ import spawn14 from "cross-spawn";
9892
10547
 
9893
10548
  // src/core/fleet.ts
9894
10549
  function selectSessions(sessions, filter) {
@@ -9930,7 +10585,7 @@ function killAllChildren(signal = "SIGTERM") {
9930
10585
  function runInPath(unit, cmd, prefix) {
9931
10586
  const { bin, args } = shellInvocation(cmd);
9932
10587
  return new Promise((resolve) => {
9933
- const child = spawn13(bin, args, {
10588
+ const child = spawn14(bin, args, {
9934
10589
  cwd: unit.path,
9935
10590
  stdio: prefix ? ["ignore", "pipe", "pipe"] : "inherit",
9936
10591
  shell: false
@@ -10162,15 +10817,15 @@ var runCommand = {
10162
10817
  };
10163
10818
 
10164
10819
  // src/commands/broadcast.ts
10165
- import fs42 from "fs";
10820
+ import fs43 from "fs";
10166
10821
  import chalk25 from "chalk";
10167
10822
 
10168
10823
  // src/core/broadcast.ts
10169
10824
  import crypto6 from "crypto";
10170
- import fs41 from "fs";
10825
+ import fs42 from "fs";
10171
10826
  function readComments(file) {
10172
10827
  try {
10173
- const parsed = JSON.parse(fs41.readFileSync(file, "utf-8"));
10828
+ const parsed = JSON.parse(fs42.readFileSync(file, "utf-8"));
10174
10829
  return Array.isArray(parsed) ? parsed : [];
10175
10830
  } catch {
10176
10831
  return [];
@@ -10178,7 +10833,7 @@ function readComments(file) {
10178
10833
  }
10179
10834
  async function appendLocked(sessionId, body) {
10180
10835
  const file = commentsFileFor(sessionId);
10181
- fs41.mkdirSync(commentsDir(), { recursive: true });
10836
+ fs42.mkdirSync(commentsDir(), { recursive: true });
10182
10837
  ensureFile(file, "[]");
10183
10838
  const comment = {
10184
10839
  id: crypto6.randomBytes(8).toString("hex"),
@@ -10215,7 +10870,7 @@ async function broadcastPrompt(sessions, filter, prompt) {
10215
10870
  // src/commands/broadcast.ts
10216
10871
  function readStdin() {
10217
10872
  try {
10218
- return fs42.readFileSync(0, "utf-8");
10873
+ return fs43.readFileSync(0, "utf-8");
10219
10874
  } catch {
10220
10875
  return "";
10221
10876
  }
@@ -10290,8 +10945,8 @@ var broadcastCommand = {
10290
10945
  };
10291
10946
 
10292
10947
  // src/completions/index.ts
10293
- import fs43 from "fs";
10294
- import path42 from "path";
10948
+ import fs44 from "fs";
10949
+ import path43 from "path";
10295
10950
  function completionHandler(current, argv, done) {
10296
10951
  const rawArgs = argv._;
10297
10952
  const args = rawArgs.slice(1, -1);
@@ -10395,7 +11050,7 @@ function completeTreeRemoveList(command, args, current, config, done) {
10395
11050
  }
10396
11051
  function completeRepoBranches(alias, current, config, done) {
10397
11052
  const repoPath = config.repos[alias];
10398
- if (!repoPath || !fs43.existsSync(repoPath)) {
11053
+ if (!repoPath || !fs44.existsSync(repoPath)) {
10399
11054
  done([]);
10400
11055
  return;
10401
11056
  }
@@ -10404,19 +11059,19 @@ function completeRepoBranches(alias, current, config, done) {
10404
11059
  done(branches);
10405
11060
  }
10406
11061
  function completeGroupBranches(groupName, repoAliases, current, config, done) {
10407
- const groupDir = path42.join(config.worktreesRoot, groupName);
10408
- if (!fs43.existsSync(groupDir)) {
11062
+ const groupDir = path43.join(config.worktreesRoot, groupName);
11063
+ if (!fs44.existsSync(groupDir)) {
10409
11064
  done([]);
10410
11065
  return;
10411
11066
  }
10412
11067
  try {
10413
- const branchDirs = fs43.readdirSync(groupDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => {
10414
- const bdPath = path42.join(groupDir, d.name);
11068
+ const branchDirs = fs44.readdirSync(groupDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => {
11069
+ const bdPath = path43.join(groupDir, d.name);
10415
11070
  for (const alias of repoAliases) {
10416
11071
  const repoPath = config.repos[alias];
10417
11072
  if (!repoPath) continue;
10418
- const subPath = path42.join(bdPath, path42.basename(repoPath));
10419
- if (fs43.existsSync(subPath)) {
11073
+ const subPath = path43.join(bdPath, path43.basename(repoPath));
11074
+ if (fs44.existsSync(subPath)) {
10420
11075
  const branch = getCurrentBranch(subPath);
10421
11076
  if (branch) return branch;
10422
11077
  }
@@ -10430,7 +11085,7 @@ function completeGroupBranches(groupName, repoAliases, current, config, done) {
10430
11085
  }
10431
11086
 
10432
11087
  // src/version.ts
10433
- var VERSION = true ? "1.5.1" : "dev";
11088
+ var VERSION = true ? "1.8.0" : "dev";
10434
11089
 
10435
11090
  // src/cli.ts
10436
11091
  function showHelp() {
@@ -10527,8 +11182,8 @@ function handleFatalError(err) {
10527
11182
  }
10528
11183
  if (err instanceof Error && err.message?.includes("pty that has already exited")) {
10529
11184
  try {
10530
- fs44.appendFileSync(
10531
- path43.join(getConfigDir(), "debug.log"),
11185
+ fs45.appendFileSync(
11186
+ path44.join(getConfigDir(), "debug.log"),
10532
11187
  `${(/* @__PURE__ */ new Date()).toISOString()} [WARN] Ignored async node-pty error: ${err.message}
10533
11188
  `
10534
11189
  );
@@ -10538,8 +11193,8 @@ function handleFatalError(err) {
10538
11193
  }
10539
11194
  try {
10540
11195
  const msg = err instanceof Error ? err.stack || err.message : String(err);
10541
- fs44.appendFileSync(
10542
- path43.join(getConfigDir(), "debug.log"),
11196
+ fs45.appendFileSync(
11197
+ path44.join(getConfigDir(), "debug.log"),
10543
11198
  `${(/* @__PURE__ */ new Date()).toISOString()} [FATAL] handleFatalError: ${msg}
10544
11199
  `
10545
11200
  );