Merge pull request #802 from zhanghunuaa/feat/follow-active-worktree

feat(sidebar): 文件树跟随会话实际所在的 git worktree(含跨仓库 linked worktree)
This commit is contained in:
Atlas Zeng authored and GitHub committed 2026-10-05 01:39:22 +08:00
commit b2599b390b
7 files changed
+417 -31

No files matched your search

+252
View File
@@ -0,0 +1,252 @@
/**
* Follow the linked git worktree a session is ACTUALLY working in.
*
* The explorer is rooted at the session's stored header cwd, which never
* changes. A session can move into a linked git worktree (`git worktree add`)
* during its life including a worktree of a repository that is not the one
* the header cwd points at and the sidebar should follow it.
*
* The active root is derived from the session's own `tool/call` arguments:
* absolute paths are collected newest-event-first (structured `cwd` / `workdir`
* / `path` / ... fields weigh more than free-form mentions, repeated mentions
* accumulate), each path's git top level is resolved with
* `git rev-parse --show-toplevel` (falling back to its directory for files),
* and only top levels whose `--absolute-git-dir` differs from their
* `--git-common-dir` (i.e. real LINKED worktrees, not the main checkout and
* not submodules) are adopted. The highest-scoring linked worktree of the
* newest event that has one wins; when there is no evidence the session cwd is
* kept (lifted to the repository top level for subdirectory sessions).
*
* Resolutions are cached process-wide, so the client's periodic re-ask is
* cheap after the first scan.
*/
import { stat } from 'node:fs/promises'
import { dirname, isAbsolute, join, sep } from 'node:path'
import type { Context, SidebarSessionEvent } from './context-types.ts'
import { requireAbsolute } from './fs-tree.ts'
import { runGitRaw } from './git.ts'
import { readPersistedSessionOf } from './session-store.ts'
/** How long one computed root is reused before the event log is scanned again. */
const ACTIVE_ROOT_TTL_MS = 3_000
/** Only the newest slice of the event log is considered. */
const ACTIVE_ROOT_MAX_EVENTS = 4_000
/** Upper bound on git probes per scan (cache misses are what cost). */
const ACTIVE_ROOT_MAX_PROBES = 24
/** Explicit override, mainly for tests and manual pinning. */
const ACTIVE_ROOT_OVERRIDE_ENV = 'DSH_SIDEBAR_WORKTREE_ROOT'
/** Keys whose string values describe where a tool actually ran. */
const ACTIVE_ROOT_STRUCTURED_FIELD = /^(cwd|workdir|work_dir|workingdirectory|path|file_path|filepath|target|root)$/i
/** Absolute Windows paths embedded in free-form command text. */
const ACTIVE_ROOT_PATH_PATTERN = /[A-Za-z]:(?:\\|\/)[^\\/\s"'\x60,;|)<>*?]+(?:[\\/][^\\/\s"'\x60,;|)<>*?]+)*/g
/**
* One computed root per session, reused for {@link ACTIVE_ROOT_TTL_MS}. `base`
* is the RAW base the caller passed (not the lifted one), because the entry has
* to be usable BEFORE the git probe below: that probe is a real process spawn
* (measured ~7 ms), and the repeated asks every debounced watch frame, every
* route call, the client's 5 s poll are exactly what the TTL exists to keep
* free.
*/
const activeWorktreeRootCache = new Map<string, { root: string; base: string; expires: number }>()
const pathTopCache = new Map<string, string | undefined>()
const linkedWorktreeCache = new Map<string, boolean>()
/** Normalized identity of a path (case- and separator-insensitive). */
function pathKeyOf(value: string): string {
return value.replace(/[\\/]+/g, '/').replace(/\/+$/, '').toLowerCase()
}
/** Whether `target` is `base` itself or lives under it. */
function pathUnderOf(base: string, target: string): boolean {
const b = pathKeyOf(base)
const t = pathKeyOf(target)
return t === b || t.startsWith(`${b}/`)
}
/** `git rev-parse --show-toplevel` of an existing directory, or undefined. */
async function gitTopLevelOf(cwd: string): Promise<string | undefined> {
if (cwd === '' || !isAbsolute(cwd)) return undefined
try {
if (!(await stat(cwd)).isDirectory()) return undefined
return (await runGitRaw(cwd, ['rev-parse', '--show-toplevel'])).trim()
} catch {
return undefined
}
}
/** Collapse duplicated separators without destroying a UNC prefix. */
function normalizeActivePath(value: string): string {
const trimmed = value.replace(/[\\/]+$/, '')
if (trimmed.startsWith('\\\\')) return `\\\\${trimmed.slice(2).replace(/[\\/]+/g, '\\')}`
// Fold to the PLATFORM separator, never unconditionally to a backslash: a
// POSIX path folded to `\private\var\…` is no longer absolute for
// `path.isAbsolute`, and `addActivePath` below then drops it the whole
// scan silently found nothing on Linux/macOS. On Windows `sep` IS `\`, so
// the behavior there is unchanged.
return trimmed.replace(/[\\/]+/g, sep)
}
function addActivePath(map: Map<string, number>, value: unknown, weight: number): void {
if (typeof value !== 'string') return
const normalized = normalizeActivePath(value)
if (normalized === '' || !isAbsolute(normalized)) return
const key = pathKeyOf(normalized)
map.set(key, (map.get(key) ?? 0) + weight)
}
/**
* Collect every absolute path one tool call mentions.
* @param value - JSON-decoded tool arguments (nested values are walked).
* @param map - accumulator keyed by normalized path identity.
* @param structured - whether the current value sits in a cwd/workdir/path field.
*/
function collectActivePaths(value: unknown, map: Map<string, number>, structured: boolean): void {
if (typeof value === 'string') {
if (isAbsolute(value)) {
addActivePath(map, value, structured ? 8 : 1)
return
}
const head = value.charCodeAt(0)
if (head === 0x7b || head === 0x5b) {
try {
collectActivePaths(JSON.parse(value) as unknown, map, structured)
} catch {
// Not JSON: fall through to the embedded-path scan.
}
}
for (const match of value.match(ACTIVE_ROOT_PATH_PATTERN) ?? []) addActivePath(map, match, 1)
return
}
if (Array.isArray(value)) {
for (const item of value) collectActivePaths(item, map, structured)
return
}
if (value !== null && typeof value === 'object') {
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
const isStructured = ACTIVE_ROOT_STRUCTURED_FIELD.test(key)
collectActivePaths(item, map, structured || isStructured)
}
}
}
/** git top level for one path (its directory when the path names a file). */
async function topOfActivePath(value: string): Promise<string | undefined> {
const key = pathKeyOf(value)
if (pathTopCache.has(key)) return pathTopCache.get(key)
let top = await gitTopLevelOf(value)
if (top === undefined) top = await gitTopLevelOf(dirname(value))
const result = top === undefined ? undefined : requireAbsolute(top)
pathTopCache.set(key, result)
return result
}
/**
* Whether a git top level is a LINKED worktree: its git dir lives under the
* common dir (`<main>/.git/worktrees/<name>`) instead of being it. Submodules
* report the same dir for both, so they are excluded.
*/
async function isLinkedWorktree(top: string): Promise<boolean> {
const key = pathKeyOf(top)
const cached = linkedWorktreeCache.get(key)
if (cached !== undefined) return cached
let linked = false
try {
const out = (await runGitRaw(top, ['rev-parse', '--absolute-git-dir', '--git-common-dir'])).trim().split(/\r?\n/)
const gitDir = out[0]
const commonRaw = out[1] ?? ''
if (gitDir !== undefined && gitDir !== '' && commonRaw !== '') {
const common = isAbsolute(commonRaw) ? commonRaw : join(top, commonRaw)
linked = pathKeyOf(requireAbsolute(gitDir)) !== pathKeyOf(requireAbsolute(common))
}
} catch {
linked = false
}
linkedWorktreeCache.set(key, linked)
return linked
}
/** The newest linked worktree the session's tool/call paths resolve to. */
async function activeRootFromEvents(events: readonly SidebarSessionEvent[], base: string): Promise<string | undefined> {
if (events.length === 0) return undefined
const baseKey = pathKeyOf(base)
const start = Math.max(0, events.length - ACTIVE_ROOT_MAX_EVENTS)
let probes = 0
for (let index = events.length - 1; index >= start; index -= 1) {
const event = events[index]
if (event === undefined || event.type !== 'tool/call') continue
const weights = new Map<string, number>()
collectActivePaths(event.data, weights, false)
if (weights.size === 0) continue
const ordered = [...weights.entries()].sort((left, right) => right[1] - left[1])
const scores = new Map<string, { top: string; score: number }>()
for (const [value, weight] of ordered) {
if (probes >= ACTIVE_ROOT_MAX_PROBES) break
probes += 1
const top = await topOfActivePath(value)
if (top === undefined) continue
const topKey = pathKeyOf(top)
if (topKey === baseKey) continue
if (!(await isLinkedWorktree(top))) continue
const entry = scores.get(topKey)
if (entry === undefined) scores.set(topKey, { top, score: weight })
else entry.score += weight
}
if (scores.size > 0) {
let best: string | undefined
let bestScore = -1
for (const entry of scores.values()) {
if (entry.score > bestScore) {
best = entry.top
bestScore = entry.score
}
}
if (best !== undefined) return best
}
if (probes >= ACTIVE_ROOT_MAX_PROBES) return undefined
}
return undefined
}
/** The session's live event log, or the persisted one while it is detached. */
async function sessionEventsOf(ctx: Context, sessionId: string): Promise<readonly SidebarSessionEvent[]> {
const live = ctx.sessions.get(sessionId)
// Session-store fakes in tests (and some embedders) expose only the header;
// a missing snapshot must degrade to the persisted log, never throw.
const events = typeof live?.snapshotEvents === 'function' ? live.snapshotEvents() : undefined
if (events !== undefined) return events
const persisted = await readPersistedSessionOf(ctx, sessionId)
return persisted?.events ?? []
}
/**
* The directory the sidebar should treat as the session's root.
* @param ctx - host plugin context.
* @param sessionId - session whose tool calls are inspected.
* @param base - the authoritative session cwd (already resolved by the caller).
* @returns the active linked worktree, the repository top level, or `base`.
*/
export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base: string): Promise<string> {
if (base === '') return base
const override = (process.env[ACTIVE_ROOT_OVERRIDE_ENV] ?? '').trim()
if (override !== '' && isAbsolute(override)) return requireAbsolute(override)
// The cache is consulted BEFORE the probe: doing it afterwards still pays the
// spawn on every ask, which is the whole cost the TTL is there to avoid. The
// comparison is on the raw base, so a session whose caller switched base (the
// `/sidebar/*` routes pass the client's own) never reuses the other one's root.
const cached = activeWorktreeRootCache.get(sessionId)
if (cached !== undefined && cached.expires > Date.now() && cached.base === base) return cached.root
const top = await gitTopLevelOf(base)
if (top === undefined) {
// "Not inside a repository" is an answer too (the base itself), and caching
// it is what keeps a non-repo session from re-probing on every ask.
activeWorktreeRootCache.set(sessionId, { root: base, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS })
return base
}
const canonicalTop = requireAbsolute(top)
const effectiveBase = pathUnderOf(base, canonicalTop) ? base : canonicalTop
const active = await activeRootFromEvents(await sessionEventsOf(ctx, sessionId), effectiveBase)
const root = active ?? effectiveBase
activeWorktreeRootCache.set(sessionId, { root, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS })
return root
}
+4 -17
View File
@@ -51,7 +51,7 @@ import { useHostFeeds } from './sidebar/use-host-feeds.ts'
import { mountedSessions } from './native/surface.ts'
import type { TabDragPayload } from './TabBar.tsx'
import { t } from './locales.ts'
import { api } from './api.ts'
import { useSessionRoot } from './use-session-root.ts'
import css from './sidebar.module.css'
/**
@@ -218,7 +218,6 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
const state = snapshot.state
const sessionId = snapshot.sessionId
const summaryCwd = sessionId === undefined ? undefined : sessionList.byId[sessionId]?.cwd
// 空白会话(无 user/assistant message)里宿主不渲染会话头,本插件的会话头入口不可达:
// 由 DockFallback 自行按会话相位决定是否渲染(sidebar/dock-fallback.tsx),二者互斥。
@@ -278,21 +277,9 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
return () => { for (const tag of tags) tag.remove() }
}, [presetCss, customCss, preset?.id])
// While the session's header is still hydrating (or the session is blank),
// the list summary may carry no cwd; ask the host once (it falls back to
// the process cwd) so the explorer root and the git rows are real from
// first paint instead of showing "no session".
const [fetchedCwd, setFetchedCwd] = useState<string | undefined>(undefined)
useEffect(() => {
setFetchedCwd(undefined)
if (sessionId === undefined || summaryCwd !== undefined) return
let cancelled = false
api.sessionCwd({ sessionId })
.then(result => { if (!cancelled) setFetchedCwd(result.cwd) })
.catch(() => { /* the explorer/git rows surface their own errors */ })
return () => { cancelled = true }
}, [sessionId, summaryCwd])
const cwd = summaryCwd ?? fetchedCwd
// The live root shared by both client surfaces: the host follows the
// session's active linked git worktree, the list summary only seeds first paint.
const cwd = useSessionRoot(ctx, sessionId)
// The + menu options ride a memo so the workbench does not rebuild the
// array identity across renders that did not change the store (drag state,
+2 -9
View File
@@ -30,6 +30,7 @@ import type { SessionScope } from '../api.ts'
import { RenderBoundary } from '../RenderBoundary.tsx'
import { OrphanedTab } from '../OrphanedTab.tsx'
import { referenceInChat } from '../reference-in-chat.ts'
import { useSessionRoot } from '../use-session-root.ts'
import type { BetterSidebarService } from '../service.ts'
import { toggleExpanded } from '../state.ts'
import type { SidebarStore, SidebarTab, TabType } from '../state.ts'
@@ -360,14 +361,6 @@ function useRecordVersion(records: NativeTabRecords, sessionId: string, id: stri
)
}
/** The current session's workspace root, live from the client session list. */
function useSessionCwd(ctx: Context, sessionId: string): string | undefined {
return useSyncExternalStore(
useMemo(() => (listener: () => void) => ctx.sessions.list.subscribe(listener), [ctx]),
() => ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd,
)
}
/**
* One plugin tab rendered inside the native right Sidebar: the descriptor's
* own component with the plugin's props, over a synthetic record minted from
@@ -391,7 +384,7 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro
const seatSessionId = props.sessionId
const scopeSessionId = props.sessionIdOf?.(info) ?? seatSessionId
const version = useRecordVersion(records, seatSessionId, nativeTab.id)
const cwd = useSessionCwd(ctx, scopeSessionId)
const cwd = useSessionRoot(ctx, scopeSessionId)
const scope = useMemo((): SessionScope => ({ sessionId: scopeSessionId, cwd }), [scopeSessionId, cwd])
// `version` is not read: it only forces this render when the record changed.
void version
+66
View File
@@ -0,0 +1,66 @@
/**
* The root the explorer and the git panel should use for one session.
*
* The client session list carries the session HEADER cwd, captured once when
* the session started. The HOST is the authority on where the session is
* actually working, because it can follow the agent into a linked git worktree
* including one belonging to a different repository. Ask the host, prefer
* its answer, and re-ask when the window regains focus, when a file refresh is
* requested, and on a slow timer so a mid-session worktree move is picked up.
*
* Shared by both client surfaces: the plugin's own sidebar shell
* (`Sidebar.tsx`) and the native DSH right-sidebar tab body
* (`native/tab-adapter.tsx`). They used to disagree the native body read the
* frozen list summary directly, so a host-side worktree change never reached
* the file list drawn in the host's own right Sidebar.
*/
import { useEffect, useMemo, useState, useSyncExternalStore } from 'react'
import type { Context } from '../context-types.ts'
import { api } from './api.ts'
/** How often the host is re-asked while the document is visible. */
const SESSION_ROOT_POLL_MS = 5_000
/**
* Resolve the live workspace root for one session.
* @param ctx - client plugin context (owns the session list feed + API).
* @param sessionId - the session to resolve; `undefined` resolves to `undefined`.
* @returns the host's active root, falling back to the list summary cwd.
*/
export function useSessionRoot(ctx: Context, sessionId: string | undefined): string | undefined {
const summaryCwd = useSyncExternalStore(
useMemo(() => (listener: () => void) => ctx.sessions.list.subscribe(listener), [ctx]),
() => sessionId === undefined ? undefined : ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd,
)
const [fetched, setFetched] = useState<{ sessionId: string; cwd: string } | undefined>(undefined)
useEffect(() => {
if (sessionId === undefined) return
let cancelled = false
const load = (): void => {
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
api.sessionCwd({ sessionId })
.then(result => {
if (cancelled) return
setFetched(previous => (
previous !== undefined && previous.sessionId === sessionId && previous.cwd === result.cwd
? previous
: { sessionId, cwd: result.cwd }
))
})
.catch(() => { /* the explorer/git rows surface their own errors */ })
}
load()
window.addEventListener('focus', load)
window.addEventListener('dsh-sidebar:refresh-files', load)
const timer = window.setInterval(load, SESSION_ROOT_POLL_MS)
return () => {
cancelled = true
window.removeEventListener('focus', load)
window.removeEventListener('dsh-sidebar:refresh-files', load)
window.clearInterval(timer)
}
}, [sessionId])
return fetched !== undefined && fetched.sessionId === sessionId ? fetched.cwd : summaryCwd
}
+6
View File
@@ -195,6 +195,12 @@ function runGit(cwd: string, args: string[], timeoutMs = 30_000): Promise<string
})
}
/** Raw stdout of one git command. Callers that only need text (no status
* parsing) should use this instead of re-implementing the spawn. */
export function runGitRaw(cwd: string, args: string[], timeoutMs = 30_000): Promise<string> {
return runGit(cwd, args, timeoutMs)
}
/** Cap on child directories probed by the workspace-container fallback scan.
* A home-directory cwd can hold hundreds of visible folders (Library, iCloud
* mounts…); probing them all serially is what froze the panel in #369. */
+6 -5
View File
@@ -54,6 +54,7 @@ import { readPersistedSession } from './session-store.ts'
// Shared with the client's batch splitter: the two halves must agree on the
// row bound, so it lives in a dependency-free module both can import.
import { FS_TREES_MAX_PATHS } from './fs-batch.ts'
import { activeWorktreeRootOf } from './active-worktree.ts'
export { Config }
export type { SidebarConfig, ResolvedSidebarConfig }
@@ -282,7 +283,7 @@ function buildApi(
const sessionId = requireString(payload, 'sessionId')
const record = payload as { cwd?: unknown } | null
const clientCwd = typeof record?.cwd === 'string' && record.cwd !== '' ? record.cwd : undefined
return { sessionId, cwd: await sessionCwdOf(ctx, sessionId, clientCwd) }
return { sessionId, cwd: await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId, clientCwd)) }
}
/** Resolve the optional Git-panel checkout selector against the selected
* session repository. Unlike `cwd`, `worktree` is never trusted directly. */
@@ -1003,7 +1004,7 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
if (sessionId === null || dir === null || relativePath === null || relativePath.trim() === '') {
throw new SidebarError('bad-request', 'sessionId, dir, and relativePath are required')
}
const cwd = await sessionCwdOf(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
const cwd = await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId, url.searchParams.get('cwd') ?? undefined))
const { path, size } = await writeWorkspaceUpload({
cwd,
dir,
@@ -1076,7 +1077,7 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
const sessionId = url.searchParams.get('sessionId')
const raw = url.searchParams.get('path')
if (sessionId === null || raw === null) throw new SidebarError('bad-request', 'sessionId and path are required')
const cwd = await sessionCwdOf(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
const cwd = await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId, url.searchParams.get('cwd') ?? undefined))
// Resolution is the shared contract's alone: relative joins the
// session cwd, absolute stays, `~` expands against the home (#713),
// remote-mirror namespaces project. Pre-joining here would paste a
@@ -1154,7 +1155,7 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
// back to the process cwd and is normally refused by the workspace
// real-path guard, with the same semantics as the media route's
// fallback.
const cwd = await sessionCwdOf(ctx, sessionId)
const cwd = await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId))
const absolute = await ensureWorkspacePath(cwd, path)
const info = await stat(absolute)
if (!info.isFile() || info.size > resolved.mediaLimit) {
@@ -1301,7 +1302,7 @@ async function handleFsWatchFrame(
const path = typeof frame.path === 'string' ? frame.path : undefined
if (path === undefined || path === '') return
try {
const cwd = await sessionCwdOf(ctx, sessionId)
const cwd = await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId))
const dir = await ensureWorkspacePath(cwd, path)
if (frame.op === 'unwatch') {
watchers.remove(dir)
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it } from 'vitest'
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { activeWorktreeRootOf } from '../src/active-worktree.ts'
import type { Context } from '../src/context-types.ts'
const IDENTITY = {
GIT_AUTHOR_NAME: 'dsh-better-sidebar-test',
GIT_AUTHOR_EMAIL: 'test@dsh.invalid',
GIT_COMMITTER_NAME: 'dsh-better-sidebar-test',
GIT_COMMITTER_EMAIL: 'test@dsh.invalid',
}
function git(cwd: string, args: string[]): string {
// `core.hooksPath=` keeps a developer's global commit-msg hook out of the scratch repos.
const result = spawnSync('git', ['-c', 'core.hooksPath=', '-C', cwd, ...args], {
encoding: 'utf8',
env: { ...process.env, ...IDENTITY },
})
if (result.status !== 0) throw new Error(result.stderr || `git ${args.join(' ')} failed`)
return result.stdout
}
function initRepo(path: string, file: string): void {
mkdirSync(path, { recursive: true })
git(path, ['init', '-q'])
git(path, ['checkout', '-q', '-b', 'main'])
writeFileSync(join(path, file), 'base\n')
git(path, ['add', '-A'])
git(path, ['commit', '-q', '-m', 'base'])
}
/** A minimal live-session face: header cwd plus the tool/call events to scan. */
function sessionCtx(cwd: string, calls: Array<Record<string, unknown>>): Context {
return {
sessions: {
get: () => ({
header: { cwd },
snapshotEvents: () => calls.map((data, index) => ({ type: 'tool/call', seq: index, time: index, data })),
}),
},
get: () => undefined,
} as never
}
describe('active worktree root', () => {
it('follows a linked worktree of a DIFFERENT repository named by the tool calls', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repoA = join(root, 'repo-a')
const repoB = join(root, 'repo-b')
const worktreeB = join(root, 'worktree-b')
try {
initRepo(repoA, 'a.txt')
initRepo(repoB, 'b.txt')
git(repoB, ['worktree', 'add', '-q', '-b', 'agent', worktreeB])
// The session's header cwd is repo A, but its newest tool call works in
// a linked worktree of repo B the sidebar must follow that worktree.
const ctx = sessionCtx(repoA, [{ cwd: worktreeB, path: join(worktreeB, 'b.txt') }])
// The roots come back from `git rev-parse --show-toplevel`, i.e. already
// canonical: compare against the real path (macOS tmpdirs live under the
// `/var` → `/private/var` symlink; same convention as git-worktree.spec).
await expect(activeWorktreeRootOf(ctx, 's-cross-repo', repoA)).resolves.toBe(realpathSync.native(worktreeB))
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('keeps the session cwd when no tool call points at a linked worktree', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repo = join(root, 'repo')
try {
initRepo(repo, 'a.txt')
const ctx = sessionCtx(repo, [{ cwd: join(repo, 'src') }])
await expect(activeWorktreeRootOf(ctx, 's-no-worktree', repo)).resolves.toBe(realpathSync.native(repo))
} finally {
rmSync(root, { recursive: true, force: true })
}
})
})