mirror of
https://ghproxy.cflmy.top/https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-12-02 10:09:36 +08:00
feat(forge): show other branches by branch, in their worktrees, and keep the local changes row
The head picker of the local changes view lists the Session's own checkout and the repository's local and remote-tracking branches, and no longer lists delegated Sessions. A branch that a worktree of the repository has checked out is read in that worktree with every scope; a branch that no worktree has checked out is read from its commits in the branch scope alone. A scope names the branch by its full ref, and each read looks the worktree up again and confirms that a checkout of the same repository holds the branch there. The Session panel's local changes row shows in every Git checkout, with an empty size while the branch scope changes nothing, so the view opens from a clean checkout. `forgePanel.diffBases` and `forgePanel.localCommits` take the head as a branch ref, `relatedCheckouts` is removed, and the package no longer depends on the subagent package. The API catalog, the config catalog, and two web expected outputs are regenerated.
This commit is contained in:
1 parent
0057f19a78
commit
a69613bcb3
46 files changed
+1078
-1120
No files matched your search
@@ -9,14 +9,14 @@
|
||||
en: 344bcc7e9825bbc8
|
||||
zh: c1d0f4b54f5b3786
|
||||
/agent-note-change-request-panel-and-worktree-sessions/decision:
|
||||
en: 1d095ea8963ad4d8
|
||||
zh: 05aab545cc5f1c1a
|
||||
en: 2e44597477bbf5c0
|
||||
zh: cf8760e149a216e1
|
||||
/agent-note-change-request-panel-and-worktree-sessions/deferred:
|
||||
en: e76e8129691db30f
|
||||
zh: fd242e67bab2633d
|
||||
/agent-note-change-request-panel-and-worktree-sessions/alternatives-considered:
|
||||
en: 22edd6323a8c5e22
|
||||
zh: 67574ed0791a6516
|
||||
en: 27f5625022a15674
|
||||
zh: d7215f613fb13adf
|
||||
/agent-note-change-request-panel-and-worktree-sessions/consequences:
|
||||
en: 283cab5ad7256f39
|
||||
zh: 83967aa79e58c73f
|
||||
en: 68625753024f512a
|
||||
zh: a660e87e88422e75
|
||||
@@ -30,6 +30,8 @@ The panel also shows the changes behind a Session's work in a changes view, a re
|
||||
|
||||
The changes view also writes the checkout, on whole files: the Unstaged scope stages and restores, and the Staged scope unstages. A reader of an Agent's work keeps the accepted part in the index and discards the rest, and without these writes that meant leaving the application. The reader's press is the authorization, as archiving is for the worktree service's removal of a checkout, so the writing commands run without the Session's sandbox policy: that policy bounds what the Agent does, and the reader stages in a read-only Session or from a Session directory below the checkout's root. Staging and restoring name each file with the digest of the change the reader saw, and the Remote refuses the write when the `unstaged` scope, read again, shows another change: the Agent can edit a file between the reader's look and the press. The undo of staging and unstaging returns the index entries to a tree written before the write. Restoring has no undo, so it asks first.
|
||||
|
||||
The local changes view reads more than the Session's own checkout. A menu at the start of its header chooses another local or remote-tracking branch of the repository. A branch that a worktree of the repository has checked out is read in that worktree with every scope, which shows what a subagent changed in its own worktree, uncommitted files included; a branch that no worktree has checked out shows committed content only. A local scope names the choice as an optional `head` instead of the view gaining a second kind of source, so every read, the lens request, the viewed-mark key, and the key of the loaded data carry it through the scope they already take; the Session's own checkout names none, so the viewed marks and comment records a browser holds for it keep their identities. The page sends a branch ref and never a path: the Host verifies the ref, asks Git which worktree has the branch checked out, confirms by inspection that a checkout of the same repository has it checked out there, and runs Git there under the reading Session's sandbox policy. Another head is read-only, and plugin slots and line annotations stay with the Session's own checkout, so `ctx.forgeChanges`, the face other plugins use, is unchanged. The Session panel's local changes row shows in every Git checkout, with an empty size when nothing changed, so the view and its menu open from a Session whose own checkout is clean while its subagents work in worktrees.
|
||||
|
||||
Review comments capture the file, side, range, complete hunk, and reviewed head when the user selects code. Agent references enter the existing composer quote mechanism, so the user controls batching and the sent message records exactly what the model receives. GitHub writes belong to the optional forge provider operation: preflight checks the current head, the write addresses that commit, and an ambiguous outcome blocks another write until the user reconciles it. Inline records of Agent references and published comments, and the review summary, belong to a browser tab occurrence, not to the Session log; a pull request comment kept for a later review goes to the code host's pending review, as [the pending review decision](2026-11-05-forge-pending-review-drafts.md) records. Switching Sessions retains that occurrence; closing it discards the local state and rejects late write completions. Published GitHub comments remain external records.
|
||||
|
||||
## Deferred
|
||||
@@ -100,6 +102,14 @@ The changes view offers no scope for one commit or for the last turn yet; both w
|
||||
|
||||
**Automatically retrying a review write.** A lost response does not mean that GitHub rejected the request. Retaining the outgoing request and requiring reconciliation prevents a transport failure from silently duplicating comments.
|
||||
|
||||
**A separate view type for another branch.** Each read, the lens request, the viewed-mark key, and the data key would need a second case. An optional `head` on the local scope reaches all of them through the value they already take.
|
||||
|
||||
**A menu group of the Sessions delegated from the reading one.** Each row named a delegated Session's checkout by Session id. Every listing then read the subagent catalogs and each delegated Session's records, several Sessions in one checkout needed one label, and a Session that moved to another directory kept its row under the old name. Git's worktree list reaches the same working trees through the branch a reader searches for, without a dependency on the subagent service.
|
||||
|
||||
**Committed content only for every other branch.** Reading a branch that another worktree has checked out from its commits alone hides the edits a subagent has not committed yet, which a reader checks while that subagent works.
|
||||
|
||||
**Writes and plugin entries on another head.** The slots, the annotations, and `ctx.forgeChanges` address the Session's own local changes; another head stays read-only and without those entries, which leaves that face as it is.
|
||||
|
||||
## Consequences
|
||||
|
||||
The panel shows current status only while it is open; checks that finish while nothing is mounted produce no notification. Changes made outside the Session appear after Refresh or the next tool result. A local write is not recorded in the Session and the model is not told about it; the Agent meets the result the next time it reads the checkout. A local write runs the clean and smudge filters named in the repository's configuration with the Host's permissions, measured for `git add` and `git reset`, and a Session that can write its checkout can add one. Every inspection spawns up to twelve short Git processes in the Session's execution world with one remote, and two more for each further remote it tries for a fork point. A worktree exists only for a Session that requested it before its first step, and a failed or cancelled attempt can leave its branch or checkout behind. A message that enters while the Agent runs a turn or other maintenance gets no hold, so its worktree is created within the first turn and a removed worktree is not checked. While a message waits, the Agent stays idle in maintenance: the composer offers no stop, and callers waiting for the Agent to become idle wait as well. Restoring loses changes that were never committed. A base branch that requires a merge queue cannot merge from the panel. The bundle mounts two independent worktree services; the model's tool never sees the panel's service. A local or change request diff over `maxDiffBytes`, or one the host refuses, shows no files. Expanding unchanged lines of a change request reads each file from the code host once.
|
||||
The panel shows current status only while it is open; checks that finish while nothing is mounted produce no notification. Changes made outside the Session appear after Refresh or the next tool result. A local write is not recorded in the Session and the model is not told about it; the Agent meets the result the next time it reads the checkout. A local write runs the clean and smudge filters named in the repository's configuration with the Host's permissions, measured for `git add` and `git reset`, and a Session that can write its checkout can add one. Every inspection spawns up to twelve short Git processes in the Session's execution world with one remote, and two more for each further remote it tries for a fork point. A worktree exists only for a Session that requested it before its first step, and a failed or cancelled attempt can leave its branch or checkout behind. A message that enters while the Agent runs a turn or other maintenance gets no hold, so its worktree is created within the first turn and a removed worktree is not checked. While a message waits, the Agent stays idle in maintenance: the composer offers no stop, and callers waiting for the Agent to become idle wait as well. Restoring loses changes that were never committed. A base branch that requires a merge queue cannot merge from the panel. The bundle mounts two independent worktree services; the model's tool never sees the panel's service. A local or change request diff over `maxDiffBytes`, or one the host refuses, shows no files. Expanding unchanged lines of a change request reads each file from the code host once. The head menu finds only worktrees of the Session's repository, by branch: work a delegated Session does in a plain directory or in another repository does not show, and a worktree shows under its branch name, not under the Session that works there. Another head is read again when the Session's own checkout is, on Refresh or after its own changes, not after each edit in the other worktree.
|
||||
@@ -30,6 +30,8 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都
|
||||
|
||||
变更视图也写 checkout,粒度是整个文件:“未暂存”范围可以暂存和还原,“已暂存”范围可以取消暂存。评审 Agent 工作的人把认可的部分放进暂存区、丢弃其余部分,没有这些写操作就得离开应用去做。读者按下按钮就是授权,正如归档之于 worktree 服务移除 checkout,所以写入命令不受 Session 沙箱策略约束:该策略约束的是 Agent 的行为,读者可以在只读的 Session 里暂存,也可以在目录位于 checkout 根目录之下的 Session 里暂存。暂存和还原为每个文件带上读者所见改动的 digest,Remote 重新读取 `unstaged` 范围,改动不同就拒绝写入:从读者看到文件到按下按钮之间,Agent 可能又改了它。暂存和取消暂存的撤销,是把暂存区条目恢复到写入之前写出的 tree。还原没有撤销,所以先询问。
|
||||
|
||||
本地变更视图读取的不只是 Session 自己的检出。标题栏开头的菜单可以选择仓库的另一个本地分支或远程跟踪分支。仓库里有 worktree 检出的分支在该 worktree 里读取,四个范围都可用,这样就能看到子智能体在自己的 worktree 里改了什么,包括未提交的文件;没有 worktree 检出的分支只显示已提交的内容。本地范围用可选的 `head` 表示这个选择,而不是给视图增加第二种来源,所以每次读取、透镜请求、已审阅标记的键和已加载数据的键都通过它们本来就接受的范围带上它;Session 自己的检出不带 `head`,所以浏览器为它保存的已审阅标记和评论记录保持原有标识。页面只发送分支引用,从不发送路径:Host 校验引用,向 Git 询问哪个 worktree 检出了该分支,通过检查确认那里是同一个仓库的检出并且确实检出了它,再以读取方 Session 的沙箱策略在那里运行 Git。其他 `head` 是只读的,插件插槽和行注解只留给 Session 自己的检出,所以其他插件使用的 `ctx.forgeChanges` 不变。Session 面板的本地变更行在每个 Git 检出内都显示,没有变更时显示空的行数,这样当 Session 自己的检出没有变更、而它的子智能体在 worktree 里工作时,也能打开视图和菜单。
|
||||
|
||||
评审评论在用户选择代码时固定文件、侧、行范围、完整 hunk 与所评审的 head。Agent 引用进入既有输入框引用机制,由用户决定批量发送,发送后的消息记录模型实际收到的内容。GitHub 写入属于 forge 提供方的可选操作:预检核对当前 head,写入明确指向该提交;结果不明时阻止再次写入,直到用户核对。Agent 引用与已发布评论的行内记录以及评审总结归浏览器页签实例所有,不进入 Session 日志;留待之后一起提交的 PR 评论写入代码托管平台的待提交评审,见[待提交评审决策](2026-11-05-forge-pending-review-drafts.zh.md)。切换 Session 保留该实例;关闭时丢弃本地状态并拒绝迟到的写入结果。已发布的 GitHub 评论仍保留在外部平台。
|
||||
|
||||
## Deferred
|
||||
@@ -100,6 +102,14 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都
|
||||
|
||||
**自动重试评审写入。** 丢失响应不代表 GitHub 拒绝了请求。保留发出的请求并要求核对,可以避免传输失败悄悄产生重复评论。
|
||||
|
||||
**为另一个分支单独设一种视图类型。** 每次读取、透镜请求、已审阅标记的键和数据的键都要多一种情况。本地范围上可选的 `head` 通过它们本来就接受的值到达所有这些地方。
|
||||
|
||||
**在菜单里按 Session 列出当前 Session 派出的子 Session。** 每一行用 Session id 指定一个子 Session 的检出。这样每次列出都要读取子智能体目录和每个子 Session 的记录,同一个检出里的多个 Session 需要合成一个标签,Session 后来换了目录时它的行还留在旧名称下。Git 的 worktree 列表通过读者搜索的分支就能到达同样的工作树,不依赖子智能体服务。
|
||||
|
||||
**其他分支一律只显示已提交的内容。** 对另一个 worktree 检出的分支只按提交读取,会看不到子智能体尚未提交的修改,而读者正是在子智能体工作时查看这些修改。
|
||||
|
||||
**在其他 `head` 上提供写操作和插件条目。** 插槽、注解和 `ctx.forgeChanges` 面向的是 Session 自己的本地变更;其他 `head` 保持只读、不带这些条目,这个接口就不用改。
|
||||
|
||||
## Consequences
|
||||
|
||||
面板只在打开时显示当前状态;没有任何界面挂载时检查结束不会有通知。Session 之外的改动要等到刷新或下一个工具结果才会出现。本地写操作不记录到 Session,也不告知模型;Agent 下次读取 checkout 时才看到结果。本地写操作会以 Host 的权限运行仓库配置里指定的 clean 和 smudge filter(已对 `git add` 和 `git reset` 实测),而能写自己 checkout 的 Session 可以添加这样的 filter。只有一个远端时,每次检查最多在 Session 的执行环境中启动十二个短暂的 Git 进程;为寻找分叉点每多尝试一个远端,就多启动两个。只有在第一步之前提出请求的 Session 才会有 worktree,失败或被取消的尝试可能留下它的分支或检出。Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留,因此它的 worktree 在第一轮之内创建,已删除的 worktree 也不会被检查。消息等待期间,Agent 以空闲状态处于维护任务中:输入框不提供停止,等待 Agent 空闲的调用方也会一并等待。恢复会丢失从未提交的修改。要求合并队列的基准分支无法从面板合并。组合包挂载两个互不影响的 worktree 服务;模型的工具看不到面板的服务。本地或变更请求的 diff 超过 `maxDiffBytes`,或被托管平台拒绝时,不显示任何文件。展开变更请求中未变更的行时,每个文件只从托管平台读取一次。
|
||||
面板只在打开时显示当前状态;没有任何界面挂载时检查结束不会有通知。Session 之外的改动要等到刷新或下一个工具结果才会出现。本地写操作不记录到 Session,也不告知模型;Agent 下次读取 checkout 时才看到结果。本地写操作会以 Host 的权限运行仓库配置里指定的 clean 和 smudge filter(已对 `git add` 和 `git reset` 实测),而能写自己 checkout 的 Session 可以添加这样的 filter。只有一个远端时,每次检查最多在 Session 的执行环境中启动十二个短暂的 Git 进程;为寻找分叉点每多尝试一个远端,就多启动两个。只有在第一步之前提出请求的 Session 才会有 worktree,失败或被取消的尝试可能留下它的分支或检出。Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留,因此它的 worktree 在第一轮之内创建,已删除的 worktree 也不会被检查。消息等待期间,Agent 以空闲状态处于维护任务中:输入框不提供停止,等待 Agent 空闲的调用方也会一并等待。恢复会丢失从未提交的修改。要求合并队列的基准分支无法从面板合并。组合包挂载两个互不影响的 worktree 服务;模型的工具看不到面板的服务。本地或变更请求的 diff 超过 `maxDiffBytes`,或被托管平台拒绝时,不显示任何文件。展开变更请求中未变更的行时,每个文件只从托管平台读取一次。查看分支的菜单只能按分支找到 Session 所在仓库的 worktree:子 Session 在普通目录或另一个仓库里做的工作不会出现,worktree 以它的分支名出现,而不是以在其中工作的 Session 出现。其他 `head` 在 Session 自己的检出重新读取时才重新读取(点击“刷新”或它自己的变更变化之后),而不是在另一个 worktree 每次修改之后。
|
||||
@@ -1,4 +1,4 @@
|
||||
- text: main
|
||||
- button "查看的分支:main": main
|
||||
- button "基准分支:origin/main": origin/main
|
||||
- text: 包含未提交的修改
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
- region "环境":
|
||||
- heading "环境" [level=2]
|
||||
- text: dsh-{{worktree}} {{cwd}}/workspace/.agents/worktrees dsh-{{worktree}} 工作树 · 基于 release
|
||||
- button "本地变更 · 0 个文件,新增 0 行,删除 0 行": 本地变更
|
||||
- text: +0 −0
|
||||
- button "本地变更操作"
|
||||
- region "变更请求":
|
||||
- heading "变更请求" [level=2]
|
||||
- text: "1"
|
||||
|
||||
@@ -3108,8 +3108,8 @@ it.skipIf(MODE === 'record')('writes a left and a right comment at once, each in
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('shows another branch chosen in the head picker with its committed changes alone, then the own checkout again', async () => {
|
||||
const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-head-picker')
|
||||
it.skipIf(MODE === 'record')('opens the local changes of a clean checkout and shows other branches: a worktree\'s with every scope, another\'s from its commits', async () => {
|
||||
const { scaffold, page, project, root, tripwire } = await launchPanel('web-e2e-forge-head-picker')
|
||||
await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD')
|
||||
await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main')
|
||||
await git(project, 'checkout', '--quiet', '-b', 'topic')
|
||||
@@ -3117,36 +3117,66 @@ it.skipIf(MODE === 'record')('shows another branch chosen in the head picker wit
|
||||
await git(project, 'add', 'topic.md')
|
||||
await git(project, 'commit', '--quiet', '-m', 'topic')
|
||||
await git(project, 'checkout', '--quiet', 'main')
|
||||
await writeFile(join(project, 'notes.md'), 'note\n')
|
||||
// A worktree of the repository holds `cache` with one committed, one modified, and one untracked file.
|
||||
const cache = join(root, 'cache-tree')
|
||||
await git(project, 'worktree', 'add', '--quiet', '-b', 'cache', cache)
|
||||
await writeFile(join(cache, 'cache.md'), 'cache\n')
|
||||
await git(cache, 'add', 'cache.md')
|
||||
await git(cache, 'commit', '--quiet', '-m', 'cache')
|
||||
await writeFile(join(cache, 'cache.md'), 'cache\nedited\n')
|
||||
await writeFile(join(cache, 'draft.md'), 'draft\n')
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
await settled
|
||||
await showSessionPanel(page)
|
||||
await page.locator('[data-forge-local]').getByRole('button', { name: /^本地变更 · / }).click({ timeout: 20_000 })
|
||||
|
||||
// The Session's own checkout changes nothing, and its row still opens the view.
|
||||
const row = page.locator('[data-forge-local]')
|
||||
const open = row.getByRole('button', { name: '本地变更 · 0 个文件,新增 0 行,删除 0 行', exact: true })
|
||||
await open.waitFor({ timeout: 20_000 })
|
||||
expect(await row.locator('[data-row-part="trailing"]').textContent()).toBe('+0−0')
|
||||
await open.click()
|
||||
const view = page.locator('[data-forge-changes="local"]')
|
||||
await view.locator('[data-forge-diff-file="notes.md"]').waitFor()
|
||||
const head = view.locator('[data-forge-head]')
|
||||
expect([await head.innerText(), await head.getAttribute('data-forge-head')]).toEqual(['main', ''])
|
||||
await expect.poll(async () => [await head.innerText(), await head.getAttribute('data-forge-head')], { timeout: 20_000 }).toEqual(['main', ''])
|
||||
expect(await shownPaths(view)).toEqual([])
|
||||
|
||||
await head.click()
|
||||
const menu = page.locator('[data-forge-head-menu]')
|
||||
await menu.getByRole('menuitem', { name: 'topic', exact: true }).waitFor()
|
||||
// No Session is delegated from this one, and the checked-out branch is the own checkout's row.
|
||||
expect(await menu.getByRole('group').evaluateAll(groups => groups.map(group => group.getAttribute('aria-label')))).toEqual(['当前会话', '本地分支', '远程分支'])
|
||||
await page.getByRole('searchbox', { name: '搜索分支或会话', exact: true }).fill('top')
|
||||
// The branch a worktree has checked out carries the mark; the Session's checked-out branch is its own row.
|
||||
// Branches committed within one second list in either order.
|
||||
expect((await menu.getByRole('menuitem').allTextContents()).sort()).toEqual(['cache工作树', 'main当前会话', 'origin/main', 'release', 'topic'])
|
||||
await page.getByRole('searchbox', { name: '搜索分支', exact: true }).fill('top')
|
||||
await expect.poll(async () => await menu.getByRole('menuitem').allTextContents()).toEqual(['topic'])
|
||||
await menu.getByRole('menuitem', { name: 'topic', exact: true }).click()
|
||||
await view.locator('[data-forge-diff-file="topic.md"]').waitFor()
|
||||
// The uncommitted note belongs to the Session's working tree, not to the branch.
|
||||
// No worktree has `topic`, so its committed content shows in the branch scope alone.
|
||||
expect(await shownPaths(view)).toEqual(['topic.md'])
|
||||
expect(await head.getAttribute('data-forge-head')).toBe('branch:refs/heads/topic')
|
||||
expect(await head.getAttribute('data-forge-head')).toBe('refs/heads/topic')
|
||||
expect(await view.locator('[data-forge-scope]').count()).toBe(0)
|
||||
expect(await view.getByText('包含未提交的修改', { exact: true }).count()).toBe(0)
|
||||
expect(await view.locator('[data-forge-base]').innerText()).toBe('origin/main')
|
||||
|
||||
// `cache` is read in its worktree: the branch scope counts the uncommitted files, and the other scopes apply.
|
||||
await head.click()
|
||||
await menu.getByRole('menuitem', { name: /^cache/ }).click()
|
||||
await view.locator('[data-forge-diff-file="draft.md"]').waitFor()
|
||||
expect(await shownPaths(view)).toEqual(['cache.md', 'draft.md'])
|
||||
expect(await head.getAttribute('data-forge-head')).toBe('refs/heads/cache')
|
||||
expect(await view.getByText('包含未提交的修改', { exact: true }).count()).toBe(1)
|
||||
await view.getByRole('button', { name: '分支', exact: true }).click()
|
||||
await page.getByRole('menuitem', { name: '未暂存', exact: true }).click()
|
||||
await view.locator('[data-forge-diff-file="draft.md"]').waitFor()
|
||||
expect(await shownPaths(view)).toEqual(['cache.md', 'draft.md'])
|
||||
// The one line edited in the worktree after the commit.
|
||||
expect(await view.locator('[data-forge-diff-file="cache.md"]').innerText()).toContain('+1\n−0')
|
||||
// Another worktree is read-only.
|
||||
expect(await view.locator('[data-forge-write], [data-forge-write-all]').count()).toBe(0)
|
||||
|
||||
await head.click()
|
||||
await menu.getByRole('menuitem', { name: /^main/ }).click()
|
||||
await view.locator('[data-forge-diff-file="notes.md"]').waitFor()
|
||||
expect(await shownPaths(view)).toEqual(['notes.md'])
|
||||
await expect.poll(async () => await head.getAttribute('data-forge-head')).toBe('')
|
||||
expect(await view.locator('[data-forge-scope]').count()).toBe(1)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
})
|
||||
@@ -1323,7 +1323,7 @@ export interface CotTranslationPreferences {
|
||||
## `@deepseek-ai/dsh-experimental-client-ui-forge`
|
||||
|
||||
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:639`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:655`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Host settings of the forge panel Remote. */
|
||||
|
||||
@@ -1325,7 +1325,7 @@ export interface CotTranslationPreferences {
|
||||
## `@deepseek-ai/dsh-experimental-client-ui-forge`
|
||||
|
||||
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:639`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:655`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Host settings of the forge panel Remote. */
|
||||
|
||||
@@ -30,11 +30,11 @@
|
||||
en: 74255d6005e1c9e8
|
||||
zh: 252d0d552f1e26a1
|
||||
/forges/panel:
|
||||
en: 505c34246c9eaa4c
|
||||
zh: 1e5c2210849dd621
|
||||
en: 4d9052cd8ad75b67
|
||||
zh: 302be1ab39da81d7
|
||||
/forges/panel/review-page:
|
||||
en: de8dc146c603314b
|
||||
zh: 976884cb9b3a7464
|
||||
/forges/extension-api:
|
||||
en: f35345e482e84f4f
|
||||
zh: 2ecb7d9498decb31
|
||||
en: 0691d26dfbfdfbbf
|
||||
zh: a1d05fcc8ca9f2ce
|
||||
+56
-27
@@ -1516,7 +1516,7 @@ type ForgeChangeRequestStatesFrame =
|
||||
| { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] }
|
||||
```
|
||||
|
||||
The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, which returns a patch only for that head commit, or the `ForgeCommitRange` it names through the provider's `compare`; both return files that the Host parsed into `ForgeDiffFile` hunks, each with its review layer and change digest. `localCommits` and `changeRequestCommits` list the commits a range can name, the latter as null when the provider does not read commits. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the Session panel's local changes row, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. When the head moved past the latest status, the provider returns `stale` and `ctx.forge.diff` polls the change request at once, once per head commit; `changeRequestDiff` rejects with `forgePanel/stale-head` and caches nothing, and the changes view keeps loading until a later status arrives, then reads again at that status's head. Review comments therefore always address the commit whose lines the view shows.
|
||||
The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout or of the head branch the scope names, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, which returns a patch only for that head commit, or the `ForgeCommitRange` it names through the provider's `compare`; both return files that the Host parsed into `ForgeDiffFile` hunks, each with its review layer and change digest. `localCommits` and `changeRequestCommits` list the commits a range can name, the latter as null when the provider does not read commits. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the Session panel's local changes row, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. When the head moved past the latest status, the provider returns `stale` and `ctx.forge.diff` polls the change request at once, once per head commit; `changeRequestDiff` rejects with `forgePanel/stale-head` and caches nothing, and the changes view keeps loading until a later status arrives, then reads again at that status's head. Review comments therefore always address the commit whose lines the view shows.
|
||||
|
||||
`changeRequestReview(session, url, headSha, fresh)` reads the threads of a bound change request at the head of the diff the view shows and refuses another head with `forgePanel/stale-head`, `forgePanel/review-unsupported` for a provider without review reads, and `forgePanel/review-failed` otherwise. It keeps one read per change request in memory, keyed by head commit and the status's update time and bounded by `maxCachedReviewBytes`, and reads again once the kept read is `reviewRefreshMs` old or when `fresh` asks for it, as the first read after the reader refreshes the view does: on GitHub a new comment or reply changes a pull request's update time, but resolving a thread does not. The changes view asks again at every status it receives while visible, and overlays the threads on the files the [panel README](../../packages/experimental/client-ui-forge/README.md#use-this-package) describes.
|
||||
|
||||
@@ -1537,22 +1537,32 @@ interface ForgeCommitRange {
|
||||
}
|
||||
```
|
||||
|
||||
A local scope reads the checkout of the Session's current directory unless it names a `head`: the full ref of a branch under `refs/heads/` or `refs/remotes/` that `show-ref --verify` finds in the Session's repository. The Host reads that branch where it is checked out. When `git worktree list` names a worktree of the repository for the branch and inspection finds a checkout of the same repository with the branch checked out there, Git runs in that worktree under the reading Session's sandbox policy: every scope reads its working tree, the automatic fork point is the merge base with the default branch of the code host remote, and the result names the directory in `worktree`. Otherwise, as for every remote-tracking branch, only the `branch` scope applies, and it compares committed content, with the ref in place of HEAD and without uncommitted or untracked files; another scope rejects with `forgePanel/no-working-tree`. A head that names the Session's own checked-out branch reads the Session's checkout.
|
||||
|
||||
`diffBases(session, head, query)` and `localCommits(session, head, base)` take the same head, or null for the Session's own checkout. `diffBases` leaves out the branch the scope shows and gives each local branch the directory of the worktree that has it checked out, so the page lists the branches a reader can show through the same Remote method with a null head. A head whose branch does not exist rejects a read with `forgePanel/head-missing`. `localWrite` takes no head and writes the Session's own checkout.
|
||||
|
||||
```ts type-equiv
|
||||
/** Which local changes a diff covers; each reads the Session's checkout through Git. */
|
||||
/**
|
||||
* Which local changes a diff covers. Without `head` each reads the checkout of the Session's current directory through
|
||||
* Git. With `head`, the full ref name of a branch under `refs/heads/` or `refs/remotes/`, it reads that branch in place
|
||||
* of the checked-out one: in the worktree of the repository that has the branch checked out, where every scope applies
|
||||
* and HEAD below is that worktree's, or, when no worktree has it, from the branch's commits, where only the `branch`
|
||||
* scope applies and no uncommitted or untracked file shows.
|
||||
*/
|
||||
type ForgeLocalScope =
|
||||
/**
|
||||
* The working tree and untracked files against a fork point: the merge base of HEAD with the
|
||||
* `base` ref, or while `base` is null, the base commit of the worktree the Session created,
|
||||
* else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes
|
||||
* of those commits between the fork point and HEAD, without uncommitted or untracked files.
|
||||
* `base` ref, or while `base` is null, the base commit of the worktree the Session created when it reads its own
|
||||
* checkout, else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the
|
||||
* changes of those commits between the fork point and HEAD, without uncommitted or untracked files.
|
||||
*/
|
||||
| { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null }
|
||||
| { readonly kind: 'branch'; readonly head?: string; readonly base: string | null; readonly commits: ForgeCommitRange | null }
|
||||
/** The working tree and untracked files against HEAD. */
|
||||
| { readonly kind: 'uncommitted' }
|
||||
| { readonly kind: 'uncommitted'; readonly head?: string }
|
||||
/** The working tree and untracked files against the index. */
|
||||
| { readonly kind: 'unstaged' }
|
||||
| { readonly kind: 'unstaged'; readonly head?: string }
|
||||
/** The index against HEAD. */
|
||||
| { readonly kind: 'staged' }
|
||||
| { readonly kind: 'staged'; readonly head?: string }
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
@@ -1562,6 +1572,11 @@ interface ForgeBaseBranch {
|
||||
readonly ref: string
|
||||
/** The ref without `refs/heads/` or `refs/remotes/`, such as `master` or `origin/master`. */
|
||||
readonly name: string
|
||||
/**
|
||||
* Directory Git registered for the worktree that has this local branch checked out, absent when none has; a scope
|
||||
* that names the branch as its head reads that worktree.
|
||||
*/
|
||||
readonly worktree?: string
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1582,7 +1597,7 @@ interface ForgeBaseBranches {
|
||||
readonly automatic: ForgeAutomaticBase | null
|
||||
/** Remote-tracking branches without symbolic refs such as `origin/HEAD`, most recently committed first, at most `maxBranches`. */
|
||||
readonly remote: readonly ForgeBaseBranch[]
|
||||
/** Local branches other than the checked-out one, most recently committed first, at most `maxBranches`. */
|
||||
/** Local branches other than the one the scope shows, most recently committed first, at most `maxBranches`. */
|
||||
readonly local: readonly ForgeBaseBranch[]
|
||||
}
|
||||
```
|
||||
@@ -1659,6 +1674,11 @@ interface ForgeLocalDiff {
|
||||
readonly files: readonly ForgeDiffFile[]
|
||||
/** Untracked files left out beyond `maxUntrackedFiles`. */
|
||||
readonly omitted: number
|
||||
/**
|
||||
* Top-level directory of the worktree the scope read for its `head`; absent for the Session's own checkout and for
|
||||
* a head read from its commits.
|
||||
*/
|
||||
readonly worktree?: string
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1845,7 +1865,7 @@ interface ForgeLensKeep {
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.forgeChanges` also mints and reads changes addresses, names the tab `kinds`, and opens a view with `open(target, { path, lens })` in the Session the sidebar shows. `registerAnnotations(source)` adds line annotations: the source observes each view's annotations by path, and its `forge.diff.line.annotation` entry, keyed by the source's identity, draws each one inside a frame the view draws. Annotations stack on the row of their last line after the comment form, the browser drafts, and the host threads, in the column of their side; whole-file annotations come first, and those written on another `digest` follow the file in their own section. A file shows at most `maxAnnotationsPerFile`, and a file that draws its lines draws no annotation before its section comes within reach of the scrollport. The owner props of every slot live in [`src/client/slots.ts`](../../packages/experimental/client-ui-forge/src/client/slots.ts).
|
||||
`ctx.forgeChanges` also mints and reads changes addresses, names the tab `kinds`, and opens a view with `open(target, { path, lens })` in the Session the sidebar shows. `registerAnnotations(source)` adds line annotations: the source observes each view's annotations by path, and its `forge.diff.line.annotation` entry, keyed by the source's identity, draws each one inside a frame the view draws. Annotations stack on the row of their last line after the comment form, the browser drafts, and the host threads, in the column of their side; whole-file annotations come first, and those written on another `digest` follow the file in their own section. A file shows at most `maxAnnotationsPerFile`, and a file that draws its lines draws no annotation before its section comes within reach of the scrollport. A local changes view that shows a `head` branch other than the Session's own checkout draws no annotation and no entry of the `forge.changes.toolbar`, `forge.changes.file.menu`, and `forge.diff.comment.actions` slots. The owner props of every slot live in [`src/client/slots.ts`](../../packages/experimental/client-ui-forge/src/client/slots.ts).
|
||||
|
||||
```ts type-equiv
|
||||
/** Where one line annotation sits in a file of a changes view. */
|
||||
@@ -2601,15 +2621,19 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeWorktreeBases>
|
||||
|
||||
/**
|
||||
* List the branches the `branch` scope of the Session's current checkout can compare with.
|
||||
* List the branches the `branch` scope can compare with, for the Session's current checkout or for a head branch
|
||||
* read in its place.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param head - full ref of the branch the scope reads in place of the checked-out one, or null for the checkout.
|
||||
* @param query - text the branch names must contain, ignoring case; empty for every branch.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the automatic fork point and at most `maxBranches` remote-tracking and local branches each,
|
||||
* most recently committed first, without the checked-out branch.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.
|
||||
* most recently committed first, without the branch the scope shows; a local branch that a worktree has checked
|
||||
* out names that worktree's directory.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head does not exist; the
|
||||
* Git error when Git fails or the listed refs exceed `maxDiffBytes`.
|
||||
*/
|
||||
@Remote async diffBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeBaseBranches>
|
||||
@Remote async diffBases(session: Session, head: string | null, query: string, signal: AbortSignal): Promise<ForgeBaseBranches>
|
||||
|
||||
/**
|
||||
* Bind a change request to a Session by URL, or restore a dismissed binding.
|
||||
@@ -2649,13 +2673,15 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async revisit(sessionId: SessionId, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Read the changes one scope covers in the checkout of the Session's
|
||||
* current directory, with Git using the Session's sandbox policy.
|
||||
* Read the changes one scope covers in the checkout of the Session's current directory, or for the head branch the
|
||||
* scope names: in the worktree that has it checked out, else from its commits. Git uses the Session's sandbox policy.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param scope - which changes to read.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the files, the base of the `branch` scope, and the untracked files left out.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch
|
||||
* @returns the files, the base of the `branch` scope, the untracked files left out, and the worktree read for a head.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head the scope names
|
||||
* does not exist; `forgePanel/no-working-tree` for another scope than `branch` whose head no worktree has checked
|
||||
* out; `forgePanel/base-missing` when the base branch
|
||||
* chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without
|
||||
* a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order;
|
||||
* `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
|
||||
@@ -2665,27 +2691,30 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise<ForgeLocalDiff>
|
||||
|
||||
/**
|
||||
* List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or
|
||||
* several of instead of the whole scope.
|
||||
* List the commits of the `branch` scope of the Session's current checkout or of a head branch read in its place,
|
||||
* which the changes view can show one or several of instead of the whole scope.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param head - full ref of the branch the scope reads in place of the checked-out one, or null for the checkout.
|
||||
* @param base - the base ref of the `branch` scope, or null for its automatic fork point.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not
|
||||
* exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`.
|
||||
* @returns the newest `maxCommits` commits between the fork point and the shown HEAD or branch, oldest first, and its commit.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head does not exist;
|
||||
* `forgePanel/base-missing` when the base branch does not exist; `forgePanel/no-fork-point` without a fork point;
|
||||
* the Git error when Git fails or the listing exceeds `maxDiffBytes`.
|
||||
*/
|
||||
@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise<ForgeLocalCommits>
|
||||
@Remote async localCommits(session: Session, head: string | null, base: string | null, signal: AbortSignal): Promise<ForgeLocalCommits>
|
||||
|
||||
/**
|
||||
* Read the new side of one changed file in a scope, which supplies the
|
||||
* unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of
|
||||
* the `branch` scope, else the working tree.
|
||||
* the `branch` scope, the branch for a head read from its commits, else the working tree of the checkout the scope reads.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param scope - the scope the diff was read in.
|
||||
* @param path - path relative to the checkout's top-level directory, as the diff names it.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the text.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`;
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` and `forgePanel/no-working-tree`
|
||||
* as for {@link ForgePanelController.localDiff}; `forgePanel/diff-too-large` over `maxDiffBytes`;
|
||||
* `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside
|
||||
* the checkout, binary content, or a failed read.
|
||||
*/
|
||||
|
||||
+56
-27
@@ -1520,7 +1520,7 @@ type ForgeChangeRequestStatesFrame =
|
||||
| { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] }
|
||||
```
|
||||
|
||||
变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更(提供方只返回描述该 head 提交的补丁),或经提供方的 `compare` 读取它指定的 `ForgeCommitRange`;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk,并带有分层与改动摘要。`localCommits` 与 `changeRequestCommits` 列出范围可以指定的提交,提供方不读取提交时后者返回 null。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供会话面板的本地变更行使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。head 已越过最新状态时,提供方返回 `stale`,`ctx.forge.diff` 立即重新轮询该变更请求(每个 head 提交一次);`changeRequestDiff` 以 `forgePanel/stale-head` 拒绝且不缓存任何内容,变更视图保持加载,直到更新的状态到达后按该状态的 head 重新读取。因此评审评论始终指向视图所显示行的那个提交。
|
||||
变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`,或该范围用 `head` 指定的分支;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更(提供方只返回描述该 head 提交的补丁),或经提供方的 `compare` 读取它指定的 `ForgeCommitRange`;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk,并带有分层与改动摘要。`localCommits` 与 `changeRequestCommits` 列出范围可以指定的提交,提供方不读取提交时后者返回 null。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供会话面板的本地变更行使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。head 已越过最新状态时,提供方返回 `stale`,`ctx.forge.diff` 立即重新轮询该变更请求(每个 head 提交一次);`changeRequestDiff` 以 `forgePanel/stale-head` 拒绝且不缓存任何内容,变更视图保持加载,直到更新的状态到达后按该状态的 head 重新读取。因此评审评论始终指向视图所显示行的那个提交。
|
||||
|
||||
`changeRequestReview(session, url, headSha, fresh)` 在视图所显示 diff 的 head 处读取已绑定变更请求的讨论;head 不同时以 `forgePanel/stale-head` 拒绝,提供方不支持读取讨论时返回 `forgePanel/review-unsupported`,其他失败返回 `forgePanel/review-failed`。每个变更请求在内存里保留一次读取结果,以 head 提交和状态的更新时间为键、受 `maxCachedReviewBytes` 约束,保留时间达到 `reviewRefreshMs` 后,或 `fresh` 要求时(读者刷新视图后的第一次读取就是这样)重新读取:在 GitHub 上,新评论和回复会改变 PR 的更新时间,解决讨论则不会。变更视图可见时,每收到一次状态就重新请求一次,并按[面板 README](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package) 所述把讨论叠加到文件上。
|
||||
|
||||
@@ -1541,22 +1541,32 @@ interface ForgeCommitRange {
|
||||
}
|
||||
```
|
||||
|
||||
本地范围读取 Session 当前目录所在的检出,除非它用 `head` 指定一个分支:`refs/heads/` 或 `refs/remotes/` 下的完整引用名,并且 `show-ref --verify` 能在 Session 的仓库里找到它。Host 在检出该分支的地方读取它。`git worktree list` 给出仓库里检出该分支的 worktree、并且检查发现那里是同一个仓库的检出且确实检出了该分支时,Git 以读取方 Session 的沙箱策略在这个 worktree 里运行:每个范围都读取它的工作树,自动分叉点是与代码托管远端默认分支的合并基准,结果在 `worktree` 中给出这个目录。否则(所有远程跟踪分支都是)只有 `branch` 范围可用,它比较已提交的内容,以该引用代替 HEAD,不含未提交和未跟踪的文件;其他范围以 `forgePanel/no-working-tree` 拒绝。`head` 指向 Session 自己检出的分支时,读取的是 Session 的检出。
|
||||
|
||||
`diffBases(session, head, query)` 与 `localCommits(session, head, base)` 接受同样的 `head`,null 表示 Session 自己的检出。`diffBases` 不列出范围正在查看的分支,并给每个本地分支写上检出它的 worktree 的目录,所以页面用同一个 Remote 方法、以 null 作为 `head` 列出可以查看的分支。`head` 指向的分支不存在时,读取以 `forgePanel/head-missing` 拒绝。`localWrite` 不接受 `head`,只写 Session 自己的检出。
|
||||
|
||||
```ts type-equiv
|
||||
/** Which local changes a diff covers; each reads the Session's checkout through Git. */
|
||||
/**
|
||||
* Which local changes a diff covers. Without `head` each reads the checkout of the Session's current directory through
|
||||
* Git. With `head`, the full ref name of a branch under `refs/heads/` or `refs/remotes/`, it reads that branch in place
|
||||
* of the checked-out one: in the worktree of the repository that has the branch checked out, where every scope applies
|
||||
* and HEAD below is that worktree's, or, when no worktree has it, from the branch's commits, where only the `branch`
|
||||
* scope applies and no uncommitted or untracked file shows.
|
||||
*/
|
||||
type ForgeLocalScope =
|
||||
/**
|
||||
* The working tree and untracked files against a fork point: the merge base of HEAD with the
|
||||
* `base` ref, or while `base` is null, the base commit of the worktree the Session created,
|
||||
* else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes
|
||||
* of those commits between the fork point and HEAD, without uncommitted or untracked files.
|
||||
* `base` ref, or while `base` is null, the base commit of the worktree the Session created when it reads its own
|
||||
* checkout, else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the
|
||||
* changes of those commits between the fork point and HEAD, without uncommitted or untracked files.
|
||||
*/
|
||||
| { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null }
|
||||
| { readonly kind: 'branch'; readonly head?: string; readonly base: string | null; readonly commits: ForgeCommitRange | null }
|
||||
/** The working tree and untracked files against HEAD. */
|
||||
| { readonly kind: 'uncommitted' }
|
||||
| { readonly kind: 'uncommitted'; readonly head?: string }
|
||||
/** The working tree and untracked files against the index. */
|
||||
| { readonly kind: 'unstaged' }
|
||||
| { readonly kind: 'unstaged'; readonly head?: string }
|
||||
/** The index against HEAD. */
|
||||
| { readonly kind: 'staged' }
|
||||
| { readonly kind: 'staged'; readonly head?: string }
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
@@ -1566,6 +1576,11 @@ interface ForgeBaseBranch {
|
||||
readonly ref: string
|
||||
/** The ref without `refs/heads/` or `refs/remotes/`, such as `master` or `origin/master`. */
|
||||
readonly name: string
|
||||
/**
|
||||
* Directory Git registered for the worktree that has this local branch checked out, absent when none has; a scope
|
||||
* that names the branch as its head reads that worktree.
|
||||
*/
|
||||
readonly worktree?: string
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1586,7 +1601,7 @@ interface ForgeBaseBranches {
|
||||
readonly automatic: ForgeAutomaticBase | null
|
||||
/** Remote-tracking branches without symbolic refs such as `origin/HEAD`, most recently committed first, at most `maxBranches`. */
|
||||
readonly remote: readonly ForgeBaseBranch[]
|
||||
/** Local branches other than the checked-out one, most recently committed first, at most `maxBranches`. */
|
||||
/** Local branches other than the one the scope shows, most recently committed first, at most `maxBranches`. */
|
||||
readonly local: readonly ForgeBaseBranch[]
|
||||
}
|
||||
```
|
||||
@@ -1663,6 +1678,11 @@ interface ForgeLocalDiff {
|
||||
readonly files: readonly ForgeDiffFile[]
|
||||
/** Untracked files left out beyond `maxUntrackedFiles`. */
|
||||
readonly omitted: number
|
||||
/**
|
||||
* Top-level directory of the worktree the scope read for its `head`; absent for the Session's own checkout and for
|
||||
* a head read from its commits.
|
||||
*/
|
||||
readonly worktree?: string
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1849,7 +1869,7 @@ interface ForgeLensKeep {
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.forgeChanges` 还可以生成和解析变更视图地址,给出标签的 `kinds`,并用 `open(target, { path, lens })` 在侧栏所显示的 Session 中打开视图。`registerAnnotations(source)` 添加行注解:数据源按路径观察每个视图的注解,它在 `forge.diff.line.annotation` 中按数据源身份登记的条目,负责绘制视图所画外框里的内容。注解放在其最后一行之后,位于评论框、浏览器草稿和托管平台讨论之后,落在所在一侧的那一栏;整个文件的注解排在最前,写在另一个 `digest` 上的注解在文件之后单独成段。每个文件最多显示 `maxAnnotationsPerFile` 条;逐行绘制的文件在文件段进入可视区附近之前不绘制注解。所有 slot 的 owner props 见 [`src/client/slots.ts`](../../packages/experimental/client-ui-forge/src/client/slots.ts)。
|
||||
`ctx.forgeChanges` 还可以生成和解析变更视图地址,给出标签的 `kinds`,并用 `open(target, { path, lens })` 在侧栏所显示的 Session 中打开视图。`registerAnnotations(source)` 添加行注解:数据源按路径观察每个视图的注解,它在 `forge.diff.line.annotation` 中按数据源身份登记的条目,负责绘制视图所画外框里的内容。注解放在其最后一行之后,位于评论框、浏览器草稿和托管平台讨论之后,落在所在一侧的那一栏;整个文件的注解排在最前,写在另一个 `digest` 上的注解在文件之后单独成段。每个文件最多显示 `maxAnnotationsPerFile` 条;逐行绘制的文件在文件段进入可视区附近之前不绘制注解。本地变更视图查看的是 `head` 指定的分支而不是 Session 自己的检出时,不绘制注解,也不绘制 `forge.changes.toolbar`、`forge.changes.file.menu` 与 `forge.diff.comment.actions` 插槽的条目。所有 slot 的 owner props 见 [`src/client/slots.ts`](../../packages/experimental/client-ui-forge/src/client/slots.ts)。
|
||||
|
||||
```ts type-equiv
|
||||
/** Where one line annotation sits in a file of a changes view. */
|
||||
@@ -2605,15 +2625,19 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async worktreeBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeWorktreeBases>
|
||||
|
||||
/**
|
||||
* List the branches the `branch` scope of the Session's current checkout can compare with.
|
||||
* List the branches the `branch` scope can compare with, for the Session's current checkout or for a head branch
|
||||
* read in its place.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param head - full ref of the branch the scope reads in place of the checked-out one, or null for the checkout.
|
||||
* @param query - text the branch names must contain, ignoring case; empty for every branch.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the automatic fork point and at most `maxBranches` remote-tracking and local branches each,
|
||||
* most recently committed first, without the checked-out branch.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.
|
||||
* most recently committed first, without the branch the scope shows; a local branch that a worktree has checked
|
||||
* out names that worktree's directory.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head does not exist; the
|
||||
* Git error when Git fails or the listed refs exceed `maxDiffBytes`.
|
||||
*/
|
||||
@Remote async diffBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeBaseBranches>
|
||||
@Remote async diffBases(session: Session, head: string | null, query: string, signal: AbortSignal): Promise<ForgeBaseBranches>
|
||||
|
||||
/**
|
||||
* Bind a change request to a Session by URL, or restore a dismissed binding.
|
||||
@@ -2653,13 +2677,15 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async revisit(sessionId: SessionId, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Read the changes one scope covers in the checkout of the Session's
|
||||
* current directory, with Git using the Session's sandbox policy.
|
||||
* Read the changes one scope covers in the checkout of the Session's current directory, or for the head branch the
|
||||
* scope names: in the worktree that has it checked out, else from its commits. Git uses the Session's sandbox policy.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param scope - which changes to read.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the files, the base of the `branch` scope, and the untracked files left out.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch
|
||||
* @returns the files, the base of the `branch` scope, the untracked files left out, and the worktree read for a head.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head the scope names
|
||||
* does not exist; `forgePanel/no-working-tree` for another scope than `branch` whose head no worktree has checked
|
||||
* out; `forgePanel/base-missing` when the base branch
|
||||
* chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without
|
||||
* a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order;
|
||||
* `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
|
||||
@@ -2669,27 +2695,30 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
@Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise<ForgeLocalDiff>
|
||||
|
||||
/**
|
||||
* List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or
|
||||
* several of instead of the whole scope.
|
||||
* List the commits of the `branch` scope of the Session's current checkout or of a head branch read in its place,
|
||||
* which the changes view can show one or several of instead of the whole scope.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param head - full ref of the branch the scope reads in place of the checked-out one, or null for the checkout.
|
||||
* @param base - the base ref of the `branch` scope, or null for its automatic fork point.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not
|
||||
* exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`.
|
||||
* @returns the newest `maxCommits` commits between the fork point and the shown HEAD or branch, oldest first, and its commit.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head does not exist;
|
||||
* `forgePanel/base-missing` when the base branch does not exist; `forgePanel/no-fork-point` without a fork point;
|
||||
* the Git error when Git fails or the listing exceeds `maxDiffBytes`.
|
||||
*/
|
||||
@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise<ForgeLocalCommits>
|
||||
@Remote async localCommits(session: Session, head: string | null, base: string | null, signal: AbortSignal): Promise<ForgeLocalCommits>
|
||||
|
||||
/**
|
||||
* Read the new side of one changed file in a scope, which supplies the
|
||||
* unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of
|
||||
* the `branch` scope, else the working tree.
|
||||
* the `branch` scope, the branch for a head read from its commits, else the working tree of the checkout the scope reads.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param scope - the scope the diff was read in.
|
||||
* @param path - path relative to the checkout's top-level directory, as the diff names it.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the text.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`;
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` and `forgePanel/no-working-tree`
|
||||
* as for {@link ForgePanelController.localDiff}; `forgePanel/diff-too-large` over `maxDiffBytes`;
|
||||
* `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside
|
||||
* the checkout, binary content, or a failed read.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.3-alpha.2/forge-local-changes-head/guide.md
|
||||
/:
|
||||
en: be9180e666c44188
|
||||
zh: b0bc959914784b4d
|
||||
/the-local-changes-reads-of-the-forge-panel-name-the-branch-they-show:
|
||||
en: 9f7fa5536bb1850e
|
||||
zh: 7ea6ea1368e72c19
|
||||
/the-local-changes-reads-of-the-forge-panel-name-the-branch-they-show/change:
|
||||
en: ff21fa32d21a459b
|
||||
zh: b6a78dd898a6aba4
|
||||
/the-local-changes-reads-of-the-forge-panel-name-the-branch-they-show/migration:
|
||||
en: 5b17c0009ec9e947
|
||||
zh: 9936f5e00cb01a16
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "forgePanel.diffBases and forgePanel.localCommits take a head argument after the Session."
|
||||
---
|
||||
|
||||
# The local changes reads of the Forge panel name the branch they show
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
The `forgePanel.diffBases` Remote took `(session, query)` and `forgePanel.localCommits` took `(session, base)`. Both now take a `head` right after the Session: `diffBases(session, head, query)` and `localCommits(session, head, base)`. `head` is `string | null`: the full ref of a branch under `refs/heads/` or `refs/remotes/` that the read shows in place of the Session's checked-out branch, or null for the Session's own checkout, which is what both methods read before.
|
||||
|
||||
`ForgeLocalScope`, the argument of `forgePanel.localDiff`, `forgePanel.localText`, and the local source of `forgePanel.changesLens`, gains an optional `head` with the same meaning on each of its four kinds. `ForgeBaseBranch` and `ForgeLocalDiff` gain an optional `worktree`. Two error codes are new: `forgePanel/head-missing` when the branch does not exist, and `forgePanel/no-working-tree` when a scope other than `branch` names a head that no worktree has checked out.
|
||||
|
||||
This affects code outside `@deepseek-ai/dsh-experimental-client-ui-forge` that calls `forgePanel.diffBases` or `forgePanel.localCommits`. Code that only builds `ForgeLocalScope` values or reads `ForgeBaseBranch` and `ForgeLocalDiff` is unaffected, because the new members are optional.
|
||||
|
||||
## Migration
|
||||
|
||||
1. In every `forgePanel.diffBases` call, pass `null` as the second argument, before the query: `diffBases(session, null, query, signal)`.
|
||||
2. In every `forgePanel.localCommits` call, pass `null` as the second argument, before the base: `localCommits(session, null, base, signal)`.
|
||||
3. Run your type check; it passes once both calls have the new argument. The reads return what they returned before.
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "forgePanel.diffBases 与 forgePanel.localCommits 在 Session 之后新增 head 参数。"
|
||||
---
|
||||
|
||||
# Forge 面板的本地变更读取要指明查看的分支
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
`forgePanel.diffBases` 这个 Remote 原先的参数是 `(session, query)`,`forgePanel.localCommits` 是 `(session, base)`。现在两者都在 Session 之后多了一个 `head`:`diffBases(session, head, query)` 与 `localCommits(session, head, base)`。`head` 的类型是 `string | null`:它是 `refs/heads/` 或 `refs/remotes/` 下某个分支的完整引用名,读取时用这个分支代替 Session 检出的分支;null 表示 Session 自己的检出,也就是两个方法原先读取的内容。
|
||||
|
||||
`ForgeLocalScope` 是 `forgePanel.localDiff`、`forgePanel.localText` 的参数,也是 `forgePanel.changesLens` 的本地来源;它的四种 kind 都新增了含义相同的可选 `head`。`ForgeBaseBranch` 与 `ForgeLocalDiff` 新增可选的 `worktree`。新增两个错误码:分支不存在时为 `forgePanel/head-missing`;`branch` 以外的范围指定了没有 worktree 检出的 `head` 时为 `forgePanel/no-working-tree`。
|
||||
|
||||
受影响的是 `@deepseek-ai/dsh-experimental-client-ui-forge` 之外调用 `forgePanel.diffBases` 或 `forgePanel.localCommits` 的代码。只构造 `ForgeLocalScope` 或只读取 `ForgeBaseBranch`、`ForgeLocalDiff` 的代码不受影响,因为新增的成员都是可选的。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 在每个 `forgePanel.diffBases` 调用中,把 `null` 作为第二个参数,放在查询文字之前:`diffBases(session, null, query, signal)`。
|
||||
2. 在每个 `forgePanel.localCommits` 调用中,把 `null` 作为第二个参数,放在基准之前:`localCommits(session, null, base, signal)`。
|
||||
3. 运行类型检查;两处调用都带上新参数后即通过。读取结果与原先相同。
|
||||
@@ -15,23 +15,23 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/use-this-package:
|
||||
en: 04eca9b83980554c
|
||||
zh: 879f0fdc038f68e4
|
||||
en: 1d1455cd4e79349f
|
||||
zh: fb5b8d394b76f88e
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
|
||||
en: ba86f9b4ea0645e7
|
||||
zh: b34809ba2ab01e9e
|
||||
en: f06f25b4653b0fd8
|
||||
zh: e6fb77256d3901f7
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/further-exploration:
|
||||
en: fa4d8c579ffc49ff
|
||||
zh: 5856ed7469e4585b
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/model-experience:
|
||||
en: fc49ba3011e952f9
|
||||
zh: e7e3a3a94f67833b
|
||||
en: 5dd844e662e37878
|
||||
zh: b6c70190b173c3c6
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/model-experience/kv-cache-effect:
|
||||
en: c1b5bfb0e5a1801e
|
||||
zh: 2bbe1a2845aa5d20
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work:
|
||||
en: a1d5b383d36f05f6
|
||||
zh: cbf128e33b2a8ae3
|
||||
en: 33a084278e95db3d
|
||||
zh: e43fe62621c43523
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -41,8 +41,9 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish
|
||||
- **Connection row** — when the Session's panel stream ends, also before it delivered a first state, a status row at the end of the Environment section says the status stopped updating and that the Git and change request details may be out of date; Retry opens the stream again and the row goes away.
|
||||
- **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll.
|
||||
- **Change requests section** — shows while the Session has bound change requests or the repository's host needs sign-in. Its title carries their count. A status row above the cards asks to sign in to the host: with the sign-in command the provider names, such as `gh auth login --hostname github.com`, which crawls into view on hover, and Copy; when the provider names none, and when the sign-in check fails, with the host's reason behind an info button, as the checkout row shows its failure. The section shows with this row alone while the Session binds no change request. Each change request is a compact card, a filled block on the panel's row columns: one line with a glyph for its state, its title, its number, and a glyph for the outcome of its checks. A press on the line opens the change request's changes in the right sidebar; with Cmd or Ctrl held, with the middle button, and for a change request no provider serves or has read yet, it opens the host's page. The state glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the toggle's yellow dot does. The card's More menu, which shows on hover or focus as on the panel's other rows, offers View changes for a change request a provider serves, Open on the code host with that host's mark, Copy change request link, Ready for review for an open draft, and Remove from this Session, whose toast offers Undo. While collapsed, the line reads its status in words to assistive technology, and the card's hover card shows the full title, the number with draft state and the head and base branches, and that status: the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended; a failed read or an unserved URL stands there instead. Cancelled checks have a separate count, which the status names when no listed check failed. The checks glyphs share one ring: a check for passed, a cross for failed, a half fill while they run, and a dash otherwise. An expanded card shows one row per fact below its line, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. The thread count and an issue's title show in a tooltip after 500ms of hover. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. A change request the host would merge now offers Merge below its rows, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. A change request the host would not merge yet offers Auto-merge there instead where the user can turn the code host's automatic merge on: the same menu, whose confirmation turns it on for the displayed head. Once it is on, the button reads Auto-merge enabled and its menu names the method and the account that turned it on, when the host names them, and offers Cancel auto-merge where the user may cancel. The list shows three cards; with more, the panel's fold control after them shows the rest and folds them again, and the Session keeps that choice while it stays open. When the Session binds exactly one change request, its card starts expanded whatever its state; with several, every card starts collapsed. A card the user expands or collapses keeps that choice across updates and while the paLine truncated
|
||||
- **Local changes row** — whenever the `branch` scope changes files, independently of bound change requests, the row names the number of changed files with the added and deleted lines and opens the changes view. Its More menu offers View changes and, when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, Create change request, which sends the Session a user message in the UI language that asks the Agent to create a change request for these changes; a toast reports whether it was sent.
|
||||
- **Changes view** — The Changes row and View changes item of a change request card and the local changes row open a right-sidebar tab that lists the changed files, closing the Session panel while it floats over the conversation. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. The Unstaged scope offers Stage file and Restore file on each file and Stage all in the header; the Staged scope offers Unstage file and Unstage all. A header button acts on the files the view shows, so files that a layer, a lens, or the test file switch hides stay as they are. Staging and unstaging report with Undo, which returns the index entries of those files to their state before the write, including an edit staged earlier. Restore file asks first, because it cannot be undone: it returns a changed or deleted file to its index entry and deletes an untracked file, and a file the index tracks without content offers none, nor does a submodule. While a write is in flight or the scope is read again afterwards, the buttons and the menu's rows for these writes cannot be activated. A deleted file whose place a directory took is refused with a notice that says to use the files inside the directory. The other scopes offer no write, since a write there could leave the shown changes as they are. The writes are the reader's own, so they work under every access mode of the Session, read-only included. In a view at most 380px wide a file's writes show under the pointer or once the keyboard reaches them, taking the place of its line counts, and the file's More menu lists the same writes. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Its icon buttons and the header's Open on the code host, which carries that host's mark, name their action after 500ms of hover or at once on keyboard focus. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one for 500ms shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head on the code host for a change request. When the header is narrow, the path, the badges, and Changed sinLine truncated
|
||||
- **Local changes row** — inside a Git checkout the row always shows, independently of bound change requests, and opens the changes view. It names the number of files the `branch` scope changes, or reads only Local changes while that scope changes none, followed by the added and deleted lines: +0 −0 for no change, and nothing while the scope has no fork point. Its More menu offers View changes and, when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, Create change request, which sends the Session a user message in the UI language that asks the Agent to create a change request for these changes; a toast reports whether it was sent.
|
||||
- **Changes view** — The Changes row and View changes item of a change request card and the local changes row open a right-sidebar tab that lists the changed files, closing the Session panel while it floats over the conversation. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, in the Branch shown menu described below, and then the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the arrow between the two menus, whose names shorten together. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. The Unstaged scope offers Stage file and Restore file on each file and Stage all in the header; the Staged scope offers Unstage file and Unstage all. A header button acts on the files the view shows, so files that a layer, a lens, or the test file switch hides stay as they are. Staging and unstaging report with Undo, which returns the index entries of those files to their state before the write, including an edit staged earlier. Restore file asks first, because it cannot be undone: it returns a changed or deleted file to its index entry and deletes an untracked file, and a file the index tracks without content offers none, nor does a submodule. While a write is in flight or the scope is read again afterwards, the buttons and the menu's rows for these writes cannot be activated. A deleted file whose place a directory took is refused with a notice that says to use the files inside the directory. The other scopes offer no write, since a write there could leave the shown changes as they are. The writes are the reader's own, so they work under every access mode of the Session, read-only included. In a view at most 380px wide a file's writes show under the pointer or once the keyboard reaches them, taking the place of its line counts, and the file's More menu lists the same writes. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Its icon buttons and the header's Open on the code host, which carries that host's mark, name their action after 500ms of hover or at once on keyboard focus. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one for 500ms shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head on the code host Line truncated
|
||||
- **Branch shown** — The local changes header starts with a searchable menu, named Branch shown, of the branch the view shows: the Session's own checkout, tagged This session and chosen at first, then, under Local branches and Remote branches, the other branches of the repository, each most recently committed first. Typing filters the listed rows at once and lists the branches whose names contain the text after a short pause. A local branch that a worktree of the repository has checked out is tagged Worktree, with that worktree's directory on hover. The view reads such a branch in its worktree: all four scopes apply, uncommitted and untracked files show, and Default is the merge base with the default branch of the code host remote. A branch that no worktree has checked out, as every remote branch, shows committed content only: the Branch scope alone, with no scope menu and no note that uncommitted changes count; choosing one from another scope shows Branch. Each read looks the worktree up again, so one added or removed after the menu listed the branch changes the scopes the view offers. The base branch menu, which leaves the shown branch out, the commit picker, the expansion of unchanged lines, and the lenses follow the choice, and each choice starts at the Default base and all commits. The menu also starts the header of the Uncommitted, Unstaged, and Staged scopes. Only the Session's own checkout offers staging, unstaging, and restoring, Create change request, and opening the whole file in the sidebar, and only there do other plugins' toolbar tools, file menu rows, comment form buttons, and line annotations show. Viewed marks and comment records are kept apart for each choice. When the chosen branch is gone, the menu strikes its name through, and the view says that it was not found and offers Back to this session instead of Retry.
|
||||
|
||||
- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; when the counts do not fit the tree's width, it shows the layer names alone and each count in the hover text of its layer. Where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the mark draws as an empty ring, and as a check in a ring once the file is viewed, and a view at most 520px wide shows the ring without its label; the toolbar shows how many of the shown files are viewed, as a ring filled to the viewed share and a label such as 2 / 3 viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. The file tree draws a viewed file subdued, and a directory once every file in it is viewed, so the files left to review stand out; a file changed since it was viewed draws as unviewed, and assistive technology reads the state as each row's description. A change of the file mode alone, such as `chmod +x`, also counts as a new change. A change request's view of all its commits uses the viewed marks its provider keeps on the code host, as the GitHub provider does: the view reads them with the diff, shows a mark at once, and saves it at the displayed head, keeping that file's checkbox disabled until the host answers; a file GitHub reports as changed since it was viewed shows Changed since viewed. A mark the host refuses, or one that new commits made stale, returns to its previous state, and a toast says why; a mark the host may have saved without confirming it stays, and a toast says to refresh to see where it stands. When the marks cannot be read, a notice says so and offers Retry, and no file can be marked. Hovering a checkbox tells where its mark is kept. Other marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits.
|
||||
- **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads. Each click on the count in a header goes to the file's next unresolved thread in the order the file shows them, threads the chosen commits do not hold last, and from the last back to the first; the Threads toolbar button opens the thread list, which groups the threads by file in file tree order and orders each file's threads the same way, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers Add to input, which quotes the whole thread, View on GitHub, and the writes the signed-in user may make. Without a pending review, its reply field replies at once, and its menu starts a pending review with the reply; with one, the field adds the reply to it, as GitHub adds every reply of the user to the pending review. Resolve thread and Unresolve thread change its state, and the menu of the user's own comment edits or deletes it after asking, saying when deleting the only comment deletes the thread. A resolved thread stays open while the user writes a reply or an edit in it. A write the code host refuses keeps the text and says why; a write whose outcome is unknown reads the threads again and asks the user to check them before trying again. Every write reads the threads again, since resolving a thread does not change a GitHub pull request's update time. Threads are read again at each status while the view shows, and from the code host after Refresh even while the panel keeps an earlier read; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none.
|
||||
@@ -66,7 +67,7 @@ All files opens a searchable directory tree with the selected file scrolled to i
|
||||
|
||||
`ForgePanelController` keeps one `SessionPanel` per followed Session and disposes it when the last follower leaves, keeping its last state, the latest snapshots, and the branch it looked up while the Session stays loaded. A panel starts with the Session's working directory and bindings, or with what the Session's previous panel kept unless the Session has moved to another directory, re-inspects after each `workspace-root/change`, `tool/result`, and `sandbox/mode` event, and publishes a new `ForgePanelState` only when the state differs from the published one, so a reinspection that finds the same checkout reaches no follower. Each change request keeps the latest snapshot a poll returned while later polls fail. A failed parallel Git read cancels and joins its siblings. Inspections run one at a time with one trailing rerun, and a result for a directory the Session has since left is dropped. The code host comes from the remotes in order: the upstream's remote, then `origin`, then the rest. When an inspection finds an upstream branch on a remote a provider recognizes, the panel asks `ctx.forgeSession.discoverBranch` to bind that branch's open change requests, once per remote and branch until a refresh, or until a panel starts or is revisited while the Session shows no change request. A sign-in probe runs within `readinessTimeoutMs` when the recognized host changes, on refresh, after the first inspection of a panel whose previous panel did not find the host ready, on a revisit while the host is not ready, and once when status reads on a host shown as ready start to be refused as unauthenticated; a refresh settles once the inspection and the probe it started have ended, and poll results arrive later. `revisit` reinspects the checkout and polls only the change requests whose latest poll is older than `statusMaxAgeMs`.
|
||||
|
||||
Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --quiet HEAD`, which names the checked-out branch when it is under `refs/heads/`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `worktreeBases` runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, takes each remote's default branch from its `refs/remotes/<remote>/HEAD`, leaves out other symbolic refs and the branches of unconfigured remotes, and keeps at most `maxBranches` local branches and `maxBranches` branches per remote whose names contain the query, with remotes in the code host order below; `requestWorktree` with a name checks it against Git's branch-name rules and runs `show-ref` in the checkout; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes row: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when the checkout lies inside the canonical workspace root of the Session's sandbox policy and the common Git directory lies inside that root or one of the policy's additional writable directories.
|
||||
Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --quiet HEAD`, which names the checked-out branch when it is under `refs/heads/`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `worktreeBases` runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, takes each remote's default branch from its `refs/remotes/<remote>/HEAD`, leaves out other symbolic refs and the branches of unconfigured remotes, and keeps at most `maxBranches` local branches and `maxBranches` branches per remote whose names contain the query, with remotes in the code host order below; `requestWorktree` with a name checks it against Git's branch-name rules and runs `show-ref` in the checkout; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD` and the branch the scope shows, and keeps at most `maxBranches` branches of each kind whose names contain the query; `worktree list --porcelain` then gives each kept local branch the directory of the worktree that has it checked out. Inspection then sizes the `branch` scope for the local changes row: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when the checkout lies inside the canonical workspace root of the Session's sandbox policy and the common Git directory lies inside that root or one of the policy's additional writable directories.
|
||||
|
||||
A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `workspace-root/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. A request names its base by the full name of a local or remote-tracking branch, as earlier panels' short local names still resolve, and may name its branch. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, with `forgePanel/invalid-branch` for an empty base, with `forgePanel/invalid-name` for a branch name Git refuses, and with `forgePanel/branch-exists` for a branch name the checkout already uses; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the next-turn queue of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. A message queued for the next step, such as a notice another plugin injects, opens no turn and starts no hold. The hold makes one attempt on the requested branch name, or on a new generated one, asking the worktree service to fetch a remote-tracking base branch first; it publishes the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, fetch, failed step, reason, and whether the branch or directory existed stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, without the fetch when its `fetch` argument is false, refused with `forgePanel/not-waiting` while none waits or one runs; `requestWorktree` with another name changes the next attempt; and withdrawing the request lets the message go on in the current checkout. Each next-turn message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason.
|
||||
|
||||
@@ -77,6 +78,8 @@ Each inspection also decides whether the worktree is missing: the Session's dire
|
||||
|
||||
`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes/<remote>/HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes row hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :<path>` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, a patch together with its `.gitattributes`, where a failed patch read cancels the attributes read and both reads end before the result, the patch's failure passing on before the attributes failure, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to thLine truncated
|
||||
|
||||
A local scope may name a `head`, the full ref of a branch under `refs/heads/` or `refs/remotes/`, that it reads in place of the checked-out branch; `localTarget` resolves it for `localDiff`, `localText`, `localCommits`, `diffBases`, and `changesLens`. The page sends only the ref, never a path. The ref must exist for `show-ref --verify`, else the read refuses with `forgePanel/head-missing`, and another ref name is refused before Git runs. For a local branch, `worktree list --porcelain`, run in the Session's checkout, names the worktree that has the branch checked out, without the entries Git marks prunable. The line-separated listing ends a directory's name at a line break, and Git before 2.31 lists a removed directory without a mark, so the Host reads in that directory only when it exists and inspection finds a checkout of the same repository with the branch checked out there. Git then runs in that worktree under the reading Session's sandbox policy with every scope, the fork point is the merge base found as above, and `ForgeLocalDiff.worktree` names the directory. A head that names the Session's own checked-out branch reads the Session's checkout as a scope without a head does. Without such a worktree, as for every remote-tracking branch, the ref stands for HEAD in `merge-base`, `log`, and `rev-parse`, the comparison is `diff <fork> <ref>` without the working tree and untracked files, `.gitattributes` and `localText` read `<ref>:<path>` through `show`, and a scope other than `branch` refuses with `forgePanel/no-working-tree`.
|
||||
|
||||
`localWrite` applies one write of the changes view to the checkout. `stage` runs `add`, `unstage` runs `reset -q`, `restore` runs `restore --worktree` for tracked files and `clean -f -q` for untracked ones, and `reindex` runs `reset -q <tree>`; paths reach Git as literal pathspecs, in as many commands as 16,000 characters of paths each allow, which keeps a command line under the Windows limit. `stage` and `restore` name each file with the digest the reader saw: the Remote reads the `unstaged` scope again and refuses the whole write with `forgePanel/local-stale` when a file is gone or its digest differs, so nothing the reader did not see is staged or discarded. `restore` refuses a file that the scope lists as added or renamed without being untracked: the index tracks its path without content, as `git add --intent-to-add` leaves it, and Git would replace the file with an empty one. It also refuses a submodule, which the parser marks from the `160000` mode in its patch header: `git restore` exits with success and leaves the checked-out commit. [`src/restore.ts`](src/restore.ts) holds both rules for the Remote and the view. A `stage` or `restore` of a deleted file whose path holds a directory refuses with `forgePanel/local-path-replaced`, found with `ctx.fs.lstat`: Git takes a path for the directory and everything in it, so the write would stage the files in it or delete them. Before `stage` and `unstage` the Remote writes the index as a tree with `write-tree` and returns its object name, and `reindex` returns the index entries of the same paths to that tree; while the index holds unmerged entries there is no tree and the view offers no undo. The reader's press is the authorization, as archiving is for the worktree service's removal of a checkout, so the writing commands run through the mounted subprocess provider without the Session's sandbox policy, which bounds what the Agent does: they work under a read-only access mode and from a Session directory below the checkout's root. The reread of the `unstaged` scope stays under that policy, like every read. Unlike a diff, `add`, `reset`, and `restore` run the clean and smudge filters the repository configures; hooks and the filesystem monitor stay off as for every command of the panel, and `restore` passes `--no-recurse-submodules`. A failure after the first command of a write leaves the paths of the earlier commands written, so the panel inspects the checkout again after every write and the view reads its scope again.
|
||||
|
||||
`changeRequestViewed`, `setFileViewed`, `rerunChecks`, `requestReviews`, `reviewerCandidates`, and `updateBranch` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`. `changeRequestViewed` reads the provider's `viewedFiles` at the head commit of the shown diff and returns null when the provider keeps no viewed marks; a moved head refuses with `forgePanel/stale-head` and another failure with `forgePanel/viewed-failed`. It keeps one read per change request, keyed by head commit, under the same `maxCachedReviewBytes` and `reviewRefreshMs` bounds as the threads, and a mark saved through `ctx.forge` at that head replaces the kept state of its file, so saving a mark costs the provider's write and no further read; the reader's refresh passes `fresh` and reads the host again. `setFileViewed` saves one file's mark at that head through `setViewed`, and `rerunChecks` and `updateBranch` pass the head commit the card showed; a moved head refuses each of them with `forgePanel/stale-head`, another refusal with `forgePanel/action-failed` and the host's reason, and an outcome the host did not confirm with `forgePanel/action-unknown`. `requestReviews` asks one or more reviewers at once, refusing an empty list or an empty login, and `reviewerCandidates` lists the accounts that match a search, refusing with `forgePanel/reviewers-failed` when the host does not list them. The changes view reads a change request's viewed marks beside its diff, refuses marks read at another head as it refuses such a diff, and lets [`src/client/host-viewed.ts`](src/client/host-viewed.ts) keep each mark the reader sets per change request and head: a read at the same head keeps the marks whose writes are in flight, a mark whose write settled stays until the next read, and a write that settles after a diff at another head loaded changes nothing in it.
|
||||
@@ -87,7 +90,7 @@ Each inspection also decides whether the worktree is missing: the Session's dire
|
||||
|
||||
`follow` and `reviewChangeRequest` watch the snapshot of each change request they show and ask `ctx.forge` for a status no older than `statusMaxAgeMs` (default 10 seconds). A Session's panel or a review page stream that starts while the latest snapshot result is older reads the status at once; one that starts with a newer result, or with none yet read by another snapshot watcher, follows the regular poll.
|
||||
|
||||
The browser entry mounts the Remote, then the UI. One stream per Session feeds the Session panel entries, the New Session option, and the creation card; it opens with the first subscriber, after a `forgePanel` Session reference has opened the Session's history, so the Host resumes the Session once rather than beside that opening, holds that reference until the stream ends, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The change requests section is the `change-requests` entry of `conversation.session.panel.section` at order 100 with its count in `conversation.session.panel.section.actions`; the checkout, local changes, and connection rows are `conversation.session.panel.environment.row` entries at orders 20, 30, and 40, after the project row, and the attention mark is a `conversation.session.panel.indicator` entry. The checkout row shortens paths with the Host home from the Remote's Host facts, read again after each transport reset; it is mounted whenever the panel shows, so on mount and on window `focus` and `visibilitychange` it calls `revisit`, throttled per Session by the shared panel store; a revisit asked for before the first panel state arrives runs once that state arrives, because the Host revisits only a panel it follows. The panel streams, the change request state stream, and the review count stream close once the page has been hidden for 30 seconds and open again when it shows, so the Host polls no code host for a page nobody sees; their last values stay readable. The toast lives in a `shell.overlay` entry so it outlives the panel. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes/<session>/local` and `dsh-resource://forge-changes/<session>/change/<url>`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.<Session>`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. Once a file's whole new side is known, read for an expansion or, for local changes, read once per comparison when the file draws, each side of each run of drawn rows is highlighted again in idle time after up to 120 lines of the file before it, the old side rebuilt from the new side and the hunks; the new colors apply in one update after every run is done, and wait while the reader drags or holds a text selection in the file. A change request's files are not read for this, since each read is a request to the code host.
|
||||
The browser entry mounts the Remote, then the UI. One stream per Session feeds the Session panel entries, the New Session option, and the creation card; it opens with the first subscriber, after a `forgePanel` Session reference has opened the Session's history, so the Host resumes the Session once rather than beside that opening, holds that reference until the stream ends, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The change requests section is the `change-requests` entry of `conversation.session.panel.section` at order 100 with its count in `conversation.session.panel.section.actions`; the checkout, local changes, and connection rows are `conversation.session.panel.environment.row` entries at orders 20, 30, and 40, after the project row, and the attention mark is a `conversation.session.panel.indicator` entry. The checkout row shortens paths with the Host home from the Remote's Host facts, read again after each transport reset; it is mounted whenever the panel shows, so on mount and on window `focus` and `visibilitychange` it calls `revisit`, throttled per Session by the shared panel store; a revisit asked for before the first panel state arrives runs once that state arrives, because the Host revisits only a panel it follows. The panel streams, the change request state stream, and the review count stream close once the page has been hidden for 30 seconds and open again when it shows, so the Host polls no code host for a page nobody sees; their last values stay readable. The toast lives in a `shell.overlay` entry so it outlives the panel. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes/<session>/local` and `dsh-resource://forge-changes/<session>/change/<url>`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, the shown branch, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.<Session>`, at most 20 sources per Session and 50 Sessions, where a source names the shown branch unless it is the Session's own checkout, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. Once a file's whole new side is known, read for an expansion or, for local changes, read once per comparison when the file draws, each side of each run of drawn rows is highlighted again in idle time after up to 120 lines of the file before it, the old side rebuilt from the new side and the hunks; the new colors apply in one update after every run is done, and wait while the reader drags or holds a text selection in the file. A change request's files are not read for this, since each read is a request to the code host.
|
||||
|
||||
| Source | Responsibility |
|
||||
|---|---|
|
||||
@@ -115,6 +118,8 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t
|
||||
| [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | Changes view |
|
||||
| [`src/client/review-page/`](src/client/review-page/) | Code review page: its registration, navigation count, lists, detail with the status column, and chat |
|
||||
| [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | Base branch menu of the Branch scope |
|
||||
| [`src/client/HeadMenu.tsx`](src/client/HeadMenu.tsx) | Menu of the branch the local changes view shows |
|
||||
| [`src/client/BranchPicker.tsx`](src/client/BranchPicker.tsx) | Trigger and searchable menu that the two branch menus share |
|
||||
| [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | One file of the changes view |
|
||||
| [`src/client/section-reach.ts`](src/client/section-reach.ts) | When file sections draw their lines |
|
||||
| [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | Lens, test file switch, and viewed progress |
|
||||
@@ -153,7 +158,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t
|
||||
<a id="model-experience"></a>
|
||||
## Model Experience
|
||||
|
||||
Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, local Branch quotes the base the view compared with, and quotes from chosen commits name them. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. Add to input on a review thread contributes a frozen `## Review Thread N` quote with File, Side, Lines, the commit those lines number, State, Source, the recorded diff hunk, and every comment's author, time, and body quoted line by line. The review page's chat quotes the change request's number, title, and URL in the draft of a blank Session, and the model reads them only in the message the user sends; the binding it records at that message adds what bound change requests contribute through the [Session bindings](../forge-session/README.md).
|
||||
Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, local Branch quotes the base the view compared with, and quotes from chosen commits name them; a local quote from a branch read in a worktree adds `Worktree` and `Branch` lines, and one from a branch read from its commits adds `Branch: <name> (committed content)`. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. Add to input on a review thread contributes a frozen `## Review Thread N` quote with File, Side, Lines, the commit those lines number, State, Source, the recorded diff hunk, and every comment's author, time, and body quoted line by line. The review page's chat quotes the change request's number, title, and URL in the draft of a blank Session, and the model reads them only in the message the user sends; the binding it records at that message adds what bound change requests contribute through the [Session bindings](../forge-session/README.md).
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
@@ -174,6 +179,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi
|
||||
- **Linked-worktree projects** — the option is unavailable when the project is itself a linked worktree, unless the sandbox policy grants its Git directory: under workspace-write that directory lies outside the writable root, so neither the new branch nor later commits could be written. On macOS and Linux the worktree service's [linked-worktree grant](../sandbox-policy-git/README.md) registers it for each Session, which makes the option available there. A grant registered while the panel shows takes effect at the next inspection. Windows processes ignore such grants, so there the option is offered and creation fails. Commits inside a created worktree need the grant too, as the [worktree service](../worktree/README.md#known-limitations-and-deferred-work) describes.
|
||||
- **Local writes** — the view stages, unstages, and restores whole files only: no hunk or line, no commit, and no restoring of every file at once. A restoration cannot be undone. The model is not told about a write; it meets the result the next time it reads the checkout. A write runs outside the Session's sandbox, so a clean or smudge filter named in the repository's configuration runs with the Host's permissions when the reader stages, unstages, or restores, and a Session that can write its checkout can add such a filter. A file with a merge conflict is not offered a write the comparison does not list it for, and restoring one fails with Git's message. An untracked file over `maxDiffBytes` has a digest of its path alone, so a rewrite of it after the reader saw it is not noticed. Undoing the staging of a file the index tracked without content leaves it untracked, since a tree holds no such entry.
|
||||
- **Changes scopes** — deferred: a scope for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen.
|
||||
- **Other branches** — the view reads a branch other than the Session's own checkout again only when it would read that checkout again: on Refresh, on a navigation, and when the summary of the Session's own Branch scope changes, so an edit in another worktree or a new commit on the shown branch appears only then. The menu finds only worktrees of the Session's repository: work a delegated Session does in a plain directory or in another repository does not show, and a worktree shows under its branch name, which is a generated one unless the worktree was named, not under the Session that works there. A branch read in another worktree offers no write.
|
||||
- **Very many branches** — the base branch menu reads every ref before it filters, so a search can reach any branch. Refs over `maxDiffBytes`, about 165,000 at the default, or a listing over `gitTimeoutMs`, leave the menu saying that branches could not be read; Default keeps working.
|
||||
- **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View on the code host. Without wrapping, the side-by-side view cuts long lines at the column edge.
|
||||
- **Highlighting across collapsed lines** — rows after collapsed unchanged lines take the colors of the lines before them only once the file is read: local files when they draw, change request files after one of their gaps expands. A code block, comment, or string that opens more than 120 lines before a run still leaves the run colored as if it started there.
|
||||
|
||||
@@ -41,8 +41,9 @@ kind: "package-reference"
|
||||
- **连接行**——Session 的面板流结束时(包括还没收到第一份状态就结束),环境分栏末尾的状态行说明状态已停止更新,Git 与变更请求信息可能已过时;「重试」重新打开流,这一行随即消失。
|
||||
- **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。
|
||||
- **变更请求分栏**——Session 有已绑定的变更请求,或仓库所在托管平台需要登录时显示。分栏标题旁显示数量。卡片上方的状态行请用户登录托管平台:显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`,悬停时滚动显示全文)和「复制」;提供方没有给出命令以及登录检查失败时,平台给出的原因收在信息按钮里,与检出行显示失败的方式相同。Session 没有绑定变更请求时,分栏只显示这一行。每个变更请求是一张紧凑卡片,即面板行列上的一块底色:一行内依次是状态图标、标题、编号和检查结果图标。点击这一行在右侧边栏打开该变更请求的变更;按住 Cmd 或 Ctrl 点击、用中键点击,以及没有提供方服务或尚未读取的变更请求,则打开托管平台上的页面。状态图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单与面板其他行一样在悬停或聚焦时出现,提供由提供方服务的变更请求的“查看变更”、带平台图标的“在代码托管平台中打开”、“复制变更请求链接”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。收起时,这一行把状态以文字读给辅助技术,卡片的悬停卡片显示完整标题、编号(带草稿状态与源分支、目标分支)和这段状态:打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则是结束时间;读取失败或没有提供方服务的 URL 则显示相应说明。已取消的检查单独计数,列出的检查没有失败项时状态显示取消数量。检查结果图标共用同一个圆环:通过为勾,失败为叉,进行中为半填充,其余为短横。展开的卡片在这一行下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。主机暂时不会合并、但用户可以启用平台自动合并的变更请求,在同一位置改为提供“自动合并”:菜单相同,确认后为显示的 head 启用。启用后按钮显示“已启用自动合并”,菜单写出平台给出的合并方式和启用人,用户可以取消时提供“取消自动合并”。列表显示三张卡片;更多时,卡片之后是面板的折叠控件,用来显示其余卡片或再次收起,Session 保持打开期间保留这一选择。Session 只绑定了一个变更请求时,无论其状态如何,它的卡片默认展开;绑定多个时,所有卡片默认收起。用户展开或收起某张卡片后,在 Session 保持打开期间,更新和隐藏面板都不会改变这一选择;用户没有动过的卡片仍按默认规则。
|
||||
- **本地变更行**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。这一行显示变更的文件数以及新增、删除行数,点击打开变更视图。它的“更多”菜单提供“查看变更”;识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,还提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。
|
||||
- **变更视图**——变更请求卡片上的“变更”一行与“查看变更”菜单项、以及本地变更行会打开一个右侧边栏标签页,列出所有变更的文件;会话面板浮在对话上方时随之关闭。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。“未暂存”范围在每个文件上提供“暂存文件”和“还原文件”,在标题行提供“全部暂存”;“已暂存”范围提供“取消暂存文件”和“全部取消暂存”。标题行的按钮作用于视图显示的文件,所以分层、透镜或测试文件开关隐藏的文件保持原样。暂存和取消暂存的提示带“撤销”,它把这些文件的暂存区条目恢复到写入之前的状态,包括更早暂存的修改。“还原文件”无法撤销,所以先询问:它把修改或删除的文件恢复成暂存区条目,并删除未跟踪的文件;暂存区只登记了路径、还没有内容的文件不提供还原,子模块也不提供。写入进行中,以及写入之后重新读取范围期间,这些写操作的按钮和菜单项都不能触发。已删除的文件所在位置被目录取代时,写入被拒绝,提示改为操作目录里的文件。其他范围不提供写操作,因为在那里写入后显示的变更可能不变。写操作是读者自己的操作,所以在 Session 的任何访问模式下都可用,包括只读。视图宽度不超过 380px 时,文件的写操作在指针悬停或键盘到达时显示,占用行数的位置;文件的“更多”菜单列出同样的写操作。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏的图标按钮和标题栏带平台图标的“在代码托管平台中打开”悬停 500ms 后显示操作说明,键盘聚焦时立即显示。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停 500ms 后显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在代码托管平台上查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之Line truncated
|
||||
- **本地变更行**——在 Git 检出内始终显示,不受已关联变更请求影响,点击打开变更视图。这一行显示 `branch` 范围变更的文件数,该范围没有变更时只显示“本地变更”,后面是新增、删除行数:没有变更时为 +0 −0,该范围没有分叉点时不显示。它的“更多”菜单提供“查看变更”;识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,还提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。
|
||||
- **变更视图**——变更请求卡片上的“变更”一行与“查看变更”菜单项、以及本地变更行会打开一个右侧边栏标签页,列出所有变更的文件;会话面板浮在对话上方时随之关闭。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏先在下文的“查看的分支”菜单里写出当前检出的分支(分离 HEAD 时为缩写提交),再写出基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏两个菜单之间的箭头,两个菜单的名称一起缩短。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。“未暂存”范围在每个文件上提供“暂存文件”和“还原文件”,在标题行提供“全部暂存”;“已暂存”范围提供“取消暂存文件”和“全部取消暂存”。标题行的按钮作用于视图显示的文件,所以分层、透镜或测试文件开关隐藏的文件保持原样。暂存和取消暂存的提示带“撤销”,它把这些文件的暂存区条目恢复到写入之前的状态,包括更早暂存的修改。“还原文件”无法撤销,所以先询问:它把修改或删除的文件恢复成暂存区条目,并删除未跟踪的文件;暂存区只登记了路径、还没有内容的文件不提供还原,子模块也不提供。写入进行中,以及写入之后重新读取范围期间,这些写操作的按钮和菜单项都不能触发。已删除的文件所在位置被目录取代时,写入被拒绝,提示改为操作目录里的文件。其他范围不提供写操作,因为在那里写入后显示的变更可能不变。写操作是读者自己的操作,所以在 Session 的任何访问模式下都可用,包括只读。视图宽度不超过 380px 时,文件的写操作在指针悬停或键盘到达时显示,占用行数的位置;文件的“更多”菜单列出同样的写操作。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏的图标按钮和标题栏带平台图标的“在代码托管平台中打开”悬停 500ms 后显示操作说明,键盘聚焦时立即显示。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停 500ms 后显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在代码托管平台上查看该文件在 head 处的页面。标题变窄时,路径、标Line truncated
|
||||
- **查看的分支**——本地变更的标题栏以一个可搜索的菜单开头,名为“查看的分支”,列出视图可以查看的分支:先是 Session 自己的检出,带“当前会话”标记,初始选中;然后在“本地分支”和“远程分支”下列出仓库的其他分支,各自按最近提交排在前。输入文字立即筛选已列出的行,短暂停顿后列出名称包含该文字的分支。仓库里有 worktree 检出的本地分支带“工作树”标记,悬停显示该 worktree 的目录。视图在这个 worktree 里读取这样的分支:四个范围都可用,未提交和未跟踪的文件会显示,“默认”是与代码托管远端默认分支的合并基准。没有 worktree 检出的分支(所有远程分支都是)只显示已提交的内容:只有“分支”范围,没有范围菜单,也没有“包含未提交的修改”;在其他范围下选中它时切换到“分支”。每次读取都重新查找 worktree,所以菜单列出分支之后新增或移除的 worktree 会改变视图提供的范围。基准分支菜单(不列出正在查看的分支)、提交选择、未变更行的展开和透镜都跟随所选分支,每次选择都从“默认”基准和全部提交开始。“未提交”“未暂存”“已暂存”范围的标题栏也以这个菜单开头。只有 Session 自己的检出提供暂存、取消暂存、还原、“创建变更请求”和在侧边栏打开整个文件,其他插件的工具栏工具、文件菜单行、评论表单按钮和行注解也只在这里显示。已审阅标记和评论记录按所选分支分开保存。所选分支已不存在时,菜单给它的名称加删除线,视图说明找不到它,并提供“回到当前会话”代替“重试”。
|
||||
|
||||
- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;文件树宽度放不下数量时,只显示各层名称,数量在悬停提示里。不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;这个标记画成空心圆环,已审阅后画成圆环里的对勾,视图宽度不超过 520px 时只显示圆环、不显示文字;工具栏以按已审阅比例填充的圆环和“已审阅 2 / 3”这样的文字显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。文件树把已审阅的文件置灰,目录下的文件全部已审阅时目录也置灰,以便看出还没审阅的文件;有新改动的文件按未审阅显示,辅助技术把这一状态读作每行的描述。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因;平台可能已保存但未确认的标记保持不变,toast 提示刷新查看实际状态。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。
|
||||
- **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上提供“添加到输入框”(把整个讨论作为引用插入)、“在 GitHub 中查看”,以及当前登录用户可以执行的写操作。没有待提交评审时,回复框立即回复,其下拉菜单可以带着这条回复开始待提交评审;有待提交评审时,回复框把回复加入其中,因为 GitHub 会把用户的每条回复都加入待提交评审。“解决讨论”和“取消解决”切换讨论状态;用户自己评论的菜单可以编辑或删除该评论,删除前会先确认,删除讨论中唯一的评论会一并删除讨论,确认时会说明这一点。用户正在讨论中写回复或编辑评论时,即使讨论已被解决,也保持展开。代码托管平台拒绝写操作时保留输入的文字并说明原因;结果不明时会重新读取讨论,并请用户核对后再重试。每次写操作后都会重新读取讨论,因为解决讨论不会改变 GitHub pull request 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。
|
||||
@@ -66,7 +67,7 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后
|
||||
|
||||
`ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它,并在 Session 保持加载期间保留它最后的状态、最近的快照和查找过的分支。面板从 Session 的工作目录与绑定开始;Session 的上一个面板留下了这些内容、且 Session 没有换到其他目录时,从它们开始。面板在每个 `workspace-root/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,只在状态与已发布的不同时发布新的 `ForgePanelState`,所以检查结果与原来相同时不会通知任何关注方。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次;面板开始或被重新访问时 Session 没有显示任何变更请求的,会再查找一次。以下情况会在 `readinessTimeoutMs` 内检查登录状态:识别出的托管平台变化时,刷新时,上一个面板没有确认托管平台已就绪的面板完成第一次检查后,重新访问时托管平台尚未就绪,以及显示为已就绪的托管平台上的状态读取开始被以未登录拒绝时(只检查一次);一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。`revisit` 重新检查 checkout,并且只轮询最近一次轮询早于 `statusMaxAgeMs` 的变更请求。
|
||||
|
||||
检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --quiet HEAD`(指向 `refs/heads/` 下的分支时即为当前分支)、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`worktreeBases` 在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,从 `refs/remotes/<remote>/HEAD` 取每个远程的默认分支,略过其他符号引用与未配置远程的分支,并按下文的代码托管识别顺序排列远程,各保留最多 `maxBranches` 个名称包含查询文字的本地分支与每个远程的分支;带名称的 `requestWorktree` 按 Git 的分支名规则检查名称,并在检出中运行 `show-ref`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更行统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下,只有检出目录位于 Session 沙箱策略的规范工作区根内,且公共 Git 目录位于该根或策略的某个额外可写目录内时才可用。
|
||||
检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --quiet HEAD`(指向 `refs/heads/` 下的分支时即为当前分支)、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`worktreeBases` 在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,从 `refs/remotes/<remote>/HEAD` 取每个远程的默认分支,略过其他符号引用与未配置远程的分支,并按下文的代码托管识别顺序排列远程,各保留最多 `maxBranches` 个名称包含查询文字的本地分支与每个远程的分支;带名称的 `requestWorktree` 按 Git 的分支名规则检查名称,并在检出中运行 `show-ref`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用和范围正在查看的分支,每类最多保留 `maxBranches` 个名称包含查询文字的分支;再用 `worktree list --porcelain` 给保留下来的每个本地分支写上检出它的 worktree 的目录。之后,检查会为本地变更行统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下,只有检出目录位于 Session 沙箱策略的规范工作区根内,且公共 Git 目录位于该根或策略的某个额外可写目录内时才可用。
|
||||
|
||||
worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `workspace-root/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。请求用本地分支或远程跟踪分支的完整引用名指定基准(早期面板记录的本地短名称仍可解析),并可指定分支名。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;基准为空时以 `forgePanel/invalid-branch` 拒绝;Git 不接受分支名时以 `forgePanel/invalid-name` 拒绝;检出中已有同名分支时以 `forgePanel/branch-exists` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的下一轮队列时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。排给下一步的消息(例如其他插件注入的通知)不开启一轮,也不启动暂留。暂留用请求的分支名或新的自动名称进行一次尝试,基准是远程跟踪分支时请 worktree 服务先获取它;它在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、是否获取、失败步骤、原因以及分支或目录是否已存在以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,`fetch` 参数为 false 时不获取,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;用另一个名称调用 `requestWorktree` 会改变下一次尝试;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入下一轮队列的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。
|
||||
|
||||
@@ -77,6 +78,8 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo
|
||||
|
||||
Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes/<remote>/HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更行保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :<path>` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,补丁与它的 `.gitattributes` 同时读取,补丁读取失败时取消 `.gitattributes` 的读取,两者都结束后才给出结果,补丁的失败优先于 `.gitattributes` 的失败,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支Line truncated
|
||||
|
||||
本地范围可以用 `head` 指定一个分支,代替检出的分支来读取;`head` 是 `refs/heads/` 或 `refs/remotes/` 下的完整引用名。`localTarget` 为 `localDiff`、`localText`、`localCommits`、`diffBases` 与 `changesLens` 解析它。页面只发送引用名,从不发送路径。引用必须能通过 `show-ref --verify`,否则读取以 `forgePanel/head-missing` 拒绝;其他引用名在运行 Git 之前就被拒绝。对本地分支,在 Session 的检出里运行的 `worktree list --porcelain` 给出检出该分支的 worktree,其中不含 Git 标为 prunable 的条目。按行分隔的列表会在换行符处截断目录名,2.31 之前的 Git 也不标记已删除的目录,所以只有目录存在、并且检查发现那里是同一个仓库的检出且确实检出了该分支时,Host 才在这个目录里读取。这时 Git 以读取方 Session 的沙箱策略在该 worktree 里运行,四个范围都可用,分叉点是按上文找到的合并基准,`ForgeLocalDiff.worktree` 给出这个目录。`head` 指向 Session 自己检出的分支时,读取的就是 Session 的检出,与不带 `head` 的范围相同。没有这样的 worktree 时(所有远程跟踪分支都是),该引用在 `merge-base`、`log` 与 `rev-parse` 中代替 HEAD,比较为 `diff <fork> <ref>`,不含工作树和未跟踪文件,`.gitattributes` 与 `localText` 通过 `show` 读取 `<ref>:<path>`,`branch` 以外的范围以 `forgePanel/no-working-tree` 拒绝。
|
||||
|
||||
`localWrite` 把变更视图的一次写操作应用到 checkout。`stage` 执行 `add`,`unstage` 执行 `reset -q`,`restore` 对已跟踪文件执行 `restore --worktree`、对未跟踪文件执行 `clean -f -q`,`reindex` 执行 `reset -q <tree>`;路径以 literal pathspec 交给 Git,每条命令最多带 16,000 个字符的路径,超出时拆成多条命令,使命令行不超过 Windows 的长度上限。`stage` 和 `restore` 为每个文件带上读者看到的 digest:Remote 重新读取 `unstaged` 范围,文件已不在其中或 digest 不同时以 `forgePanel/local-stale` 拒绝整次写入,所以读者没看过的内容不会被暂存或丢弃。`restore` 拒绝该范围列为新增或重命名、但并非未跟踪的文件:暂存区只登记了它的路径而没有内容(`git add --intent-to-add` 的结果),Git 会把文件替换成空文件。它也拒绝子模块,解析器根据补丁头里的 `160000` mode 标记子模块:`git restore` 会成功退出,而检出的提交保持不变。[`src/restore.ts`](src/restore.ts) 保存这两条规则,Remote 和视图共用。对已删除的文件执行 `stage` 或 `restore` 时,如果它的路径上是一个目录(用 `ctx.fs.lstat` 判断),以 `forgePanel/local-path-replaced` 拒绝:Git 把路径理解为该目录及其全部内容,写入会暂存或删除目录里的文件。在 `stage` 和 `unstage` 之前,Remote 用 `write-tree` 把暂存区写成 tree 并返回其对象名,`reindex` 把同一批路径的暂存区条目恢复到这个 tree;暂存区存在未合并条目时没有 tree,视图也不提供撤销。读者按下按钮就是授权,正如归档之于 worktree 服务移除 checkout,所以写入命令通过已挂载的 subprocess provider 运行,不受 Session 沙箱策略约束,该策略约束的是 Agent 的行为:只读访问模式下可用,Session 目录位于 checkout 根目录之下时也可用。重新读取 `unstaged` 范围仍在该策略下进行,和其他读取一样。与 diff 不同,`add`、`reset` 和 `restore` 会运行仓库配置的 clean 与 smudge filter;hook 和文件系统监视器像面板的其他命令一样保持关闭,`restore` 带 `--no-recurse-submodules`。一次写入在第一条命令之后失败时,前面命令的路径已经写入,所以每次写入之后面板都重新检查 checkout,视图也重新读取当前范围。
|
||||
|
||||
`changeRequestViewed`、`setFileViewed`、`rerunChecks`、`requestReviews`、`reviewerCandidates` 与 `updateBranch` 只作用于 Session 可见且有提供方服务的绑定,否则以 `forgePanel/not-bound` 拒绝。`changeRequestViewed` 在所示 diff 的 head 提交上读取提供方的 `viewedFiles`,提供方不保存已审阅标记时返回 null;head 已移动时以 `forgePanel/stale-head` 拒绝,其他失败以 `forgePanel/viewed-failed` 拒绝。每个变更请求保留一次读取结果,以 head 提交为键,受与讨论相同的 `maxCachedReviewBytes` 和 `reviewRefreshMs` 限制;经 `ctx.forge` 在该 head 上保存的标记会替换所保留的对应文件状态,所以保存一个标记只需要提供方的那次写入,不再读取;读者刷新时传入 `fresh`,重新从托管平台读取。`setFileViewed` 经 `setViewed` 在该 head 上保存一个文件的标记,`rerunChecks` 与 `updateBranch` 传入卡片显示的 head 提交;head 已移动时它们都以 `forgePanel/stale-head` 拒绝,其他拒绝以 `forgePanel/action-failed` 并附托管平台的原因,托管平台未确认的结果以 `forgePanel/action-unknown` 拒绝。`requestReviews` 一次向一位或多位评审者请求评审,拒绝空列表与空登录名;`reviewerCandidates` 列出与搜索匹配的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随变更请求的 diff 一起读取其已审阅标记,像拒绝在其他 head 上读取的 diff 一样拒绝这类标记,并由 [`src/client/host-viewed.ts`](src/client/host-viewed.ts) 按变更请求与 head 保存读者设置的每个标记:同一 head 重新读取时保留仍在写入的标记,写入已结束的标记保留到下次读取,另一个 head 的 diff 加载后才结束的写入不会改动它。
|
||||
@@ -87,7 +90,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
|
||||
`follow` 与 `reviewChangeRequest` 监听所显示的每个变更请求的快照,并要求 `ctx.forge` 提供不早于 `statusMaxAgeMs`(默认 10 秒)的状态。Session 的面板或评审页的流开始时,如果最近一次快照结果更旧,就立即读取状态;如果结果更新,或者还没有其他快照监听方读过,就跟随常规轮询。
|
||||
|
||||
浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给会话面板中的条目、新会话选项与创建卡片;第一个订阅方出现时,先由一个 `forgePanel` Session 引用打开该 Session 的历史再打开流,使 Host 只恢复一次该 Session、而不与这次打开并行,并持有该引用直到流结束;最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。变更请求分栏是 `conversation.session.panel.section` 中 order 为 100 的 `change-requests` 条目,数量位于 `conversation.session.panel.section.actions`;检出行、本地变更行与连接行是 `conversation.session.panel.environment.row` 中 order 为 20、30 与 40 的条目,位于项目行之后;提醒标记是 `conversation.session.panel.indicator` 条目。检出行用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取;面板显示时它始终挂载,因此由它在挂载时以及窗口 `focus` 与 `visibilitychange` 时调用 `revisit`,按会话由共享的面板 store 限流;首个面板状态到达前请求的重新访问等到该状态到达后执行,因为 Host 只重新访问它正在跟随的面板。页面隐藏满 30 秒后,面板流、变更请求状态流与评审计数流关闭,页面再次显示时重新打开,所以 Host 不会为没有人看的页面轮询代码托管平台;它们最后的值仍然可读。toast 位于 `shell.overlay` 条目中,因此比面板存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes/<session>/local` 与 `dsh-resource://forge-changes/<session>/change/<url>` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.<Session>` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。文件的整个新版本已知时(为展开而读取,或本地变更在文件绘制时按每次比较读取一次),每段绘制行的每一侧会在空闲时带上文件中它之前最多 120 行重新高亮,旧版本由新版本与 hunk 还原;所有段都算完后新颜色在一次更新中生效,读者正在拖选或文件内有文本选区时等它结束。变更请求的文件不为此读取,因为每次读取都是一次对代码托管平台的请求。
|
||||
浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给会话面板中的条目、新会话选项与创建卡片;第一个订阅方出现时,先由一个 `forgePanel` Session 引用打开该 Session 的历史再打开流,使 Host 只恢复一次该 Session、而不与这次打开并行,并持有该引用直到流结束;最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。变更请求分栏是 `conversation.session.panel.section` 中 order 为 100 的 `change-requests` 条目,数量位于 `conversation.session.panel.section.actions`;检出行、本地变更行与连接行是 `conversation.session.panel.environment.row` 中 order 为 20、30 与 40 的条目,位于项目行之后;提醒标记是 `conversation.session.panel.indicator` 条目。检出行用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取;面板显示时它始终挂载,因此由它在挂载时以及窗口 `focus` 与 `visibilitychange` 时调用 `revisit`,按会话由共享的面板 store 限流;首个面板状态到达前请求的重新访问等到该状态到达后执行,因为 Host 只重新访问它正在跟随的面板。页面隐藏满 30 秒后,面板流、变更请求状态流与评审计数流关闭,页面再次显示时重新打开,所以 Host 不会为没有人看的页面轮询代码托管平台;它们最后的值仍然可读。toast 位于 `shell.overlay` 条目中,因此比面板存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes/<session>/local` 与 `dsh-resource://forge-changes/<session>/change/<url>` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、查看的分支、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.<Session>` 下(每个 Session 最多 20 个来源,最多 50 个 Session;查看的不是 Session 自己的检出时,来源还包含查看的分支),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。文件的整个新版本已知时(为展开而读取,或本地变更在文件绘制时按每次比较读取一次),每段绘制行的每一侧会在空闲时带上文件中它之前最多 120 行重新高亮,旧版本由新版本与 hunk 还原;所有段都算完后新颜色在一次更新中生效,读者正在拖选或文件内有文本选区时等它结束。变更请求的文件不为此读取,因为每次读取都是一次对代码托管平台的请求。
|
||||
|
||||
| 源码 | 职责 |
|
||||
|---|---|
|
||||
@@ -115,6 +118,8 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
| [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | 变更视图 |
|
||||
| [`src/client/review-page/`](src/client/review-page/) | 代码评审页:注册、导航计数、列表、带状态栏的详情与对话 |
|
||||
| [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | “分支”范围的基准分支菜单 |
|
||||
| [`src/client/HeadMenu.tsx`](src/client/HeadMenu.tsx) | 本地变更视图所查看分支的菜单 |
|
||||
| [`src/client/BranchPicker.tsx`](src/client/BranchPicker.tsx) | 两个分支菜单共用的触发按钮与可搜索菜单 |
|
||||
| [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | 变更视图中的一个文件 |
|
||||
| [`src/client/section-reach.ts`](src/client/section-reach.ts) | 文件段何时绘制各行 |
|
||||
| [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | 分层透镜、测试文件开关与已审阅进度 |
|
||||
@@ -153,7 +158,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
<a id="model-experience"></a>
|
||||
## 模型体验
|
||||
|
||||
间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准,来自所选提交的引用还会注明这些提交。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。对评审讨论使用“添加到输入框”时,会加入一段固定的 `## Review Thread N` 引用,包含 File、Side、Lines、这些行号所在的提交、State、Source、记录下的 diff hunk,以及逐行引用的每条评论的作者、时间和正文。代码评审页的对话把变更请求的编号、标题和 URL 作为引用放进空白会话的草稿,模型只在用户发出的消息中读到它们;该消息时记录的绑定带来[会话绑定](../forge-session/README.zh.md)为已绑定变更请求提供的内容。
|
||||
间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准,来自所选提交的引用还会注明这些提交;本地引用来自在 worktree 里读取的分支时增加 `Worktree` 与 `Branch` 两行,来自按提交读取的分支时增加 `Branch: <name> (committed content)`。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。对评审讨论使用“添加到输入框”时,会加入一段固定的 `## Review Thread N` 引用,包含 File、Side、Lines、这些行号所在的提交、State、Source、记录下的 diff hunk,以及逐行引用的每条评论的作者、时间和正文。代码评审页的对话把变更请求的编号、标题和 URL 作为引用放进空白会话的草稿,模型只在用户发出的消息中读到它们;该消息时记录的绑定带来[会话绑定](../forge-session/README.zh.md)为已绑定变更请求提供的内容。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
@@ -174,6 +179,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
- **链接 worktree 项目**——项目本身是链接 worktree 时该选项不可用,除非沙箱策略授权了它的 Git 目录:在 workspace-write 下该目录位于可写根之外,新分支与之后的提交都无法写入。在 macOS 和 Linux 上,worktree 服务的[链接工作树授权](../sandbox-policy-git/README.zh.md)会为每个 Session 注册它,因此该选项在那里可用。面板显示期间注册的授权在下一次检查时生效。Windows 的进程忽略这类授权,因此在 Windows 上该选项可用但创建会失败。在创建出的 worktree 内提交同样需要该授权,见 [worktree 服务](../worktree/README.zh.md#known-limitations-and-deferred-work)的说明。
|
||||
- **本地写操作**——视图只对整个文件暂存、取消暂存和还原:不支持代码块或行,不提交,也不能一次还原所有文件。还原无法撤销。写操作不会告知模型;模型下次读取 checkout 时才看到结果。写入在 Session 的沙箱之外运行,所以读者暂存、取消暂存或还原时,仓库配置里指定的 clean 或 smudge filter 会以 Host 的权限运行,而能写自己 checkout 的 Session 可以添加这样的 filter。存在合并冲突的文件,只有比较结果列出它时才提供写操作,还原它会以 Git 的消息失败。超过 `maxDiffBytes` 的未跟踪文件,其 digest 只包含路径,所以读者看过之后它被改写不会被发现。对暂存区只登记了路径的文件,暂存后再撤销会使它变成未跟踪,因为 tree 里没有这种条目。
|
||||
- **变更范围**——待办:上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。
|
||||
- **其他分支**——查看的不是 Session 自己的检出时,视图只在会重新读取该检出的时机重新读取所查看的分支:点击“刷新”、发生导航,以及 Session 自己“分支”范围的摘要变化时;另一个 worktree 里的修改或所查看分支上的新提交到这时才出现。菜单只能找到 Session 所在仓库的 worktree:子 Session 在普通目录或另一个仓库里做的工作不会出现;worktree 以它的分支名出现(未命名的 worktree 使用自动生成的名称),而不是以在其中工作的 Session 出现。在另一个 worktree 里读取的分支不提供写操作。
|
||||
- **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。
|
||||
- **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在代码托管平台中查看”。不自动换行时,左右对比会在栏边截断长行。
|
||||
- **跨折叠行的高亮**——折叠的未变更行之后的行,要等文件被读取后才按它之前的内容着色:本地文件在绘制时读取,变更请求的文件要等它的某处折叠行展开后。在一段行之前超过 120 行处开始的代码块、注释或字符串,这段行仍按从段首开始着色。
|
||||
|
||||
@@ -115,7 +115,6 @@
|
||||
"@deepseek-ai/dsh-session-projection": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-projection-cache": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-query": "workspace:*",
|
||||
"@deepseek-ai/dsh-subagent": "workspace:*",
|
||||
"@deepseek-ai/dsh-subprocess": "workspace:*",
|
||||
"@deepseek-ai/dsh-subprocess-local": "workspace:*",
|
||||
"@deepseek-ai/dsh-system-prompt": "workspace:*",
|
||||
|
||||
@@ -109,21 +109,6 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* A Session's row names its branch first; what the Session does follows and gives way when the menu is narrow. */
|
||||
.related .name {
|
||||
flex: 0 1 auto;
|
||||
max-width: 55%;
|
||||
}
|
||||
|
||||
.who {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tag {
|
||||
flex: none;
|
||||
padding: 0 5px;
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
/** Base branch picker of the local changes view's `branch` scope: the automatic fork point, then remote-tracking and local branches. */
|
||||
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular,
|
||||
IconWarningTriangleOutlineRegular, Menu, MenuItemButton, Tooltip,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { ReactNode } from 'react'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { ForgeBaseBranch, ForgeBaseBranches } from '../types.ts'
|
||||
import { branchSearchStatus, useBranchSearch } from './branch-search.tsx'
|
||||
import { branchSearchStatus } from './branch-search.tsx'
|
||||
import { BranchPicker, useBranchPicker, type BranchPickerGroup } from './BranchPicker.tsx'
|
||||
import type { NS } from './locales.ts'
|
||||
import css from './BaseMenu.module.css'
|
||||
|
||||
@@ -31,14 +27,6 @@ export interface BaseMenuProps extends PropsLocale<typeof NS> {
|
||||
readonly choose: (base: ForgeBaseBranch | null) => void
|
||||
}
|
||||
|
||||
/** One selectable row: a branch, or the automatic fork point. */
|
||||
interface BaseOption {
|
||||
readonly key: string
|
||||
readonly name: string
|
||||
readonly base: ForgeBaseBranch | null
|
||||
readonly tag?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the trigger and, while open, the searchable menu. Opening and each
|
||||
* search read the branches again; rows already shown follow the search at once
|
||||
@@ -47,28 +35,20 @@ interface BaseOption {
|
||||
* @returns the trigger with its portalled menu.
|
||||
*/
|
||||
export function BaseMenu({ chosen, label, missing, note, visible, list, choose, t }: BaseMenuProps): ReactNode {
|
||||
const [open, setOpen] = useState(false)
|
||||
const shown = visible && open
|
||||
const { query, setQuery, listing, retry, reset } = useBranchSearch(shown, list)
|
||||
const close = (): void => {
|
||||
setOpen(false)
|
||||
reset()
|
||||
}
|
||||
const pick = (base: ForgeBaseBranch | null): void => {
|
||||
close()
|
||||
if ((base?.ref ?? null) !== (chosen?.ref ?? null)) choose(base)
|
||||
}
|
||||
|
||||
const value = listing?.ok === true ? listing.value : null
|
||||
const needle = query.trim().toLowerCase()
|
||||
const state = useBranchPicker(visible, list)
|
||||
const value = state.listing?.ok === true ? state.listing.value : null
|
||||
const needle = state.query.trim().toLowerCase()
|
||||
const matches = (name: string): boolean => name.toLowerCase().includes(needle)
|
||||
const automatic = value?.automatic ?? null
|
||||
const groups: { readonly id: string; readonly label: string; readonly options: readonly BaseOption[] }[] = [
|
||||
const branchOption = (branch: ForgeBaseBranch) => ({ key: branch.ref, name: branch.name, value: branch })
|
||||
const groups: BranchPickerGroup<ForgeBaseBranch | null>[] = [
|
||||
{
|
||||
id: 'automatic',
|
||||
label: t('diff.base.automatic'),
|
||||
// The automatic row's tag names it, so its group shows no heading.
|
||||
plain: true,
|
||||
options: automatic === null || !matches(automatic.name) ? [] : [{
|
||||
key: 'automatic', name: automatic.name, base: null, tag: t(automatic.worktree ? 'diff.base.worktree' : 'diff.base.automatic'),
|
||||
key: '', name: automatic.name, value: null, tag: t(automatic.worktree ? 'diff.base.worktree' : 'diff.base.automatic'),
|
||||
}],
|
||||
},
|
||||
{
|
||||
@@ -77,63 +57,18 @@ export function BaseMenu({ chosen, label, missing, note, visible, list, choose,
|
||||
// The automatic fork point of a code host's default branch is the same comparison as choosing that branch.
|
||||
options: (value?.remote ?? [])
|
||||
.filter(branch => matches(branch.name) && (automatic === null || automatic.worktree || branch.name !== automatic.name))
|
||||
.map(branch => ({ key: branch.ref, name: branch.name, base: branch })),
|
||||
},
|
||||
{
|
||||
id: 'local',
|
||||
label: t('diff.base.local'),
|
||||
options: (value?.local ?? []).filter(branch => matches(branch.name))
|
||||
.map(branch => ({ key: branch.ref, name: branch.name, base: branch })),
|
||||
.map(branchOption),
|
||||
},
|
||||
{ id: 'local', label: t('diff.base.local'), options: (value?.local ?? []).filter(branch => matches(branch.name)).map(branchOption) },
|
||||
].filter(group => group.options.length > 0)
|
||||
|
||||
const body: ReactNode = branchSearchStatus({ listing, empty: groups.length === 0, retry, className: css.status, t })
|
||||
?? groups.map(group => (
|
||||
<div key={group.id} role="group" aria-label={group.label}>
|
||||
{/* The automatic row's tag names it, so its group shows no heading. */}
|
||||
{group.id !== 'automatic' && <div className={css.label} role="presentation">{group.label}</div>}
|
||||
{group.options.map((option) => {
|
||||
const selected = (option.base?.ref ?? null) === (chosen?.ref ?? null)
|
||||
return (
|
||||
<MenuItemButton key={option.key} icon={<IconBranchOutlineRegular size={14} />} current={selected}
|
||||
onSelect={() => { pick(option.base) }}>
|
||||
<span className={css.option}>
|
||||
<span className={css.name}>{option.name}</span>
|
||||
{option.tag !== undefined && <span className={css.tag}>{option.tag}</span>}
|
||||
{selected && <IconCheckOutlineRegular size={14} className={css.check} />}
|
||||
</span>
|
||||
</MenuItemButton>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
))
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={shown}
|
||||
portal
|
||||
dense
|
||||
align="start"
|
||||
className={css.anchor}
|
||||
listClassName={css.menu}
|
||||
onClose={close}
|
||||
search={{ label: t('diff.base.search'), value: query, onChange: setQuery, skipAutoFocusOnTouch: true }}
|
||||
anchor={(
|
||||
<Tooltip label={t('diff.base.aria', { base: label })} side="bottom" portal delayMs={500}>
|
||||
<button type="button" className={clsx(css.trigger, missing && css.missing)} aria-haspopup="menu" aria-expanded={shown}
|
||||
aria-label={t('diff.base.aria', { base: label })} data-forge-base={chosen?.ref ?? ''}
|
||||
onClick={() => { if (shown) close(); else setOpen(true) }}>
|
||||
{missing && <IconWarningTriangleOutlineRegular size={12} className={css.warning} />}
|
||||
<span className={css.triggerName}>{label}</span>
|
||||
<IconChevronDownOutlineRegular size={12} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
>
|
||||
<div className={css.root} data-forge-base-menu="">
|
||||
<div className={css.rows}>{body}</div>
|
||||
<div className={css.note}>{note}</div>
|
||||
</div>
|
||||
</Menu>
|
||||
<BranchPicker
|
||||
state={state} label={t('diff.base.aria', { base: label })} name={label} missing={missing} anchorClassName={css.anchor}
|
||||
triggerMark={{ 'data-forge-base': chosen?.ref ?? '' }} menuMark={{ 'data-forge-base-menu': '' }}
|
||||
searchLabel={t('diff.base.search')}
|
||||
status={branchSearchStatus({ listing: state.listing, empty: groups.length === 0, retry: state.retry, className: css.status, t })}
|
||||
groups={groups} chosen={chosen?.ref ?? ''} choose={choose} note={note}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* The frame the two branch pickers of the local changes header share: a trigger that names the choice, and a
|
||||
* searchable menu of grouped rows above a note.
|
||||
*/
|
||||
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular,
|
||||
IconWarningTriangleOutlineRegular, Menu, MenuItemButton, Tooltip,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { useBranchSearch, type BranchSearch } from './branch-search.tsx'
|
||||
import css from './BaseMenu.module.css'
|
||||
|
||||
/** One selectable row of a branch picker. */
|
||||
export interface BranchPickerOption<T> {
|
||||
/** Identity among the rows, which also tells the chosen row. */
|
||||
readonly key: string
|
||||
/** Branch name the row shows. */
|
||||
readonly name: string
|
||||
/** What choosing the row picks. */
|
||||
readonly value: T
|
||||
/** A mark after the name, such as what makes the row the default. */
|
||||
readonly tag?: string
|
||||
/** Text for the pointer where the name alone does not say where the branch is. */
|
||||
readonly title?: string
|
||||
}
|
||||
|
||||
/** Rows under one heading. */
|
||||
export interface BranchPickerGroup<T> {
|
||||
readonly id: string
|
||||
/** Accessible name of the group, and its heading unless `plain`. */
|
||||
readonly label: string
|
||||
/** Whether the group shows no heading, as when its one row carries a tag that names it. */
|
||||
readonly plain?: boolean
|
||||
readonly options: readonly BranchPickerOption<T>[]
|
||||
}
|
||||
|
||||
/** A data attribute a picker puts on its trigger or its menu, for tests and automation. */
|
||||
export type PickerMark = Readonly<Record<`data-${string}`, string>>
|
||||
|
||||
/** Whether a picker's menu is open, with its search. */
|
||||
export interface BranchPickerState<L> extends BranchSearch<L> {
|
||||
/** Whether the menu shows: the reader opened it and the owning tab is visible. */
|
||||
readonly shown: boolean
|
||||
/** Close the menu and clear its search. */
|
||||
readonly close: () => void
|
||||
/** Open the menu, or close it while it shows. */
|
||||
readonly toggle: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a picker's menu and its search: opening and each search read the listing again, and a hidden tab keeps the
|
||||
* menu closed.
|
||||
* @param visible - whether the owning tab is visible.
|
||||
* @param list - reads the branches whose names contain the query; the signal aborts the read.
|
||||
* @returns the menu state and the search.
|
||||
*/
|
||||
export function useBranchPicker<L>(
|
||||
visible: boolean, list: (query: string, signal: AbortSignal) => Promise<RemoteResult<L>>,
|
||||
): BranchPickerState<L> {
|
||||
const [open, setOpen] = useState(false)
|
||||
const shown = visible && open
|
||||
const search = useBranchSearch(shown, list)
|
||||
const close = (): void => {
|
||||
setOpen(false)
|
||||
search.reset()
|
||||
}
|
||||
return { ...search, shown, close, toggle: () => { if (shown) close(); else setOpen(true) } }
|
||||
}
|
||||
|
||||
/** Props of the shared frame. */
|
||||
export interface BranchPickerProps<T, L> {
|
||||
/** The menu state and search of {@link useBranchPicker}. */
|
||||
readonly state: BranchPickerState<L>
|
||||
/** Accessible name and tooltip of the trigger. */
|
||||
readonly label: string
|
||||
/** Name the trigger shows. */
|
||||
readonly name: string
|
||||
/** Whether the choice no longer exists. */
|
||||
readonly missing: boolean
|
||||
/** Class that sizes the trigger in the header. */
|
||||
readonly anchorClassName: string | undefined
|
||||
/** Attribute of the trigger. */
|
||||
readonly triggerMark: PickerMark
|
||||
/** Attribute of the menu's content. */
|
||||
readonly menuMark: PickerMark
|
||||
/** Placeholder and accessible name of the search field. */
|
||||
readonly searchLabel: string
|
||||
/** What replaces the rows: reading, a failed read, or nothing matching; null to show `groups`. */
|
||||
readonly status: ReactNode
|
||||
/** Groups with at least one row each. */
|
||||
readonly groups: readonly BranchPickerGroup<T>[]
|
||||
/** Key of the chosen row. */
|
||||
readonly chosen: string
|
||||
/** Choose a row other than the chosen one. */
|
||||
readonly choose: (value: T) => void
|
||||
/** What the rows compare or show, under them. */
|
||||
readonly note: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a branch picker: the trigger and, while open, the portalled menu.
|
||||
* @param props - the menu state, the trigger's texts, the rows with the chosen one, and the note.
|
||||
* @returns the trigger with its menu.
|
||||
*/
|
||||
export function BranchPicker<T, L>({
|
||||
state, label, name, missing, anchorClassName, triggerMark, menuMark, searchLabel, status, groups, chosen, choose, note,
|
||||
}: BranchPickerProps<T, L>): ReactNode {
|
||||
const pick = (option: BranchPickerOption<T>): void => {
|
||||
state.close()
|
||||
if (option.key !== chosen) choose(option.value)
|
||||
}
|
||||
return (
|
||||
<Menu
|
||||
open={state.shown}
|
||||
portal
|
||||
dense
|
||||
align="start"
|
||||
className={anchorClassName}
|
||||
listClassName={css.menu}
|
||||
onClose={state.close}
|
||||
search={{ label: searchLabel, value: state.query, onChange: state.setQuery, skipAutoFocusOnTouch: true }}
|
||||
anchor={(
|
||||
<Tooltip label={label} side="bottom" portal delayMs={500}>
|
||||
<button type="button" className={clsx(css.trigger, missing && css.missing)} aria-haspopup="menu" aria-expanded={state.shown}
|
||||
aria-label={label} {...triggerMark} onClick={state.toggle}>
|
||||
{missing && <IconWarningTriangleOutlineRegular size={12} className={css.warning} />}
|
||||
<span className={css.triggerName}>{name}</span>
|
||||
<IconChevronDownOutlineRegular size={12} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
>
|
||||
<div className={css.root} {...menuMark}>
|
||||
<div className={css.rows}>
|
||||
{status ?? groups.map(group => (
|
||||
<div key={group.id} role="group" aria-label={group.label}>
|
||||
{group.plain !== true && <div className={css.label} role="presentation">{group.label}</div>}
|
||||
{group.options.map((option) => {
|
||||
const selected = option.key === chosen
|
||||
return (
|
||||
<MenuItemButton key={option.key} icon={<IconBranchOutlineRegular size={14} />} current={selected}
|
||||
onSelect={() => { pick(option) }}>
|
||||
<span className={css.option} title={option.title}>
|
||||
<span className={css.name}>{option.name}</span>
|
||||
{option.tag !== undefined && <span className={css.tag}>{option.tag}</span>}
|
||||
{selected && <IconCheckOutlineRegular size={14} className={css.check} />}
|
||||
</span>
|
||||
</MenuItemButton>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className={css.note}>{note}</div>
|
||||
</div>
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
@@ -29,8 +29,7 @@ import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import type {
|
||||
ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeExtensionState, ForgeLensFrame,
|
||||
ForgeLensKeep, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalHead, ForgeLocalScope, ForgeLocalWrite,
|
||||
ForgeLocalWriteResult, ForgeRelatedCheckout,
|
||||
ForgeLensKeep, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgeLocalWrite, ForgeLocalWriteResult,
|
||||
} from '../types.ts'
|
||||
import { restorable } from '../restore.ts'
|
||||
import { lensVersion } from '../lens-version.ts'
|
||||
@@ -119,19 +118,17 @@ export interface ChangesTabInjected {
|
||||
/** Stage, unstage, or restore files of the local changes, or return index entries to an earlier tree; never retried. */
|
||||
readonly localWrite: (write: ForgeLocalWrite) => Promise<RemoteResult<ForgeLocalWriteResult>>
|
||||
/**
|
||||
* Read the branches the `branch` scope of `head`, or of the Session's own checkout for null, can compare with,
|
||||
* whose names contain `query`; `signal` aborts the read.
|
||||
* Read the branches the `branch` scope of the head branch `head`, by its full ref, or of the Session's own checkout
|
||||
* for null, can compare with, whose names contain `query`; `signal` aborts the read.
|
||||
*/
|
||||
readonly diffBases: (head: ForgeLocalHead | null, query: string, signal: AbortSignal) => Promise<RemoteResult<ForgeBaseBranches>>
|
||||
/** Read the checkouts that Sessions delegated from this one work in; `signal` aborts the read. */
|
||||
readonly relatedCheckouts: (signal: AbortSignal) => Promise<RemoteResult<readonly ForgeRelatedCheckout[]>>
|
||||
readonly diffBases: (head: string | null, query: string, signal: AbortSignal) => Promise<RemoteResult<ForgeBaseBranches>>
|
||||
/** Read the new side of one file in a local scope. */
|
||||
readonly localText: (scope: ForgeLocalScope, path: string) => Promise<RemoteResult<string>>
|
||||
/**
|
||||
* List the commits of the `branch` scope of `head`, or of the Session's own checkout for null, compared with `base`,
|
||||
* or with the automatic fork point for null; `signal` aborts the read.
|
||||
* List the commits of the `branch` scope of the head branch `head`, or of the Session's own checkout for null,
|
||||
* compared with `base`, or with the automatic fork point for null; `signal` aborts the read.
|
||||
*/
|
||||
readonly localCommits: (head: ForgeLocalHead | null, base: string | null, signal: AbortSignal) => Promise<RemoteResult<ForgeLocalCommits>>
|
||||
readonly localCommits: (head: string | null, base: string | null, signal: AbortSignal) => Promise<RemoteResult<ForgeLocalCommits>>
|
||||
/** Read the changes of a change request, or of consecutive commits of it, by its binding URL; `signal` aborts the read. */
|
||||
readonly changeRequestDiff: (
|
||||
url: string, commits: ForgeCommitRange | null, signal: AbortSignal,
|
||||
@@ -211,8 +208,10 @@ type ChangesData =
|
||||
readonly files: readonly ForgeDiffFile[]
|
||||
/** Scope the files were read in. */
|
||||
readonly scope: ForgeLocalScope
|
||||
/** What the files show in place of the Session's own checkout, or null for that checkout. */
|
||||
/** The branch the files show in place of the Session's checked-out one, or null for the Session's own checkout. */
|
||||
readonly head: ChangesHead | null
|
||||
/** Top-level directory of the worktree the files were read in for `head`, or null when they come from its commits. */
|
||||
readonly worktree: string | null
|
||||
/** Name of what the `branch` scope compared with; null for other scopes. */
|
||||
readonly base: string | null
|
||||
/** Untracked files left out. */
|
||||
@@ -288,6 +287,9 @@ const FAILURE: Partial<Record<string, ForgePanelKey>> = {
|
||||
'forgePanel/commits-not-linear': 'commits.notLinear',
|
||||
}
|
||||
|
||||
/** Git's name for the checked-out commit, shown for a checkout that has neither a branch nor a commit yet. */
|
||||
const GIT_HEAD = 'HEAD'
|
||||
|
||||
/** Failures of a chosen base branch, which offer the automatic fork point instead of a retry. */
|
||||
const BASE_FAILURE: Partial<Record<string, ForgePanelKey>> = {
|
||||
'forgePanel/base-missing': 'diff.baseMissing',
|
||||
@@ -311,7 +313,7 @@ function baseFailureOf(failed: string | null, base: ForgeBaseBranch | null, t: T
|
||||
* status, beside the diff; marks read at another head refuse the read as the diff refuses a moved head.
|
||||
* @param source - local changes or a change request.
|
||||
* @param scope - local scope to read.
|
||||
* @param localHead - what the local scope shows in place of the Session's own checkout, or null.
|
||||
* @param localHead - the branch the local scope shows in place of the Session's checked-out one, or null.
|
||||
* @param commits - chosen commits of a change request, or null for all of it.
|
||||
* @param head - head commit of the change request's latest status, or null.
|
||||
* @param fresh - whether the viewed marks are read from the code host although the host keeps some, as after a refresh.
|
||||
@@ -332,8 +334,8 @@ async function readChanges(
|
||||
if (source.kind === 'local') {
|
||||
const result = await reads.localDiff(scope, signal)
|
||||
if (!result.ok) return result
|
||||
const { files, base, omitted } = result.value
|
||||
return { ok: true, value: { kind: 'local', files, scope, head: localHead, base, omitted } }
|
||||
const { files, base, omitted, worktree } = result.value
|
||||
return { ok: true, value: { kind: 'local', files, scope, head: localHead, worktree: worktree ?? null, base, omitted } }
|
||||
}
|
||||
const [result, marks] = await Promise.all([
|
||||
reads.changeRequestDiff(source.url, commits, signal),
|
||||
@@ -361,23 +363,13 @@ function commitsOf(scope: ForgeLocalScope): ForgeCommitRange | null {
|
||||
return scope.kind === 'branch' ? scope.commits : null
|
||||
}
|
||||
|
||||
/** The head a tab chose as review comments record it; undefined for the Session's own checkout. */
|
||||
function reviewHeadOf(head: ChangesHead | null): ReviewHead | undefined {
|
||||
if (head === null) return undefined
|
||||
return head.kind === 'branch' ? { key: `branch:${head.ref}`, name: head.name, root: null }
|
||||
: { key: `session:${head.sessionId}`, name: head.name, root: head.root }
|
||||
}
|
||||
|
||||
/** The head a local scope names on the wire; undefined for the Session's own checkout. */
|
||||
function wireHeadOf(head: ChangesHead | null): ForgeLocalHead | undefined {
|
||||
if (head === null) return undefined
|
||||
return head.kind === 'branch' ? { kind: 'branch', ref: head.ref } : { kind: 'session', sessionId: head.sessionId }
|
||||
}
|
||||
|
||||
/** The source review comments on loaded changes record: the change request head, or the local head and scope with its base. */
|
||||
/**
|
||||
* The source review comments on loaded changes record: the change request head, or the local scope with its base and,
|
||||
* for another branch than the Session's checked-out one, that branch with the worktree the changes were read in.
|
||||
*/
|
||||
function reviewSourceOf(data: ChangesData): ReviewSource {
|
||||
if (data.kind === 'change') return { kind: 'change', url: data.url, headSha: data.headSha, commits: data.commits }
|
||||
const head = reviewHeadOf(data.head)
|
||||
const head: ReviewHead | undefined = data.head === null ? undefined : { key: data.head.ref, name: data.head.name, root: data.worktree }
|
||||
return {
|
||||
kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope), commits: commitsOf(data.scope),
|
||||
...(head === undefined ? {} : { head }),
|
||||
@@ -478,13 +470,13 @@ function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDis
|
||||
}
|
||||
|
||||
/**
|
||||
* The local view's header: the head picker, then for the `branch` scope the base branch picker and, for a checkout,
|
||||
* a note that uncommitted changes count; for another scope, what it compares. Writes and the create button belong to
|
||||
* the Session's own checkout.
|
||||
* The local view's header: the head picker, then for the `branch` scope the base branch picker and, while a working
|
||||
* tree is read, a note that uncommitted changes count; for another scope, what it compares. Writes and the create
|
||||
* button belong to the Session's own checkout.
|
||||
*/
|
||||
function LocalHeader({
|
||||
state, scope, head, headMissing, base, baseLabel, missing, visible, diffBases, relatedCheckouts, chooseHead, choose, commitMenu, bulk,
|
||||
createChangeRequest, t,
|
||||
state, scope, head, headMissing, base, baseLabel, missing, visible, diffBases, chooseHead, choose, commitMenu, bulk, createChangeRequest,
|
||||
t,
|
||||
}: {
|
||||
readonly state: ChangesPanelState | null
|
||||
/** Commit picker of the `branch` scope, left of the create button. */
|
||||
@@ -492,9 +484,9 @@ function LocalHeader({
|
||||
/** The write of every shown file that the scope offers, or null for a scope, head, or Session without writes. */
|
||||
readonly bulk: { readonly label: string; readonly disabled: boolean; readonly run: () => void } | null
|
||||
readonly scope: ScopeKind
|
||||
/** What the view shows in place of the Session's own checkout, or null for that checkout. */
|
||||
/** The branch the view shows in place of the Session's checked-out one, or null for the Session's own checkout. */
|
||||
readonly head: ChangesHead | null
|
||||
/** Whether the chosen head is gone. */
|
||||
/** Whether the chosen head no longer exists. */
|
||||
readonly headMissing: boolean
|
||||
readonly base: ForgeBaseBranch | null
|
||||
/** Name of the base another head's loaded `branch` scope compared with, or null before it loaded; the panel names the own checkout's. */
|
||||
@@ -503,7 +495,6 @@ function LocalHeader({
|
||||
readonly missing: boolean
|
||||
readonly visible: boolean
|
||||
readonly diffBases: ChangesTabInjected['diffBases']
|
||||
readonly relatedCheckouts: ChangesTabInjected['relatedCheckouts']
|
||||
readonly chooseHead: (head: ChangesHead | null) => void
|
||||
readonly choose: (base: ForgeBaseBranch | null) => void
|
||||
readonly createChangeRequest: () => void
|
||||
@@ -511,17 +502,17 @@ function LocalHeader({
|
||||
}): ReactNode {
|
||||
const creatable = head === null && state !== null && state.repository !== null && openChangeRequestOf(state) === undefined
|
||||
const checkout = state?.checkout.state === 'ready' ? state.checkout.checkout : null
|
||||
const wireHead = useMemo(() => wireHeadOf(head) ?? null, [head])
|
||||
const listBases = useCallback((query: string, signal: AbortSignal) => diffBases(wireHead, query, signal), [diffBases, wireHead])
|
||||
const headRef = head?.ref ?? null
|
||||
const listBases = useCallback((query: string, signal: AbortSignal) => diffBases(headRef, query, signal), [diffBases, headRef])
|
||||
// Branches a reader can show: every branch but the one the Session has checked out, which is its own checkout's row.
|
||||
const listHeads = useCallback((query: string, signal: AbortSignal) => diffBases(null, query, signal), [diffBases])
|
||||
// A branch has no working tree; a checkout's comparison counts its uncommitted changes.
|
||||
const committedOnly = head?.kind === 'branch'
|
||||
// A branch that no worktree has checked out is read from its commits; a checkout's comparison counts its uncommitted changes.
|
||||
const committedOnly = head !== null && head.worktree === null
|
||||
return (
|
||||
<div className={css.header}>
|
||||
<span className={css.headerIcon}><IconBranchOutlineRegular size={15} /></span>
|
||||
<HeadMenu chosen={head} own={checkout?.branch ?? checkout?.commit ?? 'HEAD'} missing={headMissing} visible={visible}
|
||||
related={relatedCheckouts} list={listHeads} choose={chooseHead} t={t} />
|
||||
<HeadMenu chosen={head} own={checkout?.branch ?? checkout?.commit ?? GIT_HEAD} missing={headMissing} visible={visible}
|
||||
list={listHeads} choose={chooseHead} t={t} />
|
||||
{scope === 'branch' ? <>
|
||||
<span className={css.headerArrow} aria-hidden="true">→</span>
|
||||
<BaseMenu chosen={base} label={base?.name ?? (head === null ? state?.local?.base : baseLabel) ?? t('diff.base.automatic')}
|
||||
@@ -627,7 +618,7 @@ export function ChangesTab({ useTabInfo, sessionId, usePanel, useAnnotations, ..
|
||||
*/
|
||||
export function ChangesView({
|
||||
tab, source, target: viewTarget, snapshot, annotations: viewAnnotations, openFile, quoteCopy, useStore, actions, reconnect, localDiff,
|
||||
localWrite, diffBases, relatedCheckouts, localText,
|
||||
localWrite, diffBases, localText,
|
||||
localCommits, changeRequestDiff, changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles,
|
||||
changeRequestViewed, setFileViewed, openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue,
|
||||
submitReview, report, useLenses, useExtensions, changesLens, renderSlot, t: translate,
|
||||
@@ -756,15 +747,14 @@ export function ChangesView({
|
||||
const chosenCommits = choices?.commits ?? null
|
||||
const lens = choices?.lens ?? 'all'
|
||||
const hideTests = choices?.hideTests ?? false
|
||||
// What local changes show in place of the Session's own checkout; a change request view has none.
|
||||
// The branch local changes show in place of the Session's checked-out one; a change request view has none.
|
||||
const localHead = source.kind === 'local' ? choices?.head ?? null : null
|
||||
const wireHead = useMemo(() => wireHeadOf(localHead), [localHead])
|
||||
const headRef = localHead?.ref ?? null
|
||||
// The Session's own checkout names no head, so its scopes keep the identity they had before heads.
|
||||
const localScope = useMemo((): ForgeLocalScope => {
|
||||
const shown = wireHead === undefined ? {} : { head: wireHead }
|
||||
if (scope === 'branch') return { kind: 'branch', ...shown, base: base?.ref ?? null, commits: chosenCommits }
|
||||
return wireHead?.kind === 'session' ? { kind: scope, head: wireHead } : { kind: scope }
|
||||
}, [scope, wireHead, base, chosenCommits])
|
||||
const shown = headRef === null ? {} : { head: headRef }
|
||||
return scope === 'branch' ? { kind: 'branch', ...shown, base: base?.ref ?? null, commits: chosenCommits } : { kind: scope, ...shown }
|
||||
}, [scope, headRef, base, chosenCommits])
|
||||
// Other plugins contribute to the Session's own local changes; another head shows without their slots and annotations.
|
||||
const target = localHead === null ? viewTarget : null
|
||||
const changeCommits = source.kind === 'change' ? chosenCommits : null
|
||||
@@ -774,7 +764,7 @@ export function ChangesView({
|
||||
)
|
||||
const baseRef = base?.ref ?? null
|
||||
const listLocalCommits = useCallback(
|
||||
(signal: AbortSignal) => localCommits(wireHead ?? null, baseRef, signal), [localCommits, wireHead, baseRef],
|
||||
(signal: AbortSignal) => localCommits(headRef, baseRef, signal), [localCommits, headRef, baseRef],
|
||||
)
|
||||
const split = choices?.split ?? true
|
||||
const wrap = choices?.wrap ?? true
|
||||
@@ -790,7 +780,7 @@ export function ChangesView({
|
||||
const headCommit = state !== null && state.checkout.state === 'ready' ? state.checkout.checkout.commit : null
|
||||
// The commits change with the head of a change request, with the local HEAD, branch, or base, and on a refresh.
|
||||
const commitsVersion = `${attempt}\n${source.kind === 'local'
|
||||
? `${JSON.stringify(wireHead ?? null)}\n${baseRef ?? ''}\n${headCommit ?? ''}\n${JSON.stringify(state?.local ?? null)}` : head ?? ''}`
|
||||
? `${headRef ?? ''}\n${baseRef ?? ''}\n${headCommit ?? ''}\n${JSON.stringify(state?.local ?? null)}` : head ?? ''}`
|
||||
const dataKey = source.kind === 'local' ? JSON.stringify(localScope) : `change\n${JSON.stringify(changeCommits)}`
|
||||
const [loaded, setLoaded] = useState<{ readonly key: string; readonly data: ChangesData } | null>(null)
|
||||
const [failure, setFailure] = useState<{ readonly key: string; readonly code: string } | null>(null)
|
||||
@@ -821,17 +811,29 @@ export function ChangesView({
|
||||
setFailure(null)
|
||||
return
|
||||
}
|
||||
// The worktree that had the shown branch checked out is gone, so the tab falls back to the branch's commits,
|
||||
// read again because what it loaded for the `branch` scope counted that worktree's files.
|
||||
if (!result.ok && result.error.code === 'forgePanel/no-working-tree') {
|
||||
setFinished(null)
|
||||
setLoaded(null)
|
||||
actions.rooted(tab.id, null)
|
||||
return
|
||||
}
|
||||
finishedAttempt.current = attempt
|
||||
setFinished(read)
|
||||
if (result.ok) {
|
||||
setLoaded({ key: dataKey, data: result.value })
|
||||
setFailure(null)
|
||||
// A worktree added or removed since the branch was listed decides which scopes the branch has.
|
||||
if (result.value.kind === 'local' && localHead !== null && result.value.worktree !== localHead.worktree) {
|
||||
actions.rooted(tab.id, result.value.worktree)
|
||||
}
|
||||
} else {
|
||||
setFailure({ key: dataKey, code: result.error.code })
|
||||
}
|
||||
})
|
||||
return () => { controller.abort() }
|
||||
}, [tab.visible, read, refused, waiting, source, localScope, localHead, changeCommits, head, attempt, dataKey, localDiff,
|
||||
}, [tab.visible, tab.id, actions, read, refused, waiting, source, localScope, localHead, changeCommits, head, attempt, dataKey, localDiff,
|
||||
changeRequestDiff, changeRequestViewed])
|
||||
const data = loaded !== null && loaded.key === dataKey ? loaded.data : null
|
||||
// Threads show only while they were read at the head of the latest status and, for the whole change request, at
|
||||
@@ -1146,7 +1148,7 @@ export function ChangesView({
|
||||
}
|
||||
const recordActions: ReviewActions = {
|
||||
source: shownSource ?? (source.kind === 'local'
|
||||
? reviewSourceOf({ kind: 'local', files: [], scope: localScope, head: localHead, base: null, omitted: 0 })
|
||||
? reviewSourceOf({ kind: 'local', files: [], scope: localScope, head: localHead, worktree: localHead?.worktree ?? null, base: null, omitted: 0 })
|
||||
: { kind: 'change', url: source.url, headSha: '', commits: changeCommits }),
|
||||
records: queue, addToInput: addReviewToInput, openLink, quoteCopy, onRemoved: reportRemoved,
|
||||
}
|
||||
@@ -1468,7 +1470,7 @@ export function ChangesView({
|
||||
{source.kind === 'local'
|
||||
? <LocalHeader state={state} scope={scope} head={localHead} headMissing={headMissing} base={base}
|
||||
baseLabel={data?.kind === 'local' ? data.base : null} missing={failed === 'forgePanel/base-missing'} visible={tab.visible}
|
||||
diffBases={diffBases} relatedCheckouts={relatedCheckouts} chooseHead={(next) => { actions.headed(tab.id, next) }}
|
||||
diffBases={diffBases} chooseHead={(next) => { actions.headed(tab.id, next) }}
|
||||
choose={(next) => { actions.based(tab.id, next) }} commitMenu={commitMenu}
|
||||
bulk={writeSide === undefined ? null : {
|
||||
label: t(writeSide === 'unstaged' ? 'diff.stageAll' : 'diff.unstageAll'),
|
||||
@@ -1491,8 +1493,8 @@ export function ChangesView({
|
||||
{/* Above the file tree, the lens spans the tree's width; elsewhere a menu in the toolbar takes its place. */}
|
||||
{treeShown && <div className={css.lensCell}><LensControl {...lensProps} need={setLensWidth} /></div>}
|
||||
<div ref={toolbarRow} className={css.toolbarMain}>
|
||||
{/* A branch has no working tree, so it has the `branch` scope alone. */}
|
||||
{tab.visible && source.kind === 'local' && localHead?.kind !== 'branch'
|
||||
{/* A branch that no worktree has checked out has neither a working tree nor an index, so it has the `branch` scope alone. */}
|
||||
{tab.visible && source.kind === 'local' && (localHead === null || localHead.worktree !== null)
|
||||
&& <ScopeMenu scope={scope} choose={(next) => { actions.scoped(tab.id, next) }} t={t} />}
|
||||
{tab.visible && (
|
||||
<span className={css.filesSlot}><ChangedFilesMenu {...navigator} loading={data === null && failed === null} visible /></span>
|
||||
|
||||
@@ -187,12 +187,12 @@ export function ConnectionRow({ usePanel, reconnect, t }: ConnectionRowProps): R
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the size of the branch's changes; the row opens the local changes
|
||||
* view, and its menu offers the view and, without an open change request for
|
||||
* the branch, asking the Agent to create one. Opening the view closes the
|
||||
* panel's overlay.
|
||||
* Render the size of the branch's changes, zero included, or the row's name alone while the `branch` scope has no fork
|
||||
* point; the row opens the local changes view, where another scope or branch can be shown, and its menu offers the
|
||||
* view and, without an open change request for the branch, asking the Agent to create one. Opening the view closes
|
||||
* the panel's overlay.
|
||||
* @param props - panel snapshot hook, view and create actions, panel owner values, and copy.
|
||||
* @returns the row, or null while the branch changes no files.
|
||||
* @returns the row, or null outside a Git checkout and before the first inspection ends.
|
||||
*/
|
||||
export function LocalChangesRow({
|
||||
usePanel, dismissOverlay, viewLocalChanges, createChangeRequest, t,
|
||||
@@ -200,15 +200,16 @@ export function LocalChangesRow({
|
||||
const local = usePanel(snapshot => snapshot.state?.local ?? null)
|
||||
const creatable = usePanel(snapshot => snapshot.state !== null && snapshot.state.repository !== null
|
||||
&& openChangeRequestOf(snapshot.state) === undefined)
|
||||
const inCheckout = usePanel(snapshot => snapshot.state?.checkout.state === 'ready')
|
||||
const [open, setOpen] = useState(false)
|
||||
if (local === null || local.files.length === 0) return null
|
||||
if (!inCheckout) return null
|
||||
let additions = 0
|
||||
let deletions = 0
|
||||
for (const file of local.files) {
|
||||
for (const file of local?.files ?? []) {
|
||||
additions += file.additions
|
||||
deletions += file.deletions
|
||||
}
|
||||
const count = local.files.length
|
||||
const count = local?.files.length ?? 0
|
||||
const view = (): void => {
|
||||
viewLocalChanges()
|
||||
dismissOverlay()
|
||||
@@ -218,18 +219,21 @@ export function LocalChangesRow({
|
||||
<button
|
||||
type="button"
|
||||
data-row-part="body"
|
||||
aria-label={t('changes.local.viewAria', { count, added: additions, deleted: deletions })}
|
||||
aria-label={local === null ? t('changes.local.title') : t('changes.local.viewAria', { count, added: additions, deleted: deletions })}
|
||||
onClick={view}
|
||||
>
|
||||
<span data-row-part="icon" aria-hidden="true"><IconFilesDiffOutlineRegular size={16} /></span>
|
||||
<span data-row-part="content">{t('changes.local.summary', { count })}</span>
|
||||
<span data-row-part="content">{count === 0 ? t('changes.local.title') : t('changes.local.summary', { count })}</span>
|
||||
</button>
|
||||
<span data-row-part="trailing">
|
||||
<span className={css.diff}>
|
||||
<span className={css.added}>{`+${String(additions)}`}</span>
|
||||
<span className={css.deleted}>{`−${String(deletions)}`}</span>
|
||||
{/* Without a fork point the `branch` scope has no size; the view still shows the other scopes and takes a base. */}
|
||||
{local !== null && (
|
||||
<span data-row-part="trailing">
|
||||
<span className={css.diff}>
|
||||
<span className={css.added}>{`+${String(additions)}`}</span>
|
||||
<span className={css.deleted}>{`−${String(deletions)}`}</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
<span data-row-part="menu">
|
||||
<Menu
|
||||
open={open}
|
||||
|
||||
@@ -1,183 +1,69 @@
|
||||
/**
|
||||
* Picker of what the local changes view shows: the Session's own checkout, the checkout of a Session delegated from
|
||||
* it, or the committed content of another branch.
|
||||
* Picker of the branch the local changes view shows: the Session's checked-out one, or another local or
|
||||
* remote-tracking branch, which is read in the worktree that has it checked out, else from its commits.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronDownOutlineRegular,
|
||||
IconWarningTriangleOutlineRegular, Menu, MenuItemButton, Tooltip,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { ReactNode } from 'react'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { TextSearchIndex, type SearchKeys } from '@deepseek-ai/dsh-util-text-search'
|
||||
import type { ForgeBaseBranch, ForgeBaseBranches, ForgeRelatedCheckout } from '../types.ts'
|
||||
import { branchSearchStatus, useBranchSearch } from './branch-search.tsx'
|
||||
import type { ForgeBaseBranch, ForgeBaseBranches } from '../types.ts'
|
||||
import { branchSearchStatus } from './branch-search.tsx'
|
||||
import { BranchPicker, useBranchPicker, type BranchPickerGroup } from './BranchPicker.tsx'
|
||||
import type { ChangesHead } from './changes-store.ts'
|
||||
import type { NS } from './locales.ts'
|
||||
import css from './BaseMenu.module.css'
|
||||
|
||||
/** Props of the head picker. */
|
||||
export interface HeadMenuProps extends PropsLocale<typeof NS> {
|
||||
/** Chosen head, or null for the Session's own checkout. */
|
||||
/** Chosen branch, or null for the Session's own checkout. */
|
||||
readonly chosen: ChangesHead | null
|
||||
/** Branch of the Session's own checkout, or its commit while HEAD is detached. */
|
||||
/** Name of the Session's own checkout: its branch, its commit while HEAD is detached, or Git's name for neither. */
|
||||
readonly own: string
|
||||
/** Whether the chosen head is gone. */
|
||||
/** Whether the chosen branch no longer exists. */
|
||||
readonly missing: boolean
|
||||
/** Whether the owning tab is visible; a hidden tab keeps the menu closed. */
|
||||
readonly visible: boolean
|
||||
/** Read the checkouts that related Sessions work in; `signal` aborts the read. */
|
||||
readonly related: (signal: AbortSignal) => Promise<RemoteResult<readonly ForgeRelatedCheckout[]>>
|
||||
/** Read the branches, other than the Session's checked-out one, whose names contain `query`; `signal` aborts the read. */
|
||||
readonly list: (query: string, signal: AbortSignal) => Promise<RemoteResult<ForgeBaseBranches>>
|
||||
/** Show a head, or the Session's own checkout for null. */
|
||||
/** Show a branch, or the Session's own checkout for null. */
|
||||
readonly choose: (head: ChangesHead | null) => void
|
||||
}
|
||||
|
||||
/** One selectable row. */
|
||||
interface HeadOption {
|
||||
readonly key: string
|
||||
readonly name: string
|
||||
readonly head: ChangesHead | null
|
||||
/** Marks the Session's own checkout. */
|
||||
readonly tag?: string
|
||||
/** What the Sessions working in a related checkout do. */
|
||||
readonly who?: string
|
||||
/** Full text of a row whose name alone does not identify it, for the pointer. */
|
||||
readonly title?: string
|
||||
}
|
||||
|
||||
/** The name a related checkout shows: its branch, or its commit while HEAD is detached. */
|
||||
function relatedName(checkout: ForgeRelatedCheckout): string {
|
||||
return checkout.branch ?? checkout.commit ?? 'HEAD'
|
||||
}
|
||||
|
||||
/** A related checkout is found by its branch, and by what its Sessions do and where it lies as plain text. */
|
||||
function relatedSearchKeys(checkout: ForgeRelatedCheckout): SearchKeys {
|
||||
return { fuzzy: [relatedName(checkout)], substring: [...checkout.labels, checkout.root] }
|
||||
}
|
||||
|
||||
/** Identity of a head among the rows; null is the Session's own checkout. */
|
||||
function keyOf(head: ChangesHead | null): string {
|
||||
return head === null ? 'own' : head.kind === 'branch' ? `branch:${head.ref}` : `session:${head.sessionId}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the trigger and, while open, the searchable menu. Opening reads the related checkouts once; opening and each
|
||||
* search read the branches again, and rows already shown follow the search at once until the new listing arrives. A
|
||||
* branch that the Session or a related Session has checked out shows only as that checkout.
|
||||
* @param props - the choice, the own checkout's name, the two reads, the choose action, and copy.
|
||||
* Render the trigger and, while open, the searchable menu: the Session's own checkout, then local and remote-tracking
|
||||
* branches. A branch that a worktree has checked out carries a tag and names that worktree's directory for the pointer.
|
||||
* Opening and each search read the branches again; rows already shown follow the search at once until the new listing
|
||||
* arrives.
|
||||
* @param props - the choice, the own checkout's name, the listing read, the choose action, and copy.
|
||||
* @returns the trigger with its portalled menu.
|
||||
*/
|
||||
export function HeadMenu({ chosen, own, missing, visible, related, list, choose, t }: HeadMenuProps): ReactNode {
|
||||
const [open, setOpen] = useState(false)
|
||||
const shown = visible && open
|
||||
const { query, setQuery, listing, retry, reset } = useBranchSearch(shown, list)
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const [checkouts, setCheckouts] = useState<RemoteResult<readonly ForgeRelatedCheckout[]> | null>(null)
|
||||
useEffect(() => {
|
||||
if (!shown) return
|
||||
const controller = new AbortController()
|
||||
void related(controller.signal).then((result) => { if (!controller.signal.aborted) setCheckouts(result) })
|
||||
return () => { controller.abort() }
|
||||
}, [shown, related, attempt])
|
||||
const retryBoth = useCallback(() => {
|
||||
retry()
|
||||
setAttempt(count => count + 1)
|
||||
}, [retry])
|
||||
const close = (): void => {
|
||||
setOpen(false)
|
||||
reset()
|
||||
}
|
||||
const pick = (head: ChangesHead | null): void => {
|
||||
close()
|
||||
if (keyOf(head) !== keyOf(chosen)) choose(head)
|
||||
}
|
||||
|
||||
const listed = checkouts?.ok === true ? checkouts.value : null
|
||||
const index = useMemo(() => new TextSearchIndex(listed ?? [], relatedSearchKeys), [listed])
|
||||
const branches = listing?.ok === true ? listing.value : null
|
||||
const needle = query.trim().toLowerCase()
|
||||
export function HeadMenu({ chosen, own, missing, visible, list, choose, t }: HeadMenuProps): ReactNode {
|
||||
const state = useBranchPicker(visible, list)
|
||||
const value = state.listing?.ok === true ? state.listing.value : null
|
||||
const needle = state.query.trim().toLowerCase()
|
||||
const matches = (name: string): boolean => name.toLowerCase().includes(needle)
|
||||
// The related checkouts name their branches, so the branch groups wait for them rather than list a branch twice.
|
||||
const taken = new Set((listed ?? []).map(checkout => checkout.branch))
|
||||
const branchOptions = (group: readonly ForgeBaseBranch[], local: boolean): HeadOption[] => listed === null ? []
|
||||
: group.filter(branch => matches(branch.name) && !(local && taken.has(branch.name)))
|
||||
.map((branch): HeadOption => ({ key: `branch:${branch.ref}`, name: branch.name, head: { kind: 'branch', ref: branch.ref, name: branch.name } }))
|
||||
const groups: { readonly id: string; readonly label: string; readonly options: readonly HeadOption[] }[] = [
|
||||
{ id: 'own', label: t('diff.head.own'), options: matches(own) ? [{ key: 'own', name: own, head: null, tag: t('diff.head.own') }] : [] },
|
||||
{
|
||||
id: 'related',
|
||||
label: t('diff.head.related'),
|
||||
options: index.search(query).map((checkout): HeadOption => {
|
||||
const name = relatedName(checkout)
|
||||
return {
|
||||
key: `session:${checkout.sessionId}`, name, who: checkout.labels.join(' · '), title: checkout.root,
|
||||
head: { kind: 'session', sessionId: checkout.sessionId, name, root: checkout.root },
|
||||
}
|
||||
}),
|
||||
},
|
||||
const options = (branches: readonly ForgeBaseBranch[]) => branches.filter(branch => matches(branch.name)).map(branch => ({
|
||||
key: branch.ref,
|
||||
name: branch.name,
|
||||
value: { ref: branch.ref, name: branch.name, worktree: branch.worktree ?? null },
|
||||
...(branch.worktree === undefined ? {} : { tag: t('checkout.worktree'), title: branch.worktree }),
|
||||
}))
|
||||
const groups: BranchPickerGroup<ChangesHead | null>[] = [
|
||||
// The own row's tag names it, so its group shows no heading.
|
||||
{ id: 'own', label: t('diff.head.own'), plain: true, options: matches(own) ? [{ key: '', name: own, value: null, tag: t('diff.head.own') }] : [] },
|
||||
// What a reader looks at is usually a local branch, so the local group comes before the remote one.
|
||||
{ id: 'local', label: t('diff.base.local'), options: branchOptions(branches?.local ?? [], true) },
|
||||
{ id: 'remote', label: t('diff.base.remote'), options: branchOptions(branches?.remote ?? [], false) },
|
||||
{ id: 'local', label: t('diff.base.local'), options: options(value?.local ?? []) },
|
||||
{ id: 'remote', label: t('diff.base.remote'), options: options(value?.remote ?? []) },
|
||||
].filter(group => group.options.length > 0)
|
||||
|
||||
// Either failed read offers the retry of both; rows show once both listings arrived.
|
||||
const failed = [checkouts, listing].find(result => result?.ok === false) ?? null
|
||||
const status = branchSearchStatus({
|
||||
listing: failed ?? (checkouts === null || listing === null ? null : listing), empty: false, retry: retryBoth, className: css.status, t,
|
||||
})
|
||||
const body: ReactNode = status ?? (groups.length === 0 ? <div className={css.status} role="status">{t('diff.head.empty')}</div>
|
||||
: groups.map(group => (
|
||||
<div key={group.id} role="group" aria-label={group.label}>
|
||||
{/* The own row's tag names it, so its group shows no heading. */}
|
||||
{group.id !== 'own' && <div className={css.label} role="presentation">{group.label}</div>}
|
||||
{group.options.map((option) => {
|
||||
const selected = option.key === keyOf(chosen)
|
||||
return (
|
||||
<MenuItemButton key={option.key} icon={<IconBranchOutlineRegular size={14} />} current={selected}
|
||||
onSelect={() => { pick(option.head) }}>
|
||||
<span className={clsx(css.option, option.who !== undefined && css.related)} title={option.title}>
|
||||
<span className={css.name}>{option.name}</span>
|
||||
{option.tag !== undefined && <span className={css.tag}>{option.tag}</span>}
|
||||
{option.who !== undefined && <span className={css.who}>{option.who}</span>}
|
||||
{selected && <IconCheckOutlineRegular size={14} className={css.check} />}
|
||||
</span>
|
||||
</MenuItemButton>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)))
|
||||
|
||||
const label = chosen?.name ?? own
|
||||
const name = chosen?.name ?? own
|
||||
return (
|
||||
<Menu
|
||||
open={shown}
|
||||
portal
|
||||
dense
|
||||
align="start"
|
||||
className={css.headAnchor}
|
||||
listClassName={css.menu}
|
||||
onClose={close}
|
||||
search={{ label: t('diff.head.search'), value: query, onChange: setQuery, skipAutoFocusOnTouch: true }}
|
||||
anchor={(
|
||||
<Tooltip label={t('diff.head.aria', { head: label })} side="bottom" portal delayMs={500}>
|
||||
<button type="button" className={clsx(css.trigger, missing && css.missing)} aria-haspopup="menu" aria-expanded={shown}
|
||||
aria-label={t('diff.head.aria', { head: label })} data-forge-head={chosen === null ? '' : keyOf(chosen)}
|
||||
onClick={() => { if (shown) close(); else setOpen(true) }}>
|
||||
{missing && <IconWarningTriangleOutlineRegular size={12} className={css.warning} />}
|
||||
<span className={css.triggerName}>{label}</span>
|
||||
<IconChevronDownOutlineRegular size={12} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
>
|
||||
<div className={css.root} data-forge-head-menu="">
|
||||
<div className={css.rows}>{body}</div>
|
||||
<div className={css.note}>{t('diff.head.note')}</div>
|
||||
</div>
|
||||
</Menu>
|
||||
<BranchPicker
|
||||
state={state} label={t('diff.head.aria', { head: name })} name={name} missing={missing} anchorClassName={css.headAnchor}
|
||||
triggerMark={{ 'data-forge-head': chosen?.ref ?? '' }} menuMark={{ 'data-forge-head-menu': '' }}
|
||||
searchLabel={t('diff.base.search')}
|
||||
status={branchSearchStatus({ listing: state.listing, empty: groups.length === 0, retry: state.retry, className: css.status, t })}
|
||||
groups={groups} chosen={chosen?.ref ?? ''} choose={choose} note={t('diff.head.note')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -7,14 +7,20 @@
|
||||
*/
|
||||
|
||||
import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store'
|
||||
import type { ForgeBaseBranch, ForgeBranchHead, ForgeCommitRange, ForgeFileLayer, ForgeLocalScope, ForgeRelatedHead } from '../types.ts'
|
||||
import type { ForgeBaseBranch, ForgeCommitRange, ForgeFileLayer, ForgeLocalScope } from '../types.ts'
|
||||
|
||||
/** What local changes show in place of the Session's own checkout, with the name its picker shows. */
|
||||
export type ChangesHead =
|
||||
/** A related Session's checkout, with the branch or commit it had when chosen and its top-level directory. */
|
||||
| ForgeRelatedHead & { readonly name: string; readonly root: string }
|
||||
/** A branch's committed content, with the branch name without its ref prefix. */
|
||||
| ForgeBranchHead & { readonly name: string }
|
||||
/** The branch local changes show in place of the Session's checked-out one. */
|
||||
export interface ChangesHead {
|
||||
/** Full ref name of the branch. */
|
||||
readonly ref: string
|
||||
/** The ref without its prefix, which the picker shows. */
|
||||
readonly name: string
|
||||
/**
|
||||
* Top-level directory of the worktree that has the branch checked out, as last listed or read; null when none has,
|
||||
* so the branch has the `branch` scope alone.
|
||||
*/
|
||||
readonly worktree: string | null
|
||||
}
|
||||
|
||||
/** Files a changes tab shows: every file, or the files of one review layer. */
|
||||
export type ChangesLens = 'all' | ForgeFileLayer
|
||||
@@ -59,6 +65,7 @@ export type ChangesActions = {
|
||||
navigated: (draft: ChangesState, tabId: string, revision: number) => void
|
||||
scoped: (draft: ChangesState, tabId: string, scope: ForgeLocalScope['kind']) => void
|
||||
headed: (draft: ChangesState, tabId: string, head: ChangesHead | null) => void
|
||||
rooted: (draft: ChangesState, tabId: string, worktree: string | null) => void
|
||||
based: (draft: ChangesState, tabId: string, base: ForgeBaseBranch | null) => void
|
||||
committed: (draft: ChangesState, tabId: string, commits: ForgeCommitRange | null) => void
|
||||
lensed: (draft: ChangesState, tabId: string, lens: ChangesLens) => void
|
||||
@@ -98,18 +105,31 @@ export const changesActions: ChangesActions = {
|
||||
tab.commits = null
|
||||
},
|
||||
/**
|
||||
* Show local changes of another head, compared with its automatic fork point and with all of its commits. A branch
|
||||
* has no working tree, so choosing one shows the `branch` scope.
|
||||
* Show local changes of another branch, compared with its automatic fork point and with all of its commits. A
|
||||
* branch that no worktree has checked out has no working tree, so choosing one shows the `branch` scope.
|
||||
* @param d - draft state.
|
||||
* @param tabId - the tab being drawn.
|
||||
* @param head - the head, or null for the Session's own checkout.
|
||||
* @param head - the branch, or null for the Session's own checkout.
|
||||
*/
|
||||
headed: (d, tabId: string, head: ChangesHead | null) => {
|
||||
const tab = bucket(d, tabId)
|
||||
tab.head = head
|
||||
tab.base = null
|
||||
tab.commits = null
|
||||
if (head?.kind === 'branch') tab.scope = 'branch'
|
||||
if (head !== null && head.worktree === null) tab.scope = 'branch'
|
||||
},
|
||||
/**
|
||||
* Record where the shown branch's worktree is now, as a read found it; without one the tab shows the `branch`
|
||||
* scope. A tab that shows the Session's own checkout is unchanged.
|
||||
* @param d - draft state.
|
||||
* @param tabId - the tab being drawn.
|
||||
* @param worktree - top-level directory of the worktree, or null when no worktree has the branch checked out.
|
||||
*/
|
||||
rooted: (d, tabId: string, worktree: string | null) => {
|
||||
const tab = bucket(d, tabId)
|
||||
if (tab.head === null) return
|
||||
tab.head = { ...tab.head, worktree }
|
||||
if (worktree === null) tab.scope = 'branch'
|
||||
},
|
||||
/**
|
||||
* Compare the `branch` scope with another branch, showing all of its commits.
|
||||
|
||||
@@ -261,11 +261,8 @@ export const zh = {
|
||||
'diff.baseMissing': '找不到基准分支 {base},它可能已被删除',
|
||||
'diff.baseUnrelated': '{base} 与 HEAD 没有共同历史',
|
||||
'diff.head.aria': '查看的分支:{head}',
|
||||
'diff.head.search': '搜索分支或会话',
|
||||
'diff.head.own': '当前会话',
|
||||
'diff.head.related': '关联会话',
|
||||
'diff.head.empty': '没有匹配的分支或会话',
|
||||
'diff.head.note': '会话的目录包含未提交的修改,其他分支只比较已提交的内容',
|
||||
'diff.head.note': '工作树里的分支包含未提交的修改,其他分支只比较已提交的内容',
|
||||
'diff.head.back': '回到当前会话',
|
||||
'diff.headMissing': '找不到 {head},它可能已被删除',
|
||||
'diff.base.noteCommitted': '与所选分支的合并基准比较,只包含已提交的内容',
|
||||
@@ -945,11 +942,8 @@ export const en: Record<ForgePanelKey, string> = {
|
||||
'diff.baseMissing': 'The base branch {base} was not found; it may have been deleted',
|
||||
'diff.baseUnrelated': '{base} shares no history with HEAD',
|
||||
'diff.head.aria': 'Branch shown: {head}',
|
||||
'diff.head.search': 'Search branches or sessions',
|
||||
'diff.head.own': 'This session',
|
||||
'diff.head.related': 'Related sessions',
|
||||
'diff.head.empty': 'No matching branches or sessions',
|
||||
'diff.head.note': 'A session’s directory includes uncommitted changes; other branches compare committed content only',
|
||||
'diff.head.note': 'A branch in a worktree includes uncommitted changes; other branches compare committed content only',
|
||||
'diff.head.back': 'Back to this session',
|
||||
'diff.headMissing': '{head} was not found; it may have been deleted',
|
||||
'diff.base.noteCommitted': 'Compared with the merge base with the selected branch, committed content only',
|
||||
@@ -1633,11 +1627,8 @@ export const ja: Record<ForgePanelKey, string> = {
|
||||
'diff.baseMissing': '基準ブランチ {base} が見つかりません。削除された可能性があります',
|
||||
'diff.baseUnrelated': '{base} は HEAD と共通の履歴がありません',
|
||||
'diff.head.aria': '表示中のブランチ:{head}',
|
||||
'diff.head.search': 'ブランチまたはセッションを検索',
|
||||
'diff.head.own': 'このセッション',
|
||||
'diff.head.related': '関連セッション',
|
||||
'diff.head.empty': '一致するブランチまたはセッションがありません',
|
||||
'diff.head.note': 'セッションのディレクトリは未コミットの変更を含み、その他のブランチはコミット済みの内容のみを比較します',
|
||||
'diff.head.note': 'ワークツリーにあるブランチは未コミットの変更を含み、その他のブランチはコミット済みの内容のみを比較します',
|
||||
'diff.head.back': 'このセッションに戻る',
|
||||
'diff.headMissing': '{head} が見つかりません。削除された可能性があります',
|
||||
'diff.base.noteCommitted': '選択したブランチとのマージベースと比較、コミット済みの内容のみ',
|
||||
@@ -2314,11 +2305,8 @@ export const es: Record<ForgePanelKey, string> = {
|
||||
'diff.baseMissing': 'No se encontró la rama base {base}; puede que se haya eliminado',
|
||||
'diff.baseUnrelated': '{base} no comparte historial con HEAD',
|
||||
'diff.head.aria': 'Rama mostrada: {head}',
|
||||
'diff.head.search': 'Buscar ramas o sesiones',
|
||||
'diff.head.own': 'Esta sesión',
|
||||
'diff.head.related': 'Sesiones relacionadas',
|
||||
'diff.head.empty': 'No hay ramas ni sesiones coincidentes',
|
||||
'diff.head.note': 'El directorio de una sesión incluye los cambios sin confirmar; las demás ramas solo comparan el contenido confirmado',
|
||||
'diff.head.note': 'Una rama en un árbol de trabajo incluye los cambios sin confirmar; las demás ramas solo comparan el contenido confirmado',
|
||||
'diff.head.back': 'Volver a esta sesión',
|
||||
'diff.headMissing': 'No se encontró {head}; puede que se haya eliminado',
|
||||
'diff.base.noteCommitted': 'Comparado con la base de fusión con la rama elegida, solo el contenido confirmado',
|
||||
@@ -2995,11 +2983,8 @@ export const fr: Record<ForgePanelKey, string> = {
|
||||
'diff.baseMissing': 'La branche de base {base} est introuvable ; elle a peut-être été supprimée',
|
||||
'diff.baseUnrelated': '{base} n’a aucun historique commun avec HEAD',
|
||||
'diff.head.aria': 'Branche affichée : {head}',
|
||||
'diff.head.search': 'Rechercher des branches ou des sessions',
|
||||
'diff.head.own': 'Cette session',
|
||||
'diff.head.related': 'Sessions associées',
|
||||
'diff.head.empty': 'Aucune branche ni session correspondante',
|
||||
'diff.head.note': 'Le répertoire d’une session inclut les modifications non commitées ; les autres branches ne comparent que le contenu commité',
|
||||
'diff.head.note': 'Une branche présente dans un arbre de travail inclut les modifications non commitées ; les autres branches ne comparent que le contenu commité',
|
||||
'diff.head.back': 'Revenir à cette session',
|
||||
'diff.headMissing': '{head} est introuvable ; l’élément a peut-être été supprimé',
|
||||
'diff.base.noteCommitted': 'Comparaison avec la base de fusion avec la branche choisie, contenu commité uniquement',
|
||||
@@ -3676,11 +3661,8 @@ export const de: Record<ForgePanelKey, string> = {
|
||||
'diff.baseMissing': 'Der Basis-Branch {base} wurde nicht gefunden; er wurde möglicherweise gelöscht',
|
||||
'diff.baseUnrelated': '{base} hat keinen gemeinsamen Verlauf mit HEAD',
|
||||
'diff.head.aria': 'Angezeigter Branch: {head}',
|
||||
'diff.head.search': 'Branches oder Sitzungen suchen',
|
||||
'diff.head.own': 'Diese Sitzung',
|
||||
'diff.head.related': 'Verknüpfte Sitzungen',
|
||||
'diff.head.empty': 'Keine passenden Branches oder Sitzungen',
|
||||
'diff.head.note': 'Das Verzeichnis einer Sitzung enthält nicht committete Änderungen; andere Branches vergleichen nur committete Inhalte',
|
||||
'diff.head.note': 'Ein Branch in einem Arbeitsbaum enthält nicht committete Änderungen; andere Branches vergleichen nur committete Inhalte',
|
||||
'diff.head.back': 'Zurück zu dieser Sitzung',
|
||||
'diff.headMissing': '{head} wurde nicht gefunden; möglicherweise wurde es gelöscht',
|
||||
'diff.base.noteCommitted': 'Vergleich mit der Merge-Basis mit dem gewählten Branch, nur committete Inhalte',
|
||||
@@ -4357,11 +4339,8 @@ export const ru: Record<ForgePanelKey, string> = {
|
||||
'diff.baseMissing': 'Базовая ветка {base} не найдена; возможно, она удалена',
|
||||
'diff.baseUnrelated': 'У {base} нет общей истории с HEAD',
|
||||
'diff.head.aria': 'Показанная ветка: {head}',
|
||||
'diff.head.search': 'Поиск веток или сеансов',
|
||||
'diff.head.own': 'Этот сеанс',
|
||||
'diff.head.related': 'Связанные сеансы',
|
||||
'diff.head.empty': 'Нет подходящих веток или сеансов',
|
||||
'diff.head.note': 'Каталог сеанса включает изменения без коммита; для остальных веток сравнивается только закоммиченное содержимое',
|
||||
'diff.head.note': 'Ветка в рабочем дереве включает изменения без коммита; для остальных веток сравнивается только закоммиченное содержимое',
|
||||
'diff.head.back': 'Вернуться к этому сеансу',
|
||||
'diff.headMissing': 'Не удалось найти {head}; возможно, удалено',
|
||||
'diff.base.noteCommitted': 'Сравнение с базой слияния с выбранной веткой, только закоммиченное содержимое',
|
||||
@@ -5038,11 +5017,8 @@ export const pt: Record<ForgePanelKey, string> = {
|
||||
'diff.baseMissing': 'A branch base {base} não foi encontrada; ela pode ter sido excluída',
|
||||
'diff.baseUnrelated': '{base} não compartilha histórico com HEAD',
|
||||
'diff.head.aria': 'Branch exibida: {head}',
|
||||
'diff.head.search': 'Pesquisar branches ou sessões',
|
||||
'diff.head.own': 'Esta sessão',
|
||||
'diff.head.related': 'Sessões relacionadas',
|
||||
'diff.head.empty': 'Nenhuma branch ou sessão correspondente',
|
||||
'diff.head.note': 'O diretório de uma sessão inclui alterações sem commit; as outras branches comparam apenas o conteúdo com commit',
|
||||
'diff.head.note': 'Uma branch em uma árvore de trabalho inclui alterações sem commit; as outras branches comparam apenas o conteúdo com commit',
|
||||
'diff.head.back': 'Voltar para esta sessão',
|
||||
'diff.headMissing': '{head} não foi encontrado; pode ter sido excluído',
|
||||
'diff.base.noteCommitted': 'Comparação com a base de mesclagem com a branch escolhida, apenas conteúdo com commit',
|
||||
|
||||
@@ -393,7 +393,6 @@ function registerUi(ctx: Context): void {
|
||||
localDiff: (scope, signal) => ctx.remote.forgePanel.localDiff(sessionId, scope, signal),
|
||||
localWrite: write => ctx.remote.forgePanel.localWrite(sessionId, write),
|
||||
diffBases: (head, query, signal) => ctx.remote.forgePanel.diffBases(sessionId, head, query, signal),
|
||||
relatedCheckouts: signal => ctx.remote.forgePanel.relatedCheckouts(sessionId, signal),
|
||||
localText: (scope, path) => ctx.remote.forgePanel.localText(sessionId, scope, path),
|
||||
localCommits: (head, base, signal) => ctx.remote.forgePanel.localCommits(sessionId, head, base, signal),
|
||||
changeRequestDiff: (url, commits, signal) => ctx.remote.forgePanel.changeRequestDiff(sessionId, url, commits, signal),
|
||||
|
||||
@@ -129,7 +129,6 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void {
|
||||
localDiff: async () => await Promise.reject(new Error('forge-panel: the review page shows no local changes')),
|
||||
localWrite: async () => await Promise.reject(new Error('forge-panel: the review page shows no local changes')),
|
||||
diffBases: async () => await Promise.reject(new Error('forge-panel: the review page shows no local changes')),
|
||||
relatedCheckouts: async () => await Promise.reject(new Error('forge-panel: the review page shows no local changes')),
|
||||
localText: async () => await Promise.reject(new Error('forge-panel: the review page shows no local changes')),
|
||||
localCommits: async () => await Promise.reject(new Error('forge-panel: the review page shows no local changes')),
|
||||
changeRequestDiff: (url, commits, signal) => remote.reviewDiff(url, commits, signal),
|
||||
|
||||
@@ -47,13 +47,13 @@ export interface ReviewSelection {
|
||||
readonly comment: ReviewComment
|
||||
}
|
||||
|
||||
/** What local changes showed in place of the Session's own checkout when a comment was written. */
|
||||
/** The branch local changes showed in place of the Session's checked-out one when a comment was written. */
|
||||
export interface ReviewHead {
|
||||
/** Identity of the head among the heads of one Session: the related Session's id or the branch's full ref, after its kind. */
|
||||
/** Identity of the head among the heads of one Session: the branch's full ref name. */
|
||||
readonly key: string
|
||||
/** Branch the head showed, or the commit of a detached checkout. */
|
||||
/** Branch name without its ref prefix. */
|
||||
readonly name: string
|
||||
/** Top-level directory of a related Session's checkout, or null for a branch's committed content. */
|
||||
/** Top-level directory of the worktree the changes were read in, or null for a branch read from its commits. */
|
||||
readonly root: string | null
|
||||
}
|
||||
|
||||
|
||||
@@ -25,15 +25,13 @@ import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typer
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import { gitIn, hasBranch, inspectCheckout } from './git.ts'
|
||||
import type { Inspection } from './git.ts'
|
||||
import { branchNameProblem } from './branch-name.ts'
|
||||
import { branchNameProblem, LOCAL_REF_PREFIX } from './branch-name.ts'
|
||||
import { parseDiff } from './diff.ts'
|
||||
import {
|
||||
aheadOf, BaseMissing, baseBranches, branchTip, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, FilterConfigError,
|
||||
forkPoint, HeadMissing, localCommits, localDiff, localOldText, localText, NoForkPoint,
|
||||
aheadOf, BaseMissing, baseBranches, branchTip, branchWorktrees, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge,
|
||||
FilterConfigError, forkPoint, HeadMissing, localCommits, localDiff, localOldText, localText, NoForkPoint,
|
||||
} from './local-diff.ts'
|
||||
import type { ForkPoint } from './local-diff.ts'
|
||||
import { relatedCheckout, relatedCheckouts } from './local-head.ts'
|
||||
import type { RelatedCheckout } from './local-head.ts'
|
||||
import { LocalChangesStale, LocalPathReplaced, localWrite } from './local-write.ts'
|
||||
import { LensCache, LensFailed, lensFrames, LensRegistry, LensWithdrawn, runLens } from './lenses.ts'
|
||||
import type { LensSubject } from './lenses.ts'
|
||||
@@ -50,9 +48,9 @@ import type { KeptPanel, PanelConfig } from './panel.ts'
|
||||
import type {
|
||||
Config, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile,
|
||||
ForgeReviewChangeRequest, ForgeReviewCountFrame, ForgeReviewFrame, ForgeReviewRepository,
|
||||
ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalHead, ForgeLocalScope,
|
||||
ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope,
|
||||
ForgeLocalWrite, ForgeLocalWriteResult,
|
||||
ForgeMissingWorktree, ForgePanelState, ForgeRelatedCheckout, ForgeSessionWorktree, ForgeWorktreeBases, ForgeWorktreeState,
|
||||
ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeBases, ForgeWorktreeState,
|
||||
} from './types.ts'
|
||||
import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts'
|
||||
import type { HeldWork } from './worktree.ts'
|
||||
@@ -66,10 +64,16 @@ declare module '@deepseek-ai/cordis' {
|
||||
}
|
||||
}
|
||||
|
||||
/** What a local read targets: a checkout with the worktree record that fixes its automatic fork point, and the revision shown. */
|
||||
interface LocalTarget extends RelatedCheckout {
|
||||
/** `HEAD` for the checkout's working tree, or the verified ref of a branch whose committed content shows. */
|
||||
/** What a local read targets. */
|
||||
interface LocalTarget {
|
||||
/** The checkout Git runs in: the Session's own, or the worktree that has the head branch checked out. */
|
||||
readonly inspection: Inspection
|
||||
/** The worktree the Session created, while the read targets its own checkout; it fixes the automatic fork point. */
|
||||
readonly created: ForgeSessionWorktree | null
|
||||
/** `HEAD` for the checkout's working tree, or the verified ref of a head branch read from its commits. */
|
||||
readonly tip: string
|
||||
/** Top-level directory of the head branch's worktree, or null for the Session's own checkout and a head read from its commits. */
|
||||
readonly worktree: string | null
|
||||
}
|
||||
|
||||
/** A change request a read or action addresses, with its latest polling result. */
|
||||
@@ -761,43 +765,27 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
}
|
||||
|
||||
/**
|
||||
* List the branches the `branch` scope can compare with, for the Session's current checkout or for a head shown in
|
||||
* its place.
|
||||
* List the branches the `branch` scope can compare with, for the Session's current checkout or for a head branch
|
||||
* read in its place.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param head - what the scope shows in place of the Session's own checkout, or null for that checkout.
|
||||
* @param head - full ref of the branch the scope reads in place of the checked-out one, or null for the checkout.
|
||||
* @param query - text the branch names must contain, ignoring case; empty for every branch.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the automatic fork point and at most `maxBranches` remote-tracking and local branches each,
|
||||
* most recently committed first, without the branch the scope shows.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head is gone; the Git
|
||||
* error when Git fails or the listed refs exceed `maxDiffBytes`.
|
||||
* most recently committed first, without the branch the scope shows; a local branch that a worktree has checked
|
||||
* out names that worktree's directory.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head does not exist; the
|
||||
* Git error when Git fails or the listed refs exceed `maxDiffBytes`.
|
||||
*/
|
||||
@Remote
|
||||
async diffBases(session: Session, head: ForgeLocalHead | null, query: string, signal: AbortSignal): Promise<ForgeBaseBranches> {
|
||||
async diffBases(session: Session, head: string | null, query: string, signal: AbortSignal): Promise<ForgeBaseBranches> {
|
||||
signal.throwIfAborted()
|
||||
const { inspection, created, tip } = await this.localTarget(session, head, signal)
|
||||
const { inspection, created, tip } = await this.localTarget(session, head, false, signal)
|
||||
// A search can match any branch, so every ref is listed; a repository's refs can far exceed other short Git output.
|
||||
const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal)
|
||||
return await baseBranches(git, inspection, created, query, this.config.maxBranches, tip)
|
||||
}
|
||||
|
||||
/**
|
||||
* List the checkouts that Sessions delegated from a Session work in, which a local scope can read in place of the
|
||||
* Session's own checkout. Each listing reads the delegated Sessions' records and inspects their directories again.
|
||||
* @param session - Session whose delegated Sessions are listed.
|
||||
* @param signal - request cancellation.
|
||||
* @returns one entry per checkout other than the Session's own, in catalog order of the first Session working there;
|
||||
* none without the subagent or Session query service. Sessions the caller may not read are left out.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; an error when the subagent catalogs cannot be read.
|
||||
*/
|
||||
@Remote
|
||||
async relatedCheckouts(session: Session, signal: AbortSignal): Promise<readonly ForgeRelatedCheckout[]> {
|
||||
signal.throwIfAborted()
|
||||
const access = this.ctx.get('remoteAccess')
|
||||
return await relatedCheckouts(this.home, this.config, session, await this.checkoutOf(session, signal),
|
||||
id => access === undefined || access.allows({ kind: 'session', id }), signal)
|
||||
}
|
||||
|
||||
/* oxlint-disable typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect */
|
||||
/**
|
||||
* Bind a change request to a Session by URL, or restore a dismissed binding.
|
||||
@@ -856,14 +844,15 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the changes one scope covers in the checkout of the Session's
|
||||
* current directory or in the head the scope names, with Git using the Session's sandbox policy.
|
||||
* Read the changes one scope covers in the checkout of the Session's current directory, or for the head branch the
|
||||
* scope names: in the worktree that has it checked out, else from its commits. Git uses the Session's sandbox policy.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param scope - which changes to read.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the files, the base of the `branch` scope, and the untracked files left out.
|
||||
* @returns the files, the base of the `branch` scope, the untracked files left out, and the worktree read for a head.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head the scope names
|
||||
* is gone; `forgePanel/base-missing` when the base branch
|
||||
* does not exist; `forgePanel/no-working-tree` for another scope than `branch` whose head no worktree has checked
|
||||
* out; `forgePanel/base-missing` when the base branch
|
||||
* chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without
|
||||
* a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order;
|
||||
* `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
|
||||
@@ -873,30 +862,31 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
@Remote
|
||||
async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise<ForgeLocalDiff> {
|
||||
signal.throwIfAborted()
|
||||
const { inspection, created, tip } = await this.localTarget(session, scope.head ?? null, signal)
|
||||
const { inspection, created, tip, worktree } = await this.localTarget(session, scope.head ?? null, scope.kind !== 'branch', signal)
|
||||
const root = inspection.checkout.root
|
||||
const git = gitIn(this.home, this.config, session, root, signal)
|
||||
const fork = scope.kind !== 'branch' ? null
|
||||
: await diffing(scope.base === null ? forkPoint(git, inspection, created, tip) : chosenForkPoint(git, scope.base, tip))
|
||||
return await diffing(localDiff(this.home, this.config, session, root, fork, scope, this.layers, signal))
|
||||
const diff = await diffing(localDiff(this.home, this.config, session, root, fork, scope, this.layers, signal, tip))
|
||||
return worktree === null ? diff : { ...diff, worktree }
|
||||
}
|
||||
|
||||
/**
|
||||
* List the commits of the `branch` scope of the Session's current checkout or of a head shown in its place, which
|
||||
* the changes view can show one or several of instead of the whole scope.
|
||||
* List the commits of the `branch` scope of the Session's current checkout or of a head branch read in its place,
|
||||
* which the changes view can show one or several of instead of the whole scope.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param head - what the scope shows in place of the Session's own checkout, or null for that checkout.
|
||||
* @param head - full ref of the branch the scope reads in place of the checked-out one, or null for the checkout.
|
||||
* @param base - the base ref of the `branch` scope, or null for its automatic fork point.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the newest `maxCommits` commits between the fork point and the shown HEAD or branch, oldest first, and its commit.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head is gone;
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head does not exist;
|
||||
* `forgePanel/base-missing` when the base branch does not exist; `forgePanel/no-fork-point` without a fork point;
|
||||
* the Git error when Git fails or the listing exceeds `maxDiffBytes`.
|
||||
*/
|
||||
@Remote
|
||||
async localCommits(session: Session, head: ForgeLocalHead | null, base: string | null, signal: AbortSignal): Promise<ForgeLocalCommits> {
|
||||
async localCommits(session: Session, head: string | null, base: string | null, signal: AbortSignal): Promise<ForgeLocalCommits> {
|
||||
signal.throwIfAborted()
|
||||
const { inspection, created, tip } = await this.localTarget(session, head, signal)
|
||||
const { inspection, created, tip } = await this.localTarget(session, head, false, signal)
|
||||
const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal)
|
||||
const fork = await diffing(base === null ? forkPoint(git, inspection, created, tip) : chosenForkPoint(git, base, tip))
|
||||
if (fork === null) throw new RemoteError('forgePanel/no-fork-point', 'The checkout has no fork point to compare its branch with', {})
|
||||
@@ -906,22 +896,22 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
/**
|
||||
* Read the new side of one changed file in a scope, which supplies the
|
||||
* unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of
|
||||
* the `branch` scope, the branch for a branch head, else the working tree.
|
||||
* the `branch` scope, the branch for a head read from its commits, else the working tree of the checkout the scope reads.
|
||||
* @param session - Session whose checkout is read.
|
||||
* @param scope - the scope the diff was read in.
|
||||
* @param path - path relative to the checkout's top-level directory, as the diff names it.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the text.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head the scope names
|
||||
* is gone; `forgePanel/diff-too-large` over `maxDiffBytes`;
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` and `forgePanel/no-working-tree`
|
||||
* as for {@link ForgePanelController.localDiff}; `forgePanel/diff-too-large` over `maxDiffBytes`;
|
||||
* `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside
|
||||
* the checkout, binary content, or a failed read.
|
||||
*/
|
||||
@Remote
|
||||
async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise<string> {
|
||||
signal.throwIfAborted()
|
||||
const { inspection } = await this.localTarget(session, scope.head ?? null, signal)
|
||||
return await diffing(localText(this.home, this.config, session, inspection.checkout.root, scope, path, signal))
|
||||
const { inspection, tip } = await this.localTarget(session, scope.head ?? null, scope.kind !== 'branch', signal)
|
||||
return await diffing(localText(this.home, this.config, session, inspection.checkout.root, scope, path, signal, tip))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1596,23 +1586,32 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve what a local read targets: the Session's own checkout with the worktree it created, a related Session's
|
||||
* checkout with the worktree that Session created, or a verified branch of the Session's repository.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head is gone or the
|
||||
* caller may not read the related Session.
|
||||
* Resolve what a local read targets: the Session's own checkout with the worktree it created; for a head branch,
|
||||
* the worktree of the repository that has it checked out, read as a checkout; or, when none has, the verified
|
||||
* branch itself, read from its commits.
|
||||
* @param working - whether the read needs a working tree, as every scope but `branch` does.
|
||||
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the branch does not exist;
|
||||
* `forgePanel/no-working-tree` when `working` and no worktree has the branch checked out.
|
||||
*/
|
||||
private async localTarget(session: Session, head: ForgeLocalHead | null, signal: AbortSignal): Promise<LocalTarget> {
|
||||
if (head === null) return { inspection: await this.checkoutOf(session, signal), created: this.worktreeState(session).created, tip: 'HEAD' }
|
||||
if (head.kind === 'branch') {
|
||||
const inspection = await this.checkoutOf(session, signal)
|
||||
const git = gitIn(this.home, this.config, session, inspection.checkout.root, signal)
|
||||
return { inspection, created: null, tip: await diffing(branchTip(git, head.ref)) }
|
||||
private async localTarget(session: Session, head: string | null, working: boolean, signal: AbortSignal): Promise<LocalTarget> {
|
||||
const own = await this.checkoutOf(session, signal)
|
||||
const ownTarget: LocalTarget = { inspection: own, created: this.worktreeState(session).created, tip: 'HEAD', worktree: null }
|
||||
if (head === null) return ownTarget
|
||||
// Worktree paths are as long as the directories users choose, so the listing takes the larger limit.
|
||||
const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, own.checkout.root, signal)
|
||||
const tip = await diffing(branchTip(git, head))
|
||||
// Only a local branch can be checked out; a remote-tracking one is always read from its commits.
|
||||
const directory = head.startsWith(LOCAL_REF_PREFIX) ? (await branchWorktrees(git)).get(head) : undefined
|
||||
// The directory is as Git's listing spells it, which can be cut short or name one that is gone, so the read
|
||||
// confirms that a checkout of the branch in this repository is there.
|
||||
const inspection = directory === undefined || await this.home.fs.lstat(directory, undefined, signal) === undefined ? undefined
|
||||
: await inspectCheckout(this.home, this.config, session, directory, signal)
|
||||
if (inspection?.commonDir === own.commonDir && inspection.checkout.branch === head.slice(LOCAL_REF_PREFIX.length)) {
|
||||
return inspection.checkout.root === own.checkout.root ? ownTarget
|
||||
: { inspection, created: null, tip: 'HEAD', worktree: inspection.checkout.root }
|
||||
}
|
||||
const access = this.ctx.get('remoteAccess')
|
||||
if (access !== undefined && !access.allows({ kind: 'session', id: head.sessionId })) {
|
||||
throw new RemoteError('forgePanel/head-missing', 'The related Session cannot be read', {})
|
||||
}
|
||||
return { ...await diffing(relatedCheckout(this.home, this.config, session, head.sessionId, signal)), tip: 'HEAD' }
|
||||
if (working) throw new RemoteError('forgePanel/no-working-tree', 'No worktree has the branch checked out, so it has no working tree', {})
|
||||
return { inspection: own, created: null, tip, worktree: null }
|
||||
}
|
||||
|
||||
/** Inspect the checkout of the Session's current directory, which local diffs read. */
|
||||
@@ -1887,12 +1886,12 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
): Promise<LensSubject & { readonly key: string }> {
|
||||
if (source.kind === 'local') {
|
||||
const { scope } = source
|
||||
const { inspection, created, tip } = await this.localTarget(session, scope.head ?? null, signal)
|
||||
const { inspection, created, tip } = await this.localTarget(session, scope.head ?? null, scope.kind !== 'branch', signal)
|
||||
const root = inspection.checkout.root
|
||||
const fork: ForkPoint | null = scope.kind !== 'branch' ? null : await diffing(scope.base === null
|
||||
? forkPoint(gitIn(this.home, this.config, session, root, signal), inspection, created, tip)
|
||||
: chosenForkPoint(gitIn(this.home, this.config, session, root, signal), scope.base, tip))
|
||||
const { files } = await diffing(localDiff(this.home, this.config, session, root, fork, scope, this.layers, signal))
|
||||
const { files } = await diffing(localDiff(this.home, this.config, session, root, fork, scope, this.layers, signal, tip))
|
||||
return {
|
||||
key: JSON.stringify(['local', session.id, scope]),
|
||||
source: { kind: 'local', scope },
|
||||
@@ -1900,7 +1899,7 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
read: async (side, file, inner) => {
|
||||
if (file.binary || (side === 'old' ? file.status === 'added' : file.status === 'deleted')) return null
|
||||
return side === 'new'
|
||||
? await diffing(localText(this.home, this.config, session, root, scope, file.path, inner))
|
||||
? await diffing(localText(this.home, this.config, session, root, scope, file.path, inner, tip))
|
||||
: await diffing(localOldText(this.home, this.config, session, root, scope, fork, file.previousPath ?? file.path, inner))
|
||||
},
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import type { Git, GitConfig, GitOutput, Inspection } from './git.ts'
|
||||
import { ATTRIBUTES_PATH } from './layers.ts'
|
||||
import type { FileLayers } from './layers.ts'
|
||||
import { branchLabel } from './branch-name.ts'
|
||||
import { BASE_REF_PREFIXES, parseBaseBranches, parseName, remoteOrder } from './parse.ts'
|
||||
import { BASE_REF_PREFIXES, parseBaseBranches, parseName, parseWorktrees, remoteOrder } from './parse.ts'
|
||||
import type {
|
||||
ForgeCommitRange, ForgeLocalChanges, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgeBaseBranches, ForgeSessionWorktree,
|
||||
} from './types.ts'
|
||||
@@ -62,7 +62,7 @@ export class BaseMissing extends Error {
|
||||
override name = 'BaseMissing'
|
||||
}
|
||||
|
||||
/** Thrown when the branch a scope shows in place of the checkout does not exist. */
|
||||
/** Thrown when the branch a scope reads in place of the checked-out one does not exist. */
|
||||
export class HeadMissing extends Error {
|
||||
override name = 'HeadMissing'
|
||||
}
|
||||
@@ -183,7 +183,8 @@ async function branchOf(git: Git, ref: string): Promise<{ readonly name: string;
|
||||
* @param query - text the branch names must contain, ignoring case; empty for every branch.
|
||||
* @param limit - most branches in each group.
|
||||
* @param tip - revision the scope shows: HEAD for the checkout, or a branch ref, which the listing leaves out.
|
||||
* @returns the automatic fork point, then remote-tracking and local branches, most recently committed first.
|
||||
* @returns the automatic fork point, then remote-tracking and local branches, most recently committed first; a local
|
||||
* branch that a worktree has checked out names the directory Git registered for it.
|
||||
* @throws an Error when Git fails or prints more than the runner's output limit.
|
||||
*/
|
||||
export async function baseBranches(
|
||||
@@ -199,12 +200,29 @@ export async function baseBranches(
|
||||
'for-each-ref', '--sort=-committerdate', '--format=%(refname)%00%(symref)', ...BASE_REF_PREFIXES,
|
||||
])
|
||||
const shown = tip !== 'HEAD' ? tip : inspection.checkout.branch === null ? null : `${BASE_REF_PREFIXES[0]}${inspection.checkout.branch}`
|
||||
const { remote, local } = parseBaseBranches(refs.stdout, shown, query, limit)
|
||||
const trees = await branchWorktrees(git)
|
||||
return {
|
||||
automatic: fork === null ? null : { name: fork.label, worktree: fork.worktree },
|
||||
...parseBaseBranches(refs.stdout, shown, query, limit),
|
||||
remote,
|
||||
local: local.map((branch) => {
|
||||
const worktree = trees.get(branch.ref)
|
||||
return worktree === undefined ? branch : { ...branch, worktree }
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the worktree of the repository that has each branch checked out.
|
||||
* @param git - runner bound to a checkout of the repository.
|
||||
* @returns the directory Git registered for each checked-out branch, by full ref name, without a worktree that Git
|
||||
* marks as gone and one without a branch. {@link parseWorktrees} says why a caller confirms the directory.
|
||||
* @throws an Error when Git fails or prints more than the runner's output limit.
|
||||
*/
|
||||
export async function branchWorktrees(git: Git): Promise<ReadonlyMap<string, string>> {
|
||||
return parseWorktrees((await git('worktrees', ['worktree', 'list', '--porcelain'])).stdout)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read changes at `root` with command-local clean/process filter overrides and without
|
||||
* submodule working-tree inspection. Git's built-in newline, ident, and encoding conversions still apply.
|
||||
@@ -213,12 +231,14 @@ export async function baseBranches(
|
||||
* @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`.
|
||||
* @param config - Git and size limits.
|
||||
* @param session - Session whose sandbox policy and execution world apply.
|
||||
* @param root - top-level directory of the checkout the scope reads, or of the Session's own for a branch head.
|
||||
* @param root - top-level directory of the checkout the scope reads: the Session's own, or the worktree of its `head`.
|
||||
* @param fork - fork point of the `branch` scope, or null without one.
|
||||
* @param scope - which changes to read; of its `head`, only a branch changes what this function reads.
|
||||
* @param scope - which changes to read; its `head` is already resolved into `root` and `tip`.
|
||||
* @param layers - classifier of each file's review layer.
|
||||
* @param signal - cancellation of every command and read.
|
||||
* @returns tracked files in Git's order, then untracked files unless the scope is `staged` or shows a branch.
|
||||
* @param tip - `HEAD` to read the checkout at `root` with its working tree, or a verified branch ref that the
|
||||
* `branch` scope reads from its commits alone.
|
||||
* @returns tracked files in Git's order, then untracked files unless the scope is `staged` or reads a branch's commits.
|
||||
* @throws NoForkPoint for the `branch` scope without `fork`; FilterConfigError when filter configuration
|
||||
* cannot be read within `maxDiffBytes`; DiffTooLarge for oversized comparison output or `.gitattributes`;
|
||||
* an Error when Git or the `.gitattributes` read fails.
|
||||
@@ -232,14 +252,15 @@ export async function localDiff(
|
||||
scope: ForgeLocalScope,
|
||||
layers: FileLayers,
|
||||
signal: AbortSignal,
|
||||
tip = 'HEAD',
|
||||
): Promise<ForgeLocalDiff> {
|
||||
const git = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal)
|
||||
let range: readonly string[]
|
||||
switch (scope.kind) {
|
||||
case 'branch':
|
||||
if (fork === null) throw new NoForkPoint('The checkout has no fork point to compare its branch with')
|
||||
if (scope.commits !== null) return await commitsDiff(git, fork, scope.commits, layers, tipOf(scope))
|
||||
if (scope.head?.kind === 'branch') return await treeDiff(git, fork, fork.commit, scope.head.ref, layers)
|
||||
if (scope.commits !== null) return await commitsDiff(git, fork, scope.commits, layers, tip)
|
||||
if (tip !== 'HEAD') return await treeDiff(git, fork, fork.commit, tip, layers)
|
||||
range = [fork.commit]
|
||||
break
|
||||
case 'uncommitted': range = [await headOrEmptyTree(git)]; break
|
||||
@@ -271,7 +292,7 @@ export async function localDiff(
|
||||
/**
|
||||
* Read the new side of one file in a scope, which supplies the unchanged
|
||||
* lines between hunks: the index for `staged`, the last chosen commit for
|
||||
* chosen commits of the `branch` scope, the branch for a branch head, else the working tree.
|
||||
* chosen commits of the `branch` scope, the branch for a head read from its commits, else the working tree.
|
||||
* @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`.
|
||||
* @param config - Git and size limits.
|
||||
* @param session - Session whose sandbox policy and execution world apply.
|
||||
@@ -279,6 +300,7 @@ export async function localDiff(
|
||||
* @param scope - the scope whose new side to read.
|
||||
* @param path - path relative to `root`, as the diff names it.
|
||||
* @param signal - cancellation.
|
||||
* @param tip - `HEAD` for the checkout at `root`, or a verified branch ref whose commits the `branch` scope reads.
|
||||
* @returns the text.
|
||||
* @throws DiffTooLarge over `maxDiffBytes`; an Error for a path outside the checkout, binary content, or a failed read.
|
||||
*/
|
||||
@@ -290,13 +312,13 @@ export async function localText(
|
||||
scope: ForgeLocalScope,
|
||||
path: string,
|
||||
signal: AbortSignal,
|
||||
tip = 'HEAD',
|
||||
): Promise<string> {
|
||||
if (!insideCheckout(path)) throw new Error(`forge-panel: ${JSON.stringify(path)} is not a path inside the checkout`)
|
||||
let text: string | undefined
|
||||
const chosen = scope.kind === 'branch' && scope.commits !== null ? scope.commits.to : undefined
|
||||
if (chosen !== undefined && !COMMIT.test(chosen)) throw new CommitsMissing('The chosen commit is not a full object name')
|
||||
// A branch head arrives verified as an existing branch ref.
|
||||
const commit = scope.kind === 'staged' ? '' : chosen ?? (scope.kind === 'branch' && scope.head?.kind === 'branch' ? scope.head.ref : undefined)
|
||||
const commit = scope.kind === 'staged' ? '' : chosen ?? (scope.kind === 'branch' && tip !== 'HEAD' ? tip : undefined)
|
||||
if (commit !== undefined) {
|
||||
const git = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal)
|
||||
const shown = (await bounded(git('show', ['show', `${commit}:${path}`]))).stdout
|
||||
@@ -438,11 +460,6 @@ async function branchCommits(git: Git, fork: ForkPoint, tip: string, limit?: num
|
||||
})
|
||||
}
|
||||
|
||||
/** The revision the `branch` scope ends at: a branch head's ref, else HEAD of the checkout. */
|
||||
function tipOf(scope: Extract<ForgeLocalScope, { kind: 'branch' }>): string {
|
||||
return scope.head?.kind === 'branch' ? scope.head.ref : 'HEAD'
|
||||
}
|
||||
|
||||
/** The committed changes of consecutive commits of the `branch` scope, from the first commit's first parent to the last. */
|
||||
async function commitsDiff(git: Git, fork: ForkPoint, chosen: ForgeCommitRange, layers: FileLayers, tip: string): Promise<ForgeLocalDiff> {
|
||||
if (!COMMIT.test(chosen.from) || !COMMIT.test(chosen.to)) throw new CommitsMissing('The chosen commits are not full object names')
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
/**
|
||||
* The checkouts of Sessions delegated from a reading Session, which a local scope can read in place of the reading
|
||||
* Session's own. Each is found through the related Session's records, without resuming it, and inspected with the
|
||||
* reading Session's permissions.
|
||||
*/
|
||||
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {} from '@deepseek-ai/dsh-experimental-worktree'
|
||||
import type { Session, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type {} from '@deepseek-ai/dsh-session-query'
|
||||
import type {} from '@deepseek-ai/dsh-subagent'
|
||||
import type {} from '@deepseek-ai/dsh-working-directory'
|
||||
import { inspectCheckout } from './git.ts'
|
||||
import type { GitConfig, Inspection } from './git.ts'
|
||||
import { HeadMissing } from './local-diff.ts'
|
||||
import type { ForgeRelatedCheckout, ForgeSessionWorktree } from './types.ts'
|
||||
|
||||
/** A related Session's checkout and the worktree record that fixes its automatic fork point. */
|
||||
export interface RelatedCheckout {
|
||||
/** The checkout of the related Session's current directory. */
|
||||
readonly inspection: Inspection
|
||||
/** The worktree that Session created at the checkout, or null when it works in a checkout it did not create. */
|
||||
readonly created: ForgeSessionWorktree | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the checkout a Session delegated from the reading Session works in.
|
||||
* @param ctx - context that provides `fs`, `subprocess`, `sandbox`, `sandboxPolicy`, and an optional `sessionQuery`.
|
||||
* @param config - executable and process limits.
|
||||
* @param session - reading Session, whose sandbox policy and execution world Git uses.
|
||||
* @param sessionId - Session a `session` head names.
|
||||
* @param signal - cancellation of every read and command.
|
||||
* @returns the checkout and the worktree record of the related Session.
|
||||
* @throws HeadMissing without the Session query service, when the named Session is unknown or was not delegated from
|
||||
* the reading Session at any depth, or when its directory is gone or outside a checkout; an Error when Git fails.
|
||||
*/
|
||||
export async function relatedCheckout(
|
||||
ctx: Context, config: GitConfig, session: Session, sessionId: SessionId, signal: AbortSignal,
|
||||
): Promise<RelatedCheckout> {
|
||||
const seen = new Set<SessionId>()
|
||||
for (let current = sessionId; current !== session.id;) {
|
||||
// A header chain that returns to a Session it left names no ancestor.
|
||||
if (seen.has(current)) throw new HeadMissing(`Session ${sessionId} was not delegated from this Session`)
|
||||
seen.add(current)
|
||||
current = await delegatingSession(ctx, current, sessionId, signal)
|
||||
}
|
||||
return await checkoutOf(ctx, config, session, sessionId, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* List the checkouts that Sessions delegated from the reading Session work in, leaving out the reading Session's own.
|
||||
* Sessions that share a checkout make one entry. A Session whose directory is gone or outside a checkout is left out;
|
||||
* one whose checkout Git cannot inspect is left out with a warning.
|
||||
* @param ctx - context that provides `fs`, `subprocess`, `sandbox`, `sandboxPolicy`, and optional `subagents` and `sessionQuery`.
|
||||
* @param config - executable and process limits.
|
||||
* @param session - reading Session, whose sandbox policy and execution world Git uses.
|
||||
* @param own - the reading Session's checkout.
|
||||
* @param allowed - whether the caller may read a Session.
|
||||
* @param signal - cancellation of every read and command.
|
||||
* @returns the checkouts in catalog order of their first Session, or none without the subagent or Session query service.
|
||||
* @throws when the subagent catalogs cannot be read or `signal` aborts.
|
||||
*/
|
||||
export async function relatedCheckouts(
|
||||
ctx: Context, config: GitConfig, session: Session, own: Inspection, allowed: (sessionId: SessionId) => boolean, signal: AbortSignal,
|
||||
): Promise<ForgeRelatedCheckout[]> {
|
||||
const subagents = ctx.get('subagents')
|
||||
if (subagents === undefined || ctx.get('sessionQuery') === undefined) return []
|
||||
const byRoot = new Map<string, ForgeRelatedCheckout & { readonly labels: string[] }>()
|
||||
for (const row of await subagents.listDescendants(session.id, signal)) {
|
||||
// An external execution keeps no local Session whose directory could be read.
|
||||
if (row.kind !== 'child' || row.mode === 'external' || !allowed(row.id)) continue
|
||||
let inspection: Inspection
|
||||
try {
|
||||
({ inspection } = await checkoutOf(ctx, config, session, row.id, signal))
|
||||
} catch (error) {
|
||||
signal.throwIfAborted()
|
||||
if (!(error instanceof HeadMissing)) ctx.logger.warn(`forge-panel: inspecting the checkout of Session ${row.id} failed: ${String(error)}`)
|
||||
continue
|
||||
}
|
||||
const { root, branch, commit } = inspection.checkout
|
||||
if (root === own.checkout.root) continue
|
||||
const label = row.label ?? row.path ?? row.id
|
||||
const entry = byRoot.get(root)
|
||||
if (entry === undefined) byRoot.set(root, { sessionId: row.id, root, branch, commit, labels: [label] })
|
||||
else entry.labels.push(label)
|
||||
}
|
||||
return [...byRoot.values()]
|
||||
}
|
||||
|
||||
/** The Session that delegated to `current`, read from its header. */
|
||||
async function delegatingSession(ctx: Context, current: SessionId, named: SessionId, signal: AbortSignal): Promise<SessionId> {
|
||||
using observed = await observe(ctx, current, named, signal)
|
||||
const { origin, parentSession } = observed.header
|
||||
if (origin !== 'subagent' || parentSession === undefined) throw new HeadMissing(`Session ${named} was not delegated from this Session`)
|
||||
return parentSession
|
||||
}
|
||||
|
||||
/** Inspect the checkout of a Session's recorded directory and pick the worktree it created there. */
|
||||
async function checkoutOf(
|
||||
ctx: Context, config: GitConfig, session: Session, sessionId: SessionId, signal: AbortSignal,
|
||||
): Promise<RelatedCheckout> {
|
||||
let directory: string | undefined
|
||||
let worktrees: readonly ForgeSessionWorktree[]
|
||||
{
|
||||
using observed = await observe(ctx, sessionId, sessionId, signal)
|
||||
const values = observed.projections?.values
|
||||
directory = values?.workingDirectory ?? observed.header.cwd
|
||||
worktrees = (values?.worktree ?? []).map(({ worktree }) => ({ ...worktree, from: null }))
|
||||
}
|
||||
if (directory === undefined || await ctx.fs.lstat(directory, undefined, signal) === undefined) {
|
||||
throw new HeadMissing(`The directory of Session ${sessionId} is gone`)
|
||||
}
|
||||
const inspection = await inspectCheckout(ctx, config, session, directory, signal)
|
||||
if (inspection === undefined) throw new HeadMissing(`The directory of Session ${sessionId} is not inside a Git checkout`)
|
||||
return { inspection, created: worktrees.find(worktree => worktree.path === inspection.checkout.root) ?? null }
|
||||
}
|
||||
|
||||
/** Observe a Session's records without attaching it; an unknown Session and a missing query service are a missing head. */
|
||||
async function observe(ctx: Context, sessionId: SessionId, named: SessionId, signal: AbortSignal) {
|
||||
const query = ctx.get('sessionQuery')
|
||||
if (query === undefined) throw new HeadMissing('Reading another Session\'s checkout needs the sessionQuery service')
|
||||
try {
|
||||
return await query.observeSession(sessionId, { signal })
|
||||
} catch (error) {
|
||||
if (error instanceof Error && 'code' in error && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
|
||||
throw new HeadMissing(`Session ${named} has no records`, { cause: error })
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,28 @@ export function parseBaseBranches(
|
||||
return { remote, local }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read which worktree has each branch checked out from `git worktree list --porcelain` output: one block of lines for
|
||||
* each worktree, ended by an empty line. The NUL-separated form of the listing needs Git 2.36, so the lines are read
|
||||
* instead; a directory whose name holds a line break is cut at the break, and Git before 2.31 does not mark a worktree
|
||||
* whose directory is gone, so a caller confirms the directory before it reads there.
|
||||
* @param output - stdout of the listing.
|
||||
* @returns the directory of each worktree by the full ref of its branch, without detached, bare, and prunable entries.
|
||||
*/
|
||||
export function parseWorktrees(output: string): Map<string, string> {
|
||||
const found = new Map<string, string>()
|
||||
for (const entry of output.split('\n\n')) {
|
||||
const fields = entry.split('\n')
|
||||
const value = (name: string): string | undefined => fields.find(field => field.startsWith(`${name} `))?.slice(name.length + 1)
|
||||
const path = value('worktree')
|
||||
const branch = value('branch')
|
||||
// A prunable entry names a directory that is gone; its branch can only be read from its commits.
|
||||
if (path === undefined || branch === undefined || fields.some(field => field === 'prunable' || field.startsWith('prunable '))) continue
|
||||
found.set(branch, path)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the branches a new worktree can start from out of `git for-each-ref` output, keeping its order within
|
||||
* each group: the checked-out branch, each remote's default branch, the other local branches, and the other
|
||||
|
||||
@@ -7,7 +7,6 @@ import type {
|
||||
ForgeReadiness, ForgeRepository, ForgeViewerFilter,
|
||||
} from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session/types'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
|
||||
/** Git facts for the checkout that contains the Session's current directory. */
|
||||
export interface ForgeCheckout {
|
||||
@@ -348,6 +347,11 @@ export interface ForgeBaseBranch {
|
||||
readonly ref: string
|
||||
/** The ref without `refs/heads/` or `refs/remotes/`, such as `master` or `origin/master`. */
|
||||
readonly name: string
|
||||
/**
|
||||
* Directory Git registered for the worktree that has this local branch checked out, absent when none has; a scope
|
||||
* that names the branch as its head reads that worktree.
|
||||
*/
|
||||
readonly worktree?: string
|
||||
}
|
||||
|
||||
/** What the `branch` scope compares with while no base branch is chosen. */
|
||||
@@ -364,7 +368,7 @@ export interface ForgeBaseBranches {
|
||||
readonly automatic: ForgeAutomaticBase | null
|
||||
/** Remote-tracking branches without symbolic refs such as `origin/HEAD`, most recently committed first, at most `maxBranches`. */
|
||||
readonly remote: readonly ForgeBaseBranch[]
|
||||
/** Local branches other than the checked-out one, most recently committed first, at most `maxBranches`. */
|
||||
/** Local branches other than the one the scope shows, most recently committed first, at most `maxBranches`. */
|
||||
readonly local: readonly ForgeBaseBranch[]
|
||||
}
|
||||
|
||||
@@ -379,56 +383,27 @@ export interface ForgeCommitRange {
|
||||
readonly to: string
|
||||
}
|
||||
|
||||
/** A checkout other than the Session's own whose working tree a local scope reads. */
|
||||
export interface ForgeRelatedHead {
|
||||
readonly kind: 'session'
|
||||
/** Session delegated from the reading Session, at any depth; the scope reads the checkout of its current directory. */
|
||||
readonly sessionId: SessionId
|
||||
}
|
||||
|
||||
/** A branch whose committed content the `branch` scope reads; no working tree is involved. */
|
||||
export interface ForgeBranchHead {
|
||||
readonly kind: 'branch'
|
||||
/** Full ref name under `refs/heads/` or `refs/remotes/`. */
|
||||
readonly ref: string
|
||||
}
|
||||
|
||||
/** What the `branch` scope shows in place of the Session's own checkout. */
|
||||
export type ForgeLocalHead = ForgeRelatedHead | ForgeBranchHead
|
||||
|
||||
/**
|
||||
* Which local changes a diff covers. Without `head` each reads the checkout of the Session's current directory through
|
||||
* Git; with one, the related Session's checkout, or for the `branch` scope a branch's committed content, where HEAD
|
||||
* below names that branch and no uncommitted or untracked file shows.
|
||||
* Git. With `head`, the full ref name of a branch under `refs/heads/` or `refs/remotes/`, it reads that branch in place
|
||||
* of the checked-out one: in the worktree of the repository that has the branch checked out, where every scope applies
|
||||
* and HEAD below is that worktree's, or, when no worktree has it, from the branch's commits, where only the `branch`
|
||||
* scope applies and no uncommitted or untracked file shows.
|
||||
*/
|
||||
export type ForgeLocalScope =
|
||||
/**
|
||||
* The working tree and untracked files against a fork point: the merge base of HEAD with the
|
||||
* `base` ref, or while `base` is null, the base commit of the worktree the checkout's Session created,
|
||||
* else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes
|
||||
* of those commits between the fork point and HEAD, without uncommitted or untracked files.
|
||||
* `base` ref, or while `base` is null, the base commit of the worktree the Session created when it reads its own
|
||||
* checkout, else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the
|
||||
* changes of those commits between the fork point and HEAD, without uncommitted or untracked files.
|
||||
*/
|
||||
| { readonly kind: 'branch'; readonly head?: ForgeLocalHead; readonly base: string | null; readonly commits: ForgeCommitRange | null }
|
||||
| { readonly kind: 'branch'; readonly head?: string; readonly base: string | null; readonly commits: ForgeCommitRange | null }
|
||||
/** The working tree and untracked files against HEAD. */
|
||||
| { readonly kind: 'uncommitted'; readonly head?: ForgeRelatedHead }
|
||||
| { readonly kind: 'uncommitted'; readonly head?: string }
|
||||
/** The working tree and untracked files against the index. */
|
||||
| { readonly kind: 'unstaged'; readonly head?: ForgeRelatedHead }
|
||||
| { readonly kind: 'unstaged'; readonly head?: string }
|
||||
/** The index against HEAD. */
|
||||
| { readonly kind: 'staged'; readonly head?: ForgeRelatedHead }
|
||||
|
||||
/** A checkout that Sessions delegated from the reading Session work in, other than the reading Session's own. */
|
||||
export interface ForgeRelatedCheckout {
|
||||
/** The first of those Sessions in catalog order; a `session` head names the checkout by it. */
|
||||
readonly sessionId: SessionId
|
||||
/** Canonical top-level directory of the checkout. */
|
||||
readonly root: string
|
||||
/** Checked-out branch, or null when HEAD is detached. */
|
||||
readonly branch: string | null
|
||||
/** Abbreviated commit HEAD names, or null while the checked-out branch has no commit. */
|
||||
readonly commit: string | null
|
||||
/** What each Session working there was asked to do, or its name where no description was recorded, in catalog order. */
|
||||
readonly labels: readonly string[]
|
||||
}
|
||||
| { readonly kind: 'staged'; readonly head?: string }
|
||||
|
||||
/** One hunk of a file diff. */
|
||||
export interface ForgeDiffHunk {
|
||||
@@ -493,6 +468,11 @@ export interface ForgeLocalDiff {
|
||||
readonly files: readonly ForgeDiffFile[]
|
||||
/** Untracked files left out beyond `maxUntrackedFiles`. */
|
||||
readonly omitted: number
|
||||
/**
|
||||
* Top-level directory of the worktree the scope read for its `head`; absent for the Session's own checkout and for
|
||||
* a head read from its commits.
|
||||
*/
|
||||
readonly worktree?: string
|
||||
}
|
||||
|
||||
/** One file of a local write, as the `unstaged` scope listed it for the reader. */
|
||||
@@ -786,11 +766,13 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
'forgePanel/no-fork-point': Record<string, never>
|
||||
/** The base branch chosen for the `branch` scope does not exist, as after the branch was deleted. */
|
||||
'forgePanel/base-missing': Record<string, never>
|
||||
/**
|
||||
* What a local scope reads in place of the Session's own checkout is gone: the branch was deleted, the related
|
||||
* Session is not delegated from the reading Session, or its directory is no longer a checkout.
|
||||
*/
|
||||
/** The branch a local scope reads in place of the checked-out one does not exist, as after the branch was deleted. */
|
||||
'forgePanel/head-missing': Record<string, never>
|
||||
/**
|
||||
* A scope other than `branch` named a branch that no worktree has checked out, as after its worktree was removed;
|
||||
* only the `branch` scope reads such a branch.
|
||||
*/
|
||||
'forgePanel/no-working-tree': Record<string, never>
|
||||
/** Filter configuration could not be read completely; no comparison ran. Correct Git settings or the output limit before retrying. */
|
||||
'forgePanel/filter-config-failed': Record<string, never>
|
||||
/**
|
||||
|
||||
@@ -57,20 +57,38 @@ describe('changesDefinition', () => {
|
||||
})
|
||||
|
||||
describe('createChangesStore', () => {
|
||||
it('shows another head with its automatic base and every commit, and the branch scope for a branch', () => {
|
||||
it('shows another branch with its automatic base and every commit, and the branch scope alone without a worktree', () => {
|
||||
const store = createChangesStore().create()
|
||||
const tab = (): unknown => store.getSnapshot().byTab['tab-1']
|
||||
store.actions.navigated('tab-1', 1)
|
||||
store.actions.scoped('tab-1', 'staged')
|
||||
store.actions.based('tab-1', { ref: 'refs/heads/topic', name: 'topic' })
|
||||
store.actions.committed('tab-1', { from: 'a'.repeat(40), to: 'b'.repeat(40) })
|
||||
const related = { kind: 'session', sessionId: brandString<SessionId>('child-1'), name: 'cache', root: '/work/cache' } as const
|
||||
store.actions.headed('tab-1', related)
|
||||
expect(store.getSnapshot().byTab['tab-1']).toMatchObject({ scope: 'staged', head: related, base: null, commits: null })
|
||||
const branch = { kind: 'branch', ref: 'refs/heads/topic', name: 'topic' } as const
|
||||
store.actions.headed('tab-1', branch)
|
||||
expect(store.getSnapshot().byTab['tab-1']).toMatchObject({ scope: 'branch', head: branch })
|
||||
const checkedOut = { ref: 'refs/heads/cache', name: 'cache', worktree: '/work/cache' }
|
||||
store.actions.headed('tab-1', checkedOut)
|
||||
expect(tab()).toMatchObject({ scope: 'staged', head: checkedOut, base: null, commits: null })
|
||||
const committed = { ref: 'refs/heads/topic', name: 'topic', worktree: null }
|
||||
store.actions.headed('tab-1', committed)
|
||||
expect(tab()).toMatchObject({ scope: 'branch', head: committed })
|
||||
store.actions.headed('tab-1', null)
|
||||
expect(store.getSnapshot().byTab['tab-1']).toMatchObject({ scope: 'branch', head: null })
|
||||
expect(tab()).toMatchObject({ scope: 'branch', head: null })
|
||||
})
|
||||
|
||||
it('records the worktree a read found for the shown branch, and the branch scope once it has none', () => {
|
||||
const store = createChangesStore().create()
|
||||
const tab = (): unknown => store.getSnapshot().byTab['tab-1']
|
||||
store.actions.navigated('tab-1', 1)
|
||||
store.actions.scoped('tab-1', 'unstaged')
|
||||
// The Session's own checkout has no worktree to record.
|
||||
store.actions.rooted('tab-1', '/work/cache')
|
||||
expect(tab()).toMatchObject({ scope: 'unstaged', head: null })
|
||||
|
||||
store.actions.headed('tab-1', { ref: 'refs/heads/topic', name: 'topic', worktree: null })
|
||||
store.actions.rooted('tab-1', '/work/topic')
|
||||
expect(tab()).toMatchObject({ scope: 'branch', head: { ref: 'refs/heads/topic', name: 'topic', worktree: '/work/topic' } })
|
||||
store.actions.scoped('tab-1', 'unstaged')
|
||||
store.actions.rooted('tab-1', null)
|
||||
expect(tab()).toMatchObject({ scope: 'branch', head: { ref: 'refs/heads/topic', name: 'topic', worktree: null } })
|
||||
})
|
||||
|
||||
it('seeds a tab on its first navigation, keeps its choices, and forgets it', () => {
|
||||
|
||||
@@ -29,7 +29,6 @@ import treeCss from '../src/client/ChangedFiles.module.css'
|
||||
import threadCss from '../src/client/ReviewThreads.module.css'
|
||||
import type {
|
||||
ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeExtensionState, ForgeLensId, ForgeLocalDiff,
|
||||
ForgeRelatedCheckout,
|
||||
ForgePanelChangeRequest, ForgePanelState,
|
||||
} from '../src/types.ts'
|
||||
import type {
|
||||
@@ -150,11 +149,6 @@ const BASES: ForgeBaseBranches = {
|
||||
local: [TOPIC],
|
||||
}
|
||||
|
||||
/** Two delegated Sessions share the `cache` worktree; nothing else is related. */
|
||||
const RELATED: readonly ForgeRelatedCheckout[] = [{
|
||||
sessionId: brandString<SessionId>('child-1'), root: '/work/repo/.agents/worktrees/cache', branch: 'cache', commit: 'abc1234', labels: ['Add a cache', 'Check the cache'],
|
||||
}]
|
||||
|
||||
/** Panel state of `/work/repo` on `main` whose `branch` scope changes `src/app.ts` against `origin/main`. */
|
||||
const LOCAL_STATE = ready({ local: { base: BASE, files: [{ path: 'src/app.ts', additions: 2, deletions: 2, binary: false }] } })
|
||||
/** Panel state with change request #7 from `feat`. */
|
||||
@@ -322,7 +316,6 @@ function mount(options: MountOptions = {}) {
|
||||
localDiff: vi.fn<ChangesTabInjected['localDiff']>(async () => ok(LOCAL)),
|
||||
localWrite: vi.fn<ChangesTabInjected['localWrite']>(async () => ok({ undo: 'tree-1' })),
|
||||
diffBases: vi.fn<ChangesTabInjected['diffBases']>(async () => ok(BASES)),
|
||||
relatedCheckouts: vi.fn<ChangesTabInjected['relatedCheckouts']>(async () => ok(RELATED)),
|
||||
localText: vi.fn<ChangesTabInjected['localText']>(async () => ok(APP_TEXT)),
|
||||
changeRequestDiff: vi.fn<ChangesTabInjected['changeRequestDiff']>(async () => ok(CHANGE)),
|
||||
changeRequestText: vi.fn<ChangesTabInjected['changeRequestText']>(async () => ok(APP_TEXT)),
|
||||
@@ -3344,47 +3337,55 @@ describe('ChangesTab local writes', () => {
|
||||
})
|
||||
|
||||
describe('ChangesTab heads', () => {
|
||||
const CACHE = { kind: 'session', sessionId: brandString<SessionId>('child-1') } as const
|
||||
const CACHE_HEAD = { ...CACHE, name: 'cache', root: '/work/repo/.agents/worktrees/cache' }
|
||||
const TOPIC_HEAD = { kind: 'branch', ref: TOPIC.ref, name: 'topic' } as const
|
||||
const CACHE_ROOT = '/work/repo/.agents/worktrees/cache'
|
||||
/** `cache` is checked out in a worktree of the repository; no worktree has `topic`. */
|
||||
const CACHE: ForgeBaseBranch = { ref: 'refs/heads/cache', name: 'cache', worktree: CACHE_ROOT }
|
||||
const CACHE_HEAD = { ref: CACHE.ref, name: 'cache', worktree: CACHE_ROOT }
|
||||
const TOPIC_HEAD = { ref: TOPIC.ref, name: 'topic', worktree: null }
|
||||
const head = (m: ReturnType<typeof mount>): HTMLElement | null => m.view.container.querySelector('[data-forge-head]')
|
||||
/** The Host reads `cache` in its worktree and every other branch from its commits. */
|
||||
const worktrees = (faces: Faces): void => {
|
||||
faces.diffBases.mockImplementation(async () => ok({ ...BASES, local: [TOPIC, CACHE] }))
|
||||
faces.localDiff.mockImplementation(async scope => ok(scope.head === CACHE.ref ? { ...LOCAL, worktree: CACHE_ROOT } : LOCAL))
|
||||
}
|
||||
|
||||
it('shows a related Session\'s checkout chosen in the head picker, read-only and without other plugins\' additions', async () => {
|
||||
it('shows a branch that a worktree has checked out with every scope, read-only and without other plugins\' additions', async () => {
|
||||
const annotation = { key: 'n1', place: { side: 'R' as const, startLine: 4, endLine: 4 }, version: 1 }
|
||||
const m = mount({ annotations: new Map([['src/app.ts', [{ source: 'notes', annotation }]]]) })
|
||||
const m = mount({ annotations: new Map([['src/app.ts', [{ source: 'notes', annotation }]]]), setup: worktrees })
|
||||
await settle()
|
||||
expect(m.view.getByRole('button', { name: en['changes.local.create'] })).toBeTruthy()
|
||||
expect(m.section('src/app.ts').querySelector('[data-forge-annotation]')).not.toBeNull()
|
||||
|
||||
fireEvent.click(m.view.getByRole('button', { name: 'Branch shown: main' }))
|
||||
await settle()
|
||||
expect(m.faces.relatedCheckouts).toHaveBeenCalledTimes(1)
|
||||
// The branches a reader can show are those of the Session's own checkout.
|
||||
expect(m.faces.diffBases).toHaveBeenLastCalledWith(null, '', expect.any(AbortSignal))
|
||||
m.slotCalls.length = 0
|
||||
fireEvent.click(m.view.getByRole('menuitem', { name: /^cache/ }))
|
||||
expect(m.store.getSnapshot().byTab[TAB]?.head).toEqual(CACHE_HEAD)
|
||||
expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'branch', head: CACHE, base: null, commits: null }, expect.any(AbortSignal))
|
||||
expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'branch', head: CACHE.ref, base: null, commits: null }, expect.any(AbortSignal))
|
||||
await settle()
|
||||
expect(head(m)?.textContent).toBe('cache')
|
||||
expect(head(m)?.getAttribute('data-forge-head')).toBe('session:child-1')
|
||||
expect(head(m)?.getAttribute('data-forge-head')).toBe(CACHE.ref)
|
||||
expect(m.view.getByRole('button', { name: 'Base branch: origin/main' })).toBeTruthy()
|
||||
expect(m.view.getByText(en['diff.base.uncommitted'])).toBeTruthy()
|
||||
expect(m.faces.localCommits).toHaveBeenLastCalledWith(CACHE, null, expect.any(AbortSignal))
|
||||
expect(m.faces.localCommits).toHaveBeenLastCalledWith(CACHE.ref, null, expect.any(AbortSignal))
|
||||
expect(m.view.queryByRole('button', { name: en['changes.local.create'] })).toBeNull()
|
||||
expect(m.slotCalls).toEqual([])
|
||||
expect(m.section('src/app.ts').querySelector('[data-forge-annotation]')).toBeNull()
|
||||
|
||||
fireEvent.click(m.view.getByRole('button', { name: 'Base branch: origin/main' }))
|
||||
await settle()
|
||||
expect(m.faces.diffBases).toHaveBeenLastCalledWith(CACHE, '', expect.any(AbortSignal))
|
||||
expect(m.faces.diffBases).toHaveBeenLastCalledWith(CACHE.ref, '', expect.any(AbortSignal))
|
||||
expect(within(document.body).getByText(en['diff.base.note'])).toBeTruthy()
|
||||
fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' })
|
||||
|
||||
// The other scopes keep the picker and offer no write in a checkout the Session does not own.
|
||||
expect(m.view.container.querySelector('[data-forge-scope]')).not.toBeNull()
|
||||
act(() => { m.store.actions.scoped(TAB, 'unstaged') })
|
||||
await settle()
|
||||
expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'unstaged', head: CACHE }, expect.any(AbortSignal))
|
||||
expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'unstaged', head: CACHE.ref }, expect.any(AbortSignal))
|
||||
expect(m.store.getSnapshot().byTab[TAB]).toMatchObject({ scope: 'unstaged', head: CACHE_HEAD })
|
||||
expect(head(m)?.textContent).toBe('cache')
|
||||
expect(m.view.getByText(en['diff.scopeNote.unstaged'])).toBeTruthy()
|
||||
expect(m.view.container.querySelector('[data-forge-write], [data-forge-write-all]')).toBeNull()
|
||||
@@ -3393,17 +3394,16 @@ describe('ChangesTab heads', () => {
|
||||
expect(m.slotCalls).toEqual([])
|
||||
})
|
||||
|
||||
it('shows another branch\'s committed content in the branch scope alone, then the own checkout again', async () => {
|
||||
it('shows the committed content of a branch without a worktree in the branch scope alone, then the own checkout again', async () => {
|
||||
const m = mount()
|
||||
await settle()
|
||||
act(() => { m.store.actions.scoped(TAB, 'staged') })
|
||||
await settle()
|
||||
act(() => { m.store.actions.headed(TAB, TOPIC_HEAD) })
|
||||
expect(m.store.getSnapshot().byTab[TAB]).toMatchObject({ scope: 'branch', head: TOPIC_HEAD, base: null, commits: null })
|
||||
expect(m.faces.localDiff).toHaveBeenLastCalledWith(
|
||||
{ kind: 'branch', head: { kind: 'branch', ref: TOPIC.ref }, base: null, commits: null }, expect.any(AbortSignal))
|
||||
expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'branch', head: TOPIC.ref, base: null, commits: null }, expect.any(AbortSignal))
|
||||
await settle()
|
||||
expect(head(m)?.getAttribute('data-forge-head')).toBe('branch:refs/heads/topic')
|
||||
expect(head(m)?.getAttribute('data-forge-head')).toBe(TOPIC.ref)
|
||||
expect(m.view.container.querySelector('[data-forge-scope]')).toBeNull()
|
||||
expect(m.view.queryByText(en['diff.base.uncommitted'])).toBeNull()
|
||||
fireEvent.click(m.view.getByRole('button', { name: 'Base branch: origin/main' }))
|
||||
@@ -3418,6 +3418,28 @@ describe('ChangesTab heads', () => {
|
||||
expect(head(m)?.textContent).toBe('main')
|
||||
})
|
||||
|
||||
it('follows a worktree added or removed since the branch was listed', async () => {
|
||||
const m = mount({ setup: worktrees })
|
||||
await settle()
|
||||
// The listing said no worktree has `cache`; the read found one, so every scope becomes available.
|
||||
act(() => { m.store.actions.headed(TAB, { ...CACHE_HEAD, worktree: null }) })
|
||||
await settle()
|
||||
expect(m.store.getSnapshot().byTab[TAB]?.head).toEqual(CACHE_HEAD)
|
||||
expect(m.view.container.querySelector('[data-forge-scope]')).not.toBeNull()
|
||||
expect(m.view.getByText(en['diff.base.uncommitted'])).toBeTruthy()
|
||||
|
||||
// The worktree is gone by the next read of its unstaged changes, which the Host refuses.
|
||||
const refused = { ok: false as const, error: new RemoteError('forgePanel/no-working-tree', 'no working tree', {}) }
|
||||
m.faces.localDiff.mockImplementation(async scope => scope.kind === 'branch' ? ok(LOCAL) : refused)
|
||||
act(() => { m.store.actions.scoped(TAB, 'unstaged') })
|
||||
await settle()
|
||||
expect(m.store.getSnapshot().byTab[TAB]).toMatchObject({ scope: 'branch', head: { ...CACHE_HEAD, worktree: null } })
|
||||
expect(m.faces.localDiff).toHaveBeenLastCalledWith({ kind: 'branch', head: CACHE.ref, base: null, commits: null }, expect.any(AbortSignal))
|
||||
expect(m.view.container.querySelector('[data-forge-scope]')).toBeNull()
|
||||
expect(m.paths()).toContain('src/app.ts')
|
||||
expect(m.view.queryByRole('button', { name: en.retry })).toBeNull()
|
||||
})
|
||||
|
||||
it('names the base another head compared with only once its changes loaded', async () => {
|
||||
const m = mount({ setup: (faces) => {
|
||||
faces.localDiff.mockImplementation(async scope => scope.head === undefined ? ok(LOCAL) : new Promise(() => {}))
|
||||
@@ -3447,31 +3469,37 @@ describe('ChangesTab heads', () => {
|
||||
})
|
||||
|
||||
it('keeps viewed marks and quoted comments of one head apart from another\'s', async () => {
|
||||
const m = mount()
|
||||
const m = mount({ setup: worktrees })
|
||||
await settle()
|
||||
const viewed = (): HTMLInputElement => within(m.section('src/app.ts')).getByRole('checkbox', { name: 'Mark app.ts as viewed' })
|
||||
/** Quote line R4 of `src/app.ts` into the input, returning the source the comment records. */
|
||||
const quote = (): unknown => {
|
||||
const section = within(m.section('src/app.ts'))
|
||||
fireEvent.click(section.getByRole('button', { name: 'Select line R4' }))
|
||||
fireEvent.click(section.getByRole('button', { name: 'Add comment' }))
|
||||
fireEvent.change(section.getByRole('textbox'), { target: { value: 'Why?' } })
|
||||
fireEvent.click(section.getByRole('button', { name: 'Add to input' }))
|
||||
return m.faces.addReviewToInput.mock.lastCall?.[0].source
|
||||
}
|
||||
fireEvent.click(viewed())
|
||||
expect(viewed().checked).toBe(true)
|
||||
|
||||
// A comment quoted from a head records the branch, and the worktree when one was read.
|
||||
act(() => { m.store.actions.headed(TAB, CACHE_HEAD) })
|
||||
await settle()
|
||||
expect(viewed().checked).toBe(false)
|
||||
expect(quote()).toMatchObject({ kind: 'local', scope: 'branch', head: { key: CACHE.ref, name: 'cache', root: CACHE_ROOT } })
|
||||
expect(m.section('src/app.ts').textContent).toContain('Why?')
|
||||
fireEvent.click(viewed())
|
||||
|
||||
act(() => { m.store.actions.headed(TAB, TOPIC_HEAD) })
|
||||
await settle()
|
||||
expect(viewed().checked).toBe(false)
|
||||
expect(m.section('src/app.ts').textContent).not.toContain('Why?')
|
||||
expect(quote()).toMatchObject({ kind: 'local', scope: 'branch', head: { key: TOPIC.ref, name: 'topic', root: null } })
|
||||
|
||||
// A comment quoted from a head records whose code it is.
|
||||
const section = within(m.section('src/app.ts'))
|
||||
fireEvent.click(section.getByRole('button', { name: 'Select line R4' }))
|
||||
fireEvent.click(section.getByRole('button', { name: 'Add comment' }))
|
||||
fireEvent.change(section.getByRole('textbox'), { target: { value: 'Why?' } })
|
||||
fireEvent.click(section.getByRole('button', { name: 'Add to input' }))
|
||||
expect(m.faces.addReviewToInput.mock.lastCall?.[0].source).toMatchObject({
|
||||
kind: 'local', scope: 'branch', head: { key: 'branch:refs/heads/topic', name: 'topic', root: null },
|
||||
})
|
||||
act(() => { m.store.actions.headed(TAB, CACHE_HEAD) })
|
||||
await settle()
|
||||
expect(viewed().checked).toBe(true)
|
||||
expect(m.section('src/app.ts').textContent).not.toContain('Why?')
|
||||
})
|
||||
})
|
||||
@@ -1,90 +1,76 @@
|
||||
// @vitest-environment jsdom
|
||||
/** The head picker: its groups, searching, choosing, failures, and which branches it leaves to a checkout's row. */
|
||||
/** The head picker: its groups, the worktree mark, searching, choosing, and a failed listing. */
|
||||
import { act, cleanup, fireEvent, render, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { HeadMenu, type HeadMenuProps } from '../src/client/HeadMenu.tsx'
|
||||
import type { ChangesHead } from '../src/client/changes-store.ts'
|
||||
import css from '../src/client/BaseMenu.module.css'
|
||||
import { en } from '../src/client/locales.ts'
|
||||
import type { ForgeBaseBranch, ForgeBaseBranches, ForgeRelatedCheckout } from '../src/types.ts'
|
||||
import type { ForgeBaseBranch, ForgeBaseBranches } from '../src/types.ts'
|
||||
|
||||
const t = makeTranslate(en)
|
||||
const RELEASE: ForgeBaseBranch = { ref: 'refs/remotes/origin/release/2.4', name: 'origin/release/2.4' }
|
||||
const TOPIC: ForgeBaseBranch = { ref: 'refs/heads/topic', name: 'topic' }
|
||||
/** `cache` and `fix` are checked out by related Sessions; a remote-tracking branch may share a related checkout's short name. */
|
||||
const BRANCHES: ForgeBaseBranches = {
|
||||
automatic: { name: 'origin/main', worktree: false },
|
||||
remote: [RELEASE, { ref: 'refs/remotes/cache', name: 'cache' }],
|
||||
local: [TOPIC, { ref: 'refs/heads/cache', name: 'cache' }],
|
||||
}
|
||||
const CACHE: ForgeRelatedCheckout = {
|
||||
sessionId: brandString<SessionId>('child-1'), root: '/work/repo/.agents/worktrees/cache', branch: 'cache', commit: 'abc1234',
|
||||
labels: ['Add a cache', 'Check the cache'],
|
||||
}
|
||||
const DETACHED: ForgeRelatedCheckout = {
|
||||
sessionId: brandString<SessionId>('child-2'), root: '/work/elsewhere', branch: null, commit: 'def5678', labels: ['Bisect the failure'],
|
||||
}
|
||||
const UNBORN: ForgeRelatedCheckout = { sessionId: brandString<SessionId>('child-3'), root: '/work/new', branch: null, commit: null, labels: ['Start over'] }
|
||||
const CACHE_HEAD: ChangesHead = { kind: 'session', sessionId: CACHE.sessionId, name: 'cache', root: CACHE.root }
|
||||
const TOPIC_HEAD: ChangesHead = { kind: 'branch', ref: TOPIC.ref, name: 'topic' }
|
||||
const failed = <T,>(): RemoteResult<T> => ({ ok: false, error: new RemoteError('gateway/bad-request', 'failed', {}) })
|
||||
/** `cache` is checked out in a worktree; the listing leaves out the Session's own checked-out branch. */
|
||||
const CACHE: ForgeBaseBranch = { ref: 'refs/heads/cache', name: 'cache', worktree: '/work/repo/.agents/worktrees/cache' }
|
||||
const BRANCHES: ForgeBaseBranches = { automatic: { name: 'origin/main', worktree: false }, remote: [RELEASE], local: [TOPIC, CACHE] }
|
||||
const CACHE_HEAD: ChangesHead = { ref: CACHE.ref, name: 'cache', worktree: '/work/repo/.agents/worktrees/cache' }
|
||||
const TOPIC_HEAD: ChangesHead = { ref: TOPIC.ref, name: 'topic', worktree: null }
|
||||
const FAILED: RemoteResult<ForgeBaseBranches> = { ok: false, error: new RemoteError('gateway/bad-request', 'failed', {}) }
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function ok<T>(value: T): RemoteResult<T> {
|
||||
function ok(value: ForgeBaseBranches): RemoteResult<ForgeBaseBranches> {
|
||||
return { ok: true, value }
|
||||
}
|
||||
|
||||
/** Let the reads the menu awaits settle, past the search delay when `ms` is given. */
|
||||
/** Let the listing reads the menu awaits settle, past the search delay when `ms` is given. */
|
||||
async function settle(ms = 0): Promise<void> {
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, ms)) })
|
||||
}
|
||||
|
||||
function mount(props: Partial<HeadMenuProps> = {}) {
|
||||
const list = props.list ?? vi.fn<HeadMenuProps['list']>(async () => ok(BRANCHES))
|
||||
const related = props.related ?? vi.fn<HeadMenuProps['related']>(async () => ok([CACHE, DETACHED]))
|
||||
const choose = vi.fn<HeadMenuProps['choose']>()
|
||||
const all: HeadMenuProps = { chosen: null, own: 'main', missing: false, visible: true, t, ...props, list, related, choose }
|
||||
const all: HeadMenuProps = { chosen: null, own: 'main', missing: false, visible: true, t, ...props, list, choose }
|
||||
const view = render(<HeadMenu {...all} />)
|
||||
const trigger = (): HTMLElement => view.getByRole('button', { name: `Branch shown: ${all.chosen?.name ?? all.own}` })
|
||||
const rows = (): string[] => view.queryAllByRole('menuitem').map(row => row.textContent ?? '')
|
||||
const groups = (): (string | null)[] => view.queryAllByRole('group').map(group => group.getAttribute('aria-label'))
|
||||
const search = (): HTMLElement => view.getByRole('searchbox', { name: en['diff.head.search'] })
|
||||
const search = (): HTMLElement => view.getByRole('searchbox', { name: en['diff.base.search'] })
|
||||
const rerender = (next: Partial<HeadMenuProps>): void => { view.rerender(<HeadMenu {...all} {...next} />) }
|
||||
return { view, list, related, choose, trigger, rows, groups, search, rerender }
|
||||
return { view, list, choose, trigger, rows, groups, search, rerender }
|
||||
}
|
||||
|
||||
describe('HeadMenu listing', () => {
|
||||
it('lists the own checkout, the related checkouts, then local and remote branches no listed checkout has', async () => {
|
||||
it('lists the own checkout, then local and remote branches, marking a branch a worktree has checked out', async () => {
|
||||
const m = mount()
|
||||
expect(m.trigger().getAttribute('data-forge-head')).toBe('')
|
||||
fireEvent.click(m.trigger())
|
||||
expect(m.view.getByRole('status').textContent).toBe(en['diff.base.loading'])
|
||||
await settle()
|
||||
expect(m.related).toHaveBeenCalledTimes(1)
|
||||
expect(m.list).toHaveBeenCalledWith('', expect.any(AbortSignal))
|
||||
expect(m.groups()).toEqual([en['diff.head.own'], en['diff.head.related'], en['diff.base.local'], en['diff.base.remote']])
|
||||
// The local `cache` branch is the related checkout's row; the remote-tracking branch of that name is another branch.
|
||||
expect(m.rows()).toEqual(['mainThis session', 'cacheAdd a cache · Check the cache', 'def5678Bisect the failure', 'topic', 'origin/release/2.4', 'cache'])
|
||||
expect(m.groups()).toEqual([en['diff.head.own'], en['diff.base.local'], en['diff.base.remote']])
|
||||
expect(m.rows()).toEqual(['mainThis session', 'topic', 'cacheWorktree', 'origin/release/2.4'])
|
||||
expect(m.view.getByRole('menuitem', { name: /^main/ }).getAttribute('aria-current')).toBe('page')
|
||||
expect(m.view.getByText('Add a cache · Check the cache').parentElement?.getAttribute('title')).toBe(CACHE.root)
|
||||
// The mark names the directory for the pointer; a branch read from its commits has neither.
|
||||
expect(m.view.getByText('Worktree').parentElement?.getAttribute('title')).toBe(CACHE.worktree)
|
||||
expect(m.view.getByText('topic').parentElement?.hasAttribute('title')).toBe(false)
|
||||
expect(m.view.getByText(en['diff.head.note'])).toBeTruthy()
|
||||
|
||||
fireEvent.click(m.view.getByRole('menuitem', { name: /^cache.*Add a cache/ }))
|
||||
fireEvent.click(m.view.getByRole('menuitem', { name: /^cache/ }))
|
||||
expect(m.choose).toHaveBeenCalledWith(CACHE_HEAD)
|
||||
expect(m.rows()).toEqual([])
|
||||
})
|
||||
|
||||
it('chooses a branch, the own checkout again, and nothing for the head already shown', async () => {
|
||||
it('chooses a branch without a worktree, the own checkout again, and nothing for the head already shown', async () => {
|
||||
const m = mount({ chosen: TOPIC_HEAD })
|
||||
expect(m.trigger().getAttribute('data-forge-head')).toBe('branch:refs/heads/topic')
|
||||
expect(m.trigger().getAttribute('data-forge-head')).toBe(TOPIC.ref)
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
expect(m.view.getByRole('menuitem', { name: 'topic' }).getAttribute('aria-current')).toBe('page')
|
||||
@@ -99,74 +85,34 @@ describe('HeadMenu listing', () => {
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
fireEvent.click(m.view.getByRole('menuitem', { name: 'origin/release/2.4' }))
|
||||
expect(m.choose).toHaveBeenLastCalledWith({ kind: 'branch', ref: RELEASE.ref, name: RELEASE.name })
|
||||
expect(m.choose).toHaveBeenLastCalledWith({ ref: RELEASE.ref, name: RELEASE.name, worktree: null })
|
||||
})
|
||||
|
||||
it('names a related checkout without a branch by its commit, then by HEAD, and marks a head that is gone', async () => {
|
||||
const m = mount({ chosen: CACHE_HEAD, missing: true, related: vi.fn(async () => ok([UNBORN])) })
|
||||
it('marks a head that is gone, and keeps a hidden tab closed', async () => {
|
||||
const m = mount({ chosen: CACHE_HEAD, missing: true })
|
||||
expect(m.trigger().classList.contains(css.missing ?? '')).toBe(true)
|
||||
expect(m.trigger().getAttribute('data-forge-head')).toBe('session:child-1')
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
expect(m.rows()).toEqual(['mainThis session', 'HEADStart over', 'topic', 'cache', 'origin/release/2.4', 'cache'])
|
||||
fireEvent.click(m.view.getByRole('menuitem', { name: /^HEAD/ }))
|
||||
expect(m.choose).toHaveBeenCalledWith({ kind: 'session', sessionId: UNBORN.sessionId, name: 'HEAD', root: UNBORN.root })
|
||||
expect(m.rows()).toHaveLength(4)
|
||||
m.rerender({ chosen: CACHE_HEAD, missing: true, visible: false })
|
||||
expect(m.rows()).toEqual([])
|
||||
})
|
||||
|
||||
it('shows no row until both listings arrived, and keeps a hidden tab closed', async () => {
|
||||
let finish: (result: RemoteResult<readonly ForgeRelatedCheckout[]>) => void = () => {}
|
||||
const related = vi.fn<HeadMenuProps['related']>(() => new Promise((resolve) => { finish = resolve }))
|
||||
const m = mount({ related })
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
expect(m.rows()).toEqual([])
|
||||
expect(m.view.getByRole('status').textContent).toBe(en['diff.base.loading'])
|
||||
await act(async () => { finish(ok([])) })
|
||||
expect(m.groups()).toEqual([en['diff.head.own'], en['diff.base.local'], en['diff.base.remote']])
|
||||
|
||||
m.rerender({ visible: false })
|
||||
expect(m.rows()).toEqual([])
|
||||
expect(related.mock.calls[0]?.[0].aborted).toBe(true)
|
||||
})
|
||||
|
||||
it('drops related checkouts that arrive after the menu closed', async () => {
|
||||
let finish: (result: RemoteResult<readonly ForgeRelatedCheckout[]>) => void = () => {}
|
||||
const related = vi.fn<HeadMenuProps['related']>().mockImplementationOnce(() => new Promise((resolve) => { finish = resolve }))
|
||||
.mockImplementation(() => new Promise(() => {}))
|
||||
const m = mount({ related })
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
fireEvent.click(m.trigger())
|
||||
await act(async () => { finish(ok([CACHE])) })
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
expect(related.mock.calls[0]?.[0].aborted).toBe(true)
|
||||
expect(m.rows()).toEqual([])
|
||||
expect(m.view.getByRole('status').textContent).toBe(en['diff.base.loading'])
|
||||
})
|
||||
|
||||
it('reports either failed listing with a retry of both', async () => {
|
||||
const related = vi.fn<HeadMenuProps['related']>().mockResolvedValueOnce(failed()).mockResolvedValue(ok([CACHE]))
|
||||
const m = mount({ related })
|
||||
it('reports a failed listing with a retry', async () => {
|
||||
const m = mount({ list: vi.fn<HeadMenuProps['list']>().mockResolvedValueOnce(FAILED).mockResolvedValue(ok(BRANCHES)) })
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
const status = m.view.getByRole('status')
|
||||
expect(status.textContent).toBe(`${en['toast.branchesFailed']}${en.retry}`)
|
||||
fireEvent.click(within(status).getByRole('button', { name: en.retry }))
|
||||
await settle()
|
||||
expect([related.mock.calls.length, vi.mocked(m.list).mock.calls.length]).toEqual([2, 2])
|
||||
expect(m.rows()).toEqual(['mainThis session', 'cacheAdd a cache · Check the cache', 'topic', 'origin/release/2.4', 'cache'])
|
||||
|
||||
cleanup()
|
||||
const branches = mount({ list: vi.fn<HeadMenuProps['list']>().mockResolvedValue(failed()) })
|
||||
fireEvent.click(branches.trigger())
|
||||
await settle()
|
||||
expect(branches.view.getAllByRole('status').at(-1)?.textContent).toBe(`${en['toast.branchesFailed']}${en.retry}`)
|
||||
expect(m.list).toHaveBeenCalledTimes(2)
|
||||
expect(m.rows()).toHaveLength(4)
|
||||
})
|
||||
})
|
||||
|
||||
describe('HeadMenu search', () => {
|
||||
it('finds branches by name and related checkouts by branch, task, or directory, reading the branches after a pause', async () => {
|
||||
it('filters listed rows at once, reads the search after a pause, and finds the own checkout by its name', async () => {
|
||||
const m = mount({ list: vi.fn(async (query: string) => ok(query === '' ? BRANCHES : { automatic: null, remote: [RELEASE], local: [] })) })
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
@@ -175,35 +121,22 @@ describe('HeadMenu search', () => {
|
||||
expect(m.list).not.toHaveBeenCalledWith(' REL', expect.any(AbortSignal))
|
||||
await settle(200)
|
||||
expect(m.list).toHaveBeenLastCalledWith(' REL', expect.any(AbortSignal))
|
||||
// The related checkouts are read once per opening, whatever the search.
|
||||
expect(m.related).toHaveBeenCalledTimes(1)
|
||||
|
||||
fireEvent.change(m.search(), { target: { value: 'bisect' } })
|
||||
expect(m.rows()).toEqual(['def5678Bisect the failure'])
|
||||
fireEvent.change(m.search(), { target: { value: 'elsewhere' } })
|
||||
expect(m.rows()).toEqual(['def5678Bisect the failure'])
|
||||
fireEvent.change(m.search(), { target: { value: 'mai' } })
|
||||
expect(m.rows()).toEqual(['mainThis session'])
|
||||
})
|
||||
|
||||
it('says when nothing matches', async () => {
|
||||
it('says when no branch matches, and clears the search when the menu closes', async () => {
|
||||
const m = mount()
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
fireEvent.change(m.search(), { target: { value: 'hotfix' } })
|
||||
expect(m.view.getByText(en['diff.head.empty'])).toBeTruthy()
|
||||
expect(m.view.getByText(en['diff.base.empty'])).toBeTruthy()
|
||||
expect(m.rows()).toEqual([])
|
||||
})
|
||||
|
||||
it('clears the search when the menu closes', async () => {
|
||||
const m = mount()
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
fireEvent.change(m.search(), { target: { value: 'topic' } })
|
||||
fireEvent.click(m.trigger())
|
||||
fireEvent.click(m.trigger())
|
||||
await settle()
|
||||
expect((m.search() as HTMLInputElement).value).toBe('')
|
||||
expect(m.rows()).toHaveLength(6)
|
||||
expect(m.rows()).toHaveLength(4)
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,8 @@
|
||||
import { mkdir, rm, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type {
|
||||
ForgeBaseBranch, ForgeLens, ForgeLensFrame, ForgeLensId, ForgeLensInput, ForgeLocalDiff, ForgeLocalHead, ForgeLocalScope,
|
||||
ForgeBaseBranch, ForgeLens, ForgeLensFrame, ForgeLensId, ForgeLensInput, ForgeLocalDiff, ForgeLocalScope,
|
||||
} from '../src/index.ts'
|
||||
import { lensVersion } from '../src/lens-version.ts'
|
||||
import { bench, git, repository, scratch } from './harness.ts'
|
||||
@@ -31,14 +29,13 @@ const names = (branches: readonly ForgeBaseBranch[]): string[] => branches.map(b
|
||||
* A repository on `main` whose `origin/HEAD` names `main`, with a `topic` branch two commits ahead of it and a
|
||||
* remote-only `origin/release` at the first of those commits.
|
||||
*/
|
||||
async function project(): Promise<{ root: string; repo: string; base: string; first: string; second: string }> {
|
||||
async function project(): Promise<{ root: string; repo: string; first: string; second: string }> {
|
||||
const { path, remove } = await scratch('dsh-forge-head-')
|
||||
cleanups.push(remove)
|
||||
const repo = await repository(path)
|
||||
await git(repo, 'remote', 'add', 'origin', 'https://fake.test/octo/demo.git')
|
||||
await git(repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD')
|
||||
await git(repo, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main')
|
||||
const base = (await git(repo, 'rev-parse', 'HEAD')).trim()
|
||||
await git(repo, 'checkout', '--quiet', '-b', 'topic')
|
||||
const commits: string[] = []
|
||||
for (const [file, title] of [['topic.txt', 'one'], ['more.txt', 'two']] as const) {
|
||||
@@ -50,27 +47,38 @@ async function project(): Promise<{ root: string; repo: string; base: string; fi
|
||||
const [first = '', second = ''] = commits
|
||||
await git(repo, 'update-ref', 'refs/remotes/origin/release', first)
|
||||
await git(repo, 'checkout', '--quiet', 'main')
|
||||
return { root: path, repo, base, first, second }
|
||||
return { root: path, repo, first, second }
|
||||
}
|
||||
|
||||
const TOPIC: ForgeLocalHead = { kind: 'branch', ref: 'refs/heads/topic' }
|
||||
/** A linked worktree of `repo` that has the existing `branch` checked out, with one staged, one modified, and one untracked file. */
|
||||
async function worktree(root: string, repo: string, branch: string): Promise<string> {
|
||||
const path = join(root, `tree-${branch}`)
|
||||
await git(repo, 'worktree', 'add', '--quiet', path, branch)
|
||||
await writeFile(join(path, 'staged.txt'), 'staged\n')
|
||||
await git(path, 'add', 'staged.txt')
|
||||
await writeFile(join(path, 'tracked.txt'), `${branch}\n`)
|
||||
await writeFile(join(path, 'new.txt'), 'new\n')
|
||||
return path
|
||||
}
|
||||
|
||||
describe('forgePanel local changes of a branch head', () => {
|
||||
it('reads the committed content of another branch and leaves the working tree out', async () => {
|
||||
const TOPIC = 'refs/heads/topic'
|
||||
const whole = (head: string): ForgeLocalScope => ({ kind: 'branch', head, base: null, commits: null })
|
||||
|
||||
describe('forgePanel local changes of a branch no worktree has checked out', () => {
|
||||
it('reads the committed content of the branch and leaves the Session\'s working tree out', async () => {
|
||||
const { repo, first, second } = await project()
|
||||
await writeFile(join(repo, 'notes.md'), 'uncommitted\n')
|
||||
const opened = await open(repo)
|
||||
const { forgePanel } = opened.ctx
|
||||
const whole: ForgeLocalScope = { kind: 'branch', head: TOPIC, base: null, commits: null }
|
||||
|
||||
const automatic = await forgePanel.localDiff(opened.session, whole, signal)
|
||||
expect([automatic.base, paths(automatic), automatic.omitted]).toEqual(['origin/main', ['more.txt', 'topic.txt'], 0])
|
||||
const chosen = await forgePanel.localDiff(opened.session, { ...whole, base: 'refs/remotes/origin/release' }, signal)
|
||||
const automatic = await forgePanel.localDiff(opened.session, whole(TOPIC), signal)
|
||||
expect([automatic.base, paths(automatic), automatic.omitted, automatic.worktree]).toEqual(['origin/main', ['more.txt', 'topic.txt'], 0, undefined])
|
||||
const chosen = await forgePanel.localDiff(opened.session, { kind: 'branch', head: TOPIC, base: 'refs/remotes/origin/release', commits: null }, signal)
|
||||
expect([chosen.base, paths(chosen)]).toEqual(['origin/release', ['more.txt']])
|
||||
const one: ForgeLocalScope = { ...whole, commits: { from: first, to: first } }
|
||||
const one: ForgeLocalScope = { kind: 'branch', head: TOPIC, base: null, commits: { from: first, to: first } }
|
||||
expect(paths(await forgePanel.localDiff(opened.session, one, signal))).toEqual(['topic.txt'])
|
||||
// Neither file exists in the Session's working tree, which holds `main`.
|
||||
await expect(forgePanel.localText(opened.session, whole, 'more.txt', signal)).resolves.toBe('two\n')
|
||||
await expect(forgePanel.localText(opened.session, whole(TOPIC), 'more.txt', signal)).resolves.toBe('two\n')
|
||||
await expect(forgePanel.localText(opened.session, one, 'topic.txt', signal)).resolves.toBe('one\n')
|
||||
expect(paths(await forgePanel.localDiff(opened.session, { kind: 'branch', base: null, commits: null }, signal))).toEqual(['notes.md'])
|
||||
|
||||
@@ -79,9 +87,22 @@ describe('forgePanel local changes of a branch head', () => {
|
||||
await expect(forgePanel.localCommits(opened.session, TOPIC, 'refs/remotes/origin/release', signal))
|
||||
.resolves.toMatchObject({ commits: [{ title: 'two' }] })
|
||||
await expect(forgePanel.localCommits(opened.session, null, null, signal)).resolves.toMatchObject({ commits: [] })
|
||||
// A remote-tracking branch is never checked out, so it too is read from its commits.
|
||||
const remote = await forgePanel.localDiff(opened.session, whole('refs/remotes/origin/release'), signal)
|
||||
expect([paths(remote), remote.worktree]).toEqual([['topic.txt'], undefined])
|
||||
})
|
||||
|
||||
it('lists the bases of a branch head without that branch', async () => {
|
||||
it('has the branch scope alone', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
const refused = { code: 'forgePanel/no-working-tree', message: 'No worktree has the branch checked out, so it has no working tree' }
|
||||
for (const kind of ['uncommitted', 'unstaged', 'staged'] as const) {
|
||||
await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind, head: TOPIC }, signal), kind).rejects.toMatchObject(refused)
|
||||
}
|
||||
await expect(opened.ctx.forgePanel.localText(opened.session, { kind: 'unstaged', head: TOPIC }, 'topic.txt', signal)).rejects.toMatchObject(refused)
|
||||
})
|
||||
|
||||
it('lists the bases of the branch without that branch', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
const { forgePanel } = opened.ctx
|
||||
@@ -89,7 +110,7 @@ describe('forgePanel local changes of a branch head', () => {
|
||||
const local = await forgePanel.diffBases(opened.session, TOPIC, '', signal)
|
||||
expect([local.automatic, names(local.remote), names(local.local)])
|
||||
.toEqual([{ name: 'origin/main', worktree: false }, ['origin/main', 'origin/release'], ['main']])
|
||||
const remote = await forgePanel.diffBases(opened.session, { kind: 'branch', ref: 'refs/remotes/origin/release' }, '', signal)
|
||||
const remote = await forgePanel.diffBases(opened.session, 'refs/remotes/origin/release', '', signal)
|
||||
expect([names(remote.remote), names(remote.local)]).toEqual([['origin/main'], ['main', 'topic']])
|
||||
// The Session's own checkout lists every branch but the one it has checked out.
|
||||
const own = await forgePanel.diffBases(opened.session, null, '', signal)
|
||||
@@ -104,7 +125,7 @@ describe('forgePanel local changes of a branch head', () => {
|
||||
expect([names(own.remote), names(own.local)]).toEqual([['origin/main', 'origin/release'], ['main', 'topic']])
|
||||
})
|
||||
|
||||
it('classifies a branch head with a lens, reading both sides from Git', async () => {
|
||||
it('classifies the branch with a lens, reading both sides from Git', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
const reads: string[] = []
|
||||
@@ -112,7 +133,9 @@ describe('forgePanel local changes of a branch head', () => {
|
||||
id: 'fixture/reads' as ForgeLensId,
|
||||
version: '1',
|
||||
classify: async (input: ForgeLensInput) => {
|
||||
for (const file of input.files) reads.push(`${file.path} ${JSON.stringify([await input.text('old', file.path, signal), await input.text('new', file.path, signal)])}`)
|
||||
for (const file of input.files) {
|
||||
reads.push(`${file.path} ${JSON.stringify([await input.text('old', file.path, signal), await input.text('new', file.path, signal)])}`)
|
||||
}
|
||||
return { files: {} }
|
||||
},
|
||||
}
|
||||
@@ -131,204 +154,95 @@ describe('forgePanel local changes of a branch head', () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
const { forgePanel } = opened.ctx
|
||||
const gone: ForgeLocalHead = { kind: 'branch', ref: 'refs/heads/gone' }
|
||||
const gone = 'refs/heads/gone'
|
||||
const missing = { code: 'forgePanel/head-missing', message: 'The branch gone does not exist' }
|
||||
|
||||
await expect(forgePanel.localDiff(opened.session, { kind: 'branch', head: gone, base: null, commits: null }, signal)).rejects.toMatchObject(missing)
|
||||
await expect(forgePanel.localText(opened.session, { kind: 'branch', head: gone, base: null, commits: null }, 'a.txt', signal)).rejects.toMatchObject(missing)
|
||||
await expect(forgePanel.localDiff(opened.session, whole(gone), signal)).rejects.toMatchObject(missing)
|
||||
await expect(forgePanel.localText(opened.session, whole(gone), 'a.txt', signal)).rejects.toMatchObject(missing)
|
||||
await expect(forgePanel.localCommits(opened.session, gone, null, signal)).rejects.toMatchObject(missing)
|
||||
await expect(forgePanel.diffBases(opened.session, gone, '', signal)).rejects.toMatchObject(missing)
|
||||
// Revision syntax names no ref, and a name outside the two branch namespaces never reaches Git.
|
||||
await expect(forgePanel.diffBases(opened.session, { kind: 'branch', ref: 'refs/heads/topic@{0}' }, '', signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/head-missing' })
|
||||
await expect(forgePanel.diffBases(opened.session, { kind: 'branch', ref: 'HEAD' }, '', signal)).rejects.toThrow('"HEAD" is not a branch ref')
|
||||
await expect(forgePanel.diffBases(opened.session, 'refs/heads/topic@{0}', '', signal)).rejects.toMatchObject({ code: 'forgePanel/head-missing' })
|
||||
await expect(forgePanel.diffBases(opened.session, 'HEAD', '', signal)).rejects.toThrow('"HEAD" is not a branch ref')
|
||||
})
|
||||
})
|
||||
|
||||
const LEAD = brandString<SessionId>('lead')
|
||||
const id = (name: string): SessionId => brandString<SessionId>(name)
|
||||
|
||||
/** What the fake Session query knows of one Session. */
|
||||
interface Recorded {
|
||||
readonly parent?: SessionId
|
||||
readonly origin?: 'subagent'
|
||||
readonly cwd?: string
|
||||
/** Projection values, or undefined for an observation without projections. */
|
||||
readonly values?: { readonly workingDirectory?: string | null; readonly worktree?: readonly unknown[] }
|
||||
/** A read failure other than an unknown Session. */
|
||||
readonly broken?: true
|
||||
}
|
||||
|
||||
/** Serve fixed records as the Session query service and fixed rows as the subagent service. */
|
||||
function provideRelated(opened: Bench, records: Readonly<Record<string, Recorded>>, rows: readonly object[]): void {
|
||||
opened.ctx.provide('sessionQuery', {
|
||||
observeSession: async (sessionId: SessionId) => {
|
||||
const found = records[sessionId]
|
||||
if (found === undefined) throw Object.assign(new Error(`no Session ${sessionId}`), { code: 'SESSION_QUERY_SESSION_NOT_FOUND' })
|
||||
if (found.broken === true) throw new Error(`the records of ${sessionId} cannot be read`)
|
||||
return {
|
||||
header: { id: sessionId, cwd: found.cwd, origin: found.origin, parentSession: found.parent },
|
||||
projections: found.values === undefined ? undefined : { values: found.values },
|
||||
[Symbol.dispose]() {},
|
||||
}
|
||||
},
|
||||
} as never)
|
||||
opened.ctx.provide('subagents', { listDescendants: async () => rows } as never)
|
||||
}
|
||||
|
||||
/** A linked worktree of `repo` on a new branch, with one modified and one untracked file. */
|
||||
async function worktree(root: string, repo: string, branch: string): Promise<string> {
|
||||
const path = join(root, branch)
|
||||
await git(repo, 'worktree', 'add', '--quiet', '-b', branch, path, 'main')
|
||||
await writeFile(join(path, 'tracked.txt'), `${branch}\n`)
|
||||
await writeFile(join(path, 'new.txt'), 'new\n')
|
||||
return path
|
||||
}
|
||||
|
||||
describe('forgePanel local changes of a related Session', () => {
|
||||
it('lists the checkouts delegated Sessions work in, one entry per checkout', async () => {
|
||||
const { root, repo } = await project()
|
||||
const child = await worktree(root, repo, 'child')
|
||||
const plain = join(root, 'plain')
|
||||
await mkdir(plain)
|
||||
describe('forgePanel local changes of a branch a worktree has checked out', () => {
|
||||
it('reads every scope in that worktree, with its uncommitted and untracked files', async () => {
|
||||
const { root, repo, second } = await project()
|
||||
const tree = await worktree(root, repo, 'topic')
|
||||
const opened = await open(repo)
|
||||
const lead = opened.session.id
|
||||
const warn = vi.spyOn(opened.ctx.logger, 'warn')
|
||||
provideRelated(opened, {
|
||||
one: { parent: lead, origin: 'subagent', cwd: repo, values: { workingDirectory: child } },
|
||||
// Without a projected directory the header names where the Session works.
|
||||
two: { parent: id('one'), origin: 'subagent', cwd: child },
|
||||
same: { parent: lead, origin: 'subagent', cwd: repo, values: { workingDirectory: null } },
|
||||
gone: { parent: lead, origin: 'subagent', cwd: join(root, 'removed') },
|
||||
outside: { parent: lead, origin: 'subagent', cwd: plain },
|
||||
nowhere: { parent: lead, origin: 'subagent' },
|
||||
broken: { parent: lead, origin: 'subagent', broken: true },
|
||||
hidden: { parent: lead, origin: 'subagent', cwd: child },
|
||||
}, [
|
||||
{ kind: 'child', id: id('one'), mode: 'continuable', label: 'Fix the cache', name: 'cache' },
|
||||
{ kind: 'child', id: id('two'), mode: 'one-shot', path: 'cache/helper' },
|
||||
{ kind: 'child', id: id('same'), mode: 'continuable', label: 'In the lead checkout' },
|
||||
{ kind: 'child', id: id('gone'), mode: 'continuable', label: 'Removed' },
|
||||
{ kind: 'child', id: id('outside'), mode: 'continuable', label: 'Not a checkout' },
|
||||
{ kind: 'child', id: id('nowhere'), mode: 'continuable', label: 'No directory' },
|
||||
{ kind: 'child', id: id('broken'), mode: 'continuable', label: 'Unreadable' },
|
||||
{ kind: 'child', id: id('unknown'), mode: 'continuable', label: 'No records' },
|
||||
{ kind: 'child', id: id('hidden'), mode: 'continuable', label: 'Not readable by the caller' },
|
||||
{ kind: 'child', id: id('remote'), mode: 'external', label: 'External' },
|
||||
{ kind: 'diagnostic', id: id('lost'), reason: 'unavailable' },
|
||||
])
|
||||
opened.ctx.provide('remoteAccess', { allows: ({ id: asked }: { id: SessionId }) => asked !== 'hidden' } as never)
|
||||
|
||||
const listed = await opened.ctx.forgePanel.relatedCheckouts(opened.session, signal)
|
||||
expect(listed).toEqual([{
|
||||
sessionId: 'one', root: child, branch: 'child', commit: (await git(child, 'rev-parse', '--short', 'HEAD')).trim(),
|
||||
labels: ['Fix the cache', 'cache/helper'],
|
||||
}])
|
||||
expect(warn.mock.calls.map(([message]) => String(message)).filter(message => message.startsWith('forge-panel:'))).toEqual([
|
||||
'forge-panel: inspecting the checkout of Session broken failed: Error: the records of broken cannot be read',
|
||||
])
|
||||
})
|
||||
|
||||
it('names a Session by its id where its catalog row has neither description nor name', async () => {
|
||||
const { root, repo } = await project()
|
||||
const child = await worktree(root, repo, 'child')
|
||||
const opened = await open(repo)
|
||||
provideRelated(opened, { bare: { parent: opened.session.id, origin: 'subagent', cwd: child } }, [{ kind: 'child', id: id('bare'), mode: 'one-shot' }])
|
||||
await expect(opened.ctx.forgePanel.relatedCheckouts(opened.session, signal)).resolves.toMatchObject([{ sessionId: 'bare', labels: ['bare'] }])
|
||||
})
|
||||
|
||||
it('lists nothing without the subagent or the Session query service', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
await expect(opened.ctx.forgePanel.relatedCheckouts(opened.session, signal)).resolves.toEqual([])
|
||||
opened.ctx.provide('subagents', { listDescendants: async () => [] } as never)
|
||||
await expect(opened.ctx.forgePanel.relatedCheckouts(opened.session, signal)).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('stops listing when the request is cancelled', async () => {
|
||||
const { root, repo } = await project()
|
||||
const opened = await open(repo)
|
||||
const stop = new AbortController()
|
||||
opened.ctx.provide('sessionQuery', { observeSession: async () => { stop.abort(new Error('closed')); throw new Error('cancelled read') } } as never)
|
||||
opened.ctx.provide('subagents', { listDescendants: async () => [{ kind: 'child', id: id('one'), mode: 'continuable', label: 'x' }] } as never)
|
||||
void root
|
||||
await expect(opened.ctx.forgePanel.relatedCheckouts(opened.session, stop.signal)).rejects.toThrow('closed')
|
||||
})
|
||||
|
||||
it('reads a related Session\'s working tree, forking where that Session created its worktree', async () => {
|
||||
const { root, repo, base } = await project()
|
||||
const child = await worktree(root, repo, 'child')
|
||||
const entered = await worktree(root, repo, 'entered')
|
||||
const opened = await open(repo)
|
||||
const lead = opened.session.id
|
||||
provideRelated(opened, {
|
||||
one: {
|
||||
parent: lead, origin: 'subagent', cwd: repo,
|
||||
values: { workingDirectory: child, worktree: [{ worktree: { path: child, branch: 'child', baseCommit: base, repositoryRoot: repo }, owned: true }] },
|
||||
},
|
||||
// A Session two levels down that entered a worktree it did not create.
|
||||
two: { parent: id('one'), origin: 'subagent', cwd: repo, values: { workingDirectory: entered } },
|
||||
}, [])
|
||||
const { forgePanel } = opened.ctx
|
||||
const one: ForgeLocalHead = { kind: 'session', sessionId: id('one') }
|
||||
const two: ForgeLocalHead = { kind: 'session', sessionId: id('two') }
|
||||
const read = async (scope: ForgeLocalScope): Promise<[string[], string | undefined]> => {
|
||||
const diff = await forgePanel.localDiff(opened.session, scope, signal)
|
||||
return [paths(diff), diff.worktree]
|
||||
}
|
||||
|
||||
const created = await forgePanel.localDiff(opened.session, { kind: 'branch', head: one, base: null, commits: null }, signal)
|
||||
expect([created.base, paths(created)]).toEqual([base.slice(0, 7), ['tracked.txt', 'new.txt']])
|
||||
const joined = await forgePanel.localDiff(opened.session, { kind: 'branch', head: two, base: null, commits: null }, signal)
|
||||
expect([joined.base, paths(joined)]).toEqual(['origin/main', ['tracked.txt', 'new.txt']])
|
||||
expect(paths(await forgePanel.localDiff(opened.session, { kind: 'unstaged', head: one }, signal))).toEqual(['tracked.txt', 'new.txt'])
|
||||
expect(paths(await forgePanel.localDiff(opened.session, { kind: 'staged', head: one }, signal))).toEqual([])
|
||||
await expect(forgePanel.localText(opened.session, { kind: 'uncommitted', head: one }, 'tracked.txt', signal)).resolves.toBe('child\n')
|
||||
// The Session's own working tree is untouched by either worktree.
|
||||
expect(paths(await forgePanel.localDiff(opened.session, { kind: 'uncommitted' }, signal))).toEqual([])
|
||||
// The `branch` scope adds the worktree's uncommitted files to the branch's two commits.
|
||||
const branch = await forgePanel.localDiff(opened.session, whole(TOPIC), signal)
|
||||
expect([branch.base, paths(branch), branch.worktree]).toEqual(['origin/main', ['more.txt', 'staged.txt', 'topic.txt', 'tracked.txt', 'new.txt'], tree])
|
||||
await expect(read({ kind: 'uncommitted', head: TOPIC })).resolves.toEqual([['staged.txt', 'tracked.txt', 'new.txt'], tree])
|
||||
await expect(read({ kind: 'unstaged', head: TOPIC })).resolves.toEqual([['tracked.txt', 'new.txt'], tree])
|
||||
await expect(read({ kind: 'staged', head: TOPIC })).resolves.toEqual([['staged.txt'], tree])
|
||||
await expect(forgePanel.localText(opened.session, { kind: 'unstaged', head: TOPIC }, 'tracked.txt', signal)).resolves.toBe('topic\n')
|
||||
await expect(forgePanel.localText(opened.session, whole(TOPIC), 'new.txt', signal)).resolves.toBe('new\n')
|
||||
await expect(forgePanel.localCommits(opened.session, TOPIC, null, signal))
|
||||
.resolves.toMatchObject({ headSha: second, commits: [{ title: 'one' }, { title: 'two' }] })
|
||||
// The Session's own working tree is untouched by the worktree.
|
||||
await expect(read({ kind: 'uncommitted' })).resolves.toEqual([[], undefined])
|
||||
|
||||
const bases = await forgePanel.diffBases(opened.session, one, '', signal)
|
||||
expect([bases.automatic, names(bases.local)]).toEqual([{ name: base.slice(0, 7), worktree: true }, ['entered', 'main', 'topic']])
|
||||
await expect(forgePanel.localCommits(opened.session, one, null, signal)).resolves.toMatchObject({ commits: [] })
|
||||
// The bases of the worktree's branch name the Session's checkout as `main`'s worktree; the Session's own listing names the other one.
|
||||
const bases = await forgePanel.diffBases(opened.session, TOPIC, '', signal)
|
||||
expect(bases.local).toEqual([{ ref: 'refs/heads/main', name: 'main', worktree: repo }])
|
||||
const own = await forgePanel.diffBases(opened.session, null, '', signal)
|
||||
expect(own.local).toEqual([{ ref: TOPIC, name: 'topic', worktree: tree }])
|
||||
})
|
||||
|
||||
it('refuses a Session that is not delegated from the reading one, is unreadable, or has no checkout', async () => {
|
||||
it('reads the Session\'s own checkout when the head names its checked-out branch', async () => {
|
||||
const { repo } = await project()
|
||||
await writeFile(join(repo, 'notes.md'), 'uncommitted\n')
|
||||
const opened = await open(repo)
|
||||
const diff = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'uncommitted', head: 'refs/heads/main' }, signal)
|
||||
expect([paths(diff), diff.worktree]).toEqual([['notes.md'], undefined])
|
||||
})
|
||||
|
||||
it('falls back to the branch\'s commits once the worktree holds another branch or its directory is gone', async () => {
|
||||
const { root, repo } = await project()
|
||||
const child = await worktree(root, repo, 'child')
|
||||
const plain = join(root, 'plain')
|
||||
await mkdir(plain)
|
||||
const removed = await worktree(root, repo, 'removed')
|
||||
await rm(removed, { recursive: true })
|
||||
const tree = await worktree(root, repo, 'topic')
|
||||
const opened = await open(repo)
|
||||
const lead = opened.session.id
|
||||
const { forgePanel } = opened.ctx
|
||||
const read = async (name: string): Promise<ForgeLocalDiff> =>
|
||||
await forgePanel.localDiff(opened.session, { kind: 'uncommitted', head: { kind: 'session', sessionId: id(name) } }, signal)
|
||||
|
||||
// Git still registers a worktree whose directory was deleted, until it is pruned.
|
||||
await rm(tree, { recursive: true })
|
||||
const removed = await forgePanel.localDiff(opened.session, whole(TOPIC), signal)
|
||||
expect([paths(removed), removed.worktree]).toEqual([['more.txt', 'topic.txt'], undefined])
|
||||
await expect(forgePanel.localDiff(opened.session, { kind: 'unstaged', head: TOPIC }, signal)).rejects.toMatchObject({ code: 'forgePanel/no-working-tree' })
|
||||
expect((await forgePanel.diffBases(opened.session, null, '', signal)).local).toEqual([{ ref: TOPIC, name: 'topic' }])
|
||||
})
|
||||
|
||||
// Without the Session query service no related Session can be found.
|
||||
await expect(read('one')).rejects.toMatchObject({ code: 'forgePanel/head-missing' })
|
||||
provideRelated(opened, {
|
||||
one: { parent: lead, origin: 'subagent', cwd: child },
|
||||
stranger: { parent: LEAD, origin: 'subagent', cwd: child },
|
||||
[LEAD]: { cwd: repo },
|
||||
forked: { parent: lead, cwd: child },
|
||||
loop: { parent: id('pool'), origin: 'subagent', cwd: child },
|
||||
pool: { parent: id('loop'), origin: 'subagent', cwd: child },
|
||||
gone: { parent: lead, origin: 'subagent', cwd: removed },
|
||||
outside: { parent: lead, origin: 'subagent', cwd: plain },
|
||||
broken: { parent: lead, origin: 'subagent', broken: true },
|
||||
hidden: { parent: lead, origin: 'subagent', cwd: child },
|
||||
}, [])
|
||||
opened.ctx.provide('remoteAccess', { allows: ({ id: asked }: { id: SessionId }) => asked !== 'hidden' } as never)
|
||||
// A directory's name cannot hold a line break on Windows.
|
||||
it.skipIf(process.platform === 'win32')('reads the branch from its commits unless the listed directory holds a checkout of it', async () => {
|
||||
const { root, repo } = await project()
|
||||
// Git's listing ends each of these paths at the line break: at a missing directory, at one outside every
|
||||
// checkout, and at one inside the Session's checkout, which holds `main`.
|
||||
await git(repo, 'worktree', 'add', '--quiet', '-b', 'missing', join(root, 'missing\nx'))
|
||||
await git(repo, 'worktree', 'add', '--quiet', '-b', 'plain', join(root, 'plain\nx'))
|
||||
await mkdir(join(root, 'plain'))
|
||||
await git(repo, 'worktree', 'add', '--quiet', '-b', 'inside', join(repo, 'inside\nx'))
|
||||
await mkdir(join(repo, 'inside'))
|
||||
// And at another repository that has a branch of the same name checked out.
|
||||
await git(repo, 'worktree', 'add', '--quiet', '-b', 'shared', join(root, 'other\nx'))
|
||||
const other = await repository(root, 'other')
|
||||
await git(other, 'checkout', '--quiet', '-b', 'shared')
|
||||
await writeFile(join(other, 'elsewhere.txt'), 'elsewhere\n')
|
||||
const opened = await open(repo)
|
||||
const { forgePanel } = opened.ctx
|
||||
|
||||
expect(paths(await read('one'))).toEqual(['tracked.txt', 'new.txt'])
|
||||
for (const [name, message] of [
|
||||
['unknown', 'Session unknown has no records'],
|
||||
['stranger', 'Session stranger was not delegated from this Session'],
|
||||
['forked', 'Session forked was not delegated from this Session'],
|
||||
['loop', 'Session loop was not delegated from this Session'],
|
||||
['gone', 'The directory of Session gone is gone'],
|
||||
['outside', 'The directory of Session outside is not inside a Git checkout'],
|
||||
['hidden', 'The related Session cannot be read'],
|
||||
] as const) {
|
||||
await expect(read(name), name).rejects.toMatchObject({ code: 'forgePanel/head-missing', message })
|
||||
for (const branch of ['missing', 'plain', 'inside', 'shared']) {
|
||||
const head = `refs/heads/${branch}`
|
||||
const diff = await forgePanel.localDiff(opened.session, whole(head), signal)
|
||||
expect([paths(diff), diff.worktree], branch).toEqual([[], undefined])
|
||||
await expect(forgePanel.localDiff(opened.session, { kind: 'unstaged', head }, signal), branch).rejects.toMatchObject({ code: 'forgePanel/no-working-tree' })
|
||||
}
|
||||
await expect(read('broken')).rejects.toThrow('the records of broken cannot be read')
|
||||
})
|
||||
})
|
||||
@@ -56,8 +56,7 @@ import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/typ
|
||||
import type {
|
||||
ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeExtensionState, ForgeLensFrame,
|
||||
ForgeLensRequest,
|
||||
ForgeCommitRange, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalHead, ForgeLocalScope, ForgeLocalWrite, ForgeLocalWriteResult,
|
||||
ForgeRelatedCheckout,
|
||||
ForgeCommitRange, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgeLocalWrite, ForgeLocalWriteResult,
|
||||
ForgePanelState, ForgeReviewChangeRequest, ForgeReviewCountFrame,
|
||||
ForgeReviewFrame, ForgeWorktreeBases,
|
||||
} from '../src/types.ts'
|
||||
@@ -257,11 +256,9 @@ async function base() {
|
||||
localWrite: vi.fn(async (_sessionId: SessionId, _write: ForgeLocalWrite): Read<ForgeLocalWriteResult> =>
|
||||
({ ok: true, value: { undo: null } })),
|
||||
diffBases: vi.fn(async (
|
||||
_sessionId: SessionId, _head: ForgeLocalHead | null, _query: string, _signal?: AbortSignal,
|
||||
_sessionId: SessionId, _head: string | null, _query: string, _signal?: AbortSignal,
|
||||
): Read<ForgeBaseBranches> =>
|
||||
({ ok: true, value: { automatic: null, remote: [], local: [] } })),
|
||||
relatedCheckouts: vi.fn(async (_sessionId: SessionId, _signal?: AbortSignal): Read<readonly ForgeRelatedCheckout[]> =>
|
||||
({ ok: true, value: [] })),
|
||||
changeRequestChecks: vi.fn(async (
|
||||
_sessionId: SessionId, _url: string, _headSha: string, _signal: AbortSignal,
|
||||
): Read<ChangeRequestSnapshot> => ({ ok: true, value: snapshot(7) })),
|
||||
@@ -269,7 +266,7 @@ async function base() {
|
||||
_sessionId: SessionId, _url: string, _commits: ForgeCommitRange | null, _signal?: AbortSignal,
|
||||
): Read<ForgeChangeRequestDiff> => ({ ok: true, value: CHANGE })),
|
||||
localCommits: vi.fn(async (
|
||||
_sessionId: SessionId, _head: ForgeLocalHead | null, _base: string | null, _signal?: AbortSignal,
|
||||
_sessionId: SessionId, _head: string | null, _base: string | null, _signal?: AbortSignal,
|
||||
): Read<ForgeLocalCommits> =>
|
||||
({ ok: true, value: COMMITS })),
|
||||
changeRequestCommits: vi.fn(async (_sessionId: SessionId, _url: string, _signal?: AbortSignal): Read<ForgeCommitList | null> =>
|
||||
@@ -1299,11 +1296,9 @@ describe('mountForgePanel changes view', () => {
|
||||
const signal = new AbortController().signal
|
||||
expect(await view.localDiff({ kind: 'staged' }, signal)).toEqual({ ok: true, value: LOCAL })
|
||||
expect(await view.localText({ kind: 'staged' }, 'src/a.ts')).toEqual({ ok: true, value: 'a\n' })
|
||||
const shown: ForgeLocalHead = { kind: 'branch', ref: 'refs/heads/topic' }
|
||||
const shown = 'refs/heads/topic'
|
||||
expect(await view.diffBases(shown, 'rel', signal)).toEqual({ ok: true, value: { automatic: null, remote: [], local: [] } })
|
||||
expect(f.forgePanel.diffBases).toHaveBeenCalledWith(S1, shown, 'rel', signal)
|
||||
expect(await view.relatedCheckouts(signal)).toEqual({ ok: true, value: [] })
|
||||
expect(f.forgePanel.relatedCheckouts).toHaveBeenCalledWith(S1, signal)
|
||||
expect(await view.changeRequestDiff('https://github.com/octo/demo/pull/7', null, signal)).toEqual({ ok: true, value: CHANGE })
|
||||
expect(await view.changeRequestText('https://github.com/octo/demo/pull/7', 'a'.repeat(40), 'src/a.ts')).toEqual({ ok: true, value: 'b\n' })
|
||||
expect(f.forgePanel.localDiff).toHaveBeenCalledWith(S1, { kind: 'staged' }, signal)
|
||||
@@ -1895,7 +1890,6 @@ describe('mountForgePanel review page changes view', () => {
|
||||
await expect(f.view.localDiff({ kind: 'staged' }, signal)).rejects.toThrow(refusal)
|
||||
await expect(f.view.localWrite({ kind: 'unstage', paths: ['a.ts'] })).rejects.toThrow(refusal)
|
||||
await expect(f.view.diffBases(null, '', signal)).rejects.toThrow(refusal)
|
||||
await expect(f.view.relatedCheckouts(signal)).rejects.toThrow(refusal)
|
||||
await expect(f.view.localText({ kind: 'staged' }, 'a.ts')).rejects.toThrow(refusal)
|
||||
await expect(f.view.localCommits(null, null, signal)).rejects.toThrow(refusal)
|
||||
const lens: ForgeLensRequest = { source: { kind: 'change', url, commits: null }, version: 'v1', lens: 'exports' }
|
||||
|
||||
@@ -582,12 +582,31 @@ describe('LocalChangesRow', () => {
|
||||
|
||||
it.each([
|
||||
['before the first state', null],
|
||||
['before the branch scope is read', ready()],
|
||||
['while the branch scope changes nothing', ready({ local: { base: 'origin/main', files: [] } })],
|
||||
['while the first inspection runs', ready({ checkout: { state: 'pending' } })],
|
||||
['outside a Git checkout', ready({ checkout: { state: 'none' } })],
|
||||
])('renders nothing %s', (_label, state) => {
|
||||
expect(row(state).view.container.innerHTML).toBe('')
|
||||
})
|
||||
|
||||
it('stays in a checkout whose branch scope changes nothing, showing an empty size', () => {
|
||||
const b = row(ready({ local: { base: 'origin/main', files: [] } }))
|
||||
const element = b.view.container.querySelector('[data-forge-local]') as HTMLElement
|
||||
expect(rowParts(element)).toBe('button:body(icon content) trailing menu')
|
||||
expect(element.querySelector('[data-row-part="content"]')?.textContent).toBe(en['changes.local.title'])
|
||||
expect(element.querySelector('[data-row-part="trailing"]')?.textContent).toBe('+0−0')
|
||||
fireEvent.click(within(element).getByRole('button', { name: 'Local changes · 0 files, 0 lines added, 0 lines deleted' }))
|
||||
expect(b.viewLocalChanges).toHaveBeenCalledOnce()
|
||||
expect(b.dismissOverlay).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('stays without a size while the branch scope has no fork point, and still opens the view', () => {
|
||||
const b = row(ready())
|
||||
const element = b.view.container.querySelector('[data-forge-local]') as HTMLElement
|
||||
expect(rowParts(element)).toBe('button:body(icon content) menu')
|
||||
fireEvent.click(within(element).getByRole('button', { name: en['changes.local.title'] }))
|
||||
expect(b.viewLocalChanges).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }))('names the row button with its visible text first in %s', (_locale, copy) => {
|
||||
const fill = (text: string): string => text.replace('{count}', '2').replace('{added}', '5').replace('{deleted}', '1')
|
||||
expect(fill(copy['changes.local.viewAria']).startsWith(fill(copy['changes.local.summary']))).toBe(true)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
parseBaseBranches, parseName, parseRemotes, parseTopLevel, parseWorktreeBases, remoteOrder, remoteRepository, upstreamBranch,
|
||||
parseBaseBranches, parseName, parseRemotes, parseTopLevel, parseWorktreeBases, parseWorktrees, remoteOrder, remoteRepository,
|
||||
upstreamBranch,
|
||||
} from '../src/parse.ts'
|
||||
import type { GitRemote } from '../src/parse.ts'
|
||||
|
||||
@@ -151,6 +152,26 @@ describe('parseBaseBranches', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseWorktrees', () => {
|
||||
/** One `git worktree list --porcelain` entry: its lines, then an empty line. */
|
||||
const listed = (...fields: string[]): string => `${fields.join('\n')}\n\n`
|
||||
|
||||
it('maps each checked-out branch to its worktree, leaving out detached, bare, and prunable entries', () => {
|
||||
const output = [
|
||||
listed('worktree /work/repo', `HEAD ${'a'.repeat(40)}`, 'branch refs/heads/main'),
|
||||
listed('worktree /work/with space', `HEAD ${'b'.repeat(40)}`, 'branch refs/heads/feat/cache', 'locked reason'),
|
||||
listed('worktree /work/detached', `HEAD ${'c'.repeat(40)}`, 'detached'),
|
||||
listed('worktree /work/bare.git', 'bare'),
|
||||
listed('worktree /work/gone', `HEAD ${'d'.repeat(40)}`, 'branch refs/heads/gone', 'prunable gitdir file points to non-existent location'),
|
||||
listed('worktree /work/pruned', `HEAD ${'e'.repeat(40)}`, 'branch refs/heads/pruned', 'prunable'),
|
||||
].join('')
|
||||
expect([...parseWorktrees(output)]).toEqual([['refs/heads/main', '/work/repo'], ['refs/heads/feat/cache', '/work/with space']])
|
||||
expect(parseWorktrees('').size).toBe(0)
|
||||
// A line break in a directory's name ends the path the listing gives.
|
||||
expect([...parseWorktrees(listed('worktree /work/a\nb', `HEAD ${'f'.repeat(40)}`, 'branch refs/heads/odd'))]).toEqual([['refs/heads/odd', '/work/a']])
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseRemotes', () => {
|
||||
it('groups fetch and push URLs per remote in listed order', () => {
|
||||
const output = [
|
||||
|
||||
@@ -95,7 +95,6 @@ function changesFaces(threads: readonly ForgeReviewThread[] = []): ReviewChanges
|
||||
localDiff: vi.fn(local),
|
||||
localWrite: vi.fn(local),
|
||||
diffBases: vi.fn(local),
|
||||
relatedCheckouts: vi.fn(local),
|
||||
localText: vi.fn(local),
|
||||
localCommits: vi.fn(local),
|
||||
changeRequestDiff: vi.fn(async () => ok(CHANGE)),
|
||||
|
||||
@@ -268,8 +268,8 @@ describe('pending reviews', () => {
|
||||
it('keeps records of another head apart and restores the head they were written on', () => {
|
||||
const queue = new ReviewQueue('review-test')
|
||||
const own = { kind: 'local' as const, scope: 'branch', base: 'origin/main', baseRef: null, commits: null }
|
||||
const related = { ...own, head: { key: 'session:child-1', name: 'cache', root: '/work/cache' } }
|
||||
const branch = { ...own, head: { key: 'branch:refs/heads/topic', name: 'topic', root: null } }
|
||||
const related = { ...own, head: { key: 'refs/heads/cache', name: 'cache', root: '/work/cache' } }
|
||||
const branch = { ...own, head: { key: 'refs/heads/topic', name: 'topic', root: null } }
|
||||
expect(queue.recordAgent({ ...selection, source: related })).toBe(true)
|
||||
expect(queue.fileComments('a.ts', related).threads).toHaveLength(1)
|
||||
expect(queue.fileComments('a.ts', own).threads).toHaveLength(0)
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
"src/diff.ts",
|
||||
"src/git.ts",
|
||||
"src/local-diff.ts",
|
||||
"src/local-head.ts",
|
||||
"src/local-write.ts",
|
||||
"src/layers.ts",
|
||||
"src/lens-version.ts",
|
||||
@@ -68,9 +67,6 @@
|
||||
{
|
||||
"path": "../../storage/storage-domain"
|
||||
},
|
||||
{
|
||||
"path": "../../subagent/subagent"
|
||||
},
|
||||
{
|
||||
"path": "../../subprocess/subprocess"
|
||||
},
|
||||
|
||||
@@ -1803,11 +1803,11 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
throws: ['`forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async diffBases(session: Session, query: string, signal: AbortSignal): Promise<ForgeBaseBranches>',
|
||||
description: 'List the branches the `branch` scope of the Session\'s current checkout can compare with.',
|
||||
parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'query', description: 'text the branch names must contain, ignoring case; empty for every branch.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'the automatic fork point and at most `maxBranches` remote-tracking and local branches each, most recently committed first, without the checked-out branch.',
|
||||
throws: ['`forgePanel/not-a-checkout` outside a checkout; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.'],
|
||||
signature: '@Remote async diffBases(session: Session, head: string | null, query: string, signal: AbortSignal): Promise<ForgeBaseBranches>',
|
||||
description: 'List the branches the `branch` scope can compare with, for the Session\'s current checkout or for a head branch read in its place.',
|
||||
parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'head', description: 'full ref of the branch the scope reads in place of the checked-out one, or null for the checkout.' }, { name: 'query', description: 'text the branch names must contain, ignoring case; empty for every branch.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'the automatic fork point and at most `maxBranches` remote-tracking and local branches each, most recently committed first, without the branch the scope shows; a local branch that a worktree has checked out names that worktree\'s directory.',
|
||||
throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head does not exist; the Git error when Git fails or the listed refs exceed `maxDiffBytes`.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async track(session: Session, url: string, signal: AbortSignal): Promise<void>',
|
||||
@@ -1834,24 +1834,24 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
},
|
||||
{
|
||||
signature: '@Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise<ForgeLocalDiff>',
|
||||
description: 'Read the changes one scope covers in the checkout of the Session\'s current directory, with Git using the Session\'s sandbox policy.',
|
||||
description: 'Read the changes one scope covers in the checkout of the Session\'s current directory, or for the head branch the scope names: in the worktree that has it checked out, else from its commits. Git uses the Session\'s sandbox policy.',
|
||||
parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'scope', description: 'which changes to read.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'the files, the base of the `branch` scope, and the untracked files left out.',
|
||||
throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; `forgePanel/commits-not-linear` when a chosen commit\'s first parent is not the commit listed before it; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.'],
|
||||
returns: 'the files, the base of the `branch` scope, the untracked files left out, and the worktree read for a head.',
|
||||
throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head the scope names does not exist; `forgePanel/no-working-tree` for another scope than `branch` whose head no worktree has checked out; `forgePanel/base-missing` when the base branch chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; `forgePanel/commits-not-linear` when a chosen commit\'s first parent is not the commit listed before it; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise<ForgeLocalCommits>',
|
||||
description: 'List the commits of the `branch` scope of the Session\'s current checkout, which the changes view can show one or several of instead of the whole scope.',
|
||||
parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'base', description: 'the base ref of the `branch` scope, or null for its automatic fork point.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD\'s commit.',
|
||||
throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`.'],
|
||||
signature: '@Remote async localCommits(session: Session, head: string | null, base: string | null, signal: AbortSignal): Promise<ForgeLocalCommits>',
|
||||
description: 'List the commits of the `branch` scope of the Session\'s current checkout or of a head branch read in its place, which the changes view can show one or several of instead of the whole scope.',
|
||||
parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'head', description: 'full ref of the branch the scope reads in place of the checked-out one, or null for the checkout.' }, { name: 'base', description: 'the base ref of the `branch` scope, or null for its automatic fork point.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'the newest `maxCommits` commits between the fork point and the shown HEAD or branch, oldest first, and its commit.',
|
||||
throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` when the head does not exist; `forgePanel/base-missing` when the base branch does not exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise<string>',
|
||||
description: 'Read the new side of one changed file in a scope, which supplies the unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of the `branch` scope, else the working tree.',
|
||||
description: 'Read the new side of one changed file in a scope, which supplies the unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of the `branch` scope, the branch for a head read from its commits, else the working tree of the checkout the scope reads.',
|
||||
parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'scope', description: 'the scope the diff was read in.' }, { name: 'path', description: 'path relative to the checkout\'s top-level directory, as the diff names it.' }, { name: 'signal', description: 'request cancellation.' }],
|
||||
returns: 'the text.',
|
||||
throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`; `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside the checkout, binary content, or a failed read.'],
|
||||
throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/head-missing` and `forgePanel/no-working-tree` as for {@link ForgePanelController.localDiff}; `forgePanel/diff-too-large` over `maxDiffBytes`; `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside the checkout, binary content, or a failed read.'],
|
||||
},
|
||||
{
|
||||
signature: '@Remote async localWrite(session: Session, write: ForgeLocalWrite, signal: AbortSignal): Promise<ForgeLocalWriteResult>',
|
||||
@@ -7993,7 +7993,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'ForgeBaseBranch',
|
||||
declaration: 'export interface ForgeBaseBranch {\n readonly ref: string;\n readonly name: string;\n}',
|
||||
declaration: 'export interface ForgeBaseBranch {\n readonly ref: string;\n readonly name: string;\n readonly worktree?: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeBaseBranches',
|
||||
@@ -8145,11 +8145,11 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'ForgeLocalDiff',
|
||||
declaration: 'export interface ForgeLocalDiff {\n readonly base: string | null;\n readonly files: readonly ForgeDiffFile[];\n readonly omitted: number;\n}',
|
||||
declaration: 'export interface ForgeLocalDiff {\n readonly base: string | null;\n readonly files: readonly ForgeDiffFile[];\n readonly omitted: number;\n readonly worktree?: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ForgeLocalScope',
|
||||
declaration: 'export type ForgeLocalScope = {\n readonly kind: \'branch\';\n readonly base: string | null;\n readonly commits: ForgeCommitRange | null;\n} | {\n readonly kind: \'uncommitted\';\n} | {\n readonly kind: \'unstaged\';\n} | {\n readonly kind: \'staged\';\n};',
|
||||
declaration: 'export type ForgeLocalScope = {\n readonly kind: \'branch\';\n readonly head?: string;\n readonly base: string | null;\n readonly commits: ForgeCommitRange | null;\n} | {\n readonly kind: \'uncommitted\';\n readonly head?: string;\n} | {\n readonly kind: \'unstaged\';\n readonly head?: string;\n} | {\n readonly kind: \'staged\';\n readonly head?: string;\n};',
|
||||
},
|
||||
{
|
||||
name: 'ForgeLocalWrite',
|
||||
|
||||
Generated
-3
@@ -10626,9 +10626,6 @@ importers:
|
||||
'@deepseek-ai/dsh-session-query':
|
||||
specifier: workspace:*
|
||||
version: link:../../session-query/session-query
|
||||
'@deepseek-ai/dsh-subagent':
|
||||
specifier: workspace:*
|
||||
version: link:../../subagent/subagent
|
||||
'@deepseek-ai/dsh-subprocess':
|
||||
specifier: workspace:*
|
||||
version: link:../../subprocess/subprocess
|
||||
|
||||
Reference in new issue
Block a user