mirror of
https://ghproxy.cflmy.top/https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-11-30 17:19:35 +08:00
Merge pull request #8934 from deepseek-harness/feat/forge-review-activity
feat(forge): edit hosts, list GitLab merge requests for review, and add activity, comments, and auto-merge
This commit is contained in:
commit
da9cfe2287
136 files changed
+9636
-960
No files matched your search
@@ -9,8 +9,8 @@
|
||||
en: ad1da0c97cfc9c2d
|
||||
zh: f4420c0b004fd189
|
||||
/agent-note-code-review-page/decision:
|
||||
en: b0ba35d7c5818dc3
|
||||
zh: 5414ec6190be0726
|
||||
en: 1b41b08e216af622
|
||||
zh: e76b77274c20eaad
|
||||
/agent-note-code-review-page/alternatives-considered:
|
||||
en: 963b1be39a0e4bac
|
||||
zh: 940b86a5e2036477
|
||||
|
||||
@@ -15,9 +15,11 @@ A left-navigation Code review page in [`dsh-experimental-client-ui-forge`](../..
|
||||
- **Lists** — an optional `ForgeProvider` capability (`viewer`, `listForViewer`, `countForViewer`) returns summaries of open change requests; GitHub answers each list with one GraphQL search, because one document with several searches times out. The Host reads the lists only while a page or count stream lasts, outside the forge's status polling, since a batch snapshot of dozens of change requests exceeds GitHub's query timeout; only the shown change request is polled through `ForgeService.watch`.
|
||||
- **Reads by URL** — the page's `forgePanel/review*` methods name a change request by URL and no Session; they share the Session-bound methods' implementation and are reachable only by callers that may use the Host's code host credentials.
|
||||
- **Description** — `readDescription` returns the Markdown body, labels, and signed addresses for private attachments, which the page substitutes before rendering with HTML omitted.
|
||||
- **Activity** — two more optional `ForgeProvider` methods, `readActivity` and `addComment`, give the summary tab the comments, submitted reviews, commits, and changes of state of a change request and a field that adds a comment. A provider maps its host's records to one entry type, so the page words every entry in the reader's language and shows a host's own sentence only for a record the type has no kind for. A review's comments on lines stay on the changes tab, which already reads, answers, and resolves them; the activity counts them and opens that tab.
|
||||
- **Automatic merge** — a snapshot's optional `autoMerge` and the optional `ForgeProvider.setAutoMerge` let the merge action turn the host's automatic merge on for a confirmed head, show that it is on, and cancel it. The field is optional so a provider that sets none changes nothing, and the snapshot carries what the signed-in user may do, so no surface asks the host before it draws the button. Merge queues and merge trains stay out: there the same button would queue the change request, which is another action.
|
||||
- **Changes** — the page draws the changes view itself, split from the right-sidebar tab, with a panel state that holds only the shown change request; plugin lenses, annotations, and slots stay with the Session tab, whose extension points name a Session.
|
||||
- **Chat** — the chat tab embeds `conversation.content` for the blank Session `connectWorkspace` resolves in the Workspace named like the repository, and never offers an existing conversation. A Workspace picked in the Hero is handled by the page, as every owner of the content handles its own picks: the page connects that Workspace's blank and shows it in the chat tab, where the main Conversation opens it as the main Session. The change request is bound when the Session's first message enters its inbox, so a blank that is never used stays unbound.
|
||||
- **Hosts** — the page lists every configured host together; choosing among hosts and accounts waits for a second provider that lists change requests.
|
||||
- **Hosts** — the page lists every configured host together, GitHub and GitLab. A host whose read failed is read again later each time without delaying the others, since the bundle ships a GitLab host most users are not signed in to. A repository scope names its host and is read there only: one `owner/name` can exist on two hosts, and a GitLab project path nests groups. The filter offers each host once the lists span several, and a host that could not be read shows one notice after the lists. A row names no host, because every row would then need a second line of small text; choosing among accounts of one host is not offered.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -15,9 +15,11 @@ Status: implemented
|
||||
- **列表**——可选的 `ForgeProvider` 能力(`viewer`、`listForViewer`、`countForViewer`)返回未关闭变更请求的摘要;GitHub 每个列表用一次 GraphQL 搜索回答,因为在一个文档中放多个搜索会超时。Host 只在页面流或计数流存在时读取列表,不经过 forge 的状态轮询,因为几十个变更请求的批量快照会超过 GitHub 的查询时限;只有显示中的变更请求经 `ForgeService.watch` 轮询。
|
||||
- **按 URL 读取**——页面的 `forgePanel/review*` 方法以 URL 而不是会话指定变更请求;它们与会话绑定的方法共用实现,只有可以使用 Host 代码托管凭据的调用方能访问。
|
||||
- **描述**——`readDescription` 返回 Markdown 正文、标签以及私有附件的签名地址,页面替换这些地址后以省略 HTML 的方式渲染。
|
||||
- **动态**——另外两个可选的 `ForgeProvider` 方法 `readActivity` 与 `addComment` 为概要标签页提供变更请求的评论、已提交的评审、提交和状态变化,以及一个添加评论的输入框。提供方把所在主机的记录映射为同一种条目类型,所以页面用读者的语言表述每个条目,只有该类型没有对应种类的记录才显示主机自己的句子。评审在行上留下的评论仍在变更标签页,那里已经能读取、回复和解决它们;动态只显示条数并打开该标签页。
|
||||
- **自动合并**——快照可选的 `autoMerge` 与可选的 `ForgeProvider.setAutoMerge` 让合并操作可以为确认过的 head 启用平台的自动合并、显示它已启用,并取消它。该字段是可选的,所以不设置自动合并的提供方不受影响;快照带着当前用户能做什么,所以任何界面在绘制按钮前都不必询问平台。合并队列与合并列车不在其中:在那里同一个按钮会把变更请求加入队列,那是另一种操作。
|
||||
- **变更**——页面自己绘制变更视图(从右侧栏标签中拆出),面板状态只含显示中的变更请求;插件的透镜、行注释和插槽仍只在会话标签中,因为这些扩展点以会话为对象。
|
||||
- **对话**——对话标签为 `connectWorkspace` 在与仓库同名的工作区中解析出的空白会话嵌入 `conversation.content`,从不提供已有对话。在 Hero 中选择工作区由页面自己处理,这与内容的每个属主处理各自的选择一致:页面连接该工作区的空白会话并在对话标签中显示它,而主 Conversation 会把它打开为主会话。该会话的首条消息进入收件箱时才绑定变更请求,因此从未使用的空白会话保持未绑定。
|
||||
- **主机**——页面把所有已配置的主机合并列出;在主机与账号之间选择要等到第二个能列出变更请求的提供方。
|
||||
- **主机**——页面把所有已配置的主机合并列出,包括 GitHub 与 GitLab。读取失败的主机每次间隔更久再读,不拖慢其他主机,因为套件自带的 GitLab 主机多数用户并未登录。仓库范围带有主机,只在该主机上读取:同一个 `owner/name` 可以存在于两个主机,GitLab 的项目路径还有嵌套分组。列表跨多个主机时,筛选列出每个主机;读取失败的主机在列表之后显示一条提示。列表行不写主机,否则每一行都要多一行小字;同一主机的多个账号之间不提供选择。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
- text: "Add the pull request panel #7"
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "提交评审"
|
||||
- button "在浏览器中打开"
|
||||
- button "在 GitHub 中打开"
|
||||
- button "全部 2 个文件"
|
||||
- button "分层透镜:全部": 全部
|
||||
- switch "隐藏测试文件"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
- text: "Add the pull request panel #7"
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "提交评审"
|
||||
- button "在浏览器中打开"
|
||||
- button "在 GitHub 中打开"
|
||||
- radiogroup "分层透镜":
|
||||
- radio "全部 6" [checked]
|
||||
- radio "接口 1"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
- text: "Add the pull request panel #7"
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "提交评审"
|
||||
- button "在浏览器中打开"
|
||||
- button "在 GitHub 中打开"
|
||||
- radiogroup "分层透镜":
|
||||
- radio "全部 1" [checked]
|
||||
- radio "接口 0"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
- text: "Add the pull request panel #7"
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "提交评审"
|
||||
- button "在浏览器中打开"
|
||||
- button "在 GitHub 中打开"
|
||||
- radiogroup "分层透镜":
|
||||
- radio "全部 2" [checked]
|
||||
- radio "接口 0"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
- text: "Add the pull request panel #7"
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "提交评审"
|
||||
- button "在浏览器中打开"
|
||||
- button "在 GitHub 中打开"
|
||||
- radiogroup "分层透镜":
|
||||
- radio "全部 3" [checked]
|
||||
- radio "接口 1"
|
||||
|
||||
@@ -143,6 +143,13 @@ if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vn
|
||||
process.stdout.write(text)
|
||||
process.exit(0)
|
||||
}
|
||||
if (args[0] === 'api' && args[3] === '--method' && args[4] === 'POST' && args[5] === 'repos/octo/demo/issues/7/comments') {
|
||||
const { body } = JSON.parse(readFileSync(0, 'utf8'))
|
||||
state.comments = [...state.comments ?? [], { body, at: new Date().toISOString() }]
|
||||
save()
|
||||
process.stdout.write(JSON.stringify({ id: 1000 + state.comments.length, html_url: 'https://github.com/octo/demo/pull/7#issuecomment-1' }))
|
||||
process.exit(0)
|
||||
}
|
||||
if (args[0] === 'api' && args[3] === '--method' && args[4] === 'POST' && args[5].startsWith('repos/octo/demo/actions/')) {
|
||||
appendFileSync(join(here, 'reruns.jsonl'), args[5] + '\\n')
|
||||
state.reruns = [...state.reruns ?? [], args[5]]
|
||||
@@ -186,6 +193,10 @@ if (args[0] === 'api' && args[1] === 'graphql' && args.includes('--input')) {
|
||||
}
|
||||
state.updated = variables.input.updateMethod
|
||||
payload = { clientMutationId: null }
|
||||
} else if (field === 'enablePullRequestAutoMerge' || field === 'disablePullRequestAutoMerge') {
|
||||
// The automatic merge of pull request 7, which later status reads report.
|
||||
state.autoMerge = field === 'enablePullRequestAutoMerge' ? variables.input.mergeMethod : null
|
||||
payload = { clientMutationId: null }
|
||||
} else if (field === 'addPullRequestReview') {
|
||||
current.pending = { id: 'review-1', commit: variables.commit, threads: [] }
|
||||
for (const thread of variables.threads ?? []) current.pending.threads.push(draft(thread))
|
||||
@@ -230,6 +241,52 @@ if (args[0] === 'api' && args[1] === 'graphql') {
|
||||
})
|
||||
const overview = existsSync(join(here, 'overview.json')) ? JSON.parse(readFileSync(join(here, 'overview.json'), 'utf8')) : {}
|
||||
const none = { totalCount: 0, nodes: [] }
|
||||
if (query.includes('bodyHTML')) {
|
||||
process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: {
|
||||
body: 'Adds the panel.', bodyHTML: '<p>Adds the panel.</p>', createdAt: '2026-10-08T00:00:00Z', labels: none,
|
||||
} } } }))
|
||||
process.exit(0)
|
||||
}
|
||||
if (query.includes('timelineItems(')) {
|
||||
const account = login => ({ __typename: 'User', login, avatarUrl: null })
|
||||
const commit = (oid, messageHeadline) => ({ __typename: 'PullRequestCommit',
|
||||
commit: { oid: oid.repeat(40), messageHeadline, committedDate: '2026-10-08T01:00:00Z', author: { user: account('octo') } } })
|
||||
const comment = (body, createdAt, login) => ({ __typename: 'IssueComment', createdAt, body, author: account(login),
|
||||
url: 'https://github.com/octo/demo/pull/7#issuecomment-1' })
|
||||
process.stdout.write(JSON.stringify({ data: { repository: { isArchived: false, viewerPermission: 'WRITE', pullRequest: {
|
||||
locked: false, merged: false, timelineItems: { pageInfo: { hasPreviousPage: false }, nodes: [
|
||||
commit('d', 'Add the panel'), commit('e', 'Fix the build'),
|
||||
{ __typename: 'ReviewRequestedEvent', createdAt: '2026-10-08T02:00:00Z', actor: account('octo'), requestedReviewer: { login: 'mona' } },
|
||||
{ __typename: 'PullRequestReview', createdAt: '2026-10-08T03:00:00Z', submittedAt: '2026-10-08T03:00:00Z', body: '', state: 'APPROVED',
|
||||
url: 'https://github.com/octo/demo/pull/7#pullrequestreview-1', author: account('mona'), comments: { totalCount: 0 } },
|
||||
comment('Looks **good** to me.', '2026-10-08T04:00:00Z', 'mona'),
|
||||
...(state.comments ?? []).map(posted => comment(posted.body, posted.at, 'octocat')),
|
||||
] },
|
||||
} } } }))
|
||||
process.exit(0)
|
||||
}
|
||||
if (query.includes('search(type: ISSUE')) {
|
||||
// The review page's lists and their count, which only a case that writes lists.json shows.
|
||||
if (!existsSync(join(here, 'lists.json'))) {
|
||||
process.stderr.write('no lists fixture\\n')
|
||||
process.exit(1)
|
||||
}
|
||||
const lists = JSON.parse(readFileSync(join(here, 'lists.json'), 'utf8'))
|
||||
if (query.includes('review: search(')) {
|
||||
process.stdout.write(JSON.stringify({ data: { review: { issueCount: lists['review-requested'].length },
|
||||
authored: { issueCount: lists.authored.length }, involved: { issueCount: lists.involved.length } } }))
|
||||
process.exit(0)
|
||||
}
|
||||
const q = args.find(arg => arg.startsWith('q=')).slice(2)
|
||||
const filter = q.includes('involves:@me') ? 'involved' : q.includes('review-requested:@me') ? 'review-requested' : 'authored'
|
||||
const row = number => ({ __typename: 'PullRequest', number, title: 'Pull request ' + number, url: 'https://github.com/octo/demo/pull/' + number, isDraft: false,
|
||||
updatedAt: new Date(Date.now() - 5 * 60000).toISOString(), headRefOid: 'a'.repeat(40), reviewDecision: null,
|
||||
repository: { name: 'demo', owner: { login: 'octo' } }, author: { __typename: 'User', login: 'octo', avatarUrl: null },
|
||||
commits: { nodes: [{ commit: { statusCheckRollup: { state: 'SUCCESS' } } }] }, viewerLatestReview: null,
|
||||
viewerLatestReviewRequest: filter === 'review-requested' ? { requestedReviewer: { __typename: 'User' } } : null })
|
||||
process.stdout.write(JSON.stringify({ data: { viewer: { login: VIEWER }, search: { issueCount: lists[filter].length, nodes: lists[filter].map(row) } } }))
|
||||
process.exit(0)
|
||||
}
|
||||
const requested = (state.requested ?? []).map(login => ({ asCodeOwner: false, requestedReviewer: { __typename: 'User', login, avatarUrl: null } }))
|
||||
const requests = overview.reviewRequests ?? none
|
||||
const reviewing = { totalCount: requests.totalCount + requested.length, nodes: [...requests.nodes, ...requested] }
|
||||
@@ -244,6 +301,9 @@ if (args[0] === 'api' && args[1] === 'graphql') {
|
||||
nodes: Array.from({ length: 100 }, (_, i) => check('lint', 'FAILURE', '2026-10-08T00:00:42Z', i + 1)),
|
||||
} } } }] },
|
||||
viewerCanUpdateBranch: (overview.viewerCanUpdateBranch ?? false) && state.updated === undefined, canBeRebased: overview.canBeRebased ?? false,
|
||||
viewerCanEnableAutoMerge: (overview.autoMergeAllowed ?? false) && (state.autoMerge ?? null) === null,
|
||||
viewerCanDisableAutoMerge: (state.autoMerge ?? null) !== null, isMergeQueueEnabled: false,
|
||||
autoMergeRequest: (state.autoMerge ?? null) === null ? null : { mergeMethod: state.autoMerge, enabledBy: { login: VIEWER } },
|
||||
reviewRequests: reviewing, latestReviews: overview.latestReviews ?? none, latestOpinionatedReviews: overview.latestOpinionatedReviews ?? none,
|
||||
closingIssuesReferences: overview.closingIssues ?? none,
|
||||
...overview.mergeable === undefined ? {} : { mergeable: overview.mergeable },
|
||||
@@ -258,6 +318,7 @@ if (args[0] === 'api' && args[1] === 'graphql') {
|
||||
pageInfo: { hasNextPage: false, endCursor: null }, nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z')],
|
||||
} } } }] },
|
||||
viewerCanUpdateBranch: false, canBeRebased: true, reviewRequests: none, latestReviews: none, latestOpinionatedReviews: none,
|
||||
viewerCanEnableAutoMerge: false, viewerCanDisableAutoMerge: false, isMergeQueueEnabled: false, autoMergeRequest: null,
|
||||
closingIssuesReferences: none,
|
||||
},
|
||||
}
|
||||
@@ -472,12 +533,43 @@ interface PanelLaunch {
|
||||
readonly tripwire: ReturnType<typeof watchConsole>
|
||||
}
|
||||
|
||||
/**
|
||||
* A GitLab CLI double for the review page's lists on gitlab.com: user `lin` is asked to review merge request 12 of the
|
||||
* nested-group project `group/sub/app`, updated three minutes before each read, and has no other merge request.
|
||||
*/
|
||||
const GLAB = `#!/usr/bin/env node
|
||||
import { readFileSync } from 'node:fs'
|
||||
const args = process.argv.slice(2)
|
||||
if (args[0] === 'api' && args[1] === 'graphql') {
|
||||
const { query, variables } = JSON.parse(readFileSync(0, 'utf8'))
|
||||
const row = { iid: '12', title: 'Fix the gateway timeout', webUrl: 'https://gitlab.com/group/sub/app/-/merge_requests/12', draft: false,
|
||||
updatedAt: new Date(Date.now() - 3 * 60000).toISOString(), diffHeadSha: 'c'.repeat(40), approved: false,
|
||||
author: { username: 'mona', avatarUrl: null, bot: false }, project: { fullPath: 'group/sub/app' }, headPipeline: { status: 'SUCCESS' },
|
||||
reviewers: { nodes: [{ username: 'lin', mergeRequestInteraction: { reviewState: 'UNREVIEWED' } }] } }
|
||||
const page = nodes => ({ count: nodes.length, nodes })
|
||||
const listed = variables.project === null || variables.project === 'group/sub/app' ? [row] : []
|
||||
const user = query.includes('awaited:') ? { awaited: { count: 1 }, authored: { count: 0 }, reviewed: { count: 0 }, assigned: { count: 0 } }
|
||||
: query.includes('reviewed:') ? { reviewed: page([]), assigned: page([]) }
|
||||
: query.includes('list: reviewRequestedMergeRequests') ? { list: page(listed) }
|
||||
: query.includes('list: authoredMergeRequests') ? { list: page([]) } : {}
|
||||
process.stdout.write(JSON.stringify({ data: { currentUser: { username: 'lin', ...user } } }))
|
||||
process.exit(0)
|
||||
}
|
||||
if (args[0] === 'api') {
|
||||
process.stdout.write(JSON.stringify({ username: 'lin' }))
|
||||
process.exit(0)
|
||||
}
|
||||
process.stderr.write('unexpected glab call\\n')
|
||||
process.exit(1)
|
||||
`
|
||||
|
||||
/**
|
||||
* Launch the bundle against a GitHub checkout of `main` and `release` and open the New Session screen of that workspace.
|
||||
* @param failureShot - name of the screenshot saved when the test fails.
|
||||
* @param scenario - normal conversation, a restoration follow-up, or a numbered PR lookup through `bash` or a PTC program.
|
||||
* @param options - desktop transport, checkout branch, browser input, sandbox runner availability, diff output limit, and
|
||||
* whether the extension fixture plugin loads.
|
||||
* @param options - desktop transport, checkout branch, browser input, sandbox runner availability, diff output limit,
|
||||
* whether the extension fixture plugin loads, the pull requests each review page list of github.com holds, and whether
|
||||
* the GitLab provider runs {@link GLAB} instead of the machine's GitLab CLI.
|
||||
* @returns the scaffold, page, and checkout.
|
||||
*/
|
||||
async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' | 'reference' | 'ptc-reference' = 'normal',
|
||||
@@ -488,6 +580,8 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up'
|
||||
missingSandbox?: boolean
|
||||
maxDiffBytes?: number
|
||||
extension?: boolean
|
||||
lists?: Readonly<Record<'review-requested' | 'authored' | 'involved', readonly number[]>>
|
||||
glab?: boolean
|
||||
} = {}): Promise<PanelLaunch> {
|
||||
const { desktop } = options
|
||||
const resources: { scaffold?: WebScaffold; browser?: Browser } = {}
|
||||
@@ -502,12 +596,19 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up'
|
||||
const gh = join(root, 'gh')
|
||||
await writeFile(gh, GH)
|
||||
await chmod(gh, 0o755)
|
||||
if (options.lists !== undefined) await writeFile(join(root, 'lists.json'), JSON.stringify(options.lists))
|
||||
const glab = join(root, 'glab')
|
||||
if (options.glab === true) {
|
||||
await writeFile(glab, GLAB)
|
||||
await chmod(glab, 0o755)
|
||||
}
|
||||
await writeFile(join(root, 'pr-7.diff'), PR7_DIFF)
|
||||
await writeFile(join(root, 'pr-9.diff'), PR9_DIFF)
|
||||
const panelText = `${Array.from({ length: 20 }, (_, index) => panelLine(index + 1, 'new')).join('\n')}\n`
|
||||
await writeFile(join(root, 'contents.json'), JSON.stringify({ [`src/panel.ts@${HEAD7}`]: panelText }))
|
||||
const overlay = join(root, 'forge.patch.yml')
|
||||
await writeFile(overlay, `- id: forge-github\n config: ${JSON.stringify({ ghCommand: gh })}\n`
|
||||
+ (options.glab === true ? `- id: forge-gitlab\n config: ${JSON.stringify({ glabCommand: glab })}\n` : '')
|
||||
+ (options.maxDiffBytes === undefined ? '' : `- id: forge-panel\n config: ${JSON.stringify({ maxDiffBytes: options.maxDiffBytes })}\n`)
|
||||
+ (options.missingSandbox ? `- id: sandbox\n config: ${JSON.stringify({ runnerCommand: [join(root, 'missing-sandbox')], runnerFailureSignatures: ['sandbox startup failed'] })}\n` : ''))
|
||||
const override = join(root, 'replay.override.json')
|
||||
@@ -768,6 +869,188 @@ it.skipIf(MODE === 'record')('reports incomplete filter configuration and retrie
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('lists the change requests of a GitHub and a GitLab host on the Code review page and narrows them to one host or project', async () => {
|
||||
const { scaffold, page, tripwire } = await launchPanel('web-e2e-forge-review-lists', 'normal', {
|
||||
glab: true, lists: { 'review-requested': [7], 'authored': [], 'involved': [] },
|
||||
})
|
||||
// The scaffold expects its recorded model call to be consumed, so the borrowed conversation runs first.
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
await settled
|
||||
const entry = page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '代码评审', exact: true })
|
||||
// The navigation entry counts the requests of both hosts.
|
||||
await page.getByRole('button', { name: '代码评审', exact: true, description: '2 个变更请求等你评审' }).waitFor()
|
||||
await entry.click()
|
||||
const list = page.locator('[data-forge-review-list]')
|
||||
const requested = list.locator('[data-forge-review-section="review-requested"]')
|
||||
const items = requested.locator('[data-forge-review-item]')
|
||||
const shown = async (): Promise<(string | null)[]> => await items.evaluateAll(rows => rows.map(row => row.textContent))
|
||||
const MERGE = 'https://gitlab.com/group/sub/app/-/merge_requests/12'
|
||||
|
||||
// Both hosts' change requests show together, most recently updated first, each on a card without a closing issue.
|
||||
await list.locator(`[data-forge-review-item="${MERGE}"]`).waitFor()
|
||||
await list.locator(`[data-forge-review-item="${PULL}"]`).waitFor()
|
||||
await expect.poll(shown).toEqual([
|
||||
expect.stringMatching(/^Fix the gateway timeoutapp#12·mona\d+分钟$/), expect.stringMatching(/^Pull request 7demo#7·octo\d+分钟$/),
|
||||
])
|
||||
expect(await requested.getByRole('button', { name: /待我评审/ }).textContent()).toBe('待我评审2')
|
||||
expect(await list.locator('[data-forge-review-failure]').count()).toBe(0)
|
||||
|
||||
// The repository submenu offers each host with its repositories below it; a host narrows the lists on the page.
|
||||
await list.getByRole('button', { name: '筛选', exact: true }).click()
|
||||
await page.getByRole('menuitem', { name: /^仓库/ }).click()
|
||||
const offered = page.getByRole('menu').last().getByRole('menuitem')
|
||||
await expect.poll(async () => await offered.allTextContents()).toEqual(['全部仓库', 'github.com', 'octo/demo', 'gitlab.com', 'group/sub/app'])
|
||||
await offered.filter({ hasText: 'gitlab.com' }).click()
|
||||
// One repository is left in the lists, so its name leaves the card.
|
||||
await expect.poll(shown).toEqual([expect.stringMatching(/^Fix the gateway timeout#12·mona\d+分钟$/)])
|
||||
expect(await requested.getByRole('button', { name: /待我评审/ }).textContent()).toBe('待我评审1')
|
||||
|
||||
// A project in a nested group is one choice, read on its own host only: GitHub is not asked for it, so no host fails.
|
||||
await list.getByRole('button', { name: '筛选', exact: true }).click()
|
||||
expect(await page.getByRole('menuitem', { name: /^仓库/ }).textContent()).toBe('仓库gitlab.com')
|
||||
await page.getByRole('menuitem', { name: /^仓库/ }).click()
|
||||
await page.getByRole('menu').last().getByRole('menuitem', { name: 'group/sub/app', exact: true }).click()
|
||||
await expect.poll(shown).toEqual([expect.stringMatching(/^Fix the gateway timeout#12·mona\d+分钟$/)])
|
||||
expect(await list.locator('[data-forge-review-item]').count()).toBe(1)
|
||||
expect(await list.locator('[data-forge-review-failure]').count()).toBe(0)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('shows the activity of a pull request on the Code review page and adds a comment to it', async () => {
|
||||
const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-activity', 'normal', {
|
||||
lists: { 'review-requested': [7], 'authored': [], 'involved': [] },
|
||||
})
|
||||
// The scaffold expects its recorded model call to be consumed, so the borrowed conversation runs first.
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
await settled
|
||||
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '代码评审', exact: true }).click()
|
||||
await page.locator(`[data-forge-review-item="${PULL}"]`).click()
|
||||
const activity = page.locator(`[data-forge-review-detail="${PULL}"]`).getByRole('region', { name: '动态', exact: true })
|
||||
|
||||
// Commits fold into one line; the review request, the approval, and the comment follow in the code host's order.
|
||||
const lines = async (): Promise<string[]> => await activity.locator('[data-forge-review-line]')
|
||||
.evaluateAll(rows => rows.map(row => (row.textContent ?? '').replace(/\d+ ?(天|个月|年)前.*$/, '')))
|
||||
await expect.poll(lines).toEqual(['2 次提交', 'octo 请求 mona 评审', 'mona 批准了这些更改'])
|
||||
const comments = activity.locator('[data-forge-review-comment]')
|
||||
await expect.poll(async () => await comments.count()).toBe(1)
|
||||
expect(await comments.first().locator('strong').textContent()).toBe('good')
|
||||
await activity.getByRole('button', { name: '2 次提交', exact: true }).click()
|
||||
await expect.poll(lines).toEqual(['2 次提交', 'Add the panel', 'Fix the build', 'octo 请求 mona 评审', 'mona 批准了这些更改'])
|
||||
|
||||
// A comment goes to the pull request's conversation in one request and then shows at the end of the activity.
|
||||
const field = activity.getByRole('textbox', { name: '留下评论', exact: true })
|
||||
const send = activity.getByRole('button', { name: '评论', exact: true })
|
||||
expect(await send.isDisabled()).toBe(true)
|
||||
await field.fill('Thanks for the fix')
|
||||
await send.click()
|
||||
await expect.poll(async () => await comments.count()).toBe(2)
|
||||
expect(await comments.last().textContent()).toContain('Thanks for the fix')
|
||||
expect(await field.inputValue()).toBe('')
|
||||
const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
|
||||
expect(calls.filter(call => call[4] === 'POST'))
|
||||
.toEqual([['api', '--hostname', 'github.com', '--method', 'POST', 'repos/octo/demo/issues/7/comments', '--input', '-']])
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('keeps the link actions in the detail header, folds them when it is narrow, and turns the automatic merge on and off', async () => {
|
||||
const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-header', 'normal', {
|
||||
lists: { 'review-requested': [7], 'authored': [], 'involved': [] },
|
||||
})
|
||||
// Pull request 7 is blocked by its checks and its review; the repository lets the viewer turn the automatic merge on.
|
||||
await writeFile(join(root, 'overview.json'), JSON.stringify({ viewerPermission: 'WRITE', autoMergeAllowed: true }))
|
||||
// The scaffold expects its recorded model call to be consumed, so the borrowed conversation runs first.
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
await settled
|
||||
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '代码评审', exact: true }).click()
|
||||
await page.locator(`[data-forge-review-item="${PULL}"]`).click()
|
||||
const detail = page.locator(`[data-forge-review-detail="${PULL}"]`)
|
||||
await detail.getByRole('heading', { level: 1, name: 'Add the pull request panel' }).waitFor()
|
||||
|
||||
// The three link actions show as buttons, the first with the code host's name; the menu that folds them is hidden.
|
||||
const links = detail.locator('[data-forge-review-actions]')
|
||||
const more = detail.getByRole('button', { name: '更多操作', exact: true })
|
||||
expect(await links.getByRole('button').evaluateAll(buttons => buttons.map(button => button.getAttribute('aria-label'))))
|
||||
.toEqual(['在 GitHub 中打开', '复制链接', '刷新状态'])
|
||||
expect(await more.isVisible()).toBe(false)
|
||||
|
||||
// The status column's two action lines span their blocks like a check's line, so each highlights across its block.
|
||||
const lineWidth = async (line: string): Promise<number | undefined> => (await detail.locator(line).first().boundingBox())?.width
|
||||
await detail.locator('[data-forge-review-request]').waitFor()
|
||||
const checkLine = await lineWidth('[data-forge-check-item]')
|
||||
expect(checkLine).toBeGreaterThan(200)
|
||||
expect(await lineWidth('[data-forge-review-rerun]')).toBe(checkLine)
|
||||
expect(await lineWidth('[data-forge-review-request]')).toBe(checkLine)
|
||||
|
||||
// The automatic merge: on for the head the page shows, then the state with its cancellation.
|
||||
await detail.getByRole('button', { name: '自动合并', exact: true }).click()
|
||||
await page.getByRole('menu').getByText('满足合并条件后,将 #7 合并到 main', { exact: true }).waitFor()
|
||||
await page.getByRole('menuitem', { name: '启用自动合并', exact: true }).click()
|
||||
const enabled = detail.getByRole('button', { name: '已启用自动合并', exact: true })
|
||||
await enabled.waitFor()
|
||||
await enabled.click()
|
||||
await page.getByRole('menu').getByText(/由 lin 启用/).waitFor()
|
||||
await page.getByRole('menuitem', { name: '取消自动合并', exact: true }).click()
|
||||
await detail.getByRole('button', { name: '自动合并', exact: true }).waitFor()
|
||||
const mutations = (await readFile(join(root, 'mutations.jsonl'), 'utf8')).trim().split('\n').map((line): unknown => JSON.parse(line))
|
||||
expect(mutations).toEqual([
|
||||
{ field: 'enablePullRequestAutoMerge', variables: { input: { pullRequestId: 'pull-7', mergeMethod: 'SQUASH', expectedHeadOid: HEAD7 } } },
|
||||
{ field: 'disablePullRequestAutoMerge', variables: { input: { pullRequestId: 'pull-7' } } },
|
||||
])
|
||||
|
||||
// A narrow detail folds the three link actions into the menu and keeps the merge action beside it on one row.
|
||||
await page.setViewportSize({ width: 700, height: 900 })
|
||||
await more.waitFor()
|
||||
expect(await links.isVisible()).toBe(false)
|
||||
// The sidebar leaves the page a frame after the window narrows; until then the detail is narrower and its bar has two rows.
|
||||
await expect.poll(async () => (await detail.locator('header > div').first().boundingBox())?.height).toBe(32)
|
||||
await more.click()
|
||||
expect(await page.getByRole('menu').getByRole('menuitem').allTextContents()).toEqual(['在 GitHub 中打开', '复制变更请求链接', '刷新状态'])
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('adds a host on the GitLab row of the Plugins page, which the provider serves without a restart', async () => {
|
||||
const { scaffold, page, tripwire } = await launchPanel('web-e2e-forge-hosts')
|
||||
// The scaffold expects its recorded model call to be consumed, so the borrowed conversation runs first.
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
await settled
|
||||
const merge = 'https://gitlab.example.test/group/app/-/merge_requests/3'
|
||||
expect(scaffold.ctx.forge.changeRequestFromUrl(merge)).toBeUndefined()
|
||||
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
|
||||
await page.locator('[data-plugin-panel]').getByText('变更请求与工作树', { exact: true }).first().click()
|
||||
await page.getByRole('button', { name: '配置 GitLab 变更请求', exact: true }).click()
|
||||
const hosts = page.getByRole('list', { name: '主机', exact: true })
|
||||
await hosts.locator('[data-forge-host="gitlab.com"]').waitFor()
|
||||
const input = page.getByRole('textbox', { name: '要添加的主机', exact: true })
|
||||
|
||||
// The GitHub row serves github.com, and a host has one provider.
|
||||
await input.fill('github.com')
|
||||
await input.press('Enter')
|
||||
await page.getByRole('alert').filter({ hasText: 'github.com 已由 GitHub 组件使用' }).waitFor()
|
||||
expect(await hosts.getByRole('listitem').count()).toBe(1)
|
||||
|
||||
await input.fill(merge)
|
||||
await input.press('Enter')
|
||||
const added = hosts.locator('[data-forge-host="gitlab.example.test"]')
|
||||
const unsaved = added.getByText('未保存', { exact: true })
|
||||
await unsaved.waitFor()
|
||||
expect(scaffold.ctx.forge.changeRequestFromUrl(merge)).toBeUndefined()
|
||||
await page.getByRole('button', { name: '保存', exact: true }).click()
|
||||
// The sign-in state that takes the mark's place depends on the GitLab CLI of the machine, so only the mark's removal is expected.
|
||||
await unsaved.waitFor({ state: 'detached' })
|
||||
|
||||
expect(scaffold.ctx.forge.changeRequestFromUrl(merge)).toEqual({
|
||||
repository: { forge: 'gitlab', host: 'gitlab.example.test', owner: 'group', name: 'app' }, number: 3,
|
||||
})
|
||||
expect(scaffold.ctx.forge.changeRequestFromUrl('https://gitlab.com/group/app/-/merge_requests/3')).toBeDefined()
|
||||
expect(scaffold.ctx.forge.changeRequestFromUrl(PULL)).toBeDefined()
|
||||
expect(await readFile(scaffold.ctx.settings.documentPath, 'utf8')).toMatch(/- id: forge-gitlab\n(?: .*\n)* +hosts:\n +- gitlab\.com\n +- gitlab\.example\.test\n/)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
/**
|
||||
* Expect the panel to show PR 7, which the model viewed by number without its URL in the output, and the lookup that resolved it.
|
||||
* @param launch - the panel launched for a reference scenario.
|
||||
@@ -1436,7 +1719,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
|
||||
if (await expand.count() > 0) await expand.click()
|
||||
await draft.getByRole('button', { name: '查看 #9 的变更:新增 30 行,删除 2 行', exact: true }).click({ timeout: 20_000 })
|
||||
await wide.getByRole('status').filter({ hasText: '变更太大,无法在这里显示' }).waitFor({ timeout: 20_000 })
|
||||
await wide.getByRole('button', { name: '在浏览器中查看', exact: true }).waitFor()
|
||||
await wide.getByRole('button', { name: '在 GitHub 中查看', exact: true }).waitFor()
|
||||
expect(await wide.getByRole('button', { name: '重试', exact: true }).count()).toBe(0)
|
||||
|
||||
const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
|
||||
|
||||
+22
-10
@@ -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:587`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:602`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Host settings of the forge panel Remote. */
|
||||
@@ -1391,7 +1391,7 @@ export interface Config {
|
||||
reviewListIntervalMs?: number
|
||||
/** Milliseconds between two reads of the review page's navigation count while it is shown. */
|
||||
reviewCountIntervalMs?: number
|
||||
/** Largest delay in milliseconds between two reads of the review page's lists or count after consecutive failures. */
|
||||
/** Largest delay in milliseconds between two reads of the review page's lists or count on one host after its consecutive failed reads. */
|
||||
reviewMaxBackoffMs?: number
|
||||
/** Most change requests one review page list shows, capped by each provider's own limit. */
|
||||
reviewPageSize?: number
|
||||
@@ -1428,7 +1428,7 @@ export interface Config {
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-forge`
|
||||
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:833`](../packages/experimental/forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:932`](../packages/experimental/forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
@@ -1451,15 +1451,19 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-experimental-forge-github`
|
||||
|
||||
- `inject`: `forge`
|
||||
- `source`: [`packages/experimental/forge-github/src/index.ts:19`](../packages/experimental/forge-github/src/index.ts)
|
||||
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
|
||||
- `source`: [`packages/experimental/forge-github/src/index.ts:22`](../packages/experimental/forge-github/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** GitHub CLI executable, served hosts, and invocation limits. */
|
||||
export interface Config {
|
||||
/** GitHub CLI executable name or absolute host path. */
|
||||
ghCommand?: string
|
||||
/** Host names this provider serves; list GitHub Enterprise hosts explicitly. */
|
||||
hosts?: string[]
|
||||
/**
|
||||
* Host names this provider serves, at least one; list GitHub Enterprise hosts explicitly. Editable live: the
|
||||
* provider registers again with the new list.
|
||||
*/
|
||||
hosts: Volatile<string[]>
|
||||
/** Deadline in milliseconds for one `gh` invocation. */
|
||||
timeoutMs?: number
|
||||
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */
|
||||
@@ -1824,15 +1828,19 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-forge-gitlab`
|
||||
|
||||
- `inject`: `forge`
|
||||
- `source`: [`packages/experimental/forge-gitlab/src/index.ts:19`](../packages/experimental/forge-gitlab/src/index.ts)
|
||||
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
|
||||
- `source`: [`packages/experimental/forge-gitlab/src/index.ts:22`](../packages/experimental/forge-gitlab/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** GitLab CLI executable, served hosts, and read limits. */
|
||||
export interface Config {
|
||||
/** GitLab CLI executable name or absolute host path. */
|
||||
glabCommand?: string
|
||||
/** Host names this provider serves; list self-managed GitLab hosts explicitly. */
|
||||
hosts?: string[]
|
||||
/**
|
||||
* Host names this provider serves, at least one; list self-managed GitLab hosts explicitly. Editable live: the
|
||||
* provider registers again with the new list.
|
||||
*/
|
||||
hosts: Volatile<string[]>
|
||||
/** Deadline in milliseconds for one `glab` invocation. */
|
||||
timeoutMs?: number
|
||||
/** Maximum captured bytes per `glab` output stream and combined JSON bytes of one complete check read or review read. */
|
||||
@@ -1841,7 +1849,11 @@ export interface Config {
|
||||
maxReviewThreads?: number
|
||||
/** Most commits one merge request commit listing returns, the oldest ones when there are more. */
|
||||
maxCommits?: number
|
||||
/** Most merge requests one status query reads; GitLab refuses a query over its complexity limit, which halves the batch. */
|
||||
/**
|
||||
* Most merge requests one status query reads, 1 by default: in a query that reads several, GitLab 19.5 reports a
|
||||
* mergeable merge request after the first as conflicting. GitLab refuses a query over its complexity limit, which
|
||||
* halves the batch.
|
||||
*/
|
||||
statusBatchSize?: number
|
||||
/** Most `glab` processes one status fetch runs at once. */
|
||||
maxConcurrentRequests?: number
|
||||
|
||||
+22
-10
@@ -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:587`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:602`](../packages/experimental/client-ui-forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Host settings of the forge panel Remote. */
|
||||
@@ -1393,7 +1393,7 @@ export interface Config {
|
||||
reviewListIntervalMs?: number
|
||||
/** Milliseconds between two reads of the review page's navigation count while it is shown. */
|
||||
reviewCountIntervalMs?: number
|
||||
/** Largest delay in milliseconds between two reads of the review page's lists or count after consecutive failures. */
|
||||
/** Largest delay in milliseconds between two reads of the review page's lists or count on one host after its consecutive failed reads. */
|
||||
reviewMaxBackoffMs?: number
|
||||
/** Most change requests one review page list shows, capped by each provider's own limit. */
|
||||
reviewPageSize?: number
|
||||
@@ -1430,7 +1430,7 @@ export interface Config {
|
||||
|
||||
## `@deepseek-ai/dsh-experimental-forge`
|
||||
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:833`](../packages/experimental/forge/src/types.ts)
|
||||
- `source`: [`packages/experimental/forge/src/types.ts:932`](../packages/experimental/forge/src/types.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Poll cadence and fetch deadline for watched change requests. */
|
||||
@@ -1453,15 +1453,19 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-experimental-forge-github`
|
||||
|
||||
- `inject`: `forge`
|
||||
- `source`: [`packages/experimental/forge-github/src/index.ts:19`](../packages/experimental/forge-github/src/index.ts)
|
||||
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
|
||||
- `source`: [`packages/experimental/forge-github/src/index.ts:22`](../packages/experimental/forge-github/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** GitHub CLI executable, served hosts, and invocation limits. */
|
||||
export interface Config {
|
||||
/** GitHub CLI executable name or absolute host path. */
|
||||
ghCommand?: string
|
||||
/** Host names this provider serves; list GitHub Enterprise hosts explicitly. */
|
||||
hosts?: string[]
|
||||
/**
|
||||
* Host names this provider serves, at least one; list GitHub Enterprise hosts explicitly. Editable live: the
|
||||
* provider registers again with the new list.
|
||||
*/
|
||||
hosts: Volatile<string[]>
|
||||
/** Deadline in milliseconds for one `gh` invocation. */
|
||||
timeoutMs?: number
|
||||
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */
|
||||
@@ -1826,15 +1830,19 @@ export interface Config {
|
||||
## `@deepseek-ai/dsh-forge-gitlab`
|
||||
|
||||
- `inject`: `forge`
|
||||
- `source`: [`packages/experimental/forge-gitlab/src/index.ts:19`](../packages/experimental/forge-gitlab/src/index.ts)
|
||||
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
|
||||
- `source`: [`packages/experimental/forge-gitlab/src/index.ts:22`](../packages/experimental/forge-gitlab/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** GitLab CLI executable, served hosts, and read limits. */
|
||||
export interface Config {
|
||||
/** GitLab CLI executable name or absolute host path. */
|
||||
glabCommand?: string
|
||||
/** Host names this provider serves; list self-managed GitLab hosts explicitly. */
|
||||
hosts?: string[]
|
||||
/**
|
||||
* Host names this provider serves, at least one; list self-managed GitLab hosts explicitly. Editable live: the
|
||||
* provider registers again with the new list.
|
||||
*/
|
||||
hosts: Volatile<string[]>
|
||||
/** Deadline in milliseconds for one `glab` invocation. */
|
||||
timeoutMs?: number
|
||||
/** Maximum captured bytes per `glab` output stream and combined JSON bytes of one complete check read or review read. */
|
||||
@@ -1843,7 +1851,11 @@ export interface Config {
|
||||
maxReviewThreads?: number
|
||||
/** Most commits one merge request commit listing returns, the oldest ones when there are more. */
|
||||
maxCommits?: number
|
||||
/** Most merge requests one status query reads; GitLab refuses a query over its complexity limit, which halves the batch. */
|
||||
/**
|
||||
* Most merge requests one status query reads, 1 by default: in a query that reads several, GitLab 19.5 reports a
|
||||
* mergeable merge request after the first as conflicting. GitLab refuses a query over its complexity limit, which
|
||||
* halves the batch.
|
||||
*/
|
||||
statusBatchSize?: number
|
||||
/** Most `glab` processes one status fetch runs at once. */
|
||||
maxConcurrentRequests?: number
|
||||
|
||||
@@ -47,8 +47,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
|
||||
| `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) |
|
||||
| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` |
|
||||
| `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:33`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` |
|
||||
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:42`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:35`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` |
|
||||
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:44`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
|
||||
| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
|
||||
@@ -124,7 +124,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
|
||||
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
|
||||
| `internal/service` | - | `client-ui-forge`, `gateway`, [`speech-to-text-deepseek`](../packages/experimental/speech-to-text-deepseek) |
|
||||
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `server`, `translator`, [`web`](../packages/web/web) |
|
||||
| `loader/volatile-update` | - | [`action-cards`](../packages/interaction/action-cards), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
|
||||
| `loader/volatile-update` | - | [`action-cards`](../packages/interaction/action-cards), `forge-github`, [`forge-gitlab`](../packages/experimental/forge-gitlab), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
|
||||
| `locale/change` | `locale` (`emit`) | `locale` |
|
||||
| `slots/changed` | `ui-renderer` (`emit`) | - |
|
||||
| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` |
|
||||
|
||||
@@ -49,8 +49,8 @@
|
||||
| `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) |
|
||||
| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` |
|
||||
| `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:33`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` |
|
||||
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:42`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
|
||||
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:35`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` |
|
||||
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:44`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
|
||||
| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
|
||||
@@ -126,7 +126,7 @@
|
||||
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
|
||||
| `internal/service` | - | `client-ui-forge`, `gateway`, [`speech-to-text-deepseek`](../packages/experimental/speech-to-text-deepseek) |
|
||||
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `server`, `translator`, [`web`](../packages/web/web) |
|
||||
| `loader/volatile-update` | - | [`action-cards`](../packages/interaction/action-cards), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
|
||||
| `loader/volatile-update` | - | [`action-cards`](../packages/interaction/action-cards), `forge-github`, [`forge-gitlab`](../packages/experimental/forge-gitlab), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
|
||||
| `locale/change` | `locale` (`emit`) | `locale` |
|
||||
| `slots/changed` | `ui-renderer` (`emit`) | - |
|
||||
| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` |
|
||||
|
||||
@@ -1357,6 +1357,7 @@ flowchart TD
|
||||
pkg_experimental_claude_code_mods --> pkg_working_directory
|
||||
pkg_experimental_forge_github --> pkg_experimental_forge
|
||||
pkg_experimental_forge_github --> pkg_experimental_forge_session
|
||||
pkg_experimental_forge_github --> pkg_settings
|
||||
pkg_experimental_forge_github --> pkg_subprocess
|
||||
pkg_experimental_worktree --> pkg_agent
|
||||
pkg_experimental_worktree --> pkg_error
|
||||
@@ -1373,6 +1374,7 @@ flowchart TD
|
||||
pkg_experimental_worktree --> pkg_workspace
|
||||
pkg_forge_gitlab --> pkg_experimental_forge
|
||||
pkg_forge_gitlab --> pkg_experimental_forge_session
|
||||
pkg_forge_gitlab --> pkg_settings
|
||||
pkg_forge_gitlab --> pkg_subprocess
|
||||
pkg_tool_session_query --> pkg_agent
|
||||
pkg_tool_session_query --> pkg_llm
|
||||
@@ -2007,9 +2009,9 @@ flowchart TD
|
||||
| [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
|
||||
| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) |
|
||||
| [`forge-gitlab`](../packages/experimental/forge-gitlab) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`forge-gitlab`](../packages/experimental/forge-gitlab) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
|
||||
| [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) |
|
||||
| [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`credentials`](../packages/credentials/credentials), [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) |
|
||||
|
||||
@@ -1359,6 +1359,7 @@ flowchart TD
|
||||
pkg_experimental_claude_code_mods --> pkg_working_directory
|
||||
pkg_experimental_forge_github --> pkg_experimental_forge
|
||||
pkg_experimental_forge_github --> pkg_experimental_forge_session
|
||||
pkg_experimental_forge_github --> pkg_settings
|
||||
pkg_experimental_forge_github --> pkg_subprocess
|
||||
pkg_experimental_worktree --> pkg_agent
|
||||
pkg_experimental_worktree --> pkg_error
|
||||
@@ -1375,6 +1376,7 @@ flowchart TD
|
||||
pkg_experimental_worktree --> pkg_workspace
|
||||
pkg_forge_gitlab --> pkg_experimental_forge
|
||||
pkg_forge_gitlab --> pkg_experimental_forge_session
|
||||
pkg_forge_gitlab --> pkg_settings
|
||||
pkg_forge_gitlab --> pkg_subprocess
|
||||
pkg_tool_session_query --> pkg_agent
|
||||
pkg_tool_session_query --> pkg_llm
|
||||
@@ -2009,9 +2011,9 @@ flowchart TD
|
||||
| [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
|
||||
| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
|
||||
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) |
|
||||
| [`forge-gitlab`](../packages/experimental/forge-gitlab) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`forge-gitlab`](../packages/experimental/forge-gitlab) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
|
||||
| [`webhook-github`](../packages/experimental/webhook-github) | `experimental` | [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`session`](../packages/core/session), [`webhook`](../packages/experimental/webhook) |
|
||||
| [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`credentials`](../packages/credentials/credentials), [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) |
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
en: 37c9cbfb3141702b
|
||||
zh: c5fcbb7f4fda1dbc
|
||||
/forges/providers-and-change-requests:
|
||||
en: 8df1bf8a6d294252
|
||||
zh: 79ba96596739569f
|
||||
en: ef1335232f8e2156
|
||||
zh: b19c42e7f8671b01
|
||||
/forges/status-polling:
|
||||
en: 33640257c4f9197d
|
||||
zh: b0f435bc3e03cfa4
|
||||
/forges/change-request-actions:
|
||||
en: ae735fbdbdf2d870
|
||||
zh: 9903fcc571104ad8
|
||||
en: dc3b95bf473a2ddc
|
||||
zh: 8399387a6195f70f
|
||||
/forges/review-threads:
|
||||
en: 6a4162560b1aa158
|
||||
zh: 5349e9f25d08fd97
|
||||
@@ -23,6 +23,9 @@
|
||||
/forges/viewer-lists-and-descriptions:
|
||||
en: 05dba49e668fbd82
|
||||
zh: 7502689f5dd46118
|
||||
/forges/activity-and-comments:
|
||||
en: fdfee3180c86d028
|
||||
zh: 8b092bb23594c7a7
|
||||
/forges/session-bindings:
|
||||
en: 74255d6005e1c9e8
|
||||
zh: 252d0d552f1e26a1
|
||||
@@ -30,8 +33,8 @@
|
||||
en: 83ad892728d13987
|
||||
zh: d19b012f5898ef07
|
||||
/forges/panel/review-page:
|
||||
en: f576f6e104ec9546
|
||||
zh: b97efdd34b3a9d1b
|
||||
en: de8dc146c603314b
|
||||
zh: 976884cb9b3a7464
|
||||
/forges/extension-api:
|
||||
en: f35345e482e84f4f
|
||||
zh: 2ecb7d9498decb31
|
||||
+225
-17
@@ -68,6 +68,17 @@ interface ForgeProvider {
|
||||
countForViewer?(host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>
|
||||
/** Read the description and labels of a change request. Omission declares that this provider reads no descriptions. */
|
||||
readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>
|
||||
/**
|
||||
* Read the activity of a change request: the comments in its conversation, its submitted reviews, its commits, and
|
||||
* the changes of its state. Omission declares that this provider reads no activity.
|
||||
*/
|
||||
readActivity?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestActivity | ForgeFailure>
|
||||
/**
|
||||
* Add a comment of Markdown source `body` to a change request's conversation, resolving to undefined once the host
|
||||
* saved it. A comment is never retried. Omission declares that this provider adds no comments, and its `readActivity`
|
||||
* then denies `viewerCanComment`.
|
||||
*/
|
||||
addComment?(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
|
||||
/** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */
|
||||
submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
|
||||
/**
|
||||
@@ -120,6 +131,14 @@ interface ForgeProvider {
|
||||
markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
|
||||
/** Merge a change request while its head is still `request.headSha`, resolving to undefined once merged. */
|
||||
merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
|
||||
/**
|
||||
* Turn the host's automatic merge of a change request on, while its head is still the request's `headSha`, or off,
|
||||
* resolving to undefined once the host accepted it. Omission declares that the provider sets no automatic merge, and
|
||||
* its snapshots then carry no `autoMerge`.
|
||||
*/
|
||||
setAutoMerge?(
|
||||
ref: ChangeRequestRef, request: AutoMergeRequest, signal: AbortSignal,
|
||||
): Promise<ForgeActionFailure | undefined>
|
||||
/**
|
||||
* Read the changes of a change request at head commit `headSha` as the host computes them, as one unified
|
||||
* patch with `a/` and `b/` path prefixes. A patch is returned only when it describes `headSha`; once the
|
||||
@@ -184,6 +203,28 @@ interface ForgeProvider {
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.forge.register` returns the disposer of the registration. Its `replace` puts another provider of the same family in the registered one's place; a provider whose host list is edited while it runs calls it to serve the new list:
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* What `ctx.forge.register` returns: the disposer, plus the replacement of the registered provider by another provider
|
||||
* of the same forge family, for a provider whose configuration changes while it runs.
|
||||
*/
|
||||
interface ForgeRegistrationHandle {
|
||||
/** Unregister the provider this registration holds and wait for its calls, and those of the providers it replaced, to finish. */
|
||||
(): Promise<void>
|
||||
/**
|
||||
* Replace the registered provider in one synchronous step, so no reader finds the family without a provider. The
|
||||
* replaced provider's in-flight calls are cancelled and their results discarded; watches of the family poll at once
|
||||
* and `forge/providers-changed` announces the change.
|
||||
* @param provider - provider of the same forge family.
|
||||
* @throws when the registration was withdrawn, `provider.forge` is another family, or another family's provider
|
||||
* serves one of `provider.hosts`, compared without case; the registered provider then keeps serving.
|
||||
*/
|
||||
replace(provider: ForgeProvider): void
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** One commit of a change request. */
|
||||
interface ForgeCommit {
|
||||
@@ -336,6 +377,11 @@ interface ChangeRequestSnapshot {
|
||||
readonly mergeReady: boolean
|
||||
/** Merge methods the repository accepts, the signed-in user's usual one first. */
|
||||
readonly mergeMethods: readonly MergeMethod[]
|
||||
/**
|
||||
* How the change request stands with its host's automatic merge; omitted by a provider that sets none, whose change
|
||||
* requests then offer no automatic merge.
|
||||
*/
|
||||
readonly autoMerge?: ChangeRequestAutoMerge
|
||||
/**
|
||||
* Ways the signed-in user can bring the base branch's new commits into the head branch now; empty while the head is
|
||||
* up to date, while the branches conflict, when the user cannot update the head branch, or when the provider cannot,
|
||||
@@ -487,6 +533,32 @@ interface MergeRequest {
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.forge.setAutoMerge` turns the host's automatic merge of a change request on, for the head commit the user confirmed and with one of the snapshot's `mergeMethods`, or off; the host then merges the change request by itself once its merge requirements are met. A snapshot's `autoMerge` says whether it is on, with which method and turned on by whom when the host names them, and whether the signed-in user can turn it on or off now. A provider that sets no automatic merge omits both, and `setAutoMerge` then fails without asking the host.
|
||||
|
||||
```ts type-equiv
|
||||
/** How a change request stands with its host's automatic merge. */
|
||||
interface ChangeRequestAutoMerge {
|
||||
/** Whether the host merges the change request by itself once its merge requirements are met. */
|
||||
readonly enabled: boolean
|
||||
/** How the commits enter the base branch then, while enabled and the host names the method; null otherwise. */
|
||||
readonly method: MergeMethod | null
|
||||
/** Login of the account that turned it on, while enabled and the host names one; null otherwise. */
|
||||
readonly enabledBy: string | null
|
||||
/** Whether the signed-in user can turn it on now through `setAutoMerge`; false while it is on. */
|
||||
readonly canEnable: boolean
|
||||
/** Whether the signed-in user can turn it off now through `setAutoMerge`; false while it is off. */
|
||||
readonly canDisable: boolean
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Turning a change request's automatic merge on for the head commit the user saw, or off. */
|
||||
type AutoMergeRequest =
|
||||
/** `method` is one of the snapshot's `mergeMethods`; the host refuses once the head is no longer `headSha`. */
|
||||
| { readonly enabled: true; readonly method: MergeMethod; readonly headSha: string }
|
||||
| { readonly enabled: false }
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Why a provider could not change a change request, or could not confirm that it did. */
|
||||
interface ForgeActionFailure {
|
||||
@@ -927,10 +999,6 @@ interface ChangeRequestSummary {
|
||||
* `organization/slug`, when the request asks a team the user belongs to rather than the user.
|
||||
*/
|
||||
readonly viewerRequest: { readonly team: string | null } | null
|
||||
/** Issues the host closes once the change request merges, in host order, at most the provider's limit. */
|
||||
readonly closingIssues: readonly ChangeRequestIssue[]
|
||||
/** Whether the host reported more closing issues than `closingIssues` holds. */
|
||||
readonly closingIssuesTruncated: boolean
|
||||
/** ISO 8601 time of the host's last update to the change request. */
|
||||
readonly updatedAt: string
|
||||
}
|
||||
@@ -979,6 +1047,55 @@ interface ChangeRequestLabel {
|
||||
}
|
||||
```
|
||||
|
||||
## Activity and comments
|
||||
|
||||
`ctx.forge.readActivity` reads what happened on a change request: the comments in its conversation, its submitted reviews, its commits, and the changes of its state, oldest first, at most the provider's limit with the latest entries kept. `ctx.forge.addComment` adds a comment to the conversation and then polls the change request at once when it is watched. A provider implements either method or both: `readActivity` of a provider without it returns `unsupported`, `addComment` of one without it fails, and an activity's `viewerCanComment` says whether the signed-in user can add a comment. The text of a comment or review is Markdown source whose raw HTML must not render as HTML. The [GitHub](../../packages/experimental/forge-github/README.md#use-this-package) and [GitLab](../../packages/experimental/forge-gitlab/README.md#use-this-package) provider READMEs own the requests and how each host's records become entries.
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* One entry of a change request's activity: a comment in its conversation, a submitted review, a commit, a change of
|
||||
* its state, or a record the host words itself.
|
||||
*/
|
||||
type ChangeRequestActivityItem = {
|
||||
/** ISO 8601 time of the entry. */
|
||||
readonly at: string
|
||||
/** Account the entry is by, or null when the host names none or the account no longer exists. */
|
||||
readonly actor: ForgeCommentAuthor | null
|
||||
} & (
|
||||
/** A comment in the conversation. `body` is Markdown source; it may contain raw HTML, which readers must not render as HTML. */
|
||||
| { readonly kind: 'comment'; readonly body: string; readonly url: string | null }
|
||||
/**
|
||||
* A submitted review: its decision, its own Markdown text, which follows the rule of a comment's `body` and is empty
|
||||
* without one, and the number of comments it left on lines and files.
|
||||
*/
|
||||
| { readonly kind: 'review'; readonly verdict: ReviewVerdict; readonly body: string; readonly comments: number; readonly url: string | null }
|
||||
/**
|
||||
* A commit added to the change request: its object name, abbreviated when the host records only an abbreviation, and
|
||||
* the first line of its message.
|
||||
*/
|
||||
| { readonly kind: 'commit'; readonly sha: string; readonly title: string }
|
||||
| { readonly kind: 'merged' | 'closed' | 'reopened' | 'ready-for-review' | 'converted-to-draft' | 'force-pushed' }
|
||||
| { readonly kind: 'auto-merge-enabled' | 'auto-merge-disabled' }
|
||||
/** A review was requested from an account or a team, named as the host spells it; null when the host names neither. */
|
||||
| { readonly kind: 'review-requested'; readonly reviewer: string | null }
|
||||
| { readonly kind: 'renamed'; readonly from: string; readonly to: string }
|
||||
/** A record with no kind of its own, as plain text in the host's own words. */
|
||||
| { readonly kind: 'other'; readonly text: string }
|
||||
)
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** The activity of a change request. */
|
||||
interface ChangeRequestActivity {
|
||||
/** Entries oldest first, at most the provider's limit; the latest ones when the change request has more. */
|
||||
readonly items: readonly ChangeRequestActivityItem[]
|
||||
/** Whether the change request has entries older than `items` holds. */
|
||||
readonly truncated: boolean
|
||||
/** Whether the signed-in user can add a comment through `addComment`; false for a provider without it. */
|
||||
readonly viewerCanComment: boolean
|
||||
}
|
||||
```
|
||||
|
||||
## Session bindings
|
||||
|
||||
`ctx.forgeSession` derives each Session's bindings from its own log by the command rules that providers register: forge-github's `gh` rule and forge-gitlab's `glab` rule bind the URLs that `gh pr create` and `glab mr create` results print and the change request that `gh pr view`, `glab mr view`, and their sibling reference commands act on, and `git push` results trigger head-branch discovery through `ctx.forge`; the panel also reports the branch its checkout tracks for the same discovery. Track, dismiss, and discovery actions are `plugin:forge-session/binding` records, which stay outside the model-visible conversation. The `forgeChangeRequests` projection's client view, which the Session summary carries, lists the bindings without their status. The [Session binding README](../../packages/experimental/forge-session/README.md#use-this-package) owns the recognition and discovery rules.
|
||||
@@ -1598,7 +1715,7 @@ interface ForgeLocalChanges {
|
||||
|
||||
### Review page
|
||||
|
||||
The [code review page](../../packages/experimental/client-ui-forge/README.md#use-this-package) reads change requests by URL instead of through a Session binding. Its `forgePanel` methods (`reviewLists`, `reviewCount`, `reviewChangeRequest`, `reviewDescription`, and the `review*` reads and actions that mirror the Session-bound ones) resolve the URL with `ForgeService.changeRequestFromUrl`, fail with `forgePanel/unrecognized-url` when no provider serves it, and name no Session resource, so only callers that may use the Host's code host credentials reach them. One list hub reads the [viewer lists](#viewer-lists-and-descriptions) only while a list or count stream lasts: streams of one repository scope share one reader that reads every list of every host each `reviewListIntervalMs`, hosts in parallel and each host's lists in order, stops the round's further reads on a host that refuses the viewer or is rate-limited, and backs off after failed rounds up to `reviewMaxBackoffMs`; the count reads every `reviewCountIntervalMs`, and lists of every repository refresh it too. `reviewLists` streams `ForgeReviewFrame` values with each host's lists, the items of the latest successful read, and the failure of the latest read; `reviewCount` streams `ForgeReviewCountFrame` values; and `reviewChangeRequest` streams `ForgeReviewChangeRequest` values for the shown change request, which is polled through `ForgeService.watch` while its stream lasts.
|
||||
The [code review page](../../packages/experimental/client-ui-forge/README.md#use-this-package) reads change requests by URL instead of through a Session binding. Its `forgePanel` methods (`reviewLists`, `reviewCount`, `reviewChangeRequest`, `reviewDescription`, `reviewActivity`, `reviewComment`, `reviewSetAutoMerge`, and the `review*` reads and actions that mirror the Session-bound ones) resolve the URL with `ForgeService.changeRequestFromUrl`, fail with `forgePanel/unrecognized-url` when no provider serves it, and name no Session resource, so only callers that may use the Host's code host credentials reach them. One list hub reads the [viewer lists](#viewer-lists-and-descriptions) only while a list or count stream lasts: streams of one repository scope share one reader that reads every list of every host each `reviewListIntervalMs`, hosts in parallel and each host's lists in order, stops the round's further reads on a host that refuses the viewer or is rate-limited, and reads a host whose read failed again later each time, up to `reviewMaxBackoffMs`, while the other hosts keep their cadence; the count reads every `reviewCountIntervalMs` in the same way, and lists of every repository refresh it too. A scope is every repository of every host or one `ForgeReviewRepository`, which names its host and is read on that host only. `reviewLists` streams `ForgeReviewFrame` values with each host's lists, the items of the latest successful read, the failure of the latest read, and, for a host that refused the viewer, the sign-in command its provider's `readiness` names; `reviewCount` streams `ForgeReviewCountFrame` values; and `reviewChangeRequest` streams `ForgeReviewChangeRequest` values for the shown change request, which is polled through `ForgeService.watch` while its stream lasts.
|
||||
|
||||
The chat tab starts in the blank Session `connectWorkspace` resolves and records the change request with `reviewStage`; the Host keeps that choice in memory and binds the change request once the Session's next message enters its inbox, so an untouched blank stays unbound.
|
||||
|
||||
@@ -1737,11 +1854,12 @@ Registry of forge providers. Watchers of one change request share a single polli
|
||||
* registration ends. Unregistering cancels and awaits its in-flight calls;
|
||||
* results from the withdrawn registration are discarded.
|
||||
* @param provider - provider to serve `provider.forge` on `provider.hosts`.
|
||||
* @returns the disposer that unregisters the provider and waits for its calls to finish.
|
||||
* @returns the disposer that unregisters the provider and waits for its calls to finish, carrying
|
||||
* {@link ForgeRegistrationHandle.replace}.
|
||||
* @throws when another provider already serves the same forge or one of the same hosts, compared without case, and
|
||||
* when the provider names a batch size that is not a positive safe integer.
|
||||
*/
|
||||
register(provider: ForgeProvider): () => Promise<void>
|
||||
register(provider: ForgeProvider): ForgeRegistrationHandle
|
||||
|
||||
/**
|
||||
* Name a forge family and its change requests for readers.
|
||||
@@ -1783,13 +1901,13 @@ changeRequestUrl(ref: ChangeRequestRef): string
|
||||
async findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise<readonly ChangeRequestRef[]>
|
||||
|
||||
/**
|
||||
* Report whether the provider can reach the repository's host with current credentials.
|
||||
* @param repository - repository served by a registered provider.
|
||||
* Report whether a provider can reach one host with current credentials.
|
||||
* @param repository - forge family of a registered provider and the host to probe; a repository names both.
|
||||
* @param signal - cancellation for the probe.
|
||||
* @returns the provider's readiness for the host.
|
||||
* @throws when no provider serves the repository's forge.
|
||||
* @throws when no provider serves the forge.
|
||||
*/
|
||||
async readiness(repository: ForgeRepository, signal: AbortSignal): Promise<ForgeReadiness>
|
||||
async readiness(repository: Pick<ForgeRepository, 'forge' | 'host'>, signal: AbortSignal): Promise<ForgeReadiness>
|
||||
|
||||
/**
|
||||
* Mark a draft change request ready for review, then poll it at once when it is watched.
|
||||
@@ -1854,6 +1972,17 @@ async reviewerCandidates( ref: ChangeRequestRef, query: string, signal: AbortSig
|
||||
*/
|
||||
async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
|
||||
|
||||
/**
|
||||
* Turn the host's automatic merge of a change request on, while its head is still the request's `headSha`, or off,
|
||||
* then poll it at once when it is watched.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param request - on with the merge method and the head commit the user confirmed, or off.
|
||||
* @param signal - cancellation of the request.
|
||||
* @returns undefined once the host accepted it, or why it did not; a provider that sets no automatic merge fails.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async setAutoMerge( ref: ChangeRequestRef, request: AutoMergeRequest, signal: AbortSignal, ): Promise<ForgeActionFailure | undefined>
|
||||
|
||||
/**
|
||||
* Read complete check details independently of periodic polling.
|
||||
* @param ref - change request served by a registered provider.
|
||||
@@ -1995,6 +2124,25 @@ async countForViewer(forge: string, host: string, signal: AbortSignal): Promise<
|
||||
*/
|
||||
async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Read the activity of a change request: its comments, submitted reviews, commits, and changes of state.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the activity, or why the host did not provide it; `unsupported` when the provider reads no activity.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async readActivity(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestActivity | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Add a comment to a change request's conversation, then poll it at once when it is watched.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param body - Markdown source of the comment.
|
||||
* @param signal - cancellation of the request.
|
||||
* @returns undefined once the host saved the comment, or why it did not; a provider that adds no comments fails.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async addComment(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
|
||||
|
||||
/**
|
||||
* Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced
|
||||
* with `forge/review-changed`.
|
||||
@@ -2116,13 +2264,15 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
/**
|
||||
* Stream the review page's lists of the signed-in user's open change requests on every host a provider lists them on:
|
||||
* the lists read so far first, then a frame after each read settles. Readers of one repository scope share one
|
||||
* reader, which reads every `reviewListIntervalMs` while some stream lasts and backs off after failed rounds up to
|
||||
* `reviewMaxBackoffMs`; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops.
|
||||
* @param repository - one repository to list in, or null for every repository the user can read.
|
||||
* reader, which reads each host every `reviewListIntervalMs` while some stream lasts and reads a host whose read failed
|
||||
* again later each time, up to `reviewMaxBackoffMs`, without delaying the other hosts; nothing is read while no stream
|
||||
* lasts. The stream ends when `signal` aborts or the Remote stops.
|
||||
* @param repository - one repository to list in, read on its host only, or null for every repository the user can
|
||||
* read on every host.
|
||||
* @param signal - ends the stream.
|
||||
* @returns frames, each complete.
|
||||
*/
|
||||
@Remote({ mode: 'stream' }) async *reviewLists( repository: { readonly owner: string; readonly name: string } | null, signal: AbortSignal, ): AsyncIterable<ForgeReviewFrame>
|
||||
@Remote({ mode: 'stream' }) async *reviewLists( repository: ForgeReviewRepository | null, signal: AbortSignal, ): AsyncIterable<ForgeReviewFrame>
|
||||
|
||||
/**
|
||||
* Stream the number of open change requests that ask the signed-in user for a review, summed over the hosts read:
|
||||
@@ -2139,6 +2289,18 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
*/
|
||||
@Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewRefresh(signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Report whether a provider reaches one of its hosts with the Host's current credentials, for the host list on the
|
||||
* Plugins page of that provider's row. The read names no Session, so, like the review page reads, only callers that
|
||||
* may use the Host's code host credentials reach it.
|
||||
* @param forge - forge family of a registered provider, such as `gitlab`.
|
||||
* @param host - host name as the provider's configuration lists it.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the provider's readiness for the host; `unavailable` with the reason when no provider serves the family,
|
||||
* the probe fails, or it runs past `readinessTimeoutMs`.
|
||||
*/
|
||||
@Remote async hostReadiness(forge: string, host: string, signal: AbortSignal): Promise<ForgeReadiness>
|
||||
|
||||
/**
|
||||
* Poll one change request the review page shows at once; its stream reports the result.
|
||||
* @param url - web URL of the change request.
|
||||
@@ -2169,6 +2331,27 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
*/
|
||||
@Remote async reviewDescription(url: string, signal: AbortSignal): Promise<ChangeRequestDescription>
|
||||
|
||||
/**
|
||||
* Read the activity of a change request for the review page: its comments, submitted reviews, commits, and changes
|
||||
* of state.
|
||||
* @param url - web URL of the change request.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the activity, or null when the change request's provider reads none.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/activity-failed` with the
|
||||
* host's reason when the host does not provide it.
|
||||
*/
|
||||
@Remote async reviewActivity(url: string, signal: AbortSignal): Promise<ChangeRequestActivity | null>
|
||||
|
||||
/**
|
||||
* Add a comment to the conversation of a change request the review page shows.
|
||||
* @param url - web URL of the change request.
|
||||
* @param body - Markdown source of the comment.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` when `body` is
|
||||
* blank, or with the host's reason; `forgePanel/action-unknown` when the host's answer did not confirm the comment.
|
||||
*/
|
||||
@Remote async reviewComment(url: string, body: string, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Read every check of a change request the review page shows.
|
||||
* @param url - web URL of the change request.
|
||||
@@ -2288,6 +2471,17 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
*/
|
||||
@Remote async reviewMerge(url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Turn the code host's automatic merge of a change request the review page shows on, while its head is still the
|
||||
* request's `headSha`, or off.
|
||||
* @param url - web URL of the change request.
|
||||
* @param request - on with the merge method and the head commit the user confirmed, or off.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`,
|
||||
* `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason.
|
||||
*/
|
||||
@Remote async reviewSetAutoMerge(url: string, request: AutoMergeRequest, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Rerun the failed checks of a change request the review page shows.
|
||||
* @param url - web URL of the change request.
|
||||
@@ -2649,6 +2843,20 @@ registerLens(lens: ForgeLens): () => Promise<void>
|
||||
*/
|
||||
@Remote async merge(session: Session, url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Turn the code host's automatic merge of a change request of a Session on, while its head is still the request's
|
||||
* `headSha`, or off; the change request is polled again once the host answers.
|
||||
* @param session - Session the change request is bound to.
|
||||
* @param url - binding URL of the change request.
|
||||
* @param request - on with the merge method and the head commit the user confirmed, or off.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
|
||||
* `forgePanel/stale-head` when the head moved past the request's `headSha`; `forgePanel/action-failed` with the
|
||||
* host's reason when the host refuses otherwise, cannot be reached, or sets no automatic merge;
|
||||
* `forgePanel/action-unknown` when the host's answer did not confirm the change.
|
||||
*/
|
||||
@Remote async setAutoMerge(session: Session, url: string, request: AutoMergeRequest, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Rerun the failed checks of a change request of a Session while its head is still the commit whose checks the user
|
||||
* saw; the change request is polled again once the host answers.
|
||||
@@ -2881,11 +3089,11 @@ Source: [`packages/experimental/forge-session/src/index.ts`](../../packages/expe
|
||||
|
||||
#### `forge/providers-changed` — parallel
|
||||
|
||||
Announces a provider registration or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running.
|
||||
Announces a provider registration, replacement, or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Announces a provider registration or withdrawal after the registry changes.
|
||||
* Announces a provider registration, replacement, or withdrawal after the registry changes.
|
||||
* Listener failures are logged without preventing other listeners from running.
|
||||
* @param forge - family whose provider changed.
|
||||
* @mode parallel
|
||||
|
||||
+225
-17
@@ -68,6 +68,17 @@ interface ForgeProvider {
|
||||
countForViewer?(host: string, signal: AbortSignal): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>
|
||||
/** Read the description and labels of a change request. Omission declares that this provider reads no descriptions. */
|
||||
readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>
|
||||
/**
|
||||
* Read the activity of a change request: the comments in its conversation, its submitted reviews, its commits, and
|
||||
* the changes of its state. Omission declares that this provider reads no activity.
|
||||
*/
|
||||
readActivity?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestActivity | ForgeFailure>
|
||||
/**
|
||||
* Add a comment of Markdown source `body` to a change request's conversation, resolving to undefined once the host
|
||||
* saved it. A comment is never retried. Omission declares that this provider adds no comments, and its `readActivity`
|
||||
* then denies `viewerCanComment`.
|
||||
*/
|
||||
addComment?(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
|
||||
/** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */
|
||||
submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
|
||||
/**
|
||||
@@ -120,6 +131,14 @@ interface ForgeProvider {
|
||||
markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
|
||||
/** Merge a change request while its head is still `request.headSha`, resolving to undefined once merged. */
|
||||
merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
|
||||
/**
|
||||
* Turn the host's automatic merge of a change request on, while its head is still the request's `headSha`, or off,
|
||||
* resolving to undefined once the host accepted it. Omission declares that the provider sets no automatic merge, and
|
||||
* its snapshots then carry no `autoMerge`.
|
||||
*/
|
||||
setAutoMerge?(
|
||||
ref: ChangeRequestRef, request: AutoMergeRequest, signal: AbortSignal,
|
||||
): Promise<ForgeActionFailure | undefined>
|
||||
/**
|
||||
* Read the changes of a change request at head commit `headSha` as the host computes them, as one unified
|
||||
* patch with `a/` and `b/` path prefixes. A patch is returned only when it describes `headSha`; once the
|
||||
@@ -184,6 +203,28 @@ interface ForgeProvider {
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.forge.register` 返回该次注册的 disposer。它的 `replace` 用同一家族的另一个提供方替换已注册的提供方;主机列表在运行期间被修改的提供方调用它来服务新的列表:
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* What `ctx.forge.register` returns: the disposer, plus the replacement of the registered provider by another provider
|
||||
* of the same forge family, for a provider whose configuration changes while it runs.
|
||||
*/
|
||||
interface ForgeRegistrationHandle {
|
||||
/** Unregister the provider this registration holds and wait for its calls, and those of the providers it replaced, to finish. */
|
||||
(): Promise<void>
|
||||
/**
|
||||
* Replace the registered provider in one synchronous step, so no reader finds the family without a provider. The
|
||||
* replaced provider's in-flight calls are cancelled and their results discarded; watches of the family poll at once
|
||||
* and `forge/providers-changed` announces the change.
|
||||
* @param provider - provider of the same forge family.
|
||||
* @throws when the registration was withdrawn, `provider.forge` is another family, or another family's provider
|
||||
* serves one of `provider.hosts`, compared without case; the registered provider then keeps serving.
|
||||
*/
|
||||
replace(provider: ForgeProvider): void
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** One commit of a change request. */
|
||||
interface ForgeCommit {
|
||||
@@ -336,6 +377,11 @@ interface ChangeRequestSnapshot {
|
||||
readonly mergeReady: boolean
|
||||
/** Merge methods the repository accepts, the signed-in user's usual one first. */
|
||||
readonly mergeMethods: readonly MergeMethod[]
|
||||
/**
|
||||
* How the change request stands with its host's automatic merge; omitted by a provider that sets none, whose change
|
||||
* requests then offer no automatic merge.
|
||||
*/
|
||||
readonly autoMerge?: ChangeRequestAutoMerge
|
||||
/**
|
||||
* Ways the signed-in user can bring the base branch's new commits into the head branch now; empty while the head is
|
||||
* up to date, while the branches conflict, when the user cannot update the head branch, or when the provider cannot,
|
||||
@@ -487,6 +533,32 @@ interface MergeRequest {
|
||||
}
|
||||
```
|
||||
|
||||
`ctx.forge.setAutoMerge` 为用户确认过的 head 提交启用代码托管平台的自动合并(方式取快照 `mergeMethods` 中的一种),或取消它;启用后,变更请求满足合并条件时由平台自行合并。快照的 `autoMerge` 说明它是否已启用、平台给出时的合并方式与启用人,以及当前用户现在能否启用或取消。不设置自动合并的提供方两者都不提供,此时 `setAutoMerge` 不询问平台,直接返回失败。
|
||||
|
||||
```ts type-equiv
|
||||
/** How a change request stands with its host's automatic merge. */
|
||||
interface ChangeRequestAutoMerge {
|
||||
/** Whether the host merges the change request by itself once its merge requirements are met. */
|
||||
readonly enabled: boolean
|
||||
/** How the commits enter the base branch then, while enabled and the host names the method; null otherwise. */
|
||||
readonly method: MergeMethod | null
|
||||
/** Login of the account that turned it on, while enabled and the host names one; null otherwise. */
|
||||
readonly enabledBy: string | null
|
||||
/** Whether the signed-in user can turn it on now through `setAutoMerge`; false while it is on. */
|
||||
readonly canEnable: boolean
|
||||
/** Whether the signed-in user can turn it off now through `setAutoMerge`; false while it is off. */
|
||||
readonly canDisable: boolean
|
||||
}
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Turning a change request's automatic merge on for the head commit the user saw, or off. */
|
||||
type AutoMergeRequest =
|
||||
/** `method` is one of the snapshot's `mergeMethods`; the host refuses once the head is no longer `headSha`. */
|
||||
| { readonly enabled: true; readonly method: MergeMethod; readonly headSha: string }
|
||||
| { readonly enabled: false }
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Why a provider could not change a change request, or could not confirm that it did. */
|
||||
interface ForgeActionFailure {
|
||||
@@ -931,10 +1003,6 @@ interface ChangeRequestSummary {
|
||||
* `organization/slug`, when the request asks a team the user belongs to rather than the user.
|
||||
*/
|
||||
readonly viewerRequest: { readonly team: string | null } | null
|
||||
/** Issues the host closes once the change request merges, in host order, at most the provider's limit. */
|
||||
readonly closingIssues: readonly ChangeRequestIssue[]
|
||||
/** Whether the host reported more closing issues than `closingIssues` holds. */
|
||||
readonly closingIssuesTruncated: boolean
|
||||
/** ISO 8601 time of the host's last update to the change request. */
|
||||
readonly updatedAt: string
|
||||
}
|
||||
@@ -983,6 +1051,55 @@ interface ChangeRequestLabel {
|
||||
}
|
||||
```
|
||||
|
||||
## 动态与评论
|
||||
|
||||
`ctx.forge.readActivity` 读取变更请求上发生过的事:对话中的评论、已提交的评审、提交,以及状态的变化,按时间从旧到新,最多为提供方的上限,超出时保留最新的条目。`ctx.forge.addComment` 向对话添加一条评论,之后如果该变更请求正被监视,就立即轮询一次。提供方可以实现其中一个或两个方法:没有 `readActivity` 的提供方返回 `unsupported`,没有 `addComment` 的提供方返回失败;动态的 `viewerCanComment` 说明当前用户能否添加评论。评论和评审的正文是 Markdown 源文本,其中的原始 HTML 不得作为 HTML 渲染。请求以及各主机的记录如何变成条目,由 [GitHub](../../packages/experimental/forge-github/README.zh.md#use-this-package) 与 [GitLab](../../packages/experimental/forge-gitlab/README.zh.md#use-this-package) 提供方的 README 说明。
|
||||
|
||||
```ts type-equiv
|
||||
/**
|
||||
* One entry of a change request's activity: a comment in its conversation, a submitted review, a commit, a change of
|
||||
* its state, or a record the host words itself.
|
||||
*/
|
||||
type ChangeRequestActivityItem = {
|
||||
/** ISO 8601 time of the entry. */
|
||||
readonly at: string
|
||||
/** Account the entry is by, or null when the host names none or the account no longer exists. */
|
||||
readonly actor: ForgeCommentAuthor | null
|
||||
} & (
|
||||
/** A comment in the conversation. `body` is Markdown source; it may contain raw HTML, which readers must not render as HTML. */
|
||||
| { readonly kind: 'comment'; readonly body: string; readonly url: string | null }
|
||||
/**
|
||||
* A submitted review: its decision, its own Markdown text, which follows the rule of a comment's `body` and is empty
|
||||
* without one, and the number of comments it left on lines and files.
|
||||
*/
|
||||
| { readonly kind: 'review'; readonly verdict: ReviewVerdict; readonly body: string; readonly comments: number; readonly url: string | null }
|
||||
/**
|
||||
* A commit added to the change request: its object name, abbreviated when the host records only an abbreviation, and
|
||||
* the first line of its message.
|
||||
*/
|
||||
| { readonly kind: 'commit'; readonly sha: string; readonly title: string }
|
||||
| { readonly kind: 'merged' | 'closed' | 'reopened' | 'ready-for-review' | 'converted-to-draft' | 'force-pushed' }
|
||||
| { readonly kind: 'auto-merge-enabled' | 'auto-merge-disabled' }
|
||||
/** A review was requested from an account or a team, named as the host spells it; null when the host names neither. */
|
||||
| { readonly kind: 'review-requested'; readonly reviewer: string | null }
|
||||
| { readonly kind: 'renamed'; readonly from: string; readonly to: string }
|
||||
/** A record with no kind of its own, as plain text in the host's own words. */
|
||||
| { readonly kind: 'other'; readonly text: string }
|
||||
)
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** The activity of a change request. */
|
||||
interface ChangeRequestActivity {
|
||||
/** Entries oldest first, at most the provider's limit; the latest ones when the change request has more. */
|
||||
readonly items: readonly ChangeRequestActivityItem[]
|
||||
/** Whether the change request has entries older than `items` holds. */
|
||||
readonly truncated: boolean
|
||||
/** Whether the signed-in user can add a comment through `addComment`; false for a provider without it. */
|
||||
readonly viewerCanComment: boolean
|
||||
}
|
||||
```
|
||||
|
||||
## Session 绑定
|
||||
|
||||
`ctx.forgeSession` 按提供方注册的命令规则,从每个 Session 自己的日志派生其绑定:forge-github 的 `gh` 规则与 forge-gitlab 的 `glab` 规则绑定 `gh pr create` 与 `glab mr create` 结果输出的 URL,以及 `gh pr view`、`glab mr view` 及其同类引用命令所操作的变更请求,`git push` 的结果通过 `ctx.forge` 触发按 head 分支的发现;面板也会报告其检出所跟踪的分支,触发同样的发现。track、dismiss 与发现操作都是 `plugin:forge-session/binding` 插件记录,位于模型可见对话之外。`forgeChangeRequests` 投影的客户端视图随 Session 摘要下发,列出绑定但不含其状态。识别与发现规则见 [Session 绑定 README](../../packages/experimental/forge-session/README.zh.md#use-this-package)。
|
||||
@@ -1602,7 +1719,7 @@ interface ForgeLocalChanges {
|
||||
|
||||
### 代码评审页
|
||||
|
||||
[代码评审页](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package)按 URL 读取变更请求,而不经过会话绑定。它的 `forgePanel` 方法(`reviewLists`、`reviewCount`、`reviewChangeRequest`、`reviewDescription`,以及与会话绑定版本对应的各个 `review*` 读取与操作)用 `ForgeService.changeRequestFromUrl` 解析 URL,没有提供方能处理时以 `forgePanel/unrecognized-url` 失败;它们不指向任何会话资源,因此只有可以使用 Host 代码托管凭据的调用方能访问。一个列表中心只在列表流或计数流存在时读取[登录用户的列表](#viewer-lists-and-descriptions):同一仓库范围的流共用一个读取器,它每隔 `reviewListIntervalMs` 读取每个主机的每个列表,各主机并行、同一主机的列表依次读取;某主机拒绝当前用户或触发限流时,本轮不再读取它的其余列表;连续失败的轮次按 `reviewMaxBackoffMs` 为上限退避。计数每隔 `reviewCountIntervalMs` 读取一次,全部仓库范围的列表读取也会更新它。`reviewLists` 流式返回 `ForgeReviewFrame`,含每个主机的列表、最近一次成功读取的条目以及最近一次读取的失败;`reviewCount` 流式返回 `ForgeReviewCountFrame`;`reviewChangeRequest` 为显示中的变更请求流式返回 `ForgeReviewChangeRequest`,该变更请求在其流存在期间经 `ForgeService.watch` 轮询。
|
||||
[代码评审页](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package)按 URL 读取变更请求,而不经过会话绑定。它的 `forgePanel` 方法(`reviewLists`、`reviewCount`、`reviewChangeRequest`、`reviewDescription`、`reviewActivity`、`reviewComment`、`reviewSetAutoMerge`,以及与会话绑定版本对应的各个 `review*` 读取与操作)用 `ForgeService.changeRequestFromUrl` 解析 URL,没有提供方能处理时以 `forgePanel/unrecognized-url` 失败;它们不指向任何会话资源,因此只有可以使用 Host 代码托管凭据的调用方能访问。一个列表中心只在列表流或计数流存在时读取[登录用户的列表](#viewer-lists-and-descriptions):同一仓库范围的流共用一个读取器,它每隔 `reviewListIntervalMs` 读取每个主机的每个列表,各主机并行、同一主机的列表依次读取;某主机拒绝当前用户或触发限流时,本轮不再读取它的其余列表;读取失败的主机每次间隔更久再读,以 `reviewMaxBackoffMs` 为上限,其他主机保持原来的间隔。计数每隔 `reviewCountIntervalMs` 以同样的方式读取,全部仓库范围的列表读取也会更新它。范围是全部主机的全部仓库,或一个 `ForgeReviewRepository`;后者带有主机,只在该主机上读取。`reviewLists` 流式返回 `ForgeReviewFrame`,含每个主机的列表、最近一次成功读取的条目、最近一次读取的失败,以及主机拒绝当前用户时其提供方的 `readiness` 给出的登录命令;`reviewCount` 流式返回 `ForgeReviewCountFrame`;`reviewChangeRequest` 为显示中的变更请求流式返回 `ForgeReviewChangeRequest`,该变更请求在其流存在期间经 `ForgeService.watch` 轮询。
|
||||
|
||||
对话标签在 `connectWorkspace` 解析出的空白会话中开始,并用 `reviewStage` 记录该变更请求;Host 只在内存中保存这个选择,等该会话的下一条消息进入收件箱时再绑定,因此未使用的空白会话保持未绑定。
|
||||
|
||||
@@ -1741,11 +1858,12 @@ Registry of forge providers. Watchers of one change request share a single polli
|
||||
* registration ends. Unregistering cancels and awaits its in-flight calls;
|
||||
* results from the withdrawn registration are discarded.
|
||||
* @param provider - provider to serve `provider.forge` on `provider.hosts`.
|
||||
* @returns the disposer that unregisters the provider and waits for its calls to finish.
|
||||
* @returns the disposer that unregisters the provider and waits for its calls to finish, carrying
|
||||
* {@link ForgeRegistrationHandle.replace}.
|
||||
* @throws when another provider already serves the same forge or one of the same hosts, compared without case, and
|
||||
* when the provider names a batch size that is not a positive safe integer.
|
||||
*/
|
||||
register(provider: ForgeProvider): () => Promise<void>
|
||||
register(provider: ForgeProvider): ForgeRegistrationHandle
|
||||
|
||||
/**
|
||||
* Name a forge family and its change requests for readers.
|
||||
@@ -1787,13 +1905,13 @@ changeRequestUrl(ref: ChangeRequestRef): string
|
||||
async findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise<readonly ChangeRequestRef[]>
|
||||
|
||||
/**
|
||||
* Report whether the provider can reach the repository's host with current credentials.
|
||||
* @param repository - repository served by a registered provider.
|
||||
* Report whether a provider can reach one host with current credentials.
|
||||
* @param repository - forge family of a registered provider and the host to probe; a repository names both.
|
||||
* @param signal - cancellation for the probe.
|
||||
* @returns the provider's readiness for the host.
|
||||
* @throws when no provider serves the repository's forge.
|
||||
* @throws when no provider serves the forge.
|
||||
*/
|
||||
async readiness(repository: ForgeRepository, signal: AbortSignal): Promise<ForgeReadiness>
|
||||
async readiness(repository: Pick<ForgeRepository, 'forge' | 'host'>, signal: AbortSignal): Promise<ForgeReadiness>
|
||||
|
||||
/**
|
||||
* Mark a draft change request ready for review, then poll it at once when it is watched.
|
||||
@@ -1858,6 +1976,17 @@ async reviewerCandidates( ref: ChangeRequestRef, query: string, signal: AbortSig
|
||||
*/
|
||||
async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
|
||||
|
||||
/**
|
||||
* Turn the host's automatic merge of a change request on, while its head is still the request's `headSha`, or off,
|
||||
* then poll it at once when it is watched.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param request - on with the merge method and the head commit the user confirmed, or off.
|
||||
* @param signal - cancellation of the request.
|
||||
* @returns undefined once the host accepted it, or why it did not; a provider that sets no automatic merge fails.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async setAutoMerge( ref: ChangeRequestRef, request: AutoMergeRequest, signal: AbortSignal, ): Promise<ForgeActionFailure | undefined>
|
||||
|
||||
/**
|
||||
* Read complete check details independently of periodic polling.
|
||||
* @param ref - change request served by a registered provider.
|
||||
@@ -1999,6 +2128,25 @@ async countForViewer(forge: string, host: string, signal: AbortSignal): Promise<
|
||||
*/
|
||||
async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestDescription | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Read the activity of a change request: its comments, submitted reviews, commits, and changes of state.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the activity, or why the host did not provide it; `unsupported` when the provider reads no activity.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async readActivity(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestActivity | ForgeFailure>
|
||||
|
||||
/**
|
||||
* Add a comment to a change request's conversation, then poll it at once when it is watched.
|
||||
* @param ref - change request served by a registered provider.
|
||||
* @param body - Markdown source of the comment.
|
||||
* @param signal - cancellation of the request.
|
||||
* @returns undefined once the host saved the comment, or why it did not; a provider that adds no comments fails.
|
||||
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
|
||||
*/
|
||||
async addComment(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
|
||||
|
||||
/**
|
||||
* Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced
|
||||
* with `forge/review-changed`.
|
||||
@@ -2120,13 +2268,15 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
/**
|
||||
* Stream the review page's lists of the signed-in user's open change requests on every host a provider lists them on:
|
||||
* the lists read so far first, then a frame after each read settles. Readers of one repository scope share one
|
||||
* reader, which reads every `reviewListIntervalMs` while some stream lasts and backs off after failed rounds up to
|
||||
* `reviewMaxBackoffMs`; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops.
|
||||
* @param repository - one repository to list in, or null for every repository the user can read.
|
||||
* reader, which reads each host every `reviewListIntervalMs` while some stream lasts and reads a host whose read failed
|
||||
* again later each time, up to `reviewMaxBackoffMs`, without delaying the other hosts; nothing is read while no stream
|
||||
* lasts. The stream ends when `signal` aborts or the Remote stops.
|
||||
* @param repository - one repository to list in, read on its host only, or null for every repository the user can
|
||||
* read on every host.
|
||||
* @param signal - ends the stream.
|
||||
* @returns frames, each complete.
|
||||
*/
|
||||
@Remote({ mode: 'stream' }) async *reviewLists( repository: { readonly owner: string; readonly name: string } | null, signal: AbortSignal, ): AsyncIterable<ForgeReviewFrame>
|
||||
@Remote({ mode: 'stream' }) async *reviewLists( repository: ForgeReviewRepository | null, signal: AbortSignal, ): AsyncIterable<ForgeReviewFrame>
|
||||
|
||||
/**
|
||||
* Stream the number of open change requests that ask the signed-in user for a review, summed over the hosts read:
|
||||
@@ -2143,6 +2293,18 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
*/
|
||||
@Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewRefresh(signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Report whether a provider reaches one of its hosts with the Host's current credentials, for the host list on the
|
||||
* Plugins page of that provider's row. The read names no Session, so, like the review page reads, only callers that
|
||||
* may use the Host's code host credentials reach it.
|
||||
* @param forge - forge family of a registered provider, such as `gitlab`.
|
||||
* @param host - host name as the provider's configuration lists it.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the provider's readiness for the host; `unavailable` with the reason when no provider serves the family,
|
||||
* the probe fails, or it runs past `readinessTimeoutMs`.
|
||||
*/
|
||||
@Remote async hostReadiness(forge: string, host: string, signal: AbortSignal): Promise<ForgeReadiness>
|
||||
|
||||
/**
|
||||
* Poll one change request the review page shows at once; its stream reports the result.
|
||||
* @param url - web URL of the change request.
|
||||
@@ -2173,6 +2335,27 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
*/
|
||||
@Remote async reviewDescription(url: string, signal: AbortSignal): Promise<ChangeRequestDescription>
|
||||
|
||||
/**
|
||||
* Read the activity of a change request for the review page: its comments, submitted reviews, commits, and changes
|
||||
* of state.
|
||||
* @param url - web URL of the change request.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the activity, or null when the change request's provider reads none.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/activity-failed` with the
|
||||
* host's reason when the host does not provide it.
|
||||
*/
|
||||
@Remote async reviewActivity(url: string, signal: AbortSignal): Promise<ChangeRequestActivity | null>
|
||||
|
||||
/**
|
||||
* Add a comment to the conversation of a change request the review page shows.
|
||||
* @param url - web URL of the change request.
|
||||
* @param body - Markdown source of the comment.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` when `body` is
|
||||
* blank, or with the host's reason; `forgePanel/action-unknown` when the host's answer did not confirm the comment.
|
||||
*/
|
||||
@Remote async reviewComment(url: string, body: string, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Read every check of a change request the review page shows.
|
||||
* @param url - web URL of the change request.
|
||||
@@ -2292,6 +2475,17 @@ Serves the forge panel. Following a Session inspects the checkout of its current
|
||||
*/
|
||||
@Remote async reviewMerge(url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Turn the code host's automatic merge of a change request the review page shows on, while its head is still the
|
||||
* request's `headSha`, or off.
|
||||
* @param url - web URL of the change request.
|
||||
* @param request - on with the merge method and the head commit the user confirmed, or off.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`,
|
||||
* `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason.
|
||||
*/
|
||||
@Remote async reviewSetAutoMerge(url: string, request: AutoMergeRequest, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Rerun the failed checks of a change request the review page shows.
|
||||
* @param url - web URL of the change request.
|
||||
@@ -2653,6 +2847,20 @@ registerLens(lens: ForgeLens): () => Promise<void>
|
||||
*/
|
||||
@Remote async merge(session: Session, url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Turn the code host's automatic merge of a change request of a Session on, while its head is still the request's
|
||||
* `headSha`, or off; the change request is polled again once the host answers.
|
||||
* @param session - Session the change request is bound to.
|
||||
* @param url - binding URL of the change request.
|
||||
* @param request - on with the merge method and the head commit the user confirmed, or off.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
|
||||
* `forgePanel/stale-head` when the head moved past the request's `headSha`; `forgePanel/action-failed` with the
|
||||
* host's reason when the host refuses otherwise, cannot be reached, or sets no automatic merge;
|
||||
* `forgePanel/action-unknown` when the host's answer did not confirm the change.
|
||||
*/
|
||||
@Remote async setAutoMerge(session: Session, url: string, request: AutoMergeRequest, signal: AbortSignal): Promise<void>
|
||||
|
||||
/**
|
||||
* Rerun the failed checks of a change request of a Session while its head is still the commit whose checks the user
|
||||
* saw; the change request is polled again once the host answers.
|
||||
@@ -2885,11 +3093,11 @@ Source: [`packages/experimental/forge-session/src/index.ts`](../../packages/expe
|
||||
|
||||
#### `forge/providers-changed` — parallel
|
||||
|
||||
Announces a provider registration or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running.
|
||||
Announces a provider registration, replacement, or withdrawal after the registry changes. Listener failures are logged without preventing other listeners from running.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Announces a provider registration or withdrawal after the registry changes.
|
||||
* Announces a provider registration, replacement, or withdrawal after the registry changes.
|
||||
* Listener failures are logged without preventing other listeners from running.
|
||||
* @param forge - family whose provider changed.
|
||||
* @mode parallel
|
||||
|
||||
@@ -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-review-lists-host-scope/guide.md
|
||||
/:
|
||||
en: dddf0693cecf45e8
|
||||
zh: 12f61df2a91dde58
|
||||
/the-review-page-s-lists-name-a-repository-s-host-and-a-host-s-sign-in-command:
|
||||
en: ea8d6f4615b0eaf3
|
||||
zh: c67ca2a681af12d8
|
||||
/the-review-page-s-lists-name-a-repository-s-host-and-a-host-s-sign-in-command/change:
|
||||
en: 975728115489ced6
|
||||
zh: eaebfd3c156c9f3d
|
||||
/the-review-page-s-lists-name-a-repository-s-host-and-a-host-s-sign-in-command/migration:
|
||||
en: f7453271954cc5b0
|
||||
zh: 3419aced33609310
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "forgePanel.reviewLists takes the repository's host, and ForgeReviewHost gains the required signIn."
|
||||
---
|
||||
|
||||
# The review page's lists name a repository's host and a host's sign-in command
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
The `forgePanel.reviewLists` Remote took `{ owner, name } | null` as its repository and read that repository on every host. It now takes `ForgeReviewRepository | null`, which adds the required `host`, and reads the repository on that host only. `owner` holds the whole namespace of a GitLab project, nested groups included.
|
||||
|
||||
`ForgeReviewHost`, one host's entry in each `ForgeReviewFrame` the Remote streams, gains the required `signIn: string | null`: the command that signs the provider's CLI in to the host while its latest read failed for lack of sign-in, and null otherwise.
|
||||
|
||||
This affects code outside `@deepseek-ai/dsh-experimental-client-ui-forge` that calls `forgePanel.reviewLists` with a repository or builds `ForgeReviewHost` values, such as fixtures of the review page's frames. Both types come from that package. Code that only reads frames is unaffected.
|
||||
|
||||
## Migration
|
||||
|
||||
1. In every `forgePanel.reviewLists` call that passes a repository, add `host`: the host name of the provider that lists it, such as `github.com`, as `ForgeReviewHost.host` of a frame names it. Keep passing `null` for every repository on every host.
|
||||
2. In every `ForgeReviewHost` your code builds, add `signIn: null`, or the sign-in command when the value stands for a host that is not signed in.
|
||||
3. Run your type check; it passes once every call and value has the new members.
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "forgePanel.reviewLists 的仓库参数要带主机,ForgeReviewHost 新增必填的 signIn。"
|
||||
---
|
||||
|
||||
# 评审页的列表按主机指明仓库,并给出主机的登录命令
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
`forgePanel.reviewLists` 这个 Remote 原先以 `{ owner, name } | null` 作为仓库参数,并在每个主机上读取该仓库。现在它接受 `ForgeReviewRepository | null`,多了必填的 `host`,只在该主机上读取这个仓库。`owner` 保存 GitLab 项目的整个命名空间,包括嵌套的群组。
|
||||
|
||||
`ForgeReviewHost` 是该 Remote 流出的每个 `ForgeReviewFrame` 中一个主机的条目,它新增必填的 `signIn: string | null`:最近一次读取因未登录而失败时,是让提供方的 CLI 登录该主机的命令;其他情况为 null。
|
||||
|
||||
受影响的是 `@deepseek-ai/dsh-experimental-client-ui-forge` 之外、带仓库参数调用 `forgePanel.reviewLists` 的代码,以及构造 `ForgeReviewHost` 的代码,例如评审页帧的测试数据。两个类型都来自该包。只读取帧的代码不受影响。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 在每个带仓库参数的 `forgePanel.reviewLists` 调用中加上 `host`:列出该仓库的提供方的主机名,例如 `github.com`,即帧中 `ForgeReviewHost.host` 给出的名称。要读取每个主机上的所有仓库时,仍传 `null`。
|
||||
2. 在代码构造的每个 `ForgeReviewHost` 中加上 `signIn: null`;该值代表未登录的主机时,填登录命令。
|
||||
3. 运行类型检查;每处调用和取值都带上新成员后即通过。
|
||||
@@ -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-viewer-list-rows/guide.md
|
||||
/:
|
||||
en: 91fe2557764d542b
|
||||
zh: df56ac645185f7ad
|
||||
/forge-viewer-list-rows-no-longer-carry-closing-issues:
|
||||
en: 2e75c2907ea9063d
|
||||
zh: 14d2d12787acbf68
|
||||
/forge-viewer-list-rows-no-longer-carry-closing-issues/change:
|
||||
en: 5af1ffb988831fb8
|
||||
zh: e092f9f5b57ac4ec
|
||||
/forge-viewer-list-rows-no-longer-carry-closing-issues/migration:
|
||||
en: f7e099958709e74e
|
||||
zh: faaf41046a4e9b42
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "ChangeRequestSummary loses closingIssues and closingIssuesTruncated."
|
||||
---
|
||||
|
||||
# Forge viewer list rows no longer carry closing issues
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
`ChangeRequestSummary`, the row a `ForgeProvider` returns from `listForViewer`, loses `closingIssues` and `closingIssuesTruncated`. The Code review page no longer names the issues a listed change request closes; the change request's own overview still lists them from `ChangeRequestSnapshot.closingIssues`, which is unchanged. The GitHub provider's list search no longer reads closing issues.
|
||||
|
||||
This affects third-party `ForgeProvider` implementations that offer viewer lists and other code that builds or reads `ChangeRequestSummary` values. The type comes from `@deepseek-ai/dsh-experimental-forge`.
|
||||
|
||||
## Migration
|
||||
|
||||
1. In every `ChangeRequestSummary` a provider builds, remove `closingIssues` and `closingIssuesTruncated`, and drop the read that served only them.
|
||||
2. In code that reads those fields from a list row, read `closingIssues` and `closingIssuesTruncated` of the change request's `ChangeRequestSnapshot` instead, which `ctx.forge.watch` delivers.
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "ChangeRequestSummary 去掉 closingIssues 与 closingIssuesTruncated。"
|
||||
---
|
||||
|
||||
# Forge 的 viewer 列表项不再带会关闭的 issue
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
`ChangeRequestSummary`(`ForgeProvider` 的 `listForViewer` 返回的列表项)去掉了 `closingIssues` 与 `closingIssuesTruncated`。代码评审页不再显示列表里的变更请求会关闭哪些 issue;变更请求自己的概览仍从未改动的 `ChangeRequestSnapshot.closingIssues` 列出它们。GitHub 提供方的列表搜索不再读取会关闭的 issue。
|
||||
|
||||
受影响的是提供 viewer 列表的第三方 `ForgeProvider` 实现,以及其他构造或读取 `ChangeRequestSummary` 的代码。该类型来自 `@deepseek-ai/dsh-experimental-forge`。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 在提供方构造的每个 `ChangeRequestSummary` 中去掉 `closingIssues` 与 `closingIssuesTruncated`,并删除只为它们服务的读取。
|
||||
2. 原先从列表项读取这两个字段的代码,改为读取该变更请求的 `ChangeRequestSnapshot` 上的 `closingIssues` 与 `closingIssuesTruncated`,它由 `ctx.forge.watch` 送达。
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/use-this-package:
|
||||
en: 44e46809de624c40
|
||||
zh: 934dd10fbc7b7b14
|
||||
en: 92328ca9c025aa42
|
||||
zh: cef5a98969e1e68d
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
|
||||
en: ea018cbd4c2357cb
|
||||
zh: 1a73b620bf7ad1a0
|
||||
en: e20276738f193646
|
||||
zh: 79f2fa0e734f8f93
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/further-exploration:
|
||||
en: fa4d8c579ffc49ff
|
||||
zh: 5856ed7469e4585b
|
||||
@@ -30,8 +30,8 @@
|
||||
en: c1b5bfb0e5a1801e
|
||||
zh: 2bbe1a2845aa5d20
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work:
|
||||
en: bd19347052d20055
|
||||
zh: b9fe5cb782d2d534
|
||||
en: 9363a5a012479e48
|
||||
zh: be0984691356324f
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -31,16 +31,18 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish
|
||||
|
||||
- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector. The selector's searchable menu lists, most recently committed first, the current branch, then each remote's default branch, then local branches, then one group per remote headed by its name and its repository, `owner/name` for a recognized code host or else its fetch URL without the user name and password a URL can carry; typing filters the rows at once and lists the branches whose names contain the text after a short pause, and Enter chooses the first row. A remote branch is fetched, only that branch and without tags, when the worktree is created. The menu's last row, Name the new branch, opens a dialog whose field starts with the `worktreePrefix` and checks Git's branch-name rules while the name is typed; Save asks the Host, which also refuses a name the checkout already uses as a branch, and keeps the dialog open with the reason. With a chosen name, the selector shows the name before the base, and the dialog offers to use a generated name again. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the chosen branch, or else `dsh-<first 8 hexadecimal digits of the Session id>-<4 random hexadecimal digits>`, is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists.
|
||||
- **Archive cleanup** — archiving a Session lets the [worktree service](../worktree/README.md) reclaim the clean, unreferenced worktree it created, whether through the New Session option or the model's `enter_worktree` tool, while retaining the branch and its commits. A scheduled cleanup uses the archive notice “Archived; the worktree will be cleaned up”; one that ends retained returns to the ordinary notice, and one that fails replaces it with a warning while the Session stays archived. Undo cancels deletion before admission or waits for an admitted deletion; a removed checkout uses the existing Restore worktree flow. The bundle's worktree row on the Plugins page offers Keep worktrees when archiving: once saved, archiving keeps every worktree and shows the ordinary archive notice; the switch is read at each archive, so it does not affect a cleanup already scheduled.
|
||||
- **Provider hosts** — the bundle's GitHub and GitLab rows on the Plugins page each open a page that lists the hosts the provider serves. Add, or Enter, stages the typed host name, or the host and port of a pasted URL, and refuses below the field a name that is malformed, already listed, or served by the other provider; a row's remove button stages its removal, except for the last host. Save writes the whole list to the profile patch, and the provider serves it without a restart. Each saved host shows Signed in, Not signed in with the provider's sign-in command and Copy, or Can't check with the reason; the page reads these when it shows, after a save, when the window regains focus, and from the button beside the list's title. A deployment that stores settings read-only shows the list without the edits.
|
||||
- **Creation card** — while the worktree is created, a card above the composer shows the new branch and its steps: fetching a remote base branch, creating the branch, and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again, on the chosen name or a new generated one, and Continue without a worktree withdraws the request so the message goes on in the current checkout. A failed fetch also offers Use the last fetched version, which starts from the remote branch as last fetched. When the chosen branch or its directory already exists, Rename opens the naming dialog, whose Retry saves the new name and tries again.
|
||||
- **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the Session panel's checkout row, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the checkout row's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the checkout row shows a warning glyph.
|
||||
- **Code review page** — the Code review row in the left navigation counts the open change requests that ask the signed-in user for a review and opens a page with three lists: Review requested, Created by me, and Involving me, each most recently updated first across every host a provider lists them on, read only while the page or the count shows. While a list is read, skeleton rows laid out as the chosen view stand in for its items. A list item names the repository when the lists span more than one, the author, the update time, the issues it closes, and at most one hint, such as You requested changes · Requested again or a team request; the search box filters the lists by title, number, repository, and author under the [client search rule](../../client/AGENTS.md#search-and-filter) and opens a pasted change request link with Enter. The view menu, laid out like the Session list's, switches between the Detailed view and a Compact view of one line per change request, whose title scrolls into view on hover and whose hover card lists the details, reads one repository, and leaves out team requests. The repository submenu keeps offering every repository the lists named while they were read in all, with the chosen one marked, so another repository is one choice away. The detail shows the state, repository and number, labels on one line that fold into +N, the title, author, times, and branches, the ready-for-review or merge action, and a More menu; Summary shows the description beside a status column of blocks: the merge state with the branch update, the failed, running, and cancelled checks with the rerun of the failed ones, each reviewer with their outcome and the review request, and the changed lines with the linked issues, where the checks and reviewers blocks fold after five lines and list everything on request, and a finished change request shows how it ended, its changed lines, and its reviewers, Changes shows the changes view with review threads, viewed files, and review submission, where Add to chat and Quote in chat put a comment or thread into the change request's conversation draft and count it on the Chat tab, and Chat starts a conversation in a blank Session of the Workspace whose folder has the repository's name, quoting the change request and offering three prompts, and binds the change request at the first message; New conversation starts another, and Open in main view shows it in the main view. Below 880 px of page width one column shows; signing in, rate limits, and unrecognized links show where they apply.
|
||||
- **Code review page** — the Code review row in the left navigation counts the open change requests that ask the signed-in user for a review and opens a page with three lists: Review requested, Created by me, and Involving me, each most recently updated first across every host a provider lists them on, read only while the page or the count shows. While a host's first read of a list runs, skeleton rows laid out as the chosen view stand in for its items, below the items of the hosts that answered, and the list's count and its empty text wait for that host. A list item shows its title on at most two lines and its small text on at most two: the repository when the lists span more than one, the number, and the author, with the short update time at the end of that line, then at most one hint, such as Re-review requested or a team request, which shares that line where both fit and takes the second where they do not; the search box filters the lists by title, number, repository, author, and host under the [client search rule](../../client/AGENTS.md#search-and-filter) and opens a pasted change request link with Enter. The view menu, laid out like the Session list's, switches between the Detailed view and a Compact view of one line per change request, whose title scrolls into view on hover and whose hover card lists the details, reads one repository, and leaves out team requests. The repository submenu keeps offering every repository the lists named while they were read in all, with the chosen one marked, so another repository is one choice away. Once the lists name repositories on more than one host, the submenu lists each host with its repositories below it: choosing a host shows only its change requests, and choosing a repository reads the lists in it on its host only. A host whose lists could not be read shows one notice after the lists, with the sign-in command its provider names and Copy, or else the reason, and Open settings, which opens the bundle's page on the Plugins page while that page is available; when no host listed anything, the notices are all the column shows. A host whose read failed is read again later each time, up to `reviewMaxBackoffMs`, while the other hosts keep their cadence. The detail shows the state, repository and number, labels on one line that fold into +N, the title, author, times, and branches, and at the end of its first row the ready-for-review or merge action before three icon buttons: Open on the code host, which carries that host's mark, Copy link, and Refresh status. The merge action merges now, turns the code host's automatic merge on with a chosen method, or shows that it is on with its cancellation, and a merge the host would refuse shows unavailable and names why. A detail under 760 px wide folds the three buttons into a More menu, and where the row is tight the labels fold into +N first and the repository name is cut before the actions move to a second row. While the change request is read, a skeleton of the same layout stands in for it, with the three buttons already working; Summary shows the description, with the activity under it, beside a status column of blocks: the merge state with the branch update, the failed, running, and cancelled checks with the rerun of the failed ones, each reviewer with their outcome and the review request, and the changed lines with the linked issues, where the checks and reviewers blocks fold after five lines and list everything on request, and a finished change request shows how it ended, its changed lines, and its reviewers, Changes shows the changes view with review threads, viewed files, and review submission, where Add to chat and Quote in chat put a comment or thread into the change request's conversation draft and count it on the Chat tab, and Chat starts a conversation in a blank Session of the Workspace whose folder has the repository's name, quoting the change request and offering three prompts, and binds the change request at the first message; New conversation starts another, and Open in main view shows it in the main view. Below 880 px of page width one column shows; signing in, rate limits, and links whose host no provider serves show where they apply; such a link shows Unknown code host with Add host…, which opens the bundle's page on the Plugins page while that page is available.
|
||||
- **Review page activity** — under the description, the Summary tab lists what happened on the change request, oldest first: each comment as a card with its author and Markdown text, each submitted review with its decision, each commit, and each change of state, such as a review request, a title change, or the merge. Consecutive commits show as one line that unfolds them, a review that left comments on lines or files opens the Changes tab, and a long comment starts cut short with Expand. The field under the list is three lines tall and grows with its text; the row under it names the code host the comment goes to and holds the Comment button, and Command or Control with Enter sends too. While the comment is sent the field is read-only, and when the code host did not save the comment, the field keeps its text and says why. While the activity is first read, skeleton rows stand in for it. The list is read again after a comment and whenever the change request's update time or its reviews change. A provider that reads no activity shows no such section, and the field shows only where the signed-in user can comment.
|
||||
- **Session panel** — the Environment section of the Session panel gains the checkout and local changes rows after the project row, and the connection row at its end while the panel stream is lost, and a Change requests section follows it. The panel has no refresh control: when it opens and when the window regains focus, it inspects the checkout again, checks sign-in, and polls every change request, at most once every 10 seconds per Session, so changes made outside the Session appear on return. A yellow dot on the panel toggle in the Session header marks an open change request with failed checks, requested changes, or conflicts, also while the panel is hidden.
|
||||
- **Checkout row** — names the checked-out branch, or Not on a branch with the abbreviated commit on a detached HEAD, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip, shown after 500ms of hover, adds the path with the Host home shortened to `~`, and a branch name the row clips crawls into view while the pointer rests on the row. The row and its More button open the directory menu of the checkout root. For a removed worktree it shows a warning glyph and offers Restore. When Git cannot be read, the row says so, and its info button shows the failure after 500ms of hover, at once on keyboard focus, or on a press; outside a Git checkout there is no row.
|
||||
- **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 in browser, 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. 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 panel is hidden, for as long as the Session stays open; a card the user never toggled follows the default.
|
||||
- **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. 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 in browser 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 in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A row of at most 20 lines expands with one click. A longer row expands 20 lines at a time, down from the hunk above it or up from the hunk below it, the row before the first hunk only up and the row after the last hunk only down, and shows how many lines it still hides; the first click on the unknown lines after the last hunk reads the file and shows their first 20. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. While the view reads changes it has not shown yet, it says Reading changes above file cards drawn as pulsing placeholders, one changed file in two columns when sides are split, and the files menu names no count; reduced motion keeps the placeholders still. The view reads again on Refresh and the page refresh shortcut, on each navigation, Line truncated
|
||||
- **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. 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 since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A row of at most 20 lines expands with one click. A longer row expands 20 lines at a time, down from the hunk above it or up from the hunk below it, the row before the first hunk only up and the row after the last hunk only down, and shows how many lines it still hides; the first click on the unknown lines after the last hunk reads the file and shows their first 20. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. While the view reads changes it has not shown yet, it says Reading changes above file cards drawn as pulsing placeholders, one changed file in two columns when sides are split, and the files menu names no count; reduced motion keeps the placeholders still. The view reads again on Refresh and the paLine truncated
|
||||
|
||||
- **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 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.
|
||||
@@ -77,6 +79,8 @@ Each inspection also decides whether the worktree is missing: the Session's dire
|
||||
|
||||
`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.
|
||||
|
||||
`hostReadiness(forge, host)` names no Session. It asks the provider of the forge family whether it reaches the host with the Host's credentials, within `readinessTimeoutMs`, and answers `unavailable` with the reason when no provider serves the family, the probe fails, or the time runs out; a cancelled call rejects. The provider rows' host pages read it once per saved host.
|
||||
|
||||
`changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and watches the brief of each bound change request through `ctx.forge.watchBrief`, naming the state it holds for it: a merged change request is not read again, one that an earlier run of this process read waits for its interval, and any other stored one is read at once. Closed requests use the idle polling cadence, and merged requests remain watched for explicit refresh and for a snapshot read by a panel. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service.
|
||||
|
||||
`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.
|
||||
@@ -165,7 +169,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. 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.
|
||||
- **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.
|
||||
- **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 in browser. Without wrapping, the side-by-side view cuts long lines at the column edge.
|
||||
- **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.
|
||||
- **Undrawn files** — until the reader scrolls near an expanded file, it holds 22 px per drawn line, which leaves out side-by-side pairing, wrapped lines, unchanged-line rows, and review cards, so the scroll range shifts a little as files draw; its saved review comments also appear only once it draws.
|
||||
- **Find in page over long diffs** — an expanded file draws its lines only once the reader scrolls near it, so the browser's find in page does not match lines of files further down until they are drawn; a page-wide search of the diff needs a find control of the view's own.
|
||||
@@ -174,7 +178,8 @@ None for a new worktree, as its notice belongs to the first request of the Sessi
|
||||
- **Extensions** — a lens runs only once it is chosen, and its result applies to the files the view showed when it asked; reading the old side of a whole change request needs a provider that names merge bases. Line annotations stay out of the thread list, the unresolved counts, and thread navigation.
|
||||
- **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros.
|
||||
- **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, the oldest 250 for GitHub, while the Branch scope lists its newest `maxCommits`; a run must follow first parents, so commits of a merged branch can be shown one at a time but not together with the branch's own; a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head.
|
||||
- **Review page** — only the GitHub provider lists change requests and reads descriptions, so the lists hold GitHub hosts, each provider's configured hosts together; a GitLab merge request opened from a pasted link shows its status, changes, and chat, with a read failure in place of its description. Choosing among hosts and accounts waits for a second provider that lists change requests. The changes tab shows no plugin lenses, annotations, toolbar, file-menu, or comment-form entries, whose extension points name a Session, and its quotes go to the chat's draft instead of the Session's input. The chat starts in the Workspace's shared blank Session, which New Session also shows, and does not check that the Workspace is a checkout of the repository; the change request to bind waits in Host memory until the first message, so a Host restart forgets it. Pending review comments last while the page shows their change request.
|
||||
- **Review page** — the lists hold every configured host of every provider that lists change requests, the GitHub and GitLab providers today, and what a list holds on a host is its provider's to define: the GitLab provider's lists and their differences from GitHub's are in [its limitations](../forge-gitlab/README.md#known-limitations-and-deferred-work). A list row names no host; the repository submenu and the search box tell hosts apart. The left navigation's count does not follow the host or repository the lists are narrowed to. Choosing among accounts of one host is not offered. The changes tab shows no plugin lenses, annotations, toolbar, file-menu, or comment-form entries, whose extension points name a Session, and its quotes go to the chat's draft instead of the Session's input. The chat starts in the Workspace's shared blank Session, which New Session also shows, and does not check that the Workspace is a checkout of the repository; the change request to bind waits in Host memory until the first message, so a Host restart forgets it. Pending review comments last while the page shows their change request.
|
||||
- **Review page activity** — the list holds the latest entries up to the provider's limit and links to the code host for earlier ones. Comments cannot be edited, deleted, or answered with a reaction, `@` names are not completed, a comment's images that need the user's host session do not load, and the comments a review left on lines or files are read and answered on the Changes tab only.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
@@ -31,16 +31,18 @@ kind: "package-reference"
|
||||
|
||||
- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器。选择器的菜单可搜索,按最近提交排序依次列出:当前分支、每个远程的默认分支、本地分支,然后每个远程一组,组名旁显示该远程对应的仓库(识别出代码托管仓库时为 `owner/name`,否则为去掉用户名和密码后的获取地址);输入时已列出的行立即过滤,短暂停顿后列出名称包含所输入文字的分支,按 Enter 选择第一行。远程分支在创建 worktree 时获取,只获取这一个分支,不获取标签。菜单最后一行“指定新分支名称…”打开对话框:输入框以 `worktreePrefix` 开头,输入时检查 Git 的分支名规则;“确定”交给 Host,Host 还会拒绝检出中已有的分支名,拒绝时对话框保持打开并显示原因。指定名称后,选择器在基准前显示该名称,对话框也提供“改回自动命名”。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建指定的分支,未指定时为 `dsh-<Session id 前 8 位十六进制数>-<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。
|
||||
- **归档清理**——归档一个会话后,由[工作树服务](../worktree/README.zh.md)回收它创建的干净且无人引用的工作树,无论来自新会话选项还是模型的 `enter_worktree` 工具,分支及其提交保留。清理排队后,归档提示为“已归档,工作树将被清理”;最终保留时恢复为普通归档提示,失败时替换为警告而会话仍保持归档。撤销归档会取消尚未获准的删除,或等待已获准的删除结束;已移除的工作树使用现有的“恢复工作树”流程。插件页上该套件的 worktree 行提供“归档时不删除工作树”开关:保存后,归档会保留所有工作树并显示普通归档提示;开关在每次归档时读取,不影响已排队的清理。
|
||||
- **提供方主机**——插件页上该套件的 GitHub 行与 GitLab 行各打开一个页面,列出该提供方服务的主机。“添加”或 Enter 把输入的主机名(粘贴 URL 时取其中的主机与端口)加入待保存的列表;格式不对、已在列表中或已由另一个提供方服务的主机名不会加入,原因显示在输入框下方。行尾的移除按钮把该主机从待保存的列表中去掉,最后一个主机不能移除。“保存”把整个列表写入 profile patch,提供方无需重启即服务新列表。每个已保存的主机显示“已登录”、“未登录”(附提供方给出的登录命令与“复制”)或“无法检查”(附原因);页面在显示时、保存后、窗口重新获得焦点时以及点击列表标题旁的按钮时读取这些状态。以只读方式保存设置的部署只显示列表,不能修改。
|
||||
- **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支及其步骤:获取远程基准分支、创建分支、检出文件;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”再试一次,使用指定的名称或新的自动名称;“不使用工作树”撤回请求,消息在当前检出中继续发送。获取失败时还提供“使用上次获取的版本”,从上次获取的远程分支开始。指定的分支或其目录已存在时,“更改名称”打开命名对话框,其中的“重试”保存新名称并再试一次。
|
||||
- **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(会话面板检出行中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,检出行中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间检出行显示警示图标。
|
||||
- **代码评审页**——左侧导航的“代码评审”一行显示请登录用户评审的未关闭变更请求数,点开是包含“待我评审”“我创建的”“与我有关”三个列表的页面;每个列表合并提供方能列出的全部主机,按更新时间倒序,只在页面或计数显示时读取。列表读取期间,按所选视图排布的骨架行占据列表项的位置。列表项在列表跨多个仓库时写出仓库名,并显示作者、更新时间、会关闭的 issue 和至多一条提示,如“你请求过修改 · 已再次请求”或团队请求;搜索框按[客户端搜索规则](../../client/AGENTS.md#search-and-filter)以标题、编号、仓库和作者筛选列表,粘贴变更请求链接后按 Enter 打开。视图菜单与会话列表的一致:可在“详细”与“紧凑”之间切换(紧凑为每个变更请求一行,悬停时标题滚动显示完整内容,悬停卡列出详情),可只读一个仓库,也可排除团队请求。仓库子菜单始终列出在读取全部仓库时列表里出现过的仓库,并标出当前所选的那个,因此可以直接换到另一个仓库。详情显示状态、仓库与编号、单行标签(放不下时收进 +N)、标题、作者、时间和分支,以及标记为可评审或合并操作和“更多”菜单;“概要”在描述旁显示由若干区块组成的状态栏:合并状态与更新分支,失败、进行中、已取消的检查与重跑失败项,每位评审者及其结论与请求评审,变更行数与关联 issue;检查和评审者区块超过五行时折叠,可展开查看全部,已结束的变更请求则显示结束方式、变更行数和评审者,“变更”显示变更视图,含评审讨论、已审阅文件和提交评审,其中“添加到对话”“引用到对话”把评论或讨论放进该变更请求对话的草稿,并在“对话”标签上计数;“对话”在文件夹名与仓库同名的工作区的空白会话中开始对话,引用该变更请求并提供三个提示,首条消息时绑定该变更请求;“新对话”另开一个,“在主界面打开”在主界面显示它。页面宽度不足 880 px 时只显示一栏;需要登录、触发限流或链接无法识别时在对应位置提示。
|
||||
- **代码评审页**——左侧导航的“代码评审”一行显示请登录用户评审的未关闭变更请求数,点开是包含“待我评审”“我创建的”“与我有关”三个列表的页面;每个列表合并提供方能列出的全部主机,按更新时间倒序,只在页面或计数显示时读取。某个主机首次读取列表期间,按所选视图排布的骨架行占据它的列表项的位置,排在已返回的主机的列表项之后,列表的计数与空列表文字等它返回后再显示。列表项的标题至多两行,小字至多两行:列表跨多个仓库时写出仓库名,然后是编号和作者,简短的更新时间在这一行末尾,之后是至多一条提示,如“待你复审”或团队请求,放得下时与它们同一行,放不下时换到第二行;搜索框按[客户端搜索规则](../../client/AGENTS.md#search-and-filter)以标题、编号、仓库、作者和主机筛选列表,粘贴变更请求链接后按 Enter 打开。视图菜单与会话列表的一致:可在“详细”与“紧凑”之间切换(紧凑为每个变更请求一行,悬停时标题滚动显示完整内容,悬停卡列出详情),可只读一个仓库,也可排除团队请求。仓库子菜单始终列出在读取全部仓库时列表里出现过的仓库,并标出当前所选的那个,因此可以直接换到另一个仓库。列表里的仓库来自多个主机时,子菜单列出每个主机,主机的仓库列在它下面:选主机只显示该主机的变更请求,选仓库只在它所在的主机上读取列表。读取失败的主机在列表之后各显示一条提示:提供方给出登录命令时显示该命令与“复制”,否则显示原因;另有“前往配置”,在插件页可用时打开该套件的页面;没有主机列出任何内容时,这一栏只显示这些提示。读取失败的主机每次间隔更久再读,上限为 `reviewMaxBackoffMs`,其他主机保持原来的间隔。详情显示状态、仓库与编号、单行标签(放不下时收进 +N)、标题、作者、时间和分支,第一行末尾是标记为可评审或合并操作,之后是三个图标按钮:带平台图标的“在代码托管平台中打开”、“复制链接”和“刷新状态”。合并操作可以立即合并、选定方式后启用平台的自动合并,或显示自动合并已启用并可取消;平台会拒绝的合并显示为不可用并说明原因。详情不足 760 px 宽时三个按钮收进“更多”菜单;一行放不下时标签先收成 +N,再截断仓库名,最后才把操作换到第二行。变更请求读取期间,同样布局的骨架占位,三个按钮已可使用;“概要”在描述及其下方的动态旁显示由若干区块组成的状态栏:合并状态与更新分支,失败、进行中、已取消的检查与重跑失败项,每位评审者及其结论与请求评审,变更行数与关联 issue;检查和评审者区块超过五行时折叠,可展开查看全部,已结束的变更请求则显示结束方式、变更行数和评审者,“变更”显示变更视图,含评审讨论、已审阅文件和提交评审,其中“添加到对话”“引用到对话”把评论或讨论放进该变更请求对话的草稿,并在“对话”标签上计数;“对话”在文件夹名与仓库同名的工作区的空白会话中开始对话,引用该变更请求并提供三个提示,首条消息时绑定该变更请求;“新对话”另开一个,“在主界面打开”在主界面显示它。页面宽度不足 880 px 时只显示一栏;需要登录、触发限流或链接的主机没有提供方服务时在对应位置提示;后一种情况显示“未知的代码托管平台”与“添加主机…”,在插件页可用时打开该套件的页面。
|
||||
- **评审页动态**——“概要”标签页在描述下方按时间从旧到新列出变更请求上发生过的事:每条评论是一张带作者和 Markdown 正文的卡片,每次已提交的评审带它的结论,每个提交,以及每次状态变化,如请求评审、修改标题或合并。连续的提交合成一行,可展开;在行或文件上留了评论的评审会打开“变更”标签页;长评论先截短显示,可“展开”。列表下方的输入框高三行,随文字增高;它下面一行写明评论发布到哪个代码托管平台,并放着“评论”按钮,Command / Control 加 Enter 也可发送。发送期间输入框只读;代码托管平台没有保存评论时,输入框保留文字并说明原因。动态首次读取期间由骨架行占位。添加评论之后,以及变更请求的更新时间或评审发生变化时,列表会重新读取。提供方不读取动态时不显示这一区域,输入框只在当前用户可以评论时显示。
|
||||
- **会话面板**——会话面板的“环境”分栏在项目行之后增加检出行与本地变更行,面板流断开时末尾再加连接行,其后是“变更请求”分栏。面板没有刷新控件:打开时以及窗口重新获得焦点时,它会重新检查检出与登录状态,并轮询每个变更请求,每个会话每 10 秒最多一次,因此在 Session 之外做的改动在切回来时就会出现。打开中的变更请求存在检查失败、被要求修改或冲突时,会话标题栏中的面板开关带黄点,面板隐藏时也会显示。
|
||||
- **检出行**——显示当前检出的分支(分离 HEAD 时为“不在分支上”与缩写提交),并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);悬停 500ms 后出现的提示给出路径,宿主主目录缩写为 `~`;分支名放不下时,指针停在这一行上会滚动显示全文。这一行及其“更多”按钮打开检出根目录的目录菜单。worktree 已被删除时显示警示图标并提供“恢复”。无法读取 Git 时,这一行说明这一点,行尾的信息按钮在悬停 500ms、键盘聚焦或按下时给出失败原因;不在 Git 检出中时不显示这一行。
|
||||
- **连接行**——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 之后有新提交时不会合并。列表显示三张卡片;更多时,卡片之后是面板的折叠控件,用来显示其余卡片或再次收起,Session 保持打开期间保留这一选择。Session 只绑定了一个变更请求时,无论其状态如何,它的卡片默认展开;绑定多个时,所有卡片默认收起。用户展开或收起某张卡片后,在 Session 保持打开期间,更新和隐藏面板都不会改变这一选择;用户没有动过的卡片仍按默认规则。
|
||||
- **变更请求分栏**——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。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏的图标按钮和标题栏的“在浏览器中打开”悬停 500ms 后显示操作说明,键盘聚焦时立即显示。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停 500ms 后显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。不超过 20 行的折叠行点一次全部展开。更长的折叠行每次展开 20 行,可以从上方 hunk 向下展开,也可以从下方 hunk 向上展开;第一个 hunk 之前的折叠行只能向上展开,最后一个 hunk 之后的只能向下展开;折叠行上显示还隐藏的行数。最后一个 hunk 之后行数未知的折叠行,第一次点击时读取文件并显示前 20 行。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。视图读取尚未显示过的变更时,会在显示为脉动占位的文件卡片上方写出“正在读取变更…”,并排视图下其中一个已修改文件画成两栏,文件菜单不显示数量;开启“减少动态效果”时占位不动。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更Line truncated
|
||||
- **变更视图**——变更请求卡片上的“变更”一行与“查看变更”菜单项、以及本地变更行会打开一个右侧边栏标签页,列出所有变更的文件;会话面板浮在对话上方时随之关闭。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏的图标按钮和标题栏带平台图标的“在代码托管平台中打开”悬停 500ms 后显示操作说明,键盘聚焦时立即显示。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停 500ms 后显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在代码托管平台上查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。不超过 20 行的折叠行点一次全部展开。更长的折叠行每次展开 20 行,可以从上方 hunk 向下展开,也可以从下方 hunk 向上展开;第一个 hunk 之前的折叠行只能向上展开,最后一个 hunk 之后的只能向下展开;折叠行上显示还隐藏的行数。最后一个 hunk 之后行数未知的折叠行,第一次点击时读取文件并显示前 20 行。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。视图读取尚未显示过的变更时,会在显示为脉动占位的文件卡片上方写出“正在读取变更…”,并排视图下其中一个已修改文件画成两栏,文件菜单不显示数量;开启“减少动态效果”时占位不动。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,Line truncated
|
||||
|
||||
- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;文件树宽度放不下数量时,只显示各层名称,数量在悬停提示里。不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.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 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏以按已审阅比例填充的圆环和“已审阅 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 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。
|
||||
@@ -77,6 +79,8 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
|
||||
`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 加载后才结束的写入不会改动它。
|
||||
|
||||
`hostReadiness(forge, host)` 不指定 Session。它在 `readinessTimeoutMs` 内询问该 forge 家族的提供方能否用 Host 的凭据访问该主机;没有提供方服务该家族、探测失败或超时时,返回 `unavailable` 及原因;调用被取消时拒绝。提供方行的主机页面对每个已保存的主机读取一次。
|
||||
|
||||
`changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watchBrief` 监听每个已绑定变更请求的简报,同时告知自己持有的状态:已合并的不再读取,本进程此前的运行读过的等到间隔到期,其他已存的立即读取。已关闭的按空闲间隔轮询,已合并的保留监听,以接收显式刷新和面板的快照读取结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。
|
||||
|
||||
`follow` 与 `reviewChangeRequest` 监听所显示的每个变更请求的快照,并要求 `ctx.forge` 提供不早于 `statusMaxAgeMs`(默认 10 秒)的状态。Session 的面板或评审页的流开始时,如果最近一次快照结果更旧,就立即读取状态;如果结果更新,或者还没有其他快照监听方读过,就跟随常规轮询。
|
||||
@@ -165,7 +169,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
- **链接 worktree 项目**——项目本身是链接 worktree 时该选项不可用,除非沙箱策略授权了它的 Git 目录:在 workspace-write 下该目录位于可写根之外,新分支与之后的提交都无法写入。面板显示期间注册的授权在下一次检查时生效。Windows 的进程忽略这类授权,因此在 Windows 上该选项可用但创建会失败。在创建出的 worktree 内提交同样需要该授权,见 [worktree 服务](../worktree/README.zh.md#known-limitations-and-deferred-work)的说明。
|
||||
- **变更范围**——待办:上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。
|
||||
- **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。
|
||||
- **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。
|
||||
- **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在代码托管平台中查看”。不自动换行时,左右对比会在栏边截断长行。
|
||||
- **跨折叠行的高亮**——折叠的未变更行之后的行,要等文件被读取后才按它之前的内容着色:本地文件在绘制时读取,变更请求的文件要等它的某处折叠行展开后。在一段行之前超过 120 行处开始的代码块、注释或字符串,这段行仍按从段首开始着色。
|
||||
- **尚未绘制的文件**——读者滚动到展开的文件附近之前,它按每个绘制行 22 px 占位,没有计入左右对比的配对、自动换行、未变更行按钮和评审卡片,所以文件绘制时滚动范围会略有变化;它已保存的评审评论也要等它绘制后才显示。
|
||||
- **长 diff 中的页内查找**——展开的文件要等读者滚动到附近才绘制各行,所以浏览器的页内查找在更靠后的文件绘制之前匹配不到它们的行;要在整个 diff 中查找,需要视图自己的查找控件。
|
||||
@@ -174,7 +178,8 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
|
||||
- **扩展**——透镜只在被选中后运行,结果作用于发出请求时视图所显示的文件;读取整个变更请求的旧侧需要能给出合并基准的提供方。行注解不进入讨论列表、未解决数和讨论导航。
|
||||
- **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。
|
||||
- **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。
|
||||
- **代码评审页**——只有 GitHub 提供方能列出变更请求并读取描述,因此列表中只有 GitHub 主机,每个提供方配置的主机合并列出;通过粘贴链接打开的 GitLab 合并请求显示状态、变更与对话,描述处显示读取失败。在主机与账号之间选择要等到第二个能列出变更请求的提供方。“变更”标签不显示插件的透镜、行注释、工具栏、文件菜单和评论表单入口(这些扩展点以会话为对象),引用放进对话草稿而不是会话输入框。对话在工作区共享的空白会话中开始,“新会话”也显示这个会话,且不检查该工作区是否是此仓库的检出;待绑定的变更请求在首条消息前只保存在 Host 内存中,Host 重启会丢失。未提交的评审评论只在页面显示该变更请求期间保留。
|
||||
- **代码评审页**——列表合并列出每个能列出变更请求的提供方(目前是 GitHub 与 GitLab 提供方)的全部已配置主机,某个列表在一个主机上包含什么由该主机的提供方决定:GitLab 提供方的列表及其与 GitHub 的差别见[它的限制](../forge-gitlab/README.zh.md#known-limitations-and-deferred-work)。列表行不写主机,主机通过仓库子菜单和搜索框区分。左侧导航上的计数不随列表所限定的主机或仓库变化。同一主机的多个账号之间不提供选择。“变更”标签不显示插件的透镜、行注释、工具栏、文件菜单和评论表单入口(这些扩展点以会话为对象),引用放进对话草稿而不是会话输入框。对话在工作区共享的空白会话中开始,“新会话”也显示这个会话,且不检查该工作区是否是此仓库的检出;待绑定的变更请求在首条消息前只保存在 Host 内存中,Host 重启会丢失。未提交的评审评论只在页面显示该变更请求期间保留。
|
||||
- **评审页动态**——列表保留最新的条目,数量不超过提供方的上限,更早的条目给出到代码托管平台查看的链接。评论不能编辑、删除或用表情回应,`@` 名字没有补全,评论中需要用户托管平台会话的图片无法加载;评审在行或文件上留下的评论只能在“变更”标签页查看和回复。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
* the state glyph, the title, the number, and the checks outcome, which opens
|
||||
* the changes view, and, while expanded, one row per fact (checks, review,
|
||||
* merge state, the changed lines, which open its changes too, and the linked
|
||||
* issues) above the merge action. Opening on the host, copying, viewing
|
||||
* issues) above the merge action, which merges now, turns the host's automatic
|
||||
* merge on, or shows that it is on. Opening on the host, copying, viewing
|
||||
* changes, marking a draft ready, and removing live in the card's actions
|
||||
* menu, which shows on hover or focus as on the panel's other rows.
|
||||
*/
|
||||
@@ -11,44 +12,49 @@
|
||||
import { useId, useState, type MouseEvent, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, HoverCard, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular,
|
||||
IconEllipsisOutlineRegular, IconFilesDiffOutlineRegular, IconRightUpOutlineRegular, IconTriangleRightFillRegular, Menu,
|
||||
Button, HoverCard, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconClockOutlineRegular, IconCloseOutlineRegular,
|
||||
IconCopyOutlineRegular, IconEllipsisOutlineRegular, IconFilesDiffOutlineRegular, IconTriangleRightFillRegular, Menu,
|
||||
MenuItemButton, StateDot, Tooltip,
|
||||
type MenuEntry, type MenuItem, type StateDotState,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {
|
||||
ChangeRequestSnapshot, CheckState, ChecksRollup, ForgeFailure, MergeMethod, MergeRequest,
|
||||
AutoMergeRequest, ChangeRequestAutoMerge, ChangeRequestSnapshot, CheckState, ChecksRollup, ForgeFailure, MergeMethod, MergeRequest,
|
||||
} from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { ForgePanelChangeRequest } from '../types.ts'
|
||||
import { ChecksRow, IssuesRow, MergeRow, ReviewRow, RowParts, ThreadGlyph, type OverviewActions } from './ChangeRequestOverview.tsx'
|
||||
import { openOnLabel } from './forge-copy.ts'
|
||||
import { formatAgo } from './format.ts'
|
||||
import { ChangeRequestGlyph, CheckGlyph } from './glyphs.tsx'
|
||||
import { ChangeRequestGlyph, CheckGlyph, ForgeGlyph } from './glyphs.tsx'
|
||||
import type { ForgePanelKey, NS } from './locales.ts'
|
||||
import type { ForgeChangeRequestCardActionsProps } from './slots.ts'
|
||||
import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf, type ChangeRequestEntry, type ChangeRequestTone } from './status.ts'
|
||||
import {
|
||||
ciSummary, flagOf, mergeBlockers, numberOf, TONE_LABEL, toneOf, type ChangeRequestEntry, type ChangeRequestTone,
|
||||
} from './status.ts'
|
||||
import css from './Forge.module.css'
|
||||
|
||||
type Translate = PropsLocale<typeof NS>['t']
|
||||
|
||||
/**
|
||||
* What a card can do; a surface without a Session binding omits `remove`, `markReady`, `merge`, `viewChanges`, and the
|
||||
* overview actions.
|
||||
* What a card can do; a surface without a Session binding omits `remove`, `markReady`, `merge`, `autoMerge`,
|
||||
* `viewChanges`, and the overview actions.
|
||||
*/
|
||||
export interface ChangeRequestActions extends OverviewActions {
|
||||
/** Open a URL outside the app. */
|
||||
readonly openLink: (url: string) => void
|
||||
/** Copy a URL to the clipboard. */
|
||||
readonly copyLink: (url: string) => void
|
||||
/** Read the status again after a failed read. */
|
||||
readonly retry: () => void
|
||||
/** Read the status again; a surface that knows when the read ends returns a promise that settles then. */
|
||||
readonly retry: () => void | Promise<void>
|
||||
/** Remove the change request from its Session. */
|
||||
readonly remove?: ((entry: ChangeRequestEntry) => void) | undefined
|
||||
/** Mark a draft ready for review; settles once the outcome is reported. */
|
||||
readonly markReady?: ((entry: ChangeRequestEntry) => Promise<void>) | undefined
|
||||
/** Merge the change request as `request` describes; settles once the outcome is reported. */
|
||||
readonly merge?: ((entry: ChangeRequestEntry, request: MergeRequest) => Promise<void>) | undefined
|
||||
/** Turn the code host's automatic merge on or off as `request` describes; settles once the outcome is reported. */
|
||||
readonly autoMerge?: ((entry: ChangeRequestEntry, request: AutoMergeRequest) => Promise<void>) | undefined
|
||||
/** Load complete check details independently of polling; cancellation follows the open list. */
|
||||
readonly readChecks?: ((url: string, headSha: string, signal: AbortSignal) => Promise<ChangeRequestSnapshot>) | undefined
|
||||
/** Open the changes view of the change request. */
|
||||
@@ -226,12 +232,16 @@ function identity(number: number | null, snapshot: ChangeRequestSnapshot | null,
|
||||
return parts.length === 0 ? [] : [parts.join(' · ')]
|
||||
}
|
||||
|
||||
/** The merge button and its menu: a title row, one row per method with the chosen one checked, and the confirmation. */
|
||||
function MergeMenu({ snapshot, name, usual, busy, onMerge, t }: {
|
||||
/**
|
||||
* The merge button and its menu: a title row, one row per method with the chosen one checked, and the confirmation.
|
||||
* With `auto` it is the button that turns the host's automatic merge on instead, which asks for the same two things.
|
||||
*/
|
||||
function MergeMenu({ snapshot, name, usual, busy, auto = false, onMerge, t }: {
|
||||
readonly snapshot: ChangeRequestSnapshot
|
||||
readonly name: string
|
||||
readonly usual: MergeMethod
|
||||
readonly busy: boolean
|
||||
readonly auto?: boolean
|
||||
readonly onMerge: (method: MergeMethod, headSha: string) => void
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
@@ -244,7 +254,7 @@ function MergeMenu({ snapshot, name, usual, busy, onMerge, t }: {
|
||||
const close = (): void => { setOpen(false) }
|
||||
const base = snapshot.baseBranch
|
||||
const items: MenuEntry[] = [
|
||||
{ type: 'label', id: 'title', text: t('change.mergeTitle', { name, base }) },
|
||||
{ type: 'label', id: 'title', text: t(auto ? 'change.autoMergeTitle' : 'change.mergeTitle', { name, base }) },
|
||||
...snapshot.mergeMethods.map(entry => ({
|
||||
id: entry,
|
||||
label: (
|
||||
@@ -264,8 +274,8 @@ function MergeMenu({ snapshot, name, usual, busy, onMerge, t }: {
|
||||
anchor={(
|
||||
<Button
|
||||
size="sm"
|
||||
variant="primary"
|
||||
className={clsx(css.primaryAction, css.mergeAction)}
|
||||
variant={auto ? 'outline' : 'primary'}
|
||||
className={clsx(css.primaryAction, auto ? css.autoMergeAction : css.mergeAction)}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
disabled={busy}
|
||||
@@ -274,7 +284,8 @@ function MergeMenu({ snapshot, name, usual, busy, onMerge, t }: {
|
||||
setOpen(!open)
|
||||
}}
|
||||
>
|
||||
{t('change.merge')}
|
||||
{auto && <IconClockOutlineRegular size={14} />}
|
||||
{t(auto ? 'change.autoMerge' : 'change.merge')}
|
||||
<IconTriangleRightFillRegular size={10} className={clsx(css.mergeCaret, open && css.mergeCaretOpen)} />
|
||||
</Button>
|
||||
)}
|
||||
@@ -290,28 +301,90 @@ function MergeMenu({ snapshot, name, usual, busy, onMerge, t }: {
|
||||
onMerge(method, confirmedHead)
|
||||
}}
|
||||
>
|
||||
{t(stale ? 'change.mergeChanged' : 'change.mergeConfirm')}
|
||||
{t(stale ? 'change.mergeChanged' : auto ? 'change.autoMergeConfirm' : 'change.mergeConfirm')}
|
||||
</MenuItemButton>
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the merge action of an open change request the host would merge now.
|
||||
* The button of a change request whose automatic merge is on, and its menu: where it merges, how and by whom when the
|
||||
* host names them, and the cancellation when the signed-in user may cancel.
|
||||
*/
|
||||
function AutoMergeStatus({ snapshot, autoMerge, busy, onCancel, t }: {
|
||||
readonly snapshot: ChangeRequestSnapshot
|
||||
readonly autoMerge: ChangeRequestAutoMerge
|
||||
readonly busy: boolean
|
||||
readonly onCancel: (() => void) | undefined
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const [open, setOpen] = useState(false)
|
||||
const facts = [
|
||||
...autoMerge.method === null ? [] : [t('change.autoMergeMethod', { method: t(`change.mergeMethod.${autoMerge.method}`) })],
|
||||
...autoMerge.enabledBy === null ? [] : [t('change.autoMergeBy', { login: autoMerge.enabledBy })],
|
||||
]
|
||||
const items: MenuEntry[] = [
|
||||
{ type: 'label', id: 'title', text: t('change.autoMergeOnTitle', { base: snapshot.baseBranch }) },
|
||||
...facts.length === 0 ? [] : [{ type: 'label' as const, id: 'facts', text: facts.join(' · ') }],
|
||||
]
|
||||
const close = (): void => { setOpen(false) }
|
||||
return (
|
||||
<Menu
|
||||
open={open}
|
||||
onClose={close}
|
||||
portal
|
||||
align="end"
|
||||
anchor={(
|
||||
<Button size="sm" variant="outline" className={clsx(css.primaryAction, css.autoMergeAction)} data-forge-auto-merge="on"
|
||||
aria-haspopup="menu" aria-expanded={open} disabled={busy} onClick={() => { setOpen(!open) }}>
|
||||
<IconClockOutlineRegular size={14} />
|
||||
{t('change.autoMergeOn')}
|
||||
<IconTriangleRightFillRegular size={10} className={clsx(css.mergeCaret, open && css.mergeCaretOpen)} />
|
||||
</Button>
|
||||
)}
|
||||
items={items}
|
||||
onSelect={close}
|
||||
>
|
||||
{onCancel !== undefined && (
|
||||
<MenuItemButton separatorBefore onSelect={() => { close(); onCancel() }}>{t('change.autoMergeCancel')}</MenuItemButton>
|
||||
)}
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
/** The merge button of a change request its host would not merge now: it names why on hover and focus, and does nothing. */
|
||||
function BlockedMerge({ snapshot, t }: { readonly snapshot: ChangeRequestSnapshot; readonly t: Translate }): ReactNode {
|
||||
const reason = mergeBlockers(snapshot).map(key => t(key)).join(t('issues.separator'))
|
||||
return (
|
||||
<Tooltip label={reason} side="bottom" align="end">
|
||||
<Button size="sm" variant="primary" className={clsx(css.primaryAction, css.mergeAction, css.unavailable)} aria-disabled="true"
|
||||
data-forge-merge-blocked="">
|
||||
{t('change.merge')}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the merge action of an open change request that is not a draft: the merge when the host would merge now; the
|
||||
* state of its automatic merge with the cancellation when that is on; the button that turns the automatic merge on
|
||||
* when the signed-in user can; and, with `blocked`, a merge button that names why the host would not merge.
|
||||
* @param props.entry - the change request.
|
||||
* @param props.snapshot - its latest snapshot.
|
||||
* @param props.name - how menus name it.
|
||||
* @param props.actions - the actions the surface offers.
|
||||
* @param props.className - class of the wrapper, the card footer's by default.
|
||||
* @param props.blocked - whether a change request with none of the other actions shows the merge it cannot run.
|
||||
* @param props.t - forge panel copy.
|
||||
* @returns the action, or null when the host would not merge now or the surface does not offer it.
|
||||
* @returns the action, or null for a change request with none.
|
||||
*/
|
||||
export function ChangeRequestPrimary({ entry, snapshot, name, actions, className = css.footer, t }: {
|
||||
export function ChangeRequestPrimary({ entry, snapshot, name, actions, className = css.footer, blocked = false, t }: {
|
||||
readonly entry: ChangeRequestEntry
|
||||
readonly snapshot: ChangeRequestSnapshot
|
||||
readonly name: string
|
||||
readonly actions: ChangeRequestActions
|
||||
readonly className?: string | undefined
|
||||
readonly blocked?: boolean | undefined
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
// One request at a time: the action stays disabled until the previous one settles.
|
||||
@@ -320,22 +393,30 @@ export function ChangeRequestPrimary({ entry, snapshot, name, actions, className
|
||||
setBusy(true)
|
||||
void action().finally(() => { setBusy(false) })
|
||||
}
|
||||
const { merge } = actions
|
||||
const { merge, autoMerge: setAutoMerge } = actions
|
||||
if (snapshot.state !== 'open' || snapshot.draft) return null
|
||||
const [usual] = snapshot.mergeMethods
|
||||
if (!snapshot.mergeReady || usual === undefined || merge === undefined) return null
|
||||
return (
|
||||
<div className={className}>
|
||||
<MergeMenu
|
||||
snapshot={snapshot}
|
||||
name={name}
|
||||
usual={usual}
|
||||
busy={busy}
|
||||
onMerge={(method, headSha) => { run(() => merge(entry, { method, headSha })) }}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
const auto = snapshot.autoMerge
|
||||
let action: ReactNode
|
||||
if (snapshot.mergeReady && usual !== undefined && merge !== undefined) {
|
||||
action = (
|
||||
<MergeMenu snapshot={snapshot} name={name} usual={usual} busy={busy} t={t}
|
||||
onMerge={(method, headSha) => { run(() => merge(entry, { method, headSha })) }} />
|
||||
)
|
||||
} else if (auto?.enabled === true) {
|
||||
const cancel = auto.canDisable && setAutoMerge !== undefined ? () => { run(() => setAutoMerge(entry, { enabled: false })) } : undefined
|
||||
action = <AutoMergeStatus snapshot={snapshot} autoMerge={auto} busy={busy} onCancel={cancel} t={t} />
|
||||
} else if (auto?.canEnable === true && usual !== undefined && setAutoMerge !== undefined) {
|
||||
action = (
|
||||
<MergeMenu auto snapshot={snapshot} name={name} usual={usual} busy={busy} t={t}
|
||||
onMerge={(method, headSha) => { run(() => setAutoMerge(entry, { enabled: true, method, headSha })) }} />
|
||||
)
|
||||
} else if (blocked) {
|
||||
action = <BlockedMerge snapshot={snapshot} t={t} />
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
return <div className={className}>{action}</div>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -366,7 +447,10 @@ function CardMenu({ entry, snapshot, name, url, actions, t }: {
|
||||
item: { id: 'changes', label: t('change.viewChanges'), icon: <IconFilesDiffOutlineRegular size={14} /> },
|
||||
run: () => { viewChanges(entry) },
|
||||
}] : [],
|
||||
{ item: { id: 'open', label: t('change.view'), icon: <IconRightUpOutlineRegular size={14} /> }, run: () => { actions.openLink(url) } },
|
||||
{
|
||||
item: { id: 'open', label: openOnLabel(t, entry.forge?.label ?? null), icon: <ForgeGlyph forge={entry.forge?.forge ?? null} /> },
|
||||
run: () => { actions.openLink(url) },
|
||||
},
|
||||
{ item: { id: 'copy', label: t('change.copy'), icon: <IconCopyOutlineRegular size={14} /> }, run: () => { actions.copyLink(url) } },
|
||||
...ready === undefined ? [] : [{
|
||||
item: { id: 'ready', label: t('change.markReady'), icon: <IconCheckCircleOutlineRegular size={14} />, disabled: busy },
|
||||
@@ -571,8 +655,12 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc
|
||||
<div className={css.notice}>
|
||||
<span>{t(notice)}</span>
|
||||
{entry.ref === null
|
||||
? <Button size="sm" variant="outline" onClick={() => { actions.openLink(url) }}>{t('change.view')}</Button>
|
||||
: <Button size="sm" variant="outline" onClick={actions.retry}>{t('retry')}</Button>}
|
||||
? (
|
||||
<Button size="sm" variant="outline" onClick={() => { actions.openLink(url) }}>
|
||||
{openOnLabel(t, entry.forge?.label ?? null)}
|
||||
</Button>
|
||||
)
|
||||
: <Button size="sm" variant="outline" onClick={() => { void actions.retry() }}>{t('retry')}</Button>}
|
||||
</div>
|
||||
)}
|
||||
{expanded && snapshot !== null && (
|
||||
|
||||
@@ -37,6 +37,8 @@ export interface ChangeRequestsSectionInjected {
|
||||
readonly markReady: (entry: ChangeRequestEntry) => Promise<void>
|
||||
/** Merge a change request as `request` describes; settles once the outcome is reported. */
|
||||
readonly merge: (entry: ChangeRequestEntry, request: MergeRequest) => Promise<void>
|
||||
/** Turn a change request's automatic merge on or off; settles once the outcome is reported. */
|
||||
readonly autoMerge: NonNullable<ChangeRequestActions['autoMerge']>
|
||||
/** Read the complete checks of an opened change request. */
|
||||
readonly readChecks: NonNullable<ChangeRequestActions['readChecks']>
|
||||
/** Rerun the failed checks or one check; settles once the outcome is reported. */
|
||||
@@ -158,7 +160,7 @@ function SignInRow({ need, copyText, t }: {
|
||||
* @returns the cards, or null with neither bound change requests nor a sign-in to complete.
|
||||
*/
|
||||
export function ChangeRequestsSection({
|
||||
usePanel, useLocale, dismissOverlay, refresh, remove, markReady, merge, readChecks,
|
||||
usePanel, useLocale, dismissOverlay, refresh, remove, markReady, merge, autoMerge, readChecks,
|
||||
rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, viewChanges, useStore, actions: store, renderSlot,
|
||||
renderFactorySlot, t,
|
||||
}: ChangeRequestsSectionProps): ReactNode {
|
||||
@@ -174,7 +176,7 @@ export function ChangeRequestsSection({
|
||||
const signIn = signInNeedOf(state)
|
||||
if (signIn === null && state.changeRequests.length === 0) return null
|
||||
const actions: ChangeRequestActions = {
|
||||
openLink, copyLink: copyText, retry: () => { void refresh() }, remove, markReady, merge, readChecks,
|
||||
openLink, copyLink: copyText, retry: () => { void refresh() }, remove, markReady, merge, autoMerge, readChecks,
|
||||
rerunChecks, requestReviews, reviewerCandidates, updateBranch,
|
||||
viewChanges: (entry) => {
|
||||
viewChanges(entry)
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, IconBranchOutlineRegular, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular,
|
||||
IconInfoOutlineRegular, IconFilesDiffOutlineRegular, IconNowrapFillRegular, IconRightUpOutlineRegular, IconWorkspaceTreeOutlineRegular,
|
||||
IconInfoOutlineRegular, IconFilesDiffOutlineRegular, IconNowrapFillRegular, IconWorkspaceTreeOutlineRegular,
|
||||
IconWrapFillRegular,
|
||||
Menu, Tooltip,
|
||||
type MenuEntry,
|
||||
@@ -55,7 +55,7 @@ import { changedFileTree, filesInTreeOrder } from './file-tree.ts'
|
||||
import { ChangedFilesMenu, type ChangedFilesProps, type ChangedFilesState } from './ChangedFiles.tsx'
|
||||
import { ChangesLoading } from './ChangesLoading.tsx'
|
||||
import { drawnLines, matchesHunks, revealGap, textLines, type GapExpansion, type GapReveal } from './diff-rows.ts'
|
||||
import { ChangeRequestGlyph } from './glyphs.tsx'
|
||||
import { ChangeRequestGlyph, ForgeGlyph } from './glyphs.tsx'
|
||||
import type { ForgePanelKey, NS } from './locales.ts'
|
||||
import { useForgeCopy } from './forge-copy.ts'
|
||||
import { RefreshGlyph } from './RefreshGlyph.tsx'
|
||||
@@ -428,9 +428,9 @@ function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDis
|
||||
{t('review.submit')}{reviewCount > 0 ? ` (${reviewCount})` : ''}
|
||||
</Button>
|
||||
</span>
|
||||
<Tooltip label={t('change.view')} side="bottom" delayMs={500}>
|
||||
<button type="button" className={css.tool} aria-label={t('change.view')} onClick={() => { openLink(href) }}>
|
||||
<IconRightUpOutlineRegular size={14} />
|
||||
<Tooltip label={t('change.viewOn')} side="bottom" delayMs={500}>
|
||||
<button type="button" className={css.tool} aria-label={t('change.viewOn')} onClick={() => { openLink(href) }}>
|
||||
<ForgeGlyph forge={entry?.forge?.forge ?? null} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
@@ -1070,11 +1070,13 @@ export function ChangesView({
|
||||
// Thread groups keep their identity across renders that change neither the threads nor what their cards share, so
|
||||
// only the sections whose threads changed redraw.
|
||||
const url = data?.kind === 'change' ? data.url : null
|
||||
const family = entry?.forge?.forge ?? null
|
||||
const threadActions = useMemo((): ThreadActions | null => review === null || url === null ? null : {
|
||||
author: prAuthor,
|
||||
addToInput: (thread, range) => addThreadToInput(thread, url, range),
|
||||
quoteCopy,
|
||||
openLink,
|
||||
forge: family,
|
||||
readText: (commit, path) => changeRequestText(url, commit, path),
|
||||
inputFailed: () => { live.current.report(quoteCopy?.failed ?? 'thread.inputFailed') },
|
||||
focused: focus,
|
||||
@@ -1083,7 +1085,7 @@ export function ChangesView({
|
||||
reviewStarted: review.pendingReview !== null,
|
||||
canReview: review.viewerCanReview,
|
||||
},
|
||||
}, [review, url, prAuthor, addThreadToInput, quoteCopy, openLink, changeRequestText, focus])
|
||||
}, [review, url, prAuthor, addThreadToInput, quoteCopy, openLink, family, changeRequestText, focus])
|
||||
const fileThreads = useMemo(() => new Map<string, FileThreads>(threadActions === null ? []
|
||||
: [...placed.files].map(([path, group]) => [path, { ...group, actions: threadActions }])), [placed.files, threadActions])
|
||||
/** Show a file's next unresolved thread in display order after the one last shown, or its first. */
|
||||
@@ -1511,7 +1513,7 @@ export function ChangesView({
|
||||
if (covering) setThreadList(value => ({ ...value, open: false }))
|
||||
openThread(entry, covering)
|
||||
}}
|
||||
openLink={openLink} close={closeThreadList} t={t} />
|
||||
openLink={openLink} forge={family} close={closeThreadList} t={t} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -343,6 +343,29 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* The automatic merge button: outlined and as tall as the merge button; its glyph takes the accent once it is on. */
|
||||
.primaryAction.autoMergeAction {
|
||||
gap: 6px;
|
||||
padding: 0 10px 0 12px;
|
||||
}
|
||||
|
||||
.autoMergeAction[data-forge-auto-merge='on'] > svg:first-child {
|
||||
color: var(--dsw-alias-state-business-primary);
|
||||
}
|
||||
|
||||
/* A merge the host would refuse now: the button stays reachable so it can say why, and looks and acts disabled. */
|
||||
.primaryAction.mergeAction.unavailable {
|
||||
background: color-mix(in srgb, var(--dsw-alias-button-info-fill) 92%, var(--dsw-alias-label-primary));
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.primaryAction.mergeAction.unavailable:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--dsw-alias-button-info-fill) 92%, var(--dsw-alias-label-primary));
|
||||
}
|
||||
}
|
||||
|
||||
/* A solid caret that points down, and up while the menu is open. */
|
||||
.mergeCaret {
|
||||
flex: none;
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
/* A provider row page: the host list under the Plugins form's tokens. */
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 12px 0;
|
||||
}
|
||||
|
||||
/* The recheck button stands in the column of the rows' removal buttons. */
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding-right: 8px;
|
||||
}
|
||||
|
||||
.label {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
line-height: 1.5;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.iconButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: none;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
background: none;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.iconButton:disabled,
|
||||
.iconButton[aria-disabled='true'] {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.iconButton:hover:not(:disabled, [aria-disabled='true']) {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.iconButton:focus-visible {
|
||||
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* The list is a group of read values, so it has the fields' edge without their fill. */
|
||||
.hosts {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0.5px solid var(--dsw-alias-border-l4);
|
||||
border-radius: var(--dsw-radius-md);
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.host {
|
||||
padding: 8px 8px 8px 12px;
|
||||
}
|
||||
|
||||
.host + .host {
|
||||
border-top: 0.5px solid var(--dsw-alias-border-l2);
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 24px;
|
||||
}
|
||||
|
||||
/* A host name wraps instead of being cut, so a long one stays readable where no pointer can hover it. */
|
||||
.name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: 13px;
|
||||
line-height: 18px;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.state,
|
||||
.unsaved {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12.5px;
|
||||
line-height: 18px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.unsaved {
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
/* The command and the reason end where the state text ends, short of the removal button's column. */
|
||||
.command {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
margin: 6px 34px 2px 0;
|
||||
padding: 4px 4px 4px 10px;
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
background: var(--dsw-alias-bg-module-platform);
|
||||
}
|
||||
|
||||
.commandText {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 5px 0;
|
||||
font-family: var(--ds-font-family-code);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.reason {
|
||||
margin: 4px 34px 2px 0;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.addRow {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 34px;
|
||||
padding: 0 12px;
|
||||
border: 0.5px solid var(--dsw-alias-border-l4);
|
||||
border-radius: var(--dsw-radius-md);
|
||||
background: var(--dsw-alias-bg-layer-3);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.input::placeholder {
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
.input:focus-visible {
|
||||
outline: none;
|
||||
border-color: var(--dsw-alias-state-business-primary);
|
||||
}
|
||||
|
||||
.input:disabled {
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.input[aria-invalid='true'] {
|
||||
border-color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
|
||||
.add {
|
||||
flex: none;
|
||||
height: 34px;
|
||||
padding: 0 14px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.hint,
|
||||
.invalid {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
.invalid {
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/** A provider row's page on the Plugins page: the hosts the provider serves, each with its sign-in state. */
|
||||
import { useEffect, useId, useRef, useState, type ReactNode } from 'react'
|
||||
import {
|
||||
Button, IconRefreshOutlineRegular, IconTrashOutlineRegular, SettingsForm, StateDot, Tooltip, type StateDotState,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import type { ForgePanelKey, NS } from './locales.ts'
|
||||
import type { HostFormActions, HostFormState, HostProblem } from './host-settings-form.ts'
|
||||
import type { HostSignIn } from './host-sign-in.ts'
|
||||
import { rowFormLabels } from './row-form-labels.ts'
|
||||
import css from './HostSettings.module.css'
|
||||
|
||||
/** The forge family of a provider row that has a host page. */
|
||||
export type HostForge = 'github' | 'gitlab'
|
||||
|
||||
/** Registration-side face of a provider row's host page. */
|
||||
export interface HostSettingsInjected extends HostFormActions {
|
||||
readonly hooks: {
|
||||
/** The saved and staged host lists. */
|
||||
readonly hostForm: SnapshotStore<HostFormState>
|
||||
/** Sign-in state by saved host. */
|
||||
readonly signIn: SnapshotStore<ReadonlyMap<string, HostSignIn>>
|
||||
}
|
||||
/** Which provider the row mounts. */
|
||||
readonly forge: HostForge
|
||||
/** Read the sign-in state of the saved hosts; `visibly` shows each host as being checked until its read answers. */
|
||||
readonly checkSignIn: (hosts: readonly string[], visibly: boolean) => void
|
||||
/** Copy a sign-in command and report the outcome. */
|
||||
readonly copyCommand: (command: string) => void
|
||||
}
|
||||
|
||||
export type HostSettingsProps = PropsRuntime<'plugins.row.config'> & PropsLocale<typeof NS> & InjectFace<HostSettingsInjected>
|
||||
|
||||
type Translate = HostSettingsProps['t']
|
||||
|
||||
/** What differs between the two rows' pages. */
|
||||
interface ForgeCopy {
|
||||
/** Key of what the provider's hosts call a change request. */
|
||||
readonly noun: ForgePanelKey
|
||||
/** The CLI the provider signs in with. */
|
||||
readonly cli: string
|
||||
/** A host name the field shows as its placeholder and a refusal names as an example. */
|
||||
readonly example: string
|
||||
/** Key of the refusal of a host the other provider serves. */
|
||||
readonly taken: ForgePanelKey
|
||||
}
|
||||
|
||||
const FORGES: Record<HostForge, ForgeCopy> = {
|
||||
github: { noun: 'noun.pullRequest', cli: 'gh', example: 'github.example.com', taken: 'hosts.taken.gitlab' },
|
||||
gitlab: { noun: 'noun.mergeRequest', cli: 'glab', example: 'gitlab.example.com', taken: 'hosts.taken.github' },
|
||||
}
|
||||
|
||||
const STATES: Record<HostSignIn['state'], { readonly dot: StateDotState; readonly key: ForgePanelKey }> = {
|
||||
ready: { dot: 'done', key: 'hosts.state.ready' },
|
||||
unauthenticated: { dot: 'warning', key: 'hosts.state.unauthenticated' },
|
||||
unavailable: { dot: 'error', key: 'hosts.state.unavailable' },
|
||||
checking: { dot: 'ongoing', key: 'hosts.state.checking' },
|
||||
}
|
||||
|
||||
const CHECKING: HostSignIn = { state: 'checking' }
|
||||
|
||||
function problemText(problem: HostProblem, forge: HostForge, t: Translate): string {
|
||||
switch (problem.kind) {
|
||||
case 'invalid': return t('hosts.invalid', { example: FORGES[forge].example })
|
||||
case 'duplicate': return t('hosts.duplicate', { host: problem.host })
|
||||
case 'taken': return t(FORGES[forge].taken, { host: problem.host })
|
||||
/* v8 ignore next -- closed union. */
|
||||
default: return assertNever(problem, 'HostProblem')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One host of the list: its name, its sign-in state once saved, and its removal. A host that needs sign-in shows the
|
||||
* provider's command to copy; a host that could not be checked shows why.
|
||||
*/
|
||||
function HostRow({ host, signIn, removable, disabled, onRemove, onCopy, t }: {
|
||||
readonly host: string
|
||||
/** The sign-in state of a saved host, or undefined for a host a save would add. */
|
||||
readonly signIn: HostSignIn | undefined
|
||||
/** Whether another host would remain. */
|
||||
readonly removable: boolean
|
||||
readonly disabled: boolean
|
||||
readonly onRemove: (host: string) => void
|
||||
readonly onCopy: (command: string) => void
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const command = signIn?.state === 'unauthenticated' ? signIn.signIn?.command : undefined
|
||||
const reason = signIn !== undefined && signIn.state !== 'checking' && signIn.state !== 'ready' && command === undefined ? signIn.message : null
|
||||
return (
|
||||
<li className={css.host} data-forge-host={host}>
|
||||
<div className={css.row}>
|
||||
<span className={css.name}>{host}</span>
|
||||
{signIn === undefined
|
||||
? <span className={css.unsaved}>{t('hosts.state.unsaved')}</span>
|
||||
: (
|
||||
<span className={css.state} data-state={signIn.state}>
|
||||
<StateDot state={STATES[signIn.state].dot} />
|
||||
{t(STATES[signIn.state].key)}
|
||||
</span>
|
||||
)}
|
||||
<Tooltip label={removable ? t('hosts.remove', { host }) : t('hosts.keepOne')} side="bottom" delayMs={500}>
|
||||
<button type="button" className={css.iconButton} aria-label={t('hosts.remove', { host })} aria-disabled={removable ? undefined : true}
|
||||
disabled={disabled} onClick={() => { if (removable) onRemove(host) }}>
|
||||
<IconTrashOutlineRegular size={14} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
{command !== undefined && (
|
||||
<div className={css.command}>
|
||||
<code className={css.commandText}>{command}</code>
|
||||
<Button size="sm" aria-label={t('signin.copy')} onClick={() => { onCopy(command) }}>{t('signin.copyShort')}</Button>
|
||||
</div>
|
||||
)}
|
||||
{reason !== null && reason !== '' && <p className={css.reason}>{reason}</p>}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a provider row's configuration: the hosts it serves, staged until one save, and the sign-in state of each
|
||||
* saved host, read when the page shows, after a save, and when the window regains focus. The summary view names the list.
|
||||
* @param props - the Plugins page view, the staged list with its actions, the sign-in states, and copy.
|
||||
* @returns the row page's form, or the summary line.
|
||||
*/
|
||||
export function HostSettings(props: HostSettingsProps): ReactNode {
|
||||
const { t, forge, view } = props
|
||||
const labelId = useId()
|
||||
const messageId = useId()
|
||||
const state = props.useHostForm(value => value)
|
||||
const signIn = props.useSignIn(value => value)
|
||||
const [text, setText] = useState('')
|
||||
const [problem, setProblem] = useState<HostProblem>()
|
||||
// The effect reads the latest list and check through refs, so it runs again only when the saved hosts change.
|
||||
const saved = useRef(state.saved)
|
||||
saved.current = state.saved
|
||||
const checkSignIn = useRef(props.checkSignIn)
|
||||
checkSignIn.current = props.checkSignIn
|
||||
const shown = view === 'page' && state.available
|
||||
const savedKey = state.saved.join('\n')
|
||||
useEffect(() => {
|
||||
if (!shown) return
|
||||
const again = (): void => { checkSignIn.current(saved.current, false) }
|
||||
again()
|
||||
window.addEventListener('focus', again)
|
||||
return () => { window.removeEventListener('focus', again) }
|
||||
}, [shown, savedKey])
|
||||
if (view === 'summary') return t('hosts.title')
|
||||
const disabled = !state.writable || state.saving
|
||||
const add = (): void => {
|
||||
const refused = props.add(text)
|
||||
setProblem(refused)
|
||||
if (refused === undefined) setText('')
|
||||
}
|
||||
return (
|
||||
<SettingsForm labels={rowFormLabels(t, 'hosts.unavailable')} state={state} onSave={props.save} onDiscard={props.discard}>
|
||||
<div className={css.field}>
|
||||
<div className={css.head}>
|
||||
<span className={css.label} id={labelId}>{t('hosts.title')}</span>
|
||||
<Tooltip label={t('hosts.recheck')} side="bottom" delayMs={500}>
|
||||
<button type="button" className={css.iconButton} aria-label={t('hosts.recheck')} onClick={() => { props.checkSignIn(state.saved, true) }}>
|
||||
<IconRefreshOutlineRegular size={14} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<ul className={css.hosts} aria-labelledby={labelId}>
|
||||
{state.draft.map(host => (
|
||||
<HostRow key={host} host={host} signIn={state.saved.includes(host) ? signIn.get(host) ?? CHECKING : undefined}
|
||||
removable={state.draft.length > 1} disabled={disabled} onRemove={props.remove} onCopy={props.copyCommand} t={t} />
|
||||
))}
|
||||
</ul>
|
||||
<div className={css.addRow}>
|
||||
<input className={css.input} type="text" value={text} placeholder={FORGES[forge].example} aria-label={t('hosts.addLabel')}
|
||||
aria-invalid={problem === undefined ? undefined : true} aria-describedby={messageId} disabled={disabled}
|
||||
autoComplete="off" autoCapitalize="none" spellCheck={false}
|
||||
onChange={(event) => { setText(event.target.value); setProblem(undefined) }}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Enter' || event.nativeEvent.isComposing) return
|
||||
event.preventDefault()
|
||||
add()
|
||||
}} />
|
||||
<Button variant="outline" className={css.add} disabled={disabled || text.trim() === ''} onClick={add}>{t('hosts.add')}</Button>
|
||||
</div>
|
||||
{problem === undefined
|
||||
? <p id={messageId} className={css.hint}>{t('hosts.hint', { noun: t(FORGES[forge].noun), cli: FORGES[forge].cli })}</p>
|
||||
: <p id={messageId} className={css.invalid} role="alert">{problemText(problem, forge, t)}</p>}
|
||||
</div>
|
||||
</SettingsForm>
|
||||
)
|
||||
}
|
||||
@@ -8,13 +8,14 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconEllipsisOutlineRegular, IconRightUpOutlineRegular, MarkdownText,
|
||||
Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconEllipsisOutlineRegular, MarkdownText,
|
||||
Menu, Tag, Tooltip, type MarkdownLabels,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ForgeReviewComment, ForgeReviewThread, ForgeReviewWrite, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { formatAgo } from './format.ts'
|
||||
import { ForgeGlyph } from './glyphs.tsx'
|
||||
import { anchorRange, hunkExcerpt, type ThreadPlace } from './review-threads.ts'
|
||||
import { SplitAction } from './ReviewComposer.tsx'
|
||||
import { INPUT_QUOTE_COPY, settleQuote, type QuoteCopy } from './review.ts'
|
||||
@@ -50,6 +51,8 @@ export interface ThreadActions {
|
||||
readonly quoteCopy?: QuoteCopy | undefined
|
||||
/** Open a URL outside the app. */
|
||||
readonly openLink: (url: string) => void
|
||||
/** Forge family of the change request's provider, whose mark the opening action carries; null without a provider. */
|
||||
readonly forge: string | null
|
||||
/** Read a file of the change request's repository at a commit. */
|
||||
readonly readText: (commit: string, path: string) => Promise<RemoteResult<string>>
|
||||
/** Report that the input refused a thread. */
|
||||
@@ -393,7 +396,7 @@ export function ThreadCard({ thread, place, actions, t }: PropsLocale<typeof NS>
|
||||
{t((actions.quoteCopy ?? INPUT_QUOTE_COPY).add)}
|
||||
</Button>
|
||||
{url !== null && <Button size="sm" onClick={() => { actions.openLink(url) }}>
|
||||
<IconRightUpOutlineRegular size={14} />{t('thread.openOnHost')}
|
||||
<ForgeGlyph forge={actions.forge} />{t('thread.openOnHost')}
|
||||
</Button>}
|
||||
{writes !== null && thread.viewerCanResolve && <Resolution thread={thread} writes={writes} t={t} />}
|
||||
</div>
|
||||
|
||||
@@ -5,11 +5,12 @@
|
||||
*/
|
||||
|
||||
import { useLayoutEffect, useMemo, useRef, type KeyboardEvent, type ReactNode } from 'react'
|
||||
import { IconChevronLeftOutlineRegular, IconCloseOutlineRegular, IconRightUpOutlineRegular, Tag, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { IconChevronLeftOutlineRegular, IconCloseOutlineRegular, Tag, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { ForgeDiffFile } from '../types.ts'
|
||||
import { FileLabel } from './FileLabel.tsx'
|
||||
import { ForgeGlyph } from './glyphs.tsx'
|
||||
import { SegmentedChoice } from './ReviewControls.tsx'
|
||||
import { Avatar } from './ReviewThreads.tsx'
|
||||
import { anchorRange, inFileOrder, passesFilter, THREAD_FILTERS, type ThreadFilter, type ThreadPlace } from './review-threads.ts'
|
||||
@@ -41,6 +42,8 @@ export interface ThreadListProps extends PropsLocale<typeof NS> {
|
||||
readonly open: (entry: PlacedThread, covering: boolean) => void
|
||||
/** Open a URL outside the app. */
|
||||
readonly openLink: (url: string) => void
|
||||
/** Forge family of the change request's provider, whose mark the opening action carries; null without a provider. */
|
||||
readonly forge: string | null
|
||||
/** Close the list at the reader's request. */
|
||||
readonly close: () => void
|
||||
}
|
||||
@@ -157,7 +160,7 @@ export function ThreadList(props: ThreadListProps): ReactNode {
|
||||
<div className={css.footer}>
|
||||
{props.truncated && <>{t('thread.truncated', { count: threads.length })}{' · '}</>}
|
||||
<button type="button" className={css.link} onClick={() => { props.openLink(props.url) }}>
|
||||
<IconRightUpOutlineRegular size={14} />{t('thread.openAll')}
|
||||
<ForgeGlyph forge={props.forge} />{t('thread.openAll')}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -1,22 +1,15 @@
|
||||
/** The worktree service's row page on the Plugins page: the archive cleanup switch. */
|
||||
import { useId } from 'react'
|
||||
import { SettingsForm, Switch } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { SettingsFormLabels } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
|
||||
import type { NS } from './locales.ts'
|
||||
import { rowFormLabels } from './row-form-labels.ts'
|
||||
import type { WorktreeSettingsInjected } from './worktree-settings-form.ts'
|
||||
import css from './WorktreeSettings.module.css'
|
||||
|
||||
export type WorktreeSettingsProps = PropsRuntime<'plugins.row.config'> & PropsLocale<typeof NS> & InjectFace<WorktreeSettingsInjected>
|
||||
|
||||
function formLabels(t: WorktreeSettingsProps['t']): SettingsFormLabels {
|
||||
return {
|
||||
unavailable: t('settings.unavailable'), readOnly: t('settings.readOnly'), saveFailed: t('settings.saveFailed'),
|
||||
save: t('settings.save'), saving: t('settings.saving'),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the worktree row's configuration: one switch that keeps every
|
||||
* checkout when its Session is archived. The summary view names the switch.
|
||||
@@ -29,7 +22,7 @@ export function WorktreeSettings(props: WorktreeSettingsProps) {
|
||||
const state = props.useWorktreeForm(value => value)
|
||||
if (props.view === 'summary') return t('settings.retainOnArchive.title')
|
||||
const disabled = !state.writable || state.saving
|
||||
return <SettingsForm labels={formLabels(t)} state={state} onSave={props.save} onDiscard={props.discard}>
|
||||
return <SettingsForm labels={rowFormLabels(t, 'settings.unavailable')} state={state} onSave={props.save} onDiscard={props.discard}>
|
||||
<div className={css.row}>
|
||||
<div className={css.text}>
|
||||
<label className={css.title} htmlFor={id}>{t('settings.retainOnArchive.title')}</label>
|
||||
|
||||
@@ -47,3 +47,13 @@ export function useForgeCopy(translate: TranslateNS<typeof NS>, url: string | nu
|
||||
function hostOf(url: string): string {
|
||||
return /^[a-z][a-z\d+.-]*:\/\/([^/?#]+)/i.exec(url)?.[1] ?? url
|
||||
}
|
||||
|
||||
/**
|
||||
* Name the action that opens a change request on its code host.
|
||||
* @param translate - forge panel copy.
|
||||
* @param forge - product name of the code host, or null when no provider names one.
|
||||
* @returns the label that names the code host, or the one that names the browser without a name.
|
||||
*/
|
||||
export function openOnLabel(translate: TranslateNS<typeof NS>, forge: string | null): string {
|
||||
return forge === null ? translate('change.view') : translate('change.viewOn', { forge })
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
/** Lifecycle glyphs of change requests and outcome glyphs of their checks. */
|
||||
/** Lifecycle glyphs of change requests, outcome glyphs of their checks, and the marks of their code hosts. */
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import { IconCheckCircleFillRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { IconCheckCircleFillRegular, IconRightUpOutlineRegular, LinkIconRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { CheckState, ChecksRollup } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { ChangeRequestTone } from './status.ts'
|
||||
import css from './Forge.module.css'
|
||||
@@ -148,3 +148,18 @@ export function CheckGlyph({ state, size = 16 }: { readonly state: CheckState; r
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The public host whose site mark stands for each forge family, self-hosted instances included. */
|
||||
const FORGE_SITE: Readonly<Record<string, string>> = { github: 'https://github.com', gitlab: 'https://gitlab.com' }
|
||||
|
||||
/**
|
||||
* Draw the mark of a code host on an action that opens it: the site mark of the provider's forge family, whatever the
|
||||
* host name, or the leaving arrow for a family without a mark and for no provider.
|
||||
* @param props.forge - forge family of the change request's provider, such as `github`, or null without one.
|
||||
* @param props.size - width and height in pixels, 14 by default.
|
||||
* @returns the decorative glyph.
|
||||
*/
|
||||
export function ForgeGlyph({ forge, size = 14 }: { readonly forge: string | null; readonly size?: number | undefined }): ReactNode {
|
||||
const site = forge === null ? undefined : FORGE_SITE[forge]
|
||||
return site === undefined ? <IconRightUpOutlineRegular size={size} /> : <LinkIconRegular kind="url" href={site} size={size} />
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/** Staged host list of a provider row, using the shared Plugins form model. */
|
||||
import { SettingsFormModel, type SettingsFormScope, type SettingsFormShell } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
|
||||
/** The live-editable field of a forge provider's Config. */
|
||||
export interface HostSettings {
|
||||
hosts: string[]
|
||||
}
|
||||
|
||||
/** The saved and staged host lists with the shared form status. */
|
||||
export interface HostFormState extends SettingsFormShell {
|
||||
/** Hosts the provider serves, as its configuration lists them. */
|
||||
readonly saved: readonly string[]
|
||||
/** Hosts a save would store: `saved` while nothing is staged. */
|
||||
readonly draft: readonly string[]
|
||||
}
|
||||
|
||||
/** Why a typed host was not staged. */
|
||||
export type HostProblem =
|
||||
| { readonly kind: 'invalid' }
|
||||
| { readonly kind: 'duplicate'; readonly host: string }
|
||||
| { readonly kind: 'taken'; readonly host: string }
|
||||
|
||||
/** What a provider row's host list offers its page. */
|
||||
export interface HostFormActions {
|
||||
/**
|
||||
* Stage one more host. The text is a host name with an optional port, or a URL, of which only the host is taken.
|
||||
* @param text - what the reader typed.
|
||||
* @returns undefined once staged or for blank text, else why the host was refused.
|
||||
*/
|
||||
readonly add: (text: string) => HostProblem | undefined
|
||||
/** Stage the removal of a host; the last host stays. */
|
||||
readonly remove: (host: string) => void
|
||||
/** Write the staged list, then read back what the Host accepted. */
|
||||
readonly save: () => void
|
||||
/** Drop the staged list. */
|
||||
readonly discard: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* A host name with an optional port. The providers' Config holds the same rule and decides what a save stores; this
|
||||
* copy only answers before a save.
|
||||
*/
|
||||
const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i
|
||||
|
||||
/** A URL with a scheme, of which a typed host keeps only the authority. */
|
||||
const URL_FORM = /^[a-z][a-z0-9+.-]*:\/\//i
|
||||
|
||||
/**
|
||||
* Read the host a reader typed: a URL gives its host and port, any other text is taken as written, in lowercase.
|
||||
* @param text - what the reader typed.
|
||||
* @returns the lowercase host, which may still be malformed.
|
||||
*/
|
||||
export function typedHost(text: string): string {
|
||||
const trimmed = text.trim()
|
||||
const host = URL_FORM.test(trimmed) && URL.canParse(trimmed) ? new URL(trimmed).host : trimmed
|
||||
return host.toLowerCase()
|
||||
}
|
||||
|
||||
function listed(text: string): string[] {
|
||||
return text.split('\n').filter(host => host !== '')
|
||||
}
|
||||
|
||||
/** Stages additions and removals of a provider's hosts until the reader saves them as one list. */
|
||||
export class HostSettingsForm {
|
||||
private readonly form: SettingsFormModel<HostSettings>
|
||||
private readonly state: SnapshotStore<HostFormState>
|
||||
|
||||
/**
|
||||
* @param scope - Host-backed configuration form of the provider row.
|
||||
* @param taken - hosts the other providers serve now, which this row cannot add.
|
||||
*/
|
||||
constructor(private readonly scope: SettingsFormScope<HostSettings>, private readonly taken: () => readonly string[]) {
|
||||
this.form = new SettingsFormModel(scope, [{
|
||||
field: 'hosts',
|
||||
format: value => (value as readonly string[] | undefined ?? []).join('\n'),
|
||||
// `remove` keeps the last host, so every staged text lists at least one.
|
||||
parse: text => ({ kind: 'set', value: listed(text) }),
|
||||
}])
|
||||
this.state = this.form.bind(() => ({
|
||||
...this.form.shell(), saved: this.scope.getSnapshot().value?.hosts ?? [], draft: listed(this.form.field('hosts').text),
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the registration face for the row page.
|
||||
* @returns the list observable with the add, remove, save, and discard actions.
|
||||
*/
|
||||
inject(): { hooks: { hostForm: SnapshotStore<HostFormState> } } & HostFormActions {
|
||||
const { edit, save, discard } = this.form.actions()
|
||||
const stage = (hosts: readonly string[]): void => { edit('hosts', hosts.join('\n')) }
|
||||
return {
|
||||
hooks: { hostForm: this.state },
|
||||
add: (text) => {
|
||||
const host = typedHost(text)
|
||||
if (host === '') return undefined
|
||||
if (!HOST.test(host)) return { kind: 'invalid' }
|
||||
const { draft } = this.state.getSnapshot()
|
||||
if (draft.some(other => other.toLowerCase() === host)) return { kind: 'duplicate', host }
|
||||
if (this.taken().some(other => other.toLowerCase() === host)) return { kind: 'taken', host }
|
||||
stage([...draft, host])
|
||||
return undefined
|
||||
},
|
||||
remove: (host) => {
|
||||
const { draft } = this.state.getSnapshot()
|
||||
if (draft.length > 1) stage(draft.filter(other => other !== host))
|
||||
},
|
||||
save,
|
||||
discard,
|
||||
}
|
||||
}
|
||||
|
||||
/** Release the accepted-value subscription. */
|
||||
dispose(): void { this.form.dispose() }
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/** Sign-in state of the hosts a provider row serves, read through `forgePanel.hostReadiness`. */
|
||||
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type { ForgeReadiness } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
|
||||
/** What the page knows of one host: its readiness once read, or that the first read is under way. */
|
||||
export type HostSignIn = ForgeReadiness | { readonly state: 'checking' }
|
||||
|
||||
/** Reads one host's readiness; the signal ends the read. */
|
||||
export type HostReadinessRead = (host: string, signal: AbortSignal) => Promise<RemoteResult<ForgeReadiness>>
|
||||
|
||||
/**
|
||||
* Keeps the last read sign-in state of each host of one provider. A check reads every named host at once and forgets
|
||||
* the hosts it does not name; a later check ends the reads of an earlier one.
|
||||
*/
|
||||
export class HostSignInStates {
|
||||
/** Sign-in state by host as the provider's configuration lists it. */
|
||||
readonly states: SnapshotStore<ReadonlyMap<string, HostSignIn>> = createSnapshotStore<ReadonlyMap<string, HostSignIn>>(new Map())
|
||||
private reads = new AbortController()
|
||||
|
||||
/** @param read - one host's readiness read. */
|
||||
constructor(private readonly read: HostReadinessRead) {}
|
||||
|
||||
/**
|
||||
* Read the sign-in state of `hosts`.
|
||||
* @param hosts - every host to keep a state for.
|
||||
* @param visibly - show each host as being checked until its read answers; otherwise a host keeps the state it has.
|
||||
*/
|
||||
check(hosts: readonly string[], visibly: boolean): void {
|
||||
this.reads.abort()
|
||||
const reads = new AbortController()
|
||||
this.reads = reads
|
||||
const known = this.states.getSnapshot()
|
||||
this.states.set(new Map(hosts.map(host => [host, visibly ? { state: 'checking' } : known.get(host) ?? { state: 'checking' }])))
|
||||
for (const host of hosts) {
|
||||
void this.read(host, reads.signal).then((result) => {
|
||||
if (reads.signal.aborted) return
|
||||
const readiness: ForgeReadiness = result.ok ? result.value : { state: 'unavailable', message: result.error.message, signIn: null }
|
||||
this.states.set(new Map(this.states.getSnapshot()).set(host, readiness))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** End the reads under way; their answers are dropped. */
|
||||
dispose(): void { this.reads.abort() }
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -43,6 +43,9 @@ import { ChangesTabTitle } from './ChangesTabTitle.tsx'
|
||||
import {
|
||||
CheckoutRow, ConnectionRow, LocalChangesRow, type CheckoutRowInjected, type ConnectionRowInjected, type LocalChangesRowInjected,
|
||||
} from './EnvironmentRows.tsx'
|
||||
import { HostSettings, type HostForge, type HostSettingsInjected } from './HostSettings.tsx'
|
||||
import { HostSettingsForm, type HostSettings as HostSettingsFields } from './host-settings-form.ts'
|
||||
import { HostSignInStates } from './host-sign-in.ts'
|
||||
import { de, en, es, fr, ja, NS, pt, ru, zh, type ForgePanelKey } from './locales.ts'
|
||||
import type { SessionListInjected } from './session-list.ts'
|
||||
import { SessionHoverForge } from './SessionHoverForge.tsx'
|
||||
@@ -60,12 +63,24 @@ import { WorktreeToggle, type WorktreeToggleInjected } from './WorktreeToggle.ts
|
||||
/** Services required before the Remote contribution mounts. */
|
||||
export const inject = ['remote', 'slots', 'locale', 'sidebarRightTabs', 'sidebarRight', 'sessions', 'configForms', 'remoteAccess', 'workspaces', 'uiWorkspace']
|
||||
|
||||
/** The Forge bundle, whose page on the Plugins page lists the rows below. */
|
||||
export const FORGE_BUNDLE = '@deepseek-ai/dsh-experimental-forge-bundle'
|
||||
|
||||
/** The worktree row of the Forge bundle, whose Plugins page carries the archive cleanup switch. */
|
||||
export const WORKTREE_ROW_KEY = '@deepseek-ai/dsh-experimental-forge-bundle#worktree'
|
||||
export const WORKTREE_ROW_KEY = `${FORGE_BUNDLE}#worktree`
|
||||
|
||||
/** The Loader entry id the worktree service's settings namespace follows. */
|
||||
export const WORKTREE_NS = 'worktree'
|
||||
|
||||
/**
|
||||
* The provider rows of the Forge bundle whose Plugins pages carry a host list. A row's id is also the Loader entry id
|
||||
* its settings namespace follows.
|
||||
*/
|
||||
export const HOST_ROWS: readonly { readonly forge: HostForge; readonly row: string }[] = [
|
||||
{ forge: 'github', row: 'forge-github' },
|
||||
{ forge: 'gitlab', row: 'forge-gitlab' },
|
||||
]
|
||||
|
||||
/**
|
||||
* Open a URL in a new browsing context without giving it access to this page.
|
||||
* @param url - change request web URL.
|
||||
@@ -314,6 +329,10 @@ function registerUi(ctx: Context): void {
|
||||
reportAction(entry, await ctx.remote.forgePanel.merge(sessionId, entry.url, request.method, request.headSha),
|
||||
{ done: 'toast.merged', stale: 'toast.mergeStale', failed: 'toast.mergeFailed' })
|
||||
},
|
||||
autoMerge: async (entry, request) => {
|
||||
reportAction(entry, await ctx.remote.forgePanel.setAutoMerge(sessionId, entry.url, request),
|
||||
{ done: request.enabled ? 'toast.autoMergeEnabled' : 'toast.autoMergeCancelled', stale: 'toast.autoMergeStale', failed: 'toast.autoMergeFailed' })
|
||||
},
|
||||
rerunChecks: async (entry, request) => {
|
||||
reportAction(entry, await ctx.remote.forgePanel.rerunChecks(sessionId, entry.url, request),
|
||||
{ done: 'toast.rerunRequested', stale: 'toast.rerunStale', failed: 'toast.rerunFailed' })
|
||||
@@ -527,12 +546,35 @@ function registerUi(ctx: Context): void {
|
||||
}, SessionHoverForge))
|
||||
registerReviewPage(ctx, {
|
||||
notices, settled, nameOf, openLink, copyText, copyPath, locale, quoteReview: addReviewToInput, quoteThread: addThreadToInput,
|
||||
hostSettings: FORGE_BUNDLE,
|
||||
})
|
||||
const worktreeSettings = new WorktreeSettingsForm(ctx.configForms.get<WorktreeSettingsFields>(WORKTREE_NS))
|
||||
ctx.effect(() => () => { worktreeSettings.dispose() }, 'forge-panel: worktree settings form')
|
||||
ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
|
||||
name: 'plugins.row.config', key: WORKTREE_ROW_KEY, locale: NS, inject: () => worktreeSettings.inject(),
|
||||
}, WorktreeSettings))
|
||||
const hostRows = HOST_ROWS.map(row => ({ ...row, scope: ctx.configForms.get<HostSettingsFields>(row.row) }))
|
||||
for (const { forge, row, scope } of hostRows) {
|
||||
// A host has one provider, so a row refuses the hosts the other rows serve now.
|
||||
const taken = (): string[] => hostRows.flatMap(other => other.row === row ? [] : other.scope.getSnapshot().value?.hosts ?? [])
|
||||
const form = new HostSettingsForm(scope, taken)
|
||||
const signIn = new HostSignInStates((host, signal) => ctx.remote.forgePanel.hostReadiness(forge, host, signal))
|
||||
ctx.effect(() => () => {
|
||||
form.dispose()
|
||||
signIn.dispose()
|
||||
}, `forge-panel: ${row} host settings`)
|
||||
const { hooks, ...actions } = form.inject()
|
||||
const face: HostSettingsInjected = {
|
||||
...actions,
|
||||
hooks: { ...hooks, signIn: signIn.states },
|
||||
forge,
|
||||
checkSignIn: (hosts, visibly) => { signIn.check(hosts, visibly) },
|
||||
copyCommand: (command) => { copy(command, 'toast.commandCopied') },
|
||||
}
|
||||
ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
|
||||
name: 'plugins.row.config', key: `${FORGE_BUNDLE}#${row}`, locale: NS, inject: () => face,
|
||||
}, HostSettings))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
/**
|
||||
* The summary tab's activity of one change request: its comments, submitted reviews, commits, and changes of state,
|
||||
* oldest first, and the field that adds a comment.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, IconBranchOutlineRegular, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconClockOutlineRegular,
|
||||
IconCloseCircleFillRegular, IconEditOutlineRegular, IconEyeOutlineRegular, IconUserOutlineRegular, MarkdownText, ShortcutKeys,
|
||||
type MarkdownLabels,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ChangeRequestActivity, ForgeCommentAuthor, ReviewVerdict } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import { openOnLabel } from '../forge-copy.ts'
|
||||
import { formatAgo } from '../format.ts'
|
||||
import { ChangeRequestGlyph } from '../glyphs.tsx'
|
||||
import type { NS } from '../locales.ts'
|
||||
import { Avatar } from '../ReviewThreads.tsx'
|
||||
import { activityEntries, longBody, type ActivityCommit, type ActivityEvent } from './review-activity.ts'
|
||||
import { descriptionMarkdown } from './review-lists.ts'
|
||||
import { ActivitySkeleton } from './ReviewSkeleton.tsx'
|
||||
import css from './ReviewPage.module.css'
|
||||
|
||||
type Translate = PropsLocale<typeof NS>['t']
|
||||
|
||||
/** Stands for the actor's name in a translated sentence, so each locale keeps its word order around the name. */
|
||||
const ACTOR = '\u0000'
|
||||
|
||||
/** Characters of a commit's object name a row shows. */
|
||||
const SHORT_SHA = 7
|
||||
|
||||
/** Props of the activity. */
|
||||
export interface ReviewActivityProps {
|
||||
/** URL of the change request. */
|
||||
readonly url: string
|
||||
/** A value that differs once the change request changed, after which the activity is read again. */
|
||||
readonly revision: string
|
||||
/** Product name of the change request's code host, or null once its provider left. */
|
||||
readonly forge: string | null
|
||||
/** Read the activity; null for a provider that reads none. */
|
||||
readonly read: (url: string, signal: AbortSignal) => Promise<RemoteResult<ChangeRequestActivity | null>>
|
||||
/** Add a comment to the conversation. */
|
||||
readonly comment: (url: string, body: string) => Promise<RemoteResult<void>>
|
||||
/** Show the changes tab. */
|
||||
readonly onOpenChanges: () => void
|
||||
/** Open a web page in the browser. */
|
||||
readonly openLink: (url: string) => void
|
||||
/** Current epoch milliseconds for relative times. */
|
||||
readonly now: number
|
||||
/** Localized labels of rendered Markdown. */
|
||||
readonly markdown: MarkdownLabels
|
||||
/** Forge panel copy. */
|
||||
readonly t: Translate
|
||||
}
|
||||
|
||||
/** The latest read of one change request's activity. */
|
||||
interface ActivityRead {
|
||||
readonly url: string
|
||||
/** The activity, null for a provider that reads none, or undefined while no read of this URL succeeded. */
|
||||
readonly activity: ChangeRequestActivity | null | undefined
|
||||
readonly failure: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The activity of one change request, read again when the change request changes;
|
||||
* an earlier read stays while a later one fails.
|
||||
*/
|
||||
function useActivity(url: string, revision: string, read: ReviewActivityProps['read']): {
|
||||
readonly activity: ChangeRequestActivity | null | undefined
|
||||
readonly failure: string | null
|
||||
readonly reload: () => void
|
||||
} {
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const [state, setState] = useState<ActivityRead | null>(null)
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void read(url, controller.signal).then((result) => {
|
||||
if (controller.signal.aborted) return
|
||||
setState(previous => result.ok
|
||||
? { url, activity: result.value, failure: null }
|
||||
: { url, activity: previous?.url === url ? previous.activity : undefined, failure: result.error.message })
|
||||
})
|
||||
return () => { controller.abort() }
|
||||
}, [url, revision, attempt, read])
|
||||
const current = state?.url === url ? state : null
|
||||
return { activity: current?.activity, failure: current?.failure ?? null, reload: () => { setAttempt(value => value + 1) } }
|
||||
}
|
||||
|
||||
/** The glyph of a commit. */
|
||||
function CommitGlyph(): ReactNode {
|
||||
return (
|
||||
<svg width={16} height={16} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.25} strokeLinecap="round"
|
||||
aria-hidden="true">
|
||||
<circle cx={8} cy={8} r={2.75} />
|
||||
<path d="M1.5 8h3.75M10.75 8h3.75" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One line of the activity: a glyph, what happened, when, and what stands at its end. With `act` it is a button of that
|
||||
* accessible name.
|
||||
*/
|
||||
function Line({ glyph, tone, text, at, end, nested = false, expanded, act, now, t }: {
|
||||
readonly glyph: ReactNode
|
||||
readonly tone?: 'success' | 'error' | undefined
|
||||
readonly text: ReactNode
|
||||
readonly at: string
|
||||
readonly end?: ReactNode
|
||||
readonly nested?: boolean
|
||||
readonly expanded?: boolean | undefined
|
||||
readonly act?: { readonly label: string; readonly run: () => void } | undefined
|
||||
readonly now: number
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const content = (
|
||||
<>
|
||||
<span className={css.activityGlyph} data-tone={tone}>{glyph}</span>
|
||||
<span className={css.activityText}>{text}</span>
|
||||
<span className={css.activityTime}>{formatAgo(at, now, t)}</span>
|
||||
{end !== undefined && <span className={css.activityEnd}>{end}</span>}
|
||||
</>
|
||||
)
|
||||
const className = clsx(css.activityLine, nested && css.activityNested)
|
||||
return act === undefined
|
||||
? <div className={className} data-forge-review-line="">{content}</div>
|
||||
: (
|
||||
<button type="button" className={className} data-forge-review-line="" aria-label={act.label} aria-expanded={expanded}
|
||||
onClick={act.run}>
|
||||
{content}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** A translated sentence with the actor's name set apart from the rest. */
|
||||
function sentence(text: string, actor: ForgeCommentAuthor | null, t: Translate): ReactNode {
|
||||
const [before, ...after] = text.split(ACTOR)
|
||||
const name = actor?.login ?? t('thread.deletedAuthor')
|
||||
return <>{before}<b className={css.activityActor}>{name}</b><span className={css.activityRest}>{after.join('')}</span></>
|
||||
}
|
||||
|
||||
/** One commit: its title, its time, and the start of its object name. */
|
||||
function CommitLine({ commit, nested, now, t }: {
|
||||
readonly commit: ActivityCommit
|
||||
readonly nested: boolean
|
||||
readonly now: number
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
return (
|
||||
<Line glyph={<CommitGlyph />} text={nested ? commit.title : <b className={css.activityActor}>{commit.title}</b>} at={commit.at}
|
||||
nested={nested} end={<span className={css.activitySha}>{commit.sha.slice(0, SHORT_SHA)}</span>} now={now} t={t} />
|
||||
)
|
||||
}
|
||||
|
||||
/** A run of commits: one commit as its own line, several as a line that unfolds them. */
|
||||
function Commits({ commits, now, t }: {
|
||||
readonly commits: readonly [ActivityCommit, ...ActivityCommit[]]
|
||||
readonly now: number
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [first, ...later] = commits
|
||||
const last = later.at(-1)
|
||||
if (last === undefined) return <CommitLine commit={first} nested={false} now={now} t={t} />
|
||||
const count = t('reviewPage.activity.commits', { count: commits.length })
|
||||
return (
|
||||
<>
|
||||
<Line glyph={<CommitGlyph />} text={<b className={css.activityActor}>{count}</b>}
|
||||
at={last.at} expanded={open} act={{ label: count, run: () => { setOpen(!open) } }} now={now} t={t}
|
||||
end={<IconChevronDownOutlineRegular size={12} className={clsx(css.chevron, !open && css.chevronClosed)} />} />
|
||||
{open && commits.map(commit => <CommitLine key={commit.sha} commit={commit} nested now={now} t={t} />)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** A comment's author, time, and text; a long text starts cut short. */
|
||||
function CommentCard({ actor, at, body, now, markdown, t }: {
|
||||
readonly actor: ForgeCommentAuthor | null
|
||||
readonly at: string
|
||||
readonly body: string
|
||||
readonly now: number
|
||||
readonly markdown: MarkdownLabels
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const long = longBody(body)
|
||||
const [open, setOpen] = useState(false)
|
||||
const text = useMemo(() => descriptionMarkdown(body, {}), [body])
|
||||
return (
|
||||
<div className={css.activityComment} data-forge-review-comment="">
|
||||
<div className={css.activityCommentHead}>
|
||||
<Avatar author={actor} size={20} />
|
||||
<b className={css.activityActor}>{actor?.login ?? t('thread.deletedAuthor')}</b>
|
||||
{actor?.bot === true && <span className={css.activityTag}>{t('thread.bot')}</span>}
|
||||
<span className={css.activityTime}>{formatAgo(at, now, t)}</span>
|
||||
</div>
|
||||
<div className={clsx(long && !open && css.activityClamp)}>
|
||||
<MarkdownText text={text} labels={markdown} variant="compact" omitHtml />
|
||||
</div>
|
||||
{long && (
|
||||
<button type="button" className={css.activityMore} aria-expanded={open} onClick={() => { setOpen(!open) }}>
|
||||
{t(open ? 'thread.collapse' : 'thread.expand')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The glyph, tone, and sentence of a submitted review's decision. */
|
||||
function verdictLine(verdict: ReviewVerdict, t: Translate): {
|
||||
readonly glyph: ReactNode
|
||||
readonly tone: 'success' | 'error' | undefined
|
||||
readonly text: string
|
||||
} {
|
||||
const actor = { actor: ACTOR }
|
||||
switch (verdict) {
|
||||
case 'approved':
|
||||
return { glyph: <IconCheckCircleOutlineRegular size={16} />, tone: 'success', text: t('reviewPage.activity.approved', actor) }
|
||||
case 'changes-requested':
|
||||
return { glyph: <IconEditOutlineRegular size={16} />, tone: 'error', text: t('reviewPage.activity.changesRequested', actor) }
|
||||
case 'commented':
|
||||
return { glyph: <IconEyeOutlineRegular size={16} />, tone: undefined, text: t('reviewPage.activity.commented', actor) }
|
||||
case 'dismissed':
|
||||
return { glyph: <IconCloseCircleFillRegular size={16} />, tone: undefined, text: t('reviewPage.activity.dismissed', actor) }
|
||||
/* v8 ignore next -- closed ReviewVerdict union exhaustiveness guard */
|
||||
default: return assertNever(verdict, 'ReviewVerdict')
|
||||
}
|
||||
}
|
||||
|
||||
/** One activity item other than a commit. */
|
||||
function Event({ item, onOpenChanges, now, markdown, t }: {
|
||||
readonly item: ActivityEvent
|
||||
readonly onOpenChanges: () => void
|
||||
readonly now: number
|
||||
readonly markdown: MarkdownLabels
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const line = (glyph: ReactNode, text: string): ReactNode => (
|
||||
<Line glyph={glyph} text={sentence(text, item.actor, t)} at={item.at} now={now} t={t} />
|
||||
)
|
||||
switch (item.kind) {
|
||||
case 'comment':
|
||||
return <CommentCard actor={item.actor} at={item.at} body={item.body} now={now} markdown={markdown} t={t} />
|
||||
case 'review': {
|
||||
const { glyph, tone, text } = verdictLine(item.verdict, t)
|
||||
// A review that left comments on lines or files opens the changes tab, where they show.
|
||||
const inline = item.comments === 0 ? undefined : {
|
||||
text: `${text} · ${t('reviewPage.activity.inline', { count: item.comments })}`, open: t('reviewPage.activity.viewInChanges'),
|
||||
}
|
||||
const name = item.actor?.login ?? t('thread.deletedAuthor')
|
||||
return (
|
||||
<>
|
||||
<Line glyph={glyph} tone={tone} text={sentence(inline?.text ?? text, item.actor, t)} at={item.at} now={now} t={t}
|
||||
end={inline?.open}
|
||||
act={inline === undefined ? undefined : { label: `${inline.text.replace(ACTOR, name)}, ${inline.open}`, run: onOpenChanges }} />
|
||||
{item.body.trim() !== '' && <CommentCard actor={item.actor} at={item.at} body={item.body} now={now} markdown={markdown} t={t} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
case 'merged': return line(<ChangeRequestGlyph tone="merged" size={16} />, t('reviewPage.activity.merged', { actor: ACTOR }))
|
||||
case 'closed': return line(<ChangeRequestGlyph tone="closed" size={16} />, t('reviewPage.activity.closed', { actor: ACTOR }))
|
||||
case 'reopened': return line(<ChangeRequestGlyph tone="open" size={16} />, t('reviewPage.activity.reopened', { actor: ACTOR }))
|
||||
case 'ready-for-review': return line(<IconEyeOutlineRegular size={16} />, t('reviewPage.activity.readyForReview', { actor: ACTOR }))
|
||||
case 'converted-to-draft':
|
||||
return line(<ChangeRequestGlyph tone="draft" tinted={false} size={16} />, t('reviewPage.activity.convertedToDraft', { actor: ACTOR }))
|
||||
case 'force-pushed': return line(<IconBranchOutlineRegular size={16} />, t('reviewPage.activity.forcePushed', { actor: ACTOR }))
|
||||
case 'auto-merge-enabled':
|
||||
return line(<IconCheckCircleOutlineRegular size={16} />, t('reviewPage.activity.autoMergeEnabled', { actor: ACTOR }))
|
||||
case 'auto-merge-disabled':
|
||||
return line(<IconClockOutlineRegular size={16} />, t('reviewPage.activity.autoMergeDisabled', { actor: ACTOR }))
|
||||
case 'review-requested':
|
||||
return line(<IconUserOutlineRegular size={16} />, item.reviewer === null
|
||||
? t('reviewPage.activity.reviewRequestedUnnamed', { actor: ACTOR })
|
||||
: t('reviewPage.activity.reviewRequested', { actor: ACTOR, reviewer: item.reviewer }))
|
||||
case 'renamed':
|
||||
return line(<IconEditOutlineRegular size={16} />, t('reviewPage.activity.renamed', { actor: ACTOR, from: item.from, to: item.to }))
|
||||
case 'other': return line(<IconClockOutlineRegular size={16} />, `${ACTOR} ${item.text}`)
|
||||
/* v8 ignore next -- closed ChangeRequestActivityItem kind union exhaustiveness guard */
|
||||
default: return assertNever(item, 'ChangeRequestActivityItem.kind')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The keys that send a comment, as the shortcut reference labels them: Command with Enter on Apple platforms, Control
|
||||
* with Enter elsewhere. The desktop shell names the platform on the document; a browser names it itself.
|
||||
*/
|
||||
function sendKeys(): readonly string[] {
|
||||
const platform = document.documentElement.dataset['platform'] ?? navigator.platform
|
||||
return /darwin|mac|iphone|ipad/iu.test(platform) ? ['⌘', 'Enter'] : ['Ctrl', '+', 'Enter']
|
||||
}
|
||||
|
||||
/**
|
||||
* The field that adds a comment: three lines that grow with the text, over a row that says where the comment goes and
|
||||
* holds the button that sends it. It keeps its text until the host saved the comment, and says why one was not saved.
|
||||
*/
|
||||
function Composer({ url, forge, comment, onPosted, t }: {
|
||||
readonly url: string
|
||||
readonly forge: string | null
|
||||
readonly comment: ReviewActivityProps['comment']
|
||||
readonly onPosted: () => void
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const [text, setText] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const field = useRef<HTMLTextAreaElement>(null)
|
||||
const keys = useMemo(sendKeys, [])
|
||||
// The field is as tall as its text, between the heights its style allows.
|
||||
useEffect(() => {
|
||||
const element = field.current
|
||||
element?.style.setProperty('height', 'auto')
|
||||
element?.style.setProperty('height', `${element.scrollHeight}px`)
|
||||
}, [text])
|
||||
// One comment is sent at a time; the field stays focused and read-only meanwhile.
|
||||
const post = async (): Promise<void> => {
|
||||
if (busy || text.trim() === '') return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
const result = await comment(url, text)
|
||||
setBusy(false)
|
||||
if (result.ok) {
|
||||
setText('')
|
||||
onPosted()
|
||||
} else if (result.error.code === 'forgePanel/action-unknown' && forge !== null) {
|
||||
setError(t('review.unknown', { forge }))
|
||||
} else {
|
||||
setError(t('reviewPage.activity.commentFailed', { message: result.error.message }))
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className={css.activityCompose}>
|
||||
<div className={css.activityComposer} aria-busy={busy}>
|
||||
<textarea ref={field} rows={3} value={text} readOnly={busy} aria-label={t('reviewPage.activity.commentPlaceholder')}
|
||||
placeholder={t('reviewPage.activity.commentPlaceholder')} onChange={(event) => { setText(event.target.value) }}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' && (event.metaKey || event.ctrlKey) && !event.nativeEvent.isComposing) {
|
||||
event.preventDefault()
|
||||
void post()
|
||||
}
|
||||
}} />
|
||||
<div className={css.activityComposerFoot}>
|
||||
<span className={css.activityComposerHint}>
|
||||
{forge === null ? t('reviewPage.activity.commentHintPlain') : t('reviewPage.activity.commentHint', { forge })}
|
||||
</span>
|
||||
<span className={css.activityComposerKeys} aria-hidden="true"><ShortcutKeys keys={keys} /></span>
|
||||
<Button size="sm" variant="primary" className={css.activitySend} disabled={busy || text.trim() === ''}
|
||||
onClick={() => { void post() }}>
|
||||
{t(busy ? 'reviewPage.activity.commenting' : 'reviewPage.activity.comment')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{error !== null && <p className={css.activityError} role="alert">{error}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the activity of one change request, and nothing for a provider that reads none.
|
||||
* @param props - the change request, its reads and writes, and copy.
|
||||
* @returns the activity section.
|
||||
*/
|
||||
export function ReviewActivity({
|
||||
url, revision, forge, read, comment, onOpenChanges, openLink, now, markdown, t,
|
||||
}: ReviewActivityProps): ReactNode {
|
||||
const { activity, failure, reload } = useActivity(url, revision, read)
|
||||
const entries = useMemo(() => activityEntries(activity?.items ?? []), [activity])
|
||||
if (activity === null) return null
|
||||
return (
|
||||
<section className={css.activity} aria-label={t('reviewPage.activity')} data-forge-review-activity="">
|
||||
<h3 className={css.caption}>{t('reviewPage.activity')}</h3>
|
||||
{failure !== null && (
|
||||
<div className={css.notice} role="status">
|
||||
<span>{t('reviewPage.activity.failed', { message: failure })}</span>
|
||||
<Button size="sm" variant="outline" onClick={reload}>{t('retry')}</Button>
|
||||
</div>
|
||||
)}
|
||||
{activity === undefined
|
||||
? failure === null && <ActivitySkeleton />
|
||||
: (
|
||||
<>
|
||||
{activity.truncated && (
|
||||
<p className={css.activityOlder}>
|
||||
{t('reviewPage.activity.older')}
|
||||
<button type="button" className={css.activityMore} onClick={() => { openLink(url) }}>{openOnLabel(t, forge)}</button>
|
||||
</p>
|
||||
)}
|
||||
{entries.length === 0 && <p className={css.muted}>{t('reviewPage.activity.empty')}</p>}
|
||||
<div className={css.activityLines}>
|
||||
{entries.map(entry => entry.kind === 'commits'
|
||||
? <Commits key={entry.key} commits={entry.commits} now={now} t={t} />
|
||||
: <Event key={entry.key} item={entry.item} onOpenChanges={onOpenChanges} now={now} markdown={markdown} t={t} />)}
|
||||
</div>
|
||||
{activity.viewerCanComment && <Composer url={url} forge={forge} comment={comment} onPosted={reload} t={t} />}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,27 +1,35 @@
|
||||
/**
|
||||
* The review page's detail of one change request: its header with state, repository, labels, title, author, times, and
|
||||
* branches; the ready-or-merge and more actions; and the summary, changes, and chat tabs. The summary shows the
|
||||
* description beside the status column.
|
||||
* branches; the merge action beside the actions that open the change request on its code host, copy its link, and read
|
||||
* it again; and the summary, changes, and chat tabs. The summary shows the description and the activity beside the
|
||||
* status column. While the change request is read, a skeleton of the same layout stands in for it.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, IconChevronLeftOutlineRegular, IconEllipsisOutlineRegular, IconPanelLeftOutlineRegular, MarkdownText, Menu,
|
||||
StateDot, Tooltip, type MenuEntry,
|
||||
Button, IconCheckOutlineRegular, IconChevronLeftOutlineRegular, IconCopyOutlineRegular, IconEllipsisOutlineRegular,
|
||||
IconPanelLeftOutlineRegular, MarkdownText, Menu, Tooltip, type MenuEntry,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ChangeRequestDescription, ChangeRequestSnapshot, ForgeFailure } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type {
|
||||
ChangeRequestActivity, ChangeRequestDescription, ChangeRequestSnapshot, ForgeDescription, ForgeFailure,
|
||||
} from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { ForgeReviewChangeRequest } from '../../types.ts'
|
||||
import loading from '../ChangesLoading.module.css'
|
||||
import { ChangeRequestPrimary, type ChangeRequestActions } from '../ChangeRequestCard.tsx'
|
||||
import { openOnLabel } from '../forge-copy.ts'
|
||||
import { formatAgo } from '../format.ts'
|
||||
import { ChangeRequestGlyph } from '../glyphs.tsx'
|
||||
import { ChangeRequestGlyph, ForgeGlyph } from '../glyphs.tsx'
|
||||
import { RefreshGlyph } from '../RefreshGlyph.tsx'
|
||||
import type { StreamRead } from './host-stream.ts'
|
||||
import type { ForgePanelKey, NS } from '../locales.ts'
|
||||
import { descriptionMarkdown } from './review-lists.ts'
|
||||
import type { ReviewTab } from './review-store.ts'
|
||||
import { ReviewActivity } from './ReviewActivity.tsx'
|
||||
import { ReviewLabels } from './ReviewLabels.tsx'
|
||||
import { ActivitySkeleton, DescriptionSkeleton, HeaderSkeleton, StatusSkeleton } from './ReviewSkeleton.tsx'
|
||||
import { ReviewStatus } from './ReviewStatus.tsx'
|
||||
import { TONE_LABEL, toneOf } from '../status.ts'
|
||||
import css from './ReviewPage.module.css'
|
||||
@@ -31,6 +39,9 @@ type Translate = PropsLocale<typeof NS>['t']
|
||||
/** How long before signed image addresses expire the description is read again, in milliseconds. */
|
||||
const IMAGE_RENEWAL_MS = 30_000
|
||||
|
||||
/** How long the copy action shows that it copied, in milliseconds. */
|
||||
const COPIED_MS = 1500
|
||||
|
||||
const FAILURE: Record<ForgeFailure['code'], ForgePanelKey> = {
|
||||
'not-found': 'reviewPage.notFound',
|
||||
'unauthenticated': 'change.failure.unauthenticated',
|
||||
@@ -43,8 +54,18 @@ const FAILURE: Record<ForgeFailure['code'], ForgePanelKey> = {
|
||||
|
||||
const TAB_ORDER: readonly ReviewTab[] = ['summary', 'changes', 'chat']
|
||||
|
||||
/** What the summary tab reads and writes on the code host. */
|
||||
export interface ReviewSummaryFace {
|
||||
/** Read the description and labels of a change request. */
|
||||
readonly readDescription: (url: string, signal: AbortSignal) => Promise<RemoteResult<ChangeRequestDescription>>
|
||||
/** Read the activity of a change request; null for a provider that reads none. */
|
||||
readonly readActivity: (url: string, signal: AbortSignal) => Promise<RemoteResult<ChangeRequestActivity | null>>
|
||||
/** Add a comment to a change request's conversation. */
|
||||
readonly addComment: (url: string, body: string) => Promise<RemoteResult<void>>
|
||||
}
|
||||
|
||||
/** Props of the detail. */
|
||||
export interface ReviewDetailProps {
|
||||
export interface ReviewDetailProps extends ReviewSummaryFace {
|
||||
/** URL of the change request. */
|
||||
readonly url: string
|
||||
/** The change request stream. */
|
||||
@@ -65,8 +86,8 @@ export interface ReviewDetailProps {
|
||||
readonly locale: string
|
||||
/** The card actions, acting on this change request. */
|
||||
readonly actions: ChangeRequestActions
|
||||
/** Read the description and labels. */
|
||||
readonly readDescription: (url: string, signal: AbortSignal) => Promise<RemoteResult<ChangeRequestDescription>>
|
||||
/** Open the providers' host lists, offered for a URL no provider serves; undefined while they cannot be opened. */
|
||||
readonly onAddHost: (() => void) | undefined
|
||||
/** The changes tab's content, kept while the detail shows so pending review comments survive tab switches. */
|
||||
readonly renderChanges: (frame: ForgeReviewChangeRequest) => ReactNode
|
||||
/** The chat tab's content. */
|
||||
@@ -137,44 +158,95 @@ function MarkReady({ frame, actions, t }: {
|
||||
)
|
||||
}
|
||||
|
||||
/** The more-actions menu: open in the browser, copy the link, and read the status again. */
|
||||
function MoreMenu({ url, actions, t }: { readonly url: string; readonly actions: ChangeRequestActions; readonly t: Translate }): ReactNode {
|
||||
/**
|
||||
* The actions that leave the page or read again: open the change request on its code host, copy its link, and read its
|
||||
* status again. They show as three icon buttons; where the header is narrow its style shows them folded into one menu
|
||||
* instead, so both forms render.
|
||||
*/
|
||||
function LinkActions({ url, forge, actions, onRefresh, t }: {
|
||||
readonly url: string
|
||||
readonly forge: ForgeDescription | null
|
||||
readonly actions: ChangeRequestActions
|
||||
/** Read the status again; a promise it returns settles when the read ends. */
|
||||
readonly onRefresh: () => void | Promise<void>
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
useEffect(() => {
|
||||
if (!copied) return
|
||||
const timer = setTimeout(() => { setCopied(false) }, COPIED_MS)
|
||||
return () => { clearTimeout(timer) }
|
||||
}, [copied])
|
||||
const openLabel = openOnLabel(t, forge?.label ?? null)
|
||||
const copy = (): void => {
|
||||
actions.copyLink(url)
|
||||
setCopied(true)
|
||||
}
|
||||
const refresh = (): void => {
|
||||
setRefreshing(true)
|
||||
void Promise.resolve(onRefresh()).finally(() => { setRefreshing(false) })
|
||||
}
|
||||
const items: MenuEntry[] = [
|
||||
{ id: 'open', label: t('change.view') },
|
||||
{ id: 'open', label: openLabel },
|
||||
{ id: 'copy', label: t('change.copy') },
|
||||
{ id: 'refresh', label: t('reviewPage.refresh') },
|
||||
]
|
||||
return (
|
||||
<Menu
|
||||
open={open}
|
||||
onClose={() => { setOpen(false) }}
|
||||
portal
|
||||
align="end"
|
||||
anchor={(
|
||||
<Tooltip label={t('reviewPage.more')} side="bottom">
|
||||
<button type="button" className={css.iconButton} aria-label={t('reviewPage.more')} aria-haspopup="menu" aria-expanded={open}
|
||||
onClick={() => { setOpen(!open) }}>
|
||||
<IconEllipsisOutlineRegular size={16} />
|
||||
<>
|
||||
<span className={css.linkActions} data-forge-review-actions="">
|
||||
<Tooltip label={openLabel} side="bottom">
|
||||
<button type="button" className={css.iconButton} aria-label={openLabel} onClick={() => { actions.openLink(url) }}>
|
||||
<ForgeGlyph forge={forge?.forge ?? null} size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
items={items}
|
||||
onSelect={(id) => {
|
||||
setOpen(false)
|
||||
if (id === 'open') actions.openLink(url)
|
||||
else if (id === 'copy') actions.copyLink(url)
|
||||
else actions.retry()
|
||||
}}
|
||||
/>
|
||||
<Tooltip label={t(copied ? 'reviewPage.copied' : 'reviewPage.copyLink')} side="bottom">
|
||||
<button type="button" className={css.iconButton} aria-label={t('reviewPage.copyLink')} onClick={copy}>
|
||||
{copied ? <IconCheckOutlineRegular size={16} className={css.copied} /> : <IconCopyOutlineRegular size={16} />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('reviewPage.refresh')} side="bottom" align="end">
|
||||
<button type="button" className={css.iconButton} aria-label={t('reviewPage.refresh')} onClick={refresh}>
|
||||
<RefreshGlyph busy={refreshing} size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</span>
|
||||
<span className={css.moreAction}>
|
||||
<Menu
|
||||
open={open}
|
||||
onClose={() => { setOpen(false) }}
|
||||
portal
|
||||
align="end"
|
||||
anchor={(
|
||||
<Tooltip label={t('reviewPage.more')} side="bottom">
|
||||
<button type="button" className={css.iconButton} aria-label={t('reviewPage.more')} aria-haspopup="menu" aria-expanded={open}
|
||||
onClick={() => { setOpen(!open) }}>
|
||||
<IconEllipsisOutlineRegular size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
items={items}
|
||||
onSelect={(id) => {
|
||||
setOpen(false)
|
||||
if (id === 'open') actions.openLink(url)
|
||||
else if (id === 'copy') copy()
|
||||
else refresh()
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** The summary tab: the description beside the card rows. */
|
||||
function Summary({ frame, snapshot, description, now, locale, actions, t }: {
|
||||
/** The summary tab: the description and the activity beside the card rows. */
|
||||
function Summary({ frame, snapshot, description, readActivity, addComment, onOpenChanges, now, locale, actions, t }: {
|
||||
readonly frame: ForgeReviewChangeRequest
|
||||
readonly snapshot: ChangeRequestSnapshot
|
||||
readonly description: ReturnType<typeof useDescription>
|
||||
readonly readActivity: ReviewDetailProps['readActivity']
|
||||
readonly addComment: ReviewDetailProps['addComment']
|
||||
readonly onOpenChanges: () => void
|
||||
readonly now: number
|
||||
readonly locale: string
|
||||
readonly actions: ChangeRequestActions
|
||||
@@ -193,21 +265,27 @@ function Summary({ frame, snapshot, description, now, locale, actions, t }: {
|
||||
const name = t('change.number', { number: frame.ref.number })
|
||||
return (
|
||||
<div className={css.summary}>
|
||||
<section className={css.document} aria-label={t('reviewPage.description')}>
|
||||
<h3 className={css.caption}>{t('reviewPage.description')}</h3>
|
||||
{markdown === null
|
||||
? description.failure === null
|
||||
? <StateDot state="ongoing" />
|
||||
: (
|
||||
<div className={css.notice} role="status">
|
||||
<span>{t('reviewPage.descriptionFailed', { message: description.failure })}</span>
|
||||
<Button size="sm" variant="outline" onClick={description.retry}>{t('retry')}</Button>
|
||||
</div>
|
||||
)
|
||||
: markdown.trim() === ''
|
||||
? <p className={css.muted}>{t('reviewPage.descriptionEmpty')}</p>
|
||||
: <MarkdownText text={markdown} labels={labels} omitHtml />}
|
||||
</section>
|
||||
<div className={css.document}>
|
||||
<section aria-label={t('reviewPage.description')}>
|
||||
<h3 className={css.caption}>{t('reviewPage.description')}</h3>
|
||||
{markdown === null
|
||||
? description.failure === null
|
||||
? <DescriptionSkeleton />
|
||||
: (
|
||||
<div className={css.notice} role="status">
|
||||
<span>{t('reviewPage.descriptionFailed', { message: description.failure })}</span>
|
||||
<Button size="sm" variant="outline" onClick={description.retry}>{t('retry')}</Button>
|
||||
</div>
|
||||
)
|
||||
: markdown.trim() === ''
|
||||
? <p className={css.muted}>{t('reviewPage.descriptionEmpty')}</p>
|
||||
: <MarkdownText text={markdown} labels={labels} omitHtml />}
|
||||
</section>
|
||||
{/* A submitted review or a new comment changes the activity, and each moves one of the two values. */}
|
||||
<ReviewActivity url={frame.url} revision={`${snapshot.updatedAt}\n${frame.reviewRevision}`} forge={frame.forge?.label ?? null}
|
||||
read={readActivity} comment={addComment} onOpenChanges={onOpenChanges} openLink={actions.openLink} now={now} markdown={labels}
|
||||
t={t} />
|
||||
</div>
|
||||
<aside className={css.facts} aria-label={t('reviewPage.status')}>
|
||||
<ReviewStatus frame={frame} snapshot={snapshot} name={name} now={now} actions={actions} locale={locale} t={t} />
|
||||
</aside>
|
||||
@@ -221,8 +299,8 @@ function Summary({ frame, snapshot, description, now, locale, actions, t }: {
|
||||
* @returns the detail.
|
||||
*/
|
||||
export function ReviewDetail({
|
||||
url, read, tab, onTab, listHidden, onToggleList, onBack, now, locale, actions, readDescription, renderChanges, renderChat, unseenQuotes,
|
||||
t,
|
||||
url, read, tab, onTab, listHidden, onToggleList, onBack, now, locale, actions, readDescription, readActivity, addComment, onAddHost,
|
||||
renderChanges, renderChat, unseenQuotes, t,
|
||||
}: ReviewDetailProps): ReactNode {
|
||||
const frame = read.frame
|
||||
const snapshot = frame?.snapshot ?? null
|
||||
@@ -240,26 +318,70 @@ export function ReviewDetail({
|
||||
</Tooltip>
|
||||
</>
|
||||
)
|
||||
const forge = frame?.forge ?? null
|
||||
if (frame === undefined || snapshot === null) {
|
||||
const failure = frame?.update !== undefined && frame.update !== null && 'failure' in frame.update ? frame.update.failure : undefined
|
||||
let body: ReactNode = <StateDot state="ongoing" />
|
||||
const stopped = read.stopped !== null
|
||||
const links = <LinkActions url={url} forge={forge} actions={actions} onRefresh={stopped ? read.retry : actions.retry} t={t} />
|
||||
if (!stopped && failure === undefined) {
|
||||
// Nothing is read yet: the layout of the detail in skeleton rows, with the actions that need only the URL.
|
||||
return (
|
||||
<div className={css.detail} data-forge-review-detail={url} aria-busy="true">
|
||||
<span className={css.visuallyHidden} role="status">{t('reviewPage.detailLoading')}</span>
|
||||
<header className={css.detailHeader}>
|
||||
<div className={css.detailBar}>
|
||||
{listToggle}
|
||||
<span className={clsx(loading.fill, css.skeletonChip)} aria-hidden="true" />
|
||||
<span className={clsx(loading.fill, css.skeletonRepository)} aria-hidden="true" />
|
||||
<span className={css.labelsSlot} />
|
||||
<span className={css.headerActions}>{links}</span>
|
||||
</div>
|
||||
<HeaderSkeleton />
|
||||
</header>
|
||||
<div className={css.panel}>
|
||||
<div className={css.summary}>
|
||||
<div className={css.document}>
|
||||
<section aria-label={t('reviewPage.description')}>
|
||||
<h3 className={css.caption}>{t('reviewPage.description')}</h3>
|
||||
<DescriptionSkeleton />
|
||||
</section>
|
||||
<section className={css.activity} aria-label={t('reviewPage.activity')}>
|
||||
<h3 className={css.caption}>{t('reviewPage.activity')}</h3>
|
||||
<ActivitySkeleton />
|
||||
</section>
|
||||
</div>
|
||||
<StatusSkeleton />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
let body: ReactNode
|
||||
if (read.stopped?.code === 'forgePanel/unrecognized-url') {
|
||||
body = <><p className={css.emptyTitle}>{t('reviewPage.unrecognized')}</p><p className={css.emptyHint}>{t('reviewPage.unrecognizedHint')}</p></>
|
||||
} else if (read.stopped !== null || failure !== undefined) {
|
||||
body = (
|
||||
<>
|
||||
<p className={css.emptyTitle}>{t('reviewPage.unrecognized')}</p>
|
||||
<p className={css.emptyHint}>{t('reviewPage.unrecognizedHint')}</p>
|
||||
{onAddHost !== undefined && (
|
||||
<div className={css.actions}><Button size="sm" variant="outline" onClick={onAddHost}>{t('reviewPage.addHost')}</Button></div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
} else {
|
||||
body = (
|
||||
<>
|
||||
<p className={css.emptyTitle}>{failure === undefined ? t('reviewPage.loadFailed') : t(FAILURE[failure.code])}</p>
|
||||
{failure !== undefined && failure.message !== '' && <p className={css.emptyHint}>{failure.message}</p>}
|
||||
<div className={css.actions}>
|
||||
<Button size="sm" variant="outline" onClick={read.stopped === null ? actions.retry : read.retry}>{t('retry')}</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => { actions.openLink(url) }}>{t('change.view')}</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => { void (stopped ? read.retry : actions.retry)() }}>{t('retry')}</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => { actions.openLink(url) }}>{openOnLabel(t, forge?.label ?? null)}</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className={css.detail} data-forge-review-detail={url}>
|
||||
<div className={css.detailBar}>{listToggle}</div>
|
||||
<div className={css.detailBar}>{listToggle}<span className={css.headerActions}>{links}</span></div>
|
||||
<div className={css.centered} role="status">{body}</div>
|
||||
</div>
|
||||
)
|
||||
@@ -287,7 +409,8 @@ export function ReviewDetail({
|
||||
</span>
|
||||
<a className={css.repository} href={snapshot.url} target="_blank" rel="noreferrer"
|
||||
onClick={(event) => { event.preventDefault(); actions.openLink(snapshot.url) }}>
|
||||
{`${repository.owner}/${repository.name}`}<span className={css.number}>{name}</span>
|
||||
<span className={css.repositoryName}>{`${repository.owner}/${repository.name}`}</span>
|
||||
<span className={css.number}>{name}</span>
|
||||
</a>
|
||||
<span className={css.labelsSlot}>
|
||||
{description.description !== null && (
|
||||
@@ -297,8 +420,11 @@ export function ReviewDetail({
|
||||
<span className={css.headerActions}>
|
||||
{snapshot.state === 'open' && snapshot.draft
|
||||
? <MarkReady frame={frame} actions={actions} t={t} />
|
||||
: <ChangeRequestPrimary entry={frame} snapshot={snapshot} name={name} actions={actions} className={css.primary} t={t} />}
|
||||
<MoreMenu url={snapshot.url} actions={actions} t={t} />
|
||||
: (
|
||||
<ChangeRequestPrimary entry={frame} snapshot={snapshot} name={name} actions={actions} className={css.primary} blocked
|
||||
t={t} />
|
||||
)}
|
||||
<LinkActions url={snapshot.url} forge={forge} actions={actions} onRefresh={actions.retry} t={t} />
|
||||
</span>
|
||||
</div>
|
||||
<h1 className={css.detailTitle}>{snapshot.title}</h1>
|
||||
@@ -321,7 +447,8 @@ export function ReviewDetail({
|
||||
<div className={clsx(css.panel, tab !== 'summary' && css.panelFill)} role="tabpanel" id="forge-review-panel"
|
||||
aria-labelledby={`forge-review-tab-${tab}`}>
|
||||
{tab === 'summary' && (
|
||||
<Summary frame={frame} snapshot={snapshot} description={description} now={now} locale={locale} actions={actions} t={t} />
|
||||
<Summary frame={frame} snapshot={snapshot} description={description} readActivity={readActivity} addComment={addComment}
|
||||
onOpenChanges={() => { onTab('changes') }} now={now} locale={locale} actions={actions} t={t} />
|
||||
)}
|
||||
<div className={css.changes} hidden={tab !== 'changes'}>{renderChanges(frame)}</div>
|
||||
{tab === 'chat' && renderChat(frame)}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* The review page's list column: the search box that also opens a pasted change request link, the repository filter,
|
||||
* and one foldable section per list with its items, empty state, and failure.
|
||||
* The review page's list column: the search box that also opens a pasted change request link, the filter of hosts and
|
||||
* repositories, one foldable section per list with its items and empty state, and one notice per host that could not be read.
|
||||
*/
|
||||
|
||||
import { useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
@@ -19,8 +19,8 @@ import { ChangeRequestGlyph } from '../glyphs.tsx'
|
||||
import type { ForgePanelKey, NS } from '../locales.ts'
|
||||
import { RefreshGlyph } from '../RefreshGlyph.tsx'
|
||||
import {
|
||||
mergeRepositories, pastedUrl, reviewHint, reviewRepositories, reviewSearchKeys, reviewSections, summaryTone,
|
||||
type ReviewItem, type ReviewRepository, type ReviewSection,
|
||||
mergeRepositories, pastedUrl, reviewFailures, reviewHint, reviewRepositories, reviewSearchKeys, reviewSections, sameScope,
|
||||
scopeRepository, summaryTone, type ReviewHostFailure, type ReviewItem, type ReviewRepository, type ReviewScope, type ReviewSection,
|
||||
} from './review-lists.ts'
|
||||
import type { ReviewView } from './review-store.ts'
|
||||
import loading from '../ChangesLoading.module.css'
|
||||
@@ -44,8 +44,8 @@ export interface ReviewListProps {
|
||||
readonly selected: string | null
|
||||
/** Search text. */
|
||||
readonly query: string
|
||||
/** Repository the lists are read in, or null for every repository. */
|
||||
readonly repository: ReviewRepository | null
|
||||
/** The host or repository the lists are narrowed to, or null for every repository of every host. */
|
||||
readonly scope: ReviewScope | null
|
||||
/** Whether the review-requested list leaves out requests made only of the user's teams. */
|
||||
readonly directOnly: boolean
|
||||
/** Folded sections. */
|
||||
@@ -60,8 +60,8 @@ export interface ReviewListProps {
|
||||
readonly onSearch: (query: string) => void
|
||||
/** Repositories the lists named while read in every repository, offered whatever repository the lists are read in now. */
|
||||
readonly repositories: readonly ReviewRepository[]
|
||||
/** Read the lists in one repository, or in every repository. */
|
||||
readonly onScope: (repository: ReviewRepository | null) => void
|
||||
/** Narrow the lists to one host or one repository, or to nothing. */
|
||||
readonly onScope: (scope: ReviewScope | null) => void
|
||||
/** Toggle whether the review-requested list leaves out team requests. */
|
||||
readonly onToggleDirect: () => void
|
||||
/** How list items show: two lines each, or one line each with the rest on hover. */
|
||||
@@ -76,6 +76,8 @@ export interface ReviewListProps {
|
||||
readonly onRetry: () => void
|
||||
/** Copy text and report the outcome. */
|
||||
readonly copyText: (text: string) => void
|
||||
/** Open the page where the providers' hosts and sign-in states are, or undefined while it cannot be opened. */
|
||||
readonly onOpenSettings: (() => void) | undefined
|
||||
/** Forge panel copy. */
|
||||
readonly t: Translate
|
||||
}
|
||||
@@ -84,27 +86,38 @@ export interface ReviewListProps {
|
||||
* A submenu row's label with the tick a chosen row shows, since a submenu does not mark its own choice.
|
||||
* @param text - the row's text.
|
||||
* @param chosen - whether the row is the current choice.
|
||||
* @param nested - whether the row is a repository below the row of its host.
|
||||
* @returns the label.
|
||||
*/
|
||||
function chosenLabel(text: string, chosen: boolean): ReactNode {
|
||||
function chosenLabel(text: string, chosen: boolean, nested = false): ReactNode {
|
||||
return (
|
||||
<span className={css.menuRow} data-chosen={chosen ? '' : undefined}>
|
||||
<span>{text}</span>
|
||||
<span className={nested ? css.menuNested : undefined}>{text}</span>
|
||||
{chosen && <IconCheckOutlineRegular size={14} className={css.menuCheck} />}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The view menu, laid out like the Session list's: the list view, the repository the lists are read in, and whether team requests show. */
|
||||
function FilterMenu({ frame, repository, repositories, directOnly, view, onScope, onToggleDirect, onView, t }: Pick<ReviewListProps,
|
||||
'frame' | 'repository' | 'repositories' | 'directOnly' | 'view' | 'onScope' | 'onToggleDirect' | 'onView' | 't'>): ReactNode {
|
||||
/**
|
||||
* The view menu, laid out like the Session list's: the list view, the host or repository the lists are narrowed to, and
|
||||
* whether team requests show. Once the lists name repositories on more than one host, each host is a choice with its
|
||||
* repositories below it.
|
||||
*/
|
||||
function FilterMenu({ frame, scope, repositories, directOnly, view, onScope, onToggleDirect, onView, t }: Pick<ReviewListProps,
|
||||
'frame' | 'scope' | 'repositories' | 'directOnly' | 'view' | 'onScope' | 'onToggleDirect' | 'onView' | 't'>): ReactNode {
|
||||
const [open, setOpen] = useState(false)
|
||||
const chosen = repository === null ? null : `${repository.owner}/${repository.name}`
|
||||
const repository = scopeRepository(scope)
|
||||
// Lists read in one repository name only that one, so the menu offers the repositories remembered from the lists of
|
||||
// every repository, with those the shown lists name and the chosen one, which stays offered while its lists are empty.
|
||||
const offered = mergeRepositories(repositories, reviewRepositories(frame), repository === null ? [] : [repository])
|
||||
const hosts = [...new Set(offered.map(item => item.host))]
|
||||
// Before any list of every repository was read, the offer is still growing.
|
||||
const reading = repositories.length === 0 && (frame === undefined || frame.reading)
|
||||
// A row's id is its place among the choices, which the selection reads back.
|
||||
const choices: ReviewScope[] = []
|
||||
const choice = (value: ReviewScope, text: string, nested: boolean): MenuEntry =>
|
||||
({ id: `scope:${choices.push(value) - 1}`, label: chosenLabel(text, sameScope(value, scope), nested) })
|
||||
const all = t('reviewPage.filter.allRepositories')
|
||||
const items: MenuEntry[] = [
|
||||
{ type: 'label', id: 'view', text: t('reviewPage.filter.view') },
|
||||
{ id: 'view:detailed', label: t('reviewPage.filter.detailed'), icon: <IconLayersOutlineRegular /> },
|
||||
@@ -117,13 +130,16 @@ function FilterMenu({ frame, repository, repositories, directOnly, view, onScope
|
||||
label: (
|
||||
<span className={css.menuRow}>
|
||||
<span>{t('reviewPage.filter.repository')}</span>
|
||||
<span className={css.menuValue}>{chosen ?? t('reviewPage.filter.allRepositories')}</span>
|
||||
<span className={css.menuValue}>{scope === null ? all : repository === null ? scope.host : `${repository.owner}/${repository.name}`}</span>
|
||||
</span>
|
||||
),
|
||||
submenu: [
|
||||
{ id: 'repo:', label: chosenLabel(t('reviewPage.filter.allRepositories'), chosen === null) },
|
||||
{ id: 'scope:', label: chosenLabel(all, scope === null) },
|
||||
{ type: 'separator', id: 'repo-separator' },
|
||||
...offered.map(item => `${item.owner}/${item.name}`).map(name => ({ id: `repo:${name}`, label: chosenLabel(name, name === chosen) })),
|
||||
...hosts.flatMap(host => [
|
||||
...hosts.length > 1 ? [choice({ host }, host, false)] : [],
|
||||
...offered.filter(item => item.host === host).map(item => choice(item, `${item.owner}/${item.name}`, hosts.length > 1)),
|
||||
]),
|
||||
...reading ? [{ type: 'label' as const, id: 'repo-reading', text: t('reviewPage.loading') }] : [],
|
||||
],
|
||||
},
|
||||
@@ -132,7 +148,7 @@ function FilterMenu({ frame, repository, repositories, directOnly, view, onScope
|
||||
{ id: 'requests:all', label: t('reviewPage.filter.teamRequests'), icon: <IconUsersOutlineRegular /> },
|
||||
{ id: 'requests:direct', label: t('reviewPage.filter.directOnly'), icon: <IconUserOutlineRegular /> },
|
||||
]
|
||||
const active = repository !== null || directOnly
|
||||
const active = scope !== null || directOnly
|
||||
return (
|
||||
<Menu
|
||||
open={open}
|
||||
@@ -150,39 +166,21 @@ function FilterMenu({ frame, repository, repositories, directOnly, view, onScope
|
||||
</Tooltip>
|
||||
)}
|
||||
items={items}
|
||||
selectedIds={[`view:${view}`, `repo:${chosen ?? ''}`, directOnly ? 'requests:direct' : 'requests:all']}
|
||||
selectedIds={[`view:${view}`, directOnly ? 'requests:direct' : 'requests:all']}
|
||||
onSelect={(id) => {
|
||||
setOpen(false)
|
||||
if (id === 'view:detailed' || id === 'view:compact') onView(id === 'view:compact' ? 'compact' : 'detailed')
|
||||
else if (id === 'requests:all' || id === 'requests:direct') {
|
||||
if ((id === 'requests:direct') !== directOnly) onToggleDirect()
|
||||
} else {
|
||||
// Menu never selects a submenu parent, so every remaining row is a `repo:` row.
|
||||
const [owner = '', name = ''] = id.slice('repo:'.length).split('/')
|
||||
onScope(id === 'repo:' ? null : { owner, name })
|
||||
// Menu never selects a submenu parent, so every remaining row is a `scope:` row.
|
||||
onScope(choices[Number(id.slice('scope:'.length) || NaN)] ?? null)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** The closing issues of an item: the first issue's number, and how many more. */
|
||||
function Issues({ item, t }: { readonly item: ReviewItem; readonly t: Translate }): ReactNode {
|
||||
const [first] = item.summary.closingIssues
|
||||
if (first === undefined) return null
|
||||
const more = item.summary.closingIssues.length - 1 + (item.summary.closingIssuesTruncated ? 1 : 0)
|
||||
return (
|
||||
<>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span className={css.itemIssues}>
|
||||
<span aria-hidden="true">⊙</span>
|
||||
{t('change.number', { number: first.number })}
|
||||
{more > 0 && <span>{t(item.summary.closingIssuesTruncated ? 'reviewPage.issuesMoreTruncated' : 'reviewPage.issuesMore', { count: more })}</span>}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** Props of one list item, in either view. */
|
||||
interface ItemProps {
|
||||
readonly item: ReviewItem
|
||||
@@ -191,39 +189,18 @@ interface ItemProps {
|
||||
readonly selected: boolean
|
||||
/** Whether the item names its repository, because the lists span more than one. */
|
||||
readonly qualified: boolean
|
||||
/** Whether the item's hover card names its host, because the lists span more than one. */
|
||||
readonly hosted: boolean
|
||||
readonly now: number
|
||||
readonly onSelect: (url: string) => void
|
||||
readonly t: Translate
|
||||
}
|
||||
|
||||
/** The meta line of an item: its name, author, update time, the issues it closes, and what follows them. */
|
||||
function ItemMeta({ item, name, ago, children, t }: {
|
||||
readonly item: ReviewItem
|
||||
readonly name: string
|
||||
readonly ago: string | undefined
|
||||
readonly children?: ReactNode
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
const { author } = item.summary
|
||||
return (
|
||||
<span className={css.itemMeta}>
|
||||
<span>{name}</span>
|
||||
{author !== null && <><span aria-hidden="true">·</span><span className={css.ellipsis}>{author.login}</span></>}
|
||||
{ago !== undefined && <><span aria-hidden="true">·</span><span>{ago}</span></>}
|
||||
<Issues item={item} t={t} />
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** What the hover card of a compact item shows: the full title and every fact the detailed item names. */
|
||||
function CompactDetails({ item, filter, qualified, now, t }: {
|
||||
readonly item: ReviewItem
|
||||
readonly filter: ForgeViewerFilter
|
||||
readonly qualified: boolean
|
||||
readonly now: number
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
/**
|
||||
* What the hover card of a compact item shows: the full title, the host where the lists span several, and every fact the
|
||||
* detailed item names.
|
||||
*/
|
||||
function CompactDetails({ item, filter, qualified, hosted, now, t }: Pick<ItemProps, 'item' | 'filter' | 'qualified' | 'hosted' | 'now' | 't'>): ReactNode {
|
||||
const { summary } = item
|
||||
const { repository, number } = summary.ref
|
||||
const hint = reviewHint(summary, filter)
|
||||
@@ -231,15 +208,19 @@ function CompactDetails({ item, filter, qualified, now, t }: {
|
||||
return (
|
||||
<span className={css.compactCard}>
|
||||
<span className={css.compactCardTitle}>{summary.title}</span>
|
||||
<ItemMeta item={item} name={qualified ? `${repository.owner}/${repository.name}#${number}` : t('change.number', { number })}
|
||||
ago={ago} t={t} />
|
||||
<span className={css.cardMeta}>
|
||||
{hosted && <><span>{item.host}</span><span aria-hidden="true">·</span></>}
|
||||
<span>{qualified ? `${repository.owner}/${repository.name}#${number}` : t('change.number', { number })}</span>
|
||||
{summary.author !== null && <><span aria-hidden="true">·</span><span className={css.ellipsis}>{summary.author.login}</span></>}
|
||||
{ago !== undefined && <><span aria-hidden="true">·</span><span>{ago}</span></>}
|
||||
</span>
|
||||
{hint !== undefined && <span className={css.itemHint} data-tone={hint.tone}>{t(hint.key, hint.params)}</span>}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** One listed change request on one line: its glyph, its title, which marquees while hovered, and its update time. */
|
||||
function CompactItem({ item, filter, selected, qualified, now, onSelect, t }: ItemProps): ReactNode {
|
||||
function CompactItem({ item, filter, selected, qualified, hosted, now, onSelect, t }: ItemProps): ReactNode {
|
||||
const { summary } = item
|
||||
const title = useRef<HTMLSpanElement>(null)
|
||||
const marquee = useHoverMarquee(title)
|
||||
@@ -253,7 +234,7 @@ function CompactItem({ item, filter, selected, qualified, now, onSelect, t }: It
|
||||
copyText={summary.title}
|
||||
copyLabel={t('reviewPage.copyTitle')}
|
||||
copiedLabel={t('toast.copied')}
|
||||
content={<CompactDetails item={item} filter={filter} qualified={qualified} now={now} t={t} />}
|
||||
content={<CompactDetails item={item} filter={filter} qualified={qualified} hosted={hosted} now={now} t={t} />}
|
||||
anchor={(
|
||||
<button type="button" className={css.compactItem} aria-current={selected ? 'true' : undefined} data-forge-review-item={summary.url}
|
||||
onPointerEnter={marquee.onPointerEnter} onPointerLeave={marquee.onPointerLeave} onClick={() => { onSelect(summary.url) }}>
|
||||
@@ -267,12 +248,16 @@ function CompactItem({ item, filter, selected, qualified, now, onSelect, t }: It
|
||||
)
|
||||
}
|
||||
|
||||
/** One listed change request. */
|
||||
/**
|
||||
* One listed change request: its title on at most two lines, then its small text on at most two. The small text names
|
||||
* the repository where the lists span several, the number, and the author, with the update time at the end of that
|
||||
* line; the hint follows the author where both fit, and takes the second line where they do not.
|
||||
*/
|
||||
function Item({ item, filter, selected, qualified, now, onSelect, t }: ItemProps): ReactNode {
|
||||
const { summary } = item
|
||||
const { repository, number } = summary.ref
|
||||
const hint = reviewHint(summary, filter)
|
||||
const ago = formatAgo(summary.updatedAt, now, t)
|
||||
const time = formatShortAgo(summary.updatedAt, now, t)
|
||||
const checks: Exclude<ChecksRollup, 'none'> | undefined = summary.checksRollup === 'none' ? undefined : summary.checksRollup
|
||||
return (
|
||||
<li>
|
||||
@@ -281,39 +266,58 @@ function Item({ item, filter, selected, qualified, now, onSelect, t }: ItemProps
|
||||
<span className={css.itemGlyph}><ChangeRequestGlyph tone={summaryTone(summary)} checks={checks} size={16} /></span>
|
||||
<span className={css.itemText}>
|
||||
<span className={css.itemTitle}>{summary.title}</span>
|
||||
<ItemMeta item={item} name={qualified ? `${repository.name}#${number}` : t('change.number', { number })} ago={ago} t={t}>
|
||||
{hint !== undefined && <><span aria-hidden="true">·</span><span className={css.itemHint} data-tone={hint.tone}>{t(hint.key, hint.params)}</span></>}
|
||||
</ItemMeta>
|
||||
<span className={css.itemMeta}>
|
||||
<span className={css.itemFacts}>
|
||||
<span className={css.itemLine}>
|
||||
<span className={css.itemName}>
|
||||
{qualified && <span className={css.itemRepository}>{repository.name}</span>}
|
||||
<span className={css.itemNumber}>{t('change.number', { number })}</span>
|
||||
</span>
|
||||
{summary.author !== null && <><span aria-hidden="true">·</span><span className={css.itemAuthor}>{summary.author.login}</span></>}
|
||||
</span>
|
||||
{hint !== undefined && <span className={css.itemHint} data-tone={hint.tone}>{t(hint.key, hint.params)}</span>}
|
||||
</span>
|
||||
{time !== undefined && <span className={css.itemTime}>{time}</span>}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/** A section's failure: the sign-in command for an unauthenticated GitHub host, otherwise the reason. */
|
||||
function SectionFailure({ section, copyText, t }: {
|
||||
readonly section: ReviewSection
|
||||
/**
|
||||
* One notice per host whose lists could not be read: what failed, the sign-in command for a host that needs sign-in
|
||||
* when its provider names one, and the way to the providers' settings while that page can be opened.
|
||||
*/
|
||||
function HostFailures({ failures, copyText, onOpenSettings, t }: {
|
||||
readonly failures: readonly ReviewHostFailure[]
|
||||
readonly copyText: (text: string) => void
|
||||
readonly onOpenSettings: (() => void) | undefined
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
if (section.failure === null) return null
|
||||
const { host, forge, failure } = section.failure
|
||||
if (failure.code === 'unauthenticated') {
|
||||
const command = forge === 'github' ? `gh auth login --hostname ${host}` : undefined
|
||||
return (
|
||||
<div className={css.notice} role="status">
|
||||
<span>{t('reviewPage.signIn', { host })}</span>
|
||||
{command !== undefined && (
|
||||
<span className={css.noticeCommand}>
|
||||
<code>{command}</code>
|
||||
<Button size="sm" variant="outline" onClick={() => { copyText(command) }}>{t('signin.copy')}</Button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (failure.code === 'rate-limited') return <div className={css.notice} role="status">{t('change.failure.rateLimited')}</div>
|
||||
return <div className={css.notice} role="status">{t('reviewPage.listFailed', { host, message: failure.message })}</div>
|
||||
if (failures.length === 0) return null
|
||||
return (
|
||||
<div className={css.notices}>
|
||||
{failures.map(({ forge, host, failure, signIn }) => {
|
||||
const command = failure.code === 'unauthenticated' ? signIn : null
|
||||
return (
|
||||
<div key={`${forge} ${host}`} className={css.notice} role="status" data-forge-review-failure={host}>
|
||||
<span>
|
||||
{failure.code === 'unauthenticated' ? t('reviewPage.signIn', { host })
|
||||
: t('reviewPage.listFailed', { host, message: failure.code === 'rate-limited' ? t('change.failure.rateLimited') : failure.message })}
|
||||
</span>
|
||||
{command !== null && <span className={css.noticeCommand}><code>{command}</code></span>}
|
||||
{(command !== null || onOpenSettings !== undefined) && (
|
||||
<span className={css.noticeActions}>
|
||||
{command !== null && <Button size="sm" variant="outline" onClick={() => { copyText(command) }}>{t('signin.copy')}</Button>}
|
||||
{onOpenSettings !== undefined && <Button size="sm" variant="outline" onClick={onOpenSettings}>{t('reviewPage.hostSettings')}</Button>}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -366,14 +370,18 @@ function SkeletonItems({ view, count }: { readonly view: ReviewView; readonly co
|
||||
* @returns the column.
|
||||
*/
|
||||
export function ReviewList(props: ReviewListProps): ReactNode {
|
||||
const { frame, stopped, selected, query, folded, refreshing, now, view } = props
|
||||
const { onSelect, onSearch, onFold, onRefresh, onRetry, copyText, t } = props
|
||||
const { frame, stopped, selected, query, folded, refreshing, now, view, scope } = props
|
||||
const { onSelect, onSearch, onFold, onRefresh, onRetry, copyText, onOpenSettings, t } = props
|
||||
const { directOnly } = props
|
||||
const host = scope?.host ?? null
|
||||
// Each section with its search index, rebuilt when the lists change; a blank search returns a list as built.
|
||||
const sections = useMemo(() => reviewSections(frame, directOnly).map(section =>
|
||||
({ section, index: new TextSearchIndex(section.items ?? [], reviewSearchKeys) })), [frame, directOnly])
|
||||
const sections = useMemo(() => reviewSections(frame, directOnly, host).map(section =>
|
||||
({ section, index: new TextSearchIndex(section.items ?? [], reviewSearchKeys) })), [frame, directOnly, host])
|
||||
const failures = useMemo(() => reviewFailures(frame, host), [frame, host])
|
||||
const pasted = pastedUrl(query)
|
||||
const qualified = reviewRepositories(frame).length > 1
|
||||
const named = reviewRepositories(frame).filter(item => host === null || item.host === host)
|
||||
const qualified = named.length > 1
|
||||
const hosted = new Set(named.map(item => item.host)).size > 1
|
||||
let body: ReactNode
|
||||
if (stopped !== null && frame === undefined) {
|
||||
body = (
|
||||
@@ -397,39 +405,48 @@ export function ReviewList(props: ReviewListProps): ReactNode {
|
||||
</div>
|
||||
)
|
||||
} else {
|
||||
body = sections.map(({ section, index }) => {
|
||||
const title = t(SECTION[section.filter])
|
||||
const open = folded[section.filter] !== true
|
||||
const shown = index.search(query)
|
||||
return (
|
||||
<section key={section.filter} className={css.section} data-forge-review-section={section.filter}>
|
||||
<button type="button" className={css.sectionHeader} aria-expanded={open} onClick={() => { onFold(section.filter) }}>
|
||||
<IconChevronDownOutlineRegular size={12} className={clsx(css.chevron, !open && css.chevronClosed)} />
|
||||
<span className={css.sectionTitle}>{title}</span>
|
||||
{section.items !== null && <span className={css.sectionCount}>{section.total.toLocaleString()}</span>}
|
||||
</button>
|
||||
{open && <>
|
||||
<SectionFailure section={section} copyText={copyText} t={t} />
|
||||
{section.items === null
|
||||
? section.failure === null && <div aria-busy="true"><SkeletonItems view={view} count={3} /></div>
|
||||
: shown.length === 0
|
||||
? <p className={css.sectionEmpty}>{t(query.trim() === '' ? 'reviewPage.empty.section' : 'reviewPage.empty.search')}</p>
|
||||
: (
|
||||
<ul className={css.items} data-view={view}>
|
||||
{shown.map((item) => {
|
||||
const Row = view === 'compact' ? CompactItem : Item
|
||||
return <Row key={item.summary.url} item={item} filter={section.filter} selected={item.summary.url === selected}
|
||||
qualified={qualified} now={now} onSelect={onSelect} t={t} />
|
||||
})}
|
||||
</ul>
|
||||
// A host whose first read of a list is still running: its rows are to come, so the count and the empty text wait.
|
||||
const awaits = (section: ReviewSection): boolean => section.pending && frame.reading
|
||||
// Where no host listed anything and none is still to answer, the notices of the hosts that failed are all there is to show.
|
||||
const unread = failures.length > 0 && sections.every(({ section }) => section.items === null && !awaits(section))
|
||||
body = (
|
||||
<>
|
||||
{!unread && sections.map(({ section, index }) => {
|
||||
const title = t(SECTION[section.filter])
|
||||
const open = folded[section.filter] !== true
|
||||
const shown = index.search(query)
|
||||
const awaited = awaits(section)
|
||||
return (
|
||||
<section key={section.filter} className={css.section} data-forge-review-section={section.filter}>
|
||||
<button type="button" className={css.sectionHeader} aria-expanded={open} onClick={() => { onFold(section.filter) }}>
|
||||
<IconChevronDownOutlineRegular size={12} className={clsx(css.chevron, !open && css.chevronClosed)} />
|
||||
<span className={css.sectionTitle}>{title}</span>
|
||||
{section.items !== null && !awaited && <span className={css.sectionCount}>{section.total.toLocaleString()}</span>}
|
||||
</button>
|
||||
{open && <>
|
||||
{shown.length > 0
|
||||
? (
|
||||
<ul className={css.items} data-view={view}>
|
||||
{shown.map((item) => {
|
||||
const Row = view === 'compact' ? CompactItem : Item
|
||||
return <Row key={item.summary.url} item={item} filter={section.filter} selected={item.summary.url === selected}
|
||||
qualified={qualified} hosted={hosted} now={now} onSelect={onSelect} t={t} />
|
||||
})}
|
||||
</ul>
|
||||
)
|
||||
: section.items !== null && !awaited
|
||||
&& <p className={css.sectionEmpty}>{t(query.trim() === '' ? 'reviewPage.empty.section' : 'reviewPage.empty.search')}</p>}
|
||||
{awaited && <div aria-busy="true"><SkeletonItems view={view} count={shown.length > 0 ? 1 : 3} /></div>}
|
||||
{section.truncated && query.trim() === '' && (
|
||||
<p className={css.sectionMore}>{t('reviewPage.truncated', { count: section.total - shown.length })}</p>
|
||||
)}
|
||||
{section.truncated && query.trim() === '' && (
|
||||
<p className={css.sectionMore}>{t('reviewPage.truncated', { count: section.total - shown.length })}</p>
|
||||
)}
|
||||
</>}
|
||||
</section>
|
||||
)
|
||||
})
|
||||
</>}
|
||||
</section>
|
||||
)
|
||||
})}
|
||||
<HostFailures failures={failures} copyText={copyText} onOpenSettings={onOpenSettings} t={t} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className={css.list} data-forge-review-list="">
|
||||
|
||||
+481
-13
@@ -1,7 +1,7 @@
|
||||
/* The review page: a list column beside the detail of one change request. Below 880px of page width one column shows:
|
||||
the list, or the detail with a back button. */
|
||||
.root {
|
||||
container-type: inline-size;
|
||||
container: forge-review / inline-size;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
@@ -113,6 +113,11 @@
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
/* A repository below the row of its host. */
|
||||
.menuNested {
|
||||
padding-left: 16px;
|
||||
}
|
||||
|
||||
.menuValue {
|
||||
overflow: hidden;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
@@ -223,6 +228,7 @@
|
||||
|
||||
.itemText {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
@@ -236,25 +242,84 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* An item's small text on at most two lines: "repository#number · author" and the hint in the first column, the update
|
||||
time in the second. The first column's line does not wrap; the hint follows it where both fit and wraps below it
|
||||
where they do not. */
|
||||
.itemMeta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0 4px;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: start;
|
||||
gap: 0 8px;
|
||||
min-width: 0;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.itemIssues {
|
||||
display: inline-flex;
|
||||
gap: 2px;
|
||||
.itemFacts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
column-gap: 12px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.itemLine {
|
||||
display: flex;
|
||||
flex: 0 1 auto;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Where the line is too narrow the author gives way first, then the repository name; the number is never cut. */
|
||||
.itemName {
|
||||
display: flex;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.itemRepository {
|
||||
flex: 0 1 auto;
|
||||
min-width: 2ch;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.itemNumber {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.itemAuthor {
|
||||
flex: 0 100000 auto;
|
||||
min-width: 3ch;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.itemTime {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.itemHint {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The separator before a hint is drawn in the gap to its left. A hint that starts the second line has that gap outside
|
||||
`.itemFacts`, which clips the separator there. */
|
||||
.itemFacts > .itemHint {
|
||||
position: relative;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.itemFacts > .itemHint::before {
|
||||
position: absolute;
|
||||
left: -8px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
content: '·';
|
||||
}
|
||||
|
||||
.itemHint[data-tone='error'] {
|
||||
@@ -330,7 +395,11 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.compactCard .itemMeta {
|
||||
.cardMeta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0 4px;
|
||||
min-width: 0;
|
||||
color: var(--dsw-alias-hovercard-label-tertiary);
|
||||
}
|
||||
|
||||
@@ -387,6 +456,21 @@
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.noticeActions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* The notices of the hosts that could not be read, after the sections. */
|
||||
.notices {
|
||||
padding-top: 10px;
|
||||
}
|
||||
|
||||
.notices:first-child {
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.noticeCommand code {
|
||||
font-family: var(--dsw-font-mono, ui-monospace, monospace);
|
||||
overflow-wrap: anywhere;
|
||||
@@ -455,6 +539,102 @@
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
/* The detail's skeleton. Each row has the height of the content it stands for: the state chip and the repository in
|
||||
the 32px bar, the 28px title, the 20px line under it, the tabs, 22px lines of text, and 30px rows. */
|
||||
.skeletonChip {
|
||||
flex: none;
|
||||
width: 82px;
|
||||
height: 22px;
|
||||
border-radius: 999px;
|
||||
corner-shape: round;
|
||||
}
|
||||
|
||||
.skeletonRepository {
|
||||
flex: 1000 1 72px;
|
||||
max-width: 236px;
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
.skeletonTitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 28px;
|
||||
margin: 8px 0 4px;
|
||||
}
|
||||
|
||||
.skeletonTitle > span {
|
||||
width: 62%;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.skeletonDetailMeta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.skeletonDetailMeta > span {
|
||||
width: 46%;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.skeletonTab {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
padding: 8px 10px;
|
||||
border-bottom: 2px solid transparent;
|
||||
}
|
||||
|
||||
.skeletonTab > span {
|
||||
width: 28px;
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
.skeletonLines {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.skeletonLines > span {
|
||||
height: 10px;
|
||||
margin: 6px 0;
|
||||
}
|
||||
|
||||
.skeletonLines > i {
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
.skeletonRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 30px;
|
||||
padding: 0 8px;
|
||||
}
|
||||
|
||||
.skeletonRow > .skeletonBar {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.skeletonAvatar {
|
||||
flex: none;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
corner-shape: round;
|
||||
}
|
||||
|
||||
.skeletonSummary {
|
||||
width: 112px;
|
||||
height: 10px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.skeletonHeadless {
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.empty,
|
||||
.centered {
|
||||
display: flex;
|
||||
@@ -503,7 +683,10 @@
|
||||
border-bottom: 0.5px solid var(--dsw-alias-border-l3);
|
||||
}
|
||||
|
||||
/* The bar is a container of its own: its width, not the page's, decides whether the link actions fold. The page's
|
||||
rules name the page container, since an unnamed query inside the bar would read the bar. */
|
||||
.detailBar {
|
||||
container: forge-review-bar / inline-size;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
@@ -533,13 +716,26 @@
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* A flex item wraps by its base size, so the repository link and the labels slot start small and grow: the bar then
|
||||
keeps the actions on its first row. Free room goes to the repository link until its text fits, then to the labels,
|
||||
which fold into a count; with no room left the repository name is cut and its number stays. */
|
||||
.repository {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex: 1000 1 72px;
|
||||
min-width: 0;
|
||||
max-width: max-content;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font-size: 12px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.repositoryName {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.repository:hover {
|
||||
color: var(--dsw-alias-link);
|
||||
@@ -547,12 +743,14 @@
|
||||
}
|
||||
|
||||
.number {
|
||||
flex: none;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
/* The least width holds the count the labels fold into. */
|
||||
.labelsSlot {
|
||||
flex: 1 1 120px;
|
||||
min-width: 0;
|
||||
flex: 1 1 0;
|
||||
min-width: 36px;
|
||||
}
|
||||
|
||||
.labels {
|
||||
@@ -602,6 +800,32 @@
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
/* Open on the code host, copy the link, read again: three icon buttons at the bar's end, after the merge action. */
|
||||
.linkActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.copied {
|
||||
color: var(--dsw-alias-state-success-primary);
|
||||
}
|
||||
|
||||
/* The same three actions as one menu, which a narrow bar shows in place of the buttons. */
|
||||
.moreAction {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@container forge-review-bar (max-width: 719px) {
|
||||
.linkActions {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.moreAction {
|
||||
display: inline-flex;
|
||||
}
|
||||
}
|
||||
|
||||
.primary {
|
||||
display: contents;
|
||||
}
|
||||
@@ -720,6 +944,245 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* The activity under the description: one line per commit run, review, and change of state, and a card per comment. */
|
||||
.activity {
|
||||
margin-top: 28px;
|
||||
}
|
||||
|
||||
.activityLines {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
margin: 0 -8px;
|
||||
}
|
||||
|
||||
.activityLine {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 5px 8px;
|
||||
border: 0;
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
line-height: 20px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
button.activityLine {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.activityLine:focus-visible,
|
||||
.activityMore:focus-visible {
|
||||
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
button.activityLine:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
}
|
||||
|
||||
.activityNested {
|
||||
padding-left: 32px;
|
||||
}
|
||||
|
||||
.activityGlyph {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
.activityGlyph[data-tone='success'] {
|
||||
color: var(--dsw-alias-state-success-primary);
|
||||
}
|
||||
|
||||
.activityGlyph[data-tone='error'] {
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
|
||||
.activityText {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.activityActor {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.activityRest {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.activityTime {
|
||||
flex: none;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.activityEnd {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
margin-left: auto;
|
||||
padding-left: 8px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.activitySha {
|
||||
font-family: var(--dsw-font-mono, ui-monospace, monospace);
|
||||
}
|
||||
|
||||
.activityComment {
|
||||
margin: 6px 8px;
|
||||
padding: 10px 12px;
|
||||
border: 0.5px solid var(--dsw-alias-border-l3);
|
||||
border-radius: var(--dsw-radius-md, 8px);
|
||||
}
|
||||
|
||||
.activityCommentHead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.activityTag {
|
||||
padding: 0 6px;
|
||||
border-radius: 999px;
|
||||
corner-shape: round;
|
||||
background: var(--dsw-alias-card-fill);
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
/* A long comment starts as its first lines; the control under it shows the rest. */
|
||||
.activityClamp {
|
||||
max-height: 120px;
|
||||
overflow: hidden;
|
||||
mask-image: linear-gradient(to bottom, black 60%, transparent);
|
||||
}
|
||||
|
||||
.activityMore {
|
||||
margin: 4px 0 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
background: none;
|
||||
color: var(--dsw-alias-link);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.activityOlder {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 0 8px;
|
||||
margin: 0 0 8px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.activityOlder > .activityMore {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* The comment field: three lines that grow with the text, over a row that says where the comment goes and holds the
|
||||
button that sends it. */
|
||||
.activityCompose {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.activityComposer {
|
||||
border: 0.5px solid var(--dsw-alias-border-l3);
|
||||
border-radius: var(--dsw-radius-md, 8px);
|
||||
background: var(--dsw-alias-bg-layer-1, transparent);
|
||||
transition: border-color 120ms ease, box-shadow 120ms ease;
|
||||
}
|
||||
|
||||
.activityComposer:focus-within {
|
||||
border-color: var(--dsw-alias-state-business-primary);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--dsw-alias-state-business-primary) 16%, transparent);
|
||||
}
|
||||
|
||||
.activityComposer textarea {
|
||||
display: block;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-height: 76px;
|
||||
max-height: 240px;
|
||||
padding: 10px 12px 4px;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
resize: none;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.activityComposer textarea::placeholder {
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
.activityComposerFoot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 6px 6px 12px;
|
||||
}
|
||||
|
||||
.activityComposerHint {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.activityComposerKeys {
|
||||
flex: none;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.activitySend {
|
||||
flex: none;
|
||||
min-width: 56px;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.activityComposer {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
.activityError {
|
||||
margin: 6px 0 0;
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* The status column: bordered blocks. A card holds rows of the Session panel's change request card on that card's
|
||||
row grid, without the indent that aligns them under the card's title there. */
|
||||
.statusCard,
|
||||
@@ -829,6 +1292,11 @@
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* An action line that anchors a menu spans its block like the lines around it. */
|
||||
.statusAnchor {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.placeholder {
|
||||
justify-content: center;
|
||||
}
|
||||
@@ -865,13 +1333,13 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@container (max-width: 960px) {
|
||||
@container forge-review (max-width: 960px) {
|
||||
.summary {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-width: 880px) {
|
||||
@container forge-review (max-width: 880px) {
|
||||
.page {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
@@ -8,8 +8,7 @@ import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react
|
||||
import clsx from 'clsx'
|
||||
import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-store'
|
||||
import type { ChangeRequestDescription, ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { ForgeReviewChangeRequest, ForgeReviewFrame } from '../../types.ts'
|
||||
import type { ChangeRequestActions } from '../ChangeRequestCard.tsx'
|
||||
import type { ForgeLensDescription } from '../changes-service.ts'
|
||||
@@ -17,10 +16,10 @@ import { ChangesView, type ChangesTabInjected, type ChangesViewTab } from '../Ch
|
||||
import { useHostStream, type StreamRead } from './host-stream.ts'
|
||||
import type { NS } from '../locales.ts'
|
||||
import { ReviewChat, useReviewConversation, type ReviewChatFace } from './ReviewChat.tsx'
|
||||
import { ReviewDetail } from './ReviewDetail.tsx'
|
||||
import { ReviewDetail, type ReviewSummaryFace } from './ReviewDetail.tsx'
|
||||
import { ReviewList } from './ReviewList.tsx'
|
||||
import type { QuoteCopy, ReviewSelection } from '../review.ts'
|
||||
import { reviewListsComplete, reviewRepositories } from './review-lists.ts'
|
||||
import { reviewListsComplete, reviewRepositories, scopeRepository, type ReviewRepository } from './review-lists.ts'
|
||||
import type { createReviewStore, ReviewTab } from './review-store.ts'
|
||||
import type { HostStream, StreamSnapshot } from '../source.ts'
|
||||
import type { ChangesPanelState } from '../status.ts'
|
||||
@@ -38,19 +37,23 @@ export type ReviewChangesFace = Omit<ChangesTabInjected, 'keyedHooks' | 'hooks'
|
||||
const CHAT_QUOTE_COPY: QuoteCopy = { add: 'reviewPage.addToChat', added: 'reviewPage.addedToChat', failed: 'reviewPage.addToChatFailed' }
|
||||
|
||||
/** Business face of the review page. */
|
||||
export interface ReviewPageInjected {
|
||||
/** The UI language; the renderer binds it as `useLocale`. */
|
||||
readonly hooks: { readonly locale: HostObservable<string> }
|
||||
/** Open the list stream of one repository, named `owner/name`, or of every repository for the empty string. */
|
||||
readonly openLists: (scope: string, signal: AbortSignal) => HostStream<ForgeReviewFrame>
|
||||
export interface ReviewPageInjected extends ReviewSummaryFace {
|
||||
readonly hooks: {
|
||||
/** The UI language; the renderer binds it as `useLocale`. */
|
||||
readonly locale: HostObservable<string>
|
||||
/** Whether the Plugins page can be opened; the renderer binds it as `usePluginNavigation`. */
|
||||
readonly pluginNavigation: HostObservable<boolean>
|
||||
}
|
||||
/** Open the list stream of one repository on its host, or of every repository of every host for null. */
|
||||
readonly openLists: (repository: ReviewRepository | null, signal: AbortSignal) => HostStream<ForgeReviewFrame>
|
||||
/** Open the stream of one change request by URL. */
|
||||
readonly openChangeRequest: (url: string, signal: AbortSignal) => HostStream<ForgeReviewChangeRequest>
|
||||
/** Subscribe to transport resets, after which open streams no longer deliver. */
|
||||
readonly subscribeReset: (listener: () => void) => () => void
|
||||
/** Read every list again; settles once the Host accepted the request, after reporting a failure. */
|
||||
readonly refresh: () => Promise<void>
|
||||
/** Read the description and labels of a change request. */
|
||||
readonly readDescription: (url: string, signal: AbortSignal) => Promise<RemoteResult<ChangeRequestDescription>>
|
||||
/** Open the Plugins page where the providers' hosts are listed, while `pluginNavigation` holds. */
|
||||
readonly openHostSettings: () => void
|
||||
/** The card actions acting on one change request; `showChanges` opens the changes tab. */
|
||||
readonly actionsFor: (url: string, showChanges: () => void) => ChangeRequestActions
|
||||
/** Reads and writes of the changes view. */
|
||||
@@ -148,7 +151,9 @@ interface DetailPaneProps {
|
||||
function DetailPane({
|
||||
url, read, tab, listHidden, now, locale, cardActions, conversationId, onConversation, unseenQuotes, page,
|
||||
}: DetailPaneProps): ReactNode {
|
||||
const { actions, changes, chat, quoteReview, quoteThread, readDescription, renderSlot, SessionProvider, useStore, t } = page
|
||||
const { actions, changes, chat, quoteReview, quoteThread, readDescription, readActivity, addComment, renderSlot } = page
|
||||
const { SessionProvider, useStore, t } = page
|
||||
const hostSettings = page.usePluginNavigation(value => value)
|
||||
const conversation = useReviewConversation(read.frame, conversationId, onConversation, chat)
|
||||
const { start } = conversation
|
||||
const quoteChanges = useMemo(() => {
|
||||
@@ -178,6 +183,9 @@ function DetailPane({
|
||||
locale={locale}
|
||||
actions={cardActions}
|
||||
readDescription={readDescription}
|
||||
readActivity={readActivity}
|
||||
addComment={addComment}
|
||||
onAddHost={hostSettings ? page.openHostSettings : undefined}
|
||||
renderChanges={frame => (
|
||||
<ReviewChanges frame={frame} visible={tab === 'changes'} changes={quoteChanges} useStore={useStore} actions={actions} t={t} />
|
||||
)}
|
||||
@@ -204,7 +212,8 @@ export function ReviewPage(props: ReviewPageProps): ReactNode {
|
||||
const tab = useStore(state => state.tab)
|
||||
const listHidden = useStore(state => state.listHidden)
|
||||
const folded = useStore(state => state.folded)
|
||||
const repository = useStore(state => state.repository)
|
||||
const scope = useStore(state => state.scope)
|
||||
const repository = scopeRepository(scope)
|
||||
const repositories = useStore(state => state.repositories)
|
||||
const query = useStore(state => state.query)
|
||||
const directOnly = useStore(state => state.directOnly)
|
||||
@@ -214,8 +223,11 @@ export function ReviewPage(props: ReviewPageProps): ReactNode {
|
||||
const onConversation = useMemo(() => selected === null ? null : (sessionId: SessionId | null) => {
|
||||
actions.conversed(selected, sessionId)
|
||||
}, [actions, selected])
|
||||
const scope = repository === null ? '' : `${repository.owner}/${repository.name}`
|
||||
const lists = useHostStream(openLists, scope, subscribeReset)
|
||||
// A scope that names a host only narrows the lists of every repository on the page; one repository is read on its host.
|
||||
const listsKey = repository === null ? '' : JSON.stringify([repository.host, repository.owner, repository.name])
|
||||
const openScoped = useCallback((_key: string, signal: AbortSignal) => openLists(repository, signal), [openLists, repository])
|
||||
const lists = useHostStream(openScoped, listsKey, subscribeReset)
|
||||
const hostSettings = props.usePluginNavigation(value => value)
|
||||
// Lists read in one repository name only that one, so the repository menu's offer is recorded while they are read in all.
|
||||
const listsFrame = lists.frame
|
||||
useEffect(() => {
|
||||
@@ -238,7 +250,7 @@ export function ReviewPage(props: ReviewPageProps): ReactNode {
|
||||
stopped={lists.stopped}
|
||||
selected={selected}
|
||||
query={query}
|
||||
repository={repository}
|
||||
scope={scope}
|
||||
repositories={repositories}
|
||||
directOnly={directOnly}
|
||||
folded={folded}
|
||||
@@ -254,6 +266,7 @@ export function ReviewPage(props: ReviewPageProps): ReactNode {
|
||||
onRefresh={startRefresh}
|
||||
onRetry={lists.retry}
|
||||
copyText={copyText}
|
||||
onOpenSettings={hostSettings ? props.openHostSettings : undefined}
|
||||
t={t}
|
||||
/>
|
||||
{selected === null || cardActions === null || onConversation === null
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Skeletons of the review page's detail, drawn while a change request, its description, or its activity is read.
|
||||
* Each row is as tall as the content it stands for, so the content replaces it without moving what follows.
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import loading from '../ChangesLoading.module.css'
|
||||
import css from './ReviewPage.module.css'
|
||||
|
||||
/** Widths of the description's lines in percent; zero is the gap between two paragraphs. */
|
||||
const DESCRIPTION_LINES = [96, 100, 88, 54, 0, 92, 70, 38] as const
|
||||
|
||||
/** Rows of each block of the status column, as the width of each row's text in percent; a headed block has a caption row. */
|
||||
const STATUS_BLOCKS: readonly { readonly head: boolean; readonly rows: readonly number[] }[] = [
|
||||
{ head: false, rows: [58] },
|
||||
{ head: true, rows: [46, 62, 40] },
|
||||
{ head: true, rows: [34, 30] },
|
||||
{ head: false, rows: [28] },
|
||||
]
|
||||
|
||||
function Fill({ className, width }: { readonly className?: string | undefined; readonly width?: string | undefined }): ReactNode {
|
||||
return <span className={clsx(loading.fill, className)} style={width === undefined ? undefined : { width }} />
|
||||
}
|
||||
|
||||
function Lines({ widths }: { readonly widths: readonly number[] }): ReactNode {
|
||||
return (
|
||||
<div className={css.skeletonLines}>
|
||||
{widths.map((width, index) => width === 0 ? <i key={index} /> : <Fill key={index} width={`${width}%`} />)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ width, timed = false }: { readonly width: number; readonly timed?: boolean }): ReactNode {
|
||||
return (
|
||||
<div className={css.skeletonRow}>
|
||||
<Fill className={css.skeletonGlyph} />
|
||||
<Fill className={css.skeletonBar} width={`${width}%`} />
|
||||
{timed && <Fill className={css.skeletonTime} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the title, the line under it, and the tabs of a change request that is not read yet.
|
||||
* @returns the three rows, hidden from assistive technology.
|
||||
*/
|
||||
export function HeaderSkeleton(): ReactNode {
|
||||
return (
|
||||
<>
|
||||
<div className={css.skeletonTitle} aria-hidden="true"><Fill /></div>
|
||||
<div className={css.skeletonDetailMeta} aria-hidden="true"><Fill /></div>
|
||||
<div className={css.tabs} aria-hidden="true">
|
||||
{[0, 1, 2].map(tab => <span key={tab} className={css.skeletonTab}><Fill /></span>)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the lines of a description that is not read yet.
|
||||
* @returns the lines, hidden from assistive technology.
|
||||
*/
|
||||
export function DescriptionSkeleton(): ReactNode {
|
||||
return <div aria-hidden="true" data-forge-review-skeleton="description"><Lines widths={DESCRIPTION_LINES} /></div>
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the rows of an activity that is not read yet: two lines, a comment card, and one more line.
|
||||
* @returns the rows, hidden from assistive technology.
|
||||
*/
|
||||
export function ActivitySkeleton(): ReactNode {
|
||||
return (
|
||||
<div className={css.activityLines} aria-hidden="true" data-forge-review-skeleton="activity">
|
||||
<Row width={34} timed />
|
||||
<Row width={52} timed />
|
||||
<div className={css.activityComment}>
|
||||
<div className={css.activityCommentHead}>
|
||||
<Fill className={css.skeletonAvatar} />
|
||||
<Fill className={css.skeletonBar} width="96px" />
|
||||
</div>
|
||||
<Lines widths={[94, 60]} />
|
||||
</div>
|
||||
<Row width={40} timed />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the blocks of a status column that is not read yet.
|
||||
* @returns the blocks, hidden from assistive technology.
|
||||
*/
|
||||
export function StatusSkeleton(): ReactNode {
|
||||
return (
|
||||
<aside className={css.facts} aria-hidden="true" data-forge-review-skeleton="status">
|
||||
{STATUS_BLOCKS.map((block, index) => (
|
||||
<div key={index} className={css.statusSection}>
|
||||
{block.head && (
|
||||
<div className={css.statusHead}><Fill className={css.skeletonBar} width="36px" /><Fill className={css.skeletonSummary} /></div>
|
||||
)}
|
||||
<div className={clsx(css.statusList, !block.head && css.skeletonHeadless)}>
|
||||
{block.rows.map((width, row) => <Row key={row} width={width} />)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -171,7 +171,7 @@ function Reviewers({ frame, snapshot, actions, t }: StatusProps): ReactNode {
|
||||
</button>
|
||||
)}
|
||||
{requesting !== undefined && (
|
||||
<Menu open={open} onClose={close} portal dense align="start" listClassName={overview.menu}
|
||||
<Menu open={open} onClose={close} portal dense align="start" className={css.statusAnchor} listClassName={overview.menu}
|
||||
anchor={(
|
||||
<button type="button" className={clsx(css.statusLine, css.statusLineButton, css.statusAction)} aria-haspopup="menu"
|
||||
aria-expanded={open} disabled={busy} data-forge-review-request="" onClick={() => { if (open) close(); else setOpen(true) }}>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* The summary tab's activity helpers: its rows, with every run of commits as one, and which comment texts start cut
|
||||
* short.
|
||||
*/
|
||||
|
||||
import type { ChangeRequestActivityItem } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
|
||||
/** A commit of the activity. */
|
||||
export type ActivityCommit = Extract<ChangeRequestActivityItem, { readonly kind: 'commit' }>
|
||||
|
||||
/** An activity item other than a commit. */
|
||||
export type ActivityEvent = Exclude<ChangeRequestActivityItem, ActivityCommit>
|
||||
|
||||
/**
|
||||
* One row of the activity: an item other than a commit, or the commits that follow one another. `key` tells the rows of
|
||||
* one activity apart and stays the same when a later read adds or drops other rows.
|
||||
*/
|
||||
export type ActivityEntry =
|
||||
| { readonly kind: 'commits'; readonly key: string; readonly commits: readonly [ActivityCommit, ...ActivityCommit[]] }
|
||||
| { readonly kind: 'item'; readonly key: string; readonly item: ActivityEvent }
|
||||
|
||||
/** Most characters of a comment text that shows whole from the start. */
|
||||
const WHOLE_CHARACTERS = 400
|
||||
|
||||
/** Most lines of a comment text that shows whole from the start. */
|
||||
const WHOLE_LINES = 6
|
||||
|
||||
/**
|
||||
* Lay the activity out as rows.
|
||||
* @param items - the activity, oldest first.
|
||||
* @returns the rows in the same order, with every run of consecutive commits as one row.
|
||||
*/
|
||||
export function activityEntries(items: readonly ChangeRequestActivityItem[]): readonly ActivityEntry[] {
|
||||
const entries: ActivityEntry[] = []
|
||||
const seen = new Map<string, number>()
|
||||
// Two rows of one kind, time, and actor differ by their count.
|
||||
const keyOf = (name: string): string => {
|
||||
const count = seen.get(name) ?? 0
|
||||
seen.set(name, count + 1)
|
||||
return count === 0 ? name : `${name}#${count}`
|
||||
}
|
||||
let run: [ActivityCommit, ...ActivityCommit[]] | null = null
|
||||
for (const item of items) {
|
||||
if (item.kind !== 'commit') {
|
||||
run = null
|
||||
entries.push({ kind: 'item', key: keyOf(`${item.kind}:${item.at}:${item.actor?.login ?? ''}`), item })
|
||||
} else if (run === null) {
|
||||
run = [item]
|
||||
entries.push({ kind: 'commits', key: keyOf(`commits:${item.sha}`), commits: run })
|
||||
} else {
|
||||
run.push(item)
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a comment text starts cut short, with a control that shows the rest.
|
||||
* @param body - Markdown source of the comment.
|
||||
* @returns whether it is longer than the text that shows whole.
|
||||
*/
|
||||
export function longBody(body: string): boolean {
|
||||
return body.length > WHOLE_CHARACTERS || body.split('\n').length > WHOLE_LINES
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* What the review page's list column shows from the Host's list frames: one section per list with its items and the
|
||||
* text they are searched by, the hint each item carries, the repositories the lists name, and the failure each section reports.
|
||||
* text they are searched by, the hint each item carries, the repositories the lists name by host, and the hosts whose
|
||||
* read failed.
|
||||
*/
|
||||
|
||||
import type { ChangeRequestSummary, ForgeFailure, ForgeViewerFilter } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
@@ -32,73 +33,130 @@ export interface ReviewSection {
|
||||
readonly total: number
|
||||
/** Whether some host listed fewer change requests than its total. */
|
||||
readonly truncated: boolean
|
||||
/** The first failure of the latest read on any host, or null. */
|
||||
readonly failure: { readonly host: string; readonly forge: string; readonly failure: ForgeFailure } | null
|
||||
/** Whether some host has neither read the list nor failed to, so its change requests are still to come. */
|
||||
readonly pending: boolean
|
||||
}
|
||||
|
||||
/** A repository the lists name. */
|
||||
/** A repository the lists name, on the host that listed it. */
|
||||
export interface ReviewRepository {
|
||||
/** Host the repository was listed on. */
|
||||
readonly host: string
|
||||
/** Owner or namespace. */
|
||||
readonly owner: string
|
||||
/** Repository name. */
|
||||
readonly name: string
|
||||
}
|
||||
|
||||
/** What the reader narrowed the lists to: every repository of one host, or one repository. */
|
||||
export type ReviewScope = { readonly host: string } | ReviewRepository
|
||||
|
||||
/** A host whose latest read of some list failed. */
|
||||
export interface ReviewHostFailure {
|
||||
/** Forge family of the provider that lists on the host. */
|
||||
readonly forge: string
|
||||
/** The host. */
|
||||
readonly host: string
|
||||
/** The first failure among the host's lists, in page order. */
|
||||
readonly failure: ForgeFailure
|
||||
/** The command that signs the provider's CLI in to the host, or null when the failure is another or the provider names none. */
|
||||
readonly signIn: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The repository a scope names.
|
||||
* @param scope - the reader's scope, or null for every repository of every host.
|
||||
* @returns the repository, or null for a scope that names a host only or none.
|
||||
*/
|
||||
export function scopeRepository(scope: ReviewScope | null): ReviewRepository | null {
|
||||
return scope !== null && 'name' in scope ? scope : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two scopes narrow the lists to the same host or repository.
|
||||
* @param left - one scope, or null for none.
|
||||
* @param right - the other scope, or null for none.
|
||||
* @returns whether they are the same.
|
||||
*/
|
||||
export function sameScope(left: ReviewScope | null, right: ReviewScope | null): boolean {
|
||||
if (left === null || right === null) return left === right
|
||||
const one = scopeRepository(left)
|
||||
const other = scopeRepository(right)
|
||||
return left.host === right.host && one?.owner === other?.owner && one?.name === other?.name
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the list sections from one frame.
|
||||
* @param frame - the latest frame, or undefined before the first.
|
||||
* @param directOnly - whether the review-requested list leaves out requests made only of one of the user's teams.
|
||||
* @param host - the host the reader narrowed the lists to, or null for every host of the frame.
|
||||
* @returns one section per list some host offers, in page order, each with every item most recently updated first.
|
||||
*/
|
||||
export function reviewSections(frame: ForgeReviewFrame | undefined, directOnly: boolean): readonly ReviewSection[] {
|
||||
export function reviewSections(frame: ForgeReviewFrame | undefined, directOnly: boolean, host: string | null): readonly ReviewSection[] {
|
||||
if (frame === undefined) return []
|
||||
const sections: ReviewSection[] = []
|
||||
for (const filter of REVIEW_FILTERS) {
|
||||
const lists = frame.hosts.flatMap((host) => {
|
||||
const list = host.lists[filter]
|
||||
return list === undefined ? [] : [{ host, list }]
|
||||
const lists = frame.hosts.flatMap((entry) => {
|
||||
const list = entry.lists[filter]
|
||||
return list === undefined || (host !== null && entry.host !== host) ? [] : [{ host: entry, list }]
|
||||
})
|
||||
if (lists.length === 0) continue
|
||||
let items: ReviewItem[] | null = null
|
||||
let total = 0
|
||||
let truncated = false
|
||||
let failure: ReviewSection['failure'] = null
|
||||
for (const { host, list } of lists) {
|
||||
if (list.failure !== null && failure === null) failure = { host: host.host, forge: host.forge, failure: list.failure }
|
||||
if (list.items === null) continue
|
||||
let pending = false
|
||||
for (const { host: entry, list } of lists) {
|
||||
if (list.items === null) {
|
||||
pending ||= list.failure === null
|
||||
continue
|
||||
}
|
||||
total += list.total
|
||||
truncated ||= list.total > list.items.length
|
||||
items ??= []
|
||||
for (const summary of list.items) {
|
||||
if (filter === 'review-requested' && directOnly && summary.viewerRequest !== null && summary.viewerRequest.team !== null) continue
|
||||
items.push({ summary, forge: host.forge, host: host.host })
|
||||
items.push({ summary, forge: entry.forge, host: entry.host })
|
||||
}
|
||||
}
|
||||
items?.sort((left, right) => Date.parse(right.summary.updatedAt) - Date.parse(left.summary.updatedAt))
|
||||
sections.push({ filter, items, total, truncated, failure })
|
||||
sections.push({ filter, items, total, truncated, pending })
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
/**
|
||||
* The text a listed change request is searched by under the client search rule: its title, number, repository, and
|
||||
* author each match as a substring or a word-start fuzzy subsequence.
|
||||
* List the hosts whose latest read of some list failed, so the page reports each once.
|
||||
* @param frame - the latest frame, or undefined before the first.
|
||||
* @param host - the host the reader narrowed the lists to, or null for every host of the frame.
|
||||
* @returns the hosts in frame order, each with the first failure among its lists.
|
||||
*/
|
||||
export function reviewFailures(frame: ForgeReviewFrame | undefined, host: string | null): readonly ReviewHostFailure[] {
|
||||
return (frame?.hosts ?? []).flatMap((entry) => {
|
||||
if (host !== null && entry.host !== host) return []
|
||||
const failure = REVIEW_FILTERS.map(filter => entry.lists[filter]?.failure ?? null).find(found => found !== null)
|
||||
return failure === undefined ? [] : [{ forge: entry.forge, host: entry.host, failure, signIn: entry.signIn }]
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The text a listed change request is searched by under the client search rule: its title, number, repository, author,
|
||||
* and host each match as a substring or a word-start fuzzy subsequence.
|
||||
* @param item - the listed change request.
|
||||
* @returns the search keys.
|
||||
*/
|
||||
export function reviewSearchKeys(item: ReviewItem): SearchKeys {
|
||||
const { repository, number } = item.summary.ref
|
||||
return { fuzzy: [item.summary.title, `#${number}`, `${repository.owner}/${repository.name}`, item.summary.author?.login] }
|
||||
return { fuzzy: [item.summary.title, `#${number}`, `${repository.owner}/${repository.name}`, item.summary.author?.login, item.host] }
|
||||
}
|
||||
|
||||
/**
|
||||
* List the repositories the lists name, by owner then name.
|
||||
* List the repositories the lists name, by host, then owner, then name.
|
||||
* @param frame - the latest frame, or undefined before the first.
|
||||
* @returns distinct repositories.
|
||||
*/
|
||||
export function reviewRepositories(frame: ForgeReviewFrame | undefined): readonly ReviewRepository[] {
|
||||
return mergeRepositories((frame?.hosts ?? []).flatMap(host =>
|
||||
Object.values(host.lists).flatMap(list => (list.items ?? []).map(item => item.ref.repository))))
|
||||
Object.values(host.lists).flatMap(list => (list.items ?? []).map(({ ref: { repository } }) =>
|
||||
({ host: host.host, owner: repository.owner, name: repository.name })))))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,15 +170,20 @@ export function reviewListsComplete(frame: ForgeReviewFrame | undefined): boolea
|
||||
&& frame.hosts.every(host => Object.values(host.lists).every(list => list.items !== null && list.failure === null))
|
||||
}
|
||||
|
||||
/** A repository's place in the order {@link mergeRepositories} sorts by, which is also its identity. */
|
||||
function repositoryKey({ host, owner, name }: ReviewRepository): string {
|
||||
return `${host}\n${owner}/${name}`.toLowerCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge repositories into one list without duplicates, by owner then name.
|
||||
* Merge repositories into one list without duplicates, by host, then owner, then name.
|
||||
* @param groups - lists of repositories.
|
||||
* @returns the distinct repositories, sorted as {@link reviewRepositories} sorts.
|
||||
*/
|
||||
export function mergeRepositories(...groups: readonly (readonly ReviewRepository[])[]): readonly ReviewRepository[] {
|
||||
const seen = new Map<string, ReviewRepository>()
|
||||
for (const { owner, name } of groups.flat()) seen.set(`${owner}/${name}`.toLowerCase(), { owner, name })
|
||||
return [...seen.values()].sort((left, right) => `${left.owner}/${left.name}`.localeCompare(`${right.owner}/${right.name}`))
|
||||
for (const { host, owner, name } of groups.flat()) seen.set(repositoryKey({ host, owner, name }), { host, owner, name })
|
||||
return [...seen].sort(([left], [right]) => left.localeCompare(right)).map(([, repository]) => repository)
|
||||
}
|
||||
|
||||
/** The hint an item carries: a dictionary key and its values. */
|
||||
|
||||
@@ -7,7 +7,9 @@ import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {} from '@deepseek-ai/dsh-api-remote-access/client'
|
||||
import type {} from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type {} from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client'
|
||||
import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
@@ -66,6 +68,8 @@ export interface ReviewPageDeps {
|
||||
readonly quoteThread: ReviewPageInjected['quoteThread']
|
||||
/** The UI language. */
|
||||
readonly locale: HostObservable<string>
|
||||
/** Package name of the bundle whose page on the Plugins page lists the provider rows with their host lists. */
|
||||
readonly hostSettings: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,7 +86,7 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void {
|
||||
const actionsFor = (url: string, showChanges: () => void): ChangeRequestActions => ({
|
||||
openLink,
|
||||
copyLink: copyText,
|
||||
retry: () => { void remote.reviewPoll(url).then(result => settled(result, 'toast.refreshFailed')) },
|
||||
retry: async () => { settled(await remote.reviewPoll(url), 'toast.refreshFailed') },
|
||||
markReady: async (entry) => {
|
||||
reportAction(entry, await remote.reviewMarkReady(url), { done: 'toast.markedReady', failed: 'toast.markReadyFailed' })
|
||||
},
|
||||
@@ -90,6 +94,10 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void {
|
||||
reportAction(entry, await remote.reviewMerge(url, request.method, request.headSha),
|
||||
{ done: 'toast.merged', stale: 'toast.mergeStale', failed: 'toast.mergeFailed' })
|
||||
},
|
||||
autoMerge: async (entry, request) => {
|
||||
reportAction(entry, await remote.reviewSetAutoMerge(url, request),
|
||||
{ done: request.enabled ? 'toast.autoMergeEnabled' : 'toast.autoMergeCancelled', stale: 'toast.autoMergeStale', failed: 'toast.autoMergeFailed' })
|
||||
},
|
||||
readChecks: async (_url, headSha, signal) => {
|
||||
const result = await remote.reviewChecks(url, headSha, signal)
|
||||
if (!result.ok) throw new Error(result.error.message)
|
||||
@@ -183,6 +191,14 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void {
|
||||
void remote.requestWorktree(sessionId, null, null).then(result => settled(result, 'toast.worktreeFailed'))
|
||||
},
|
||||
}
|
||||
// The Plugins page provides its navigation only while the current Peer may use it.
|
||||
const pluginNavigation = createSnapshotStore(false)
|
||||
ctx.inject(['pluginNavigation'], (scope: Context) => {
|
||||
scope.effect(() => {
|
||||
pluginNavigation.set(true)
|
||||
return () => { pluginNavigation.set(false) }
|
||||
}, 'forge-panel: plugin navigation presence')
|
||||
})
|
||||
const count = createStreamSource<ForgeReviewCountFrame, number | null>({
|
||||
open: signal => remote.reviewCount(signal),
|
||||
subscribeReset,
|
||||
@@ -196,15 +212,15 @@ export function registerReviewPage(ctx: Context, deps: ReviewPageDeps): void {
|
||||
locale: NS,
|
||||
store: createReviewStore(),
|
||||
inject: (): ReviewPageInjected => ({
|
||||
hooks: { locale: deps.locale },
|
||||
openLists: (scope, signal) => {
|
||||
const slash = scope.indexOf('/')
|
||||
return remote.reviewLists(slash < 0 ? null : { owner: scope.slice(0, slash), name: scope.slice(slash + 1) }, signal)
|
||||
},
|
||||
hooks: { locale: deps.locale, pluginNavigation },
|
||||
openLists: (repository, signal) => remote.reviewLists(repository, signal),
|
||||
openChangeRequest: (url, signal) => remote.reviewChangeRequest(url, signal),
|
||||
subscribeReset,
|
||||
refresh: async () => { settled(await remote.reviewRefresh(), 'toast.refreshFailed') },
|
||||
readDescription: (url, signal) => remote.reviewDescription(url, signal),
|
||||
readActivity: (url, signal) => remote.reviewActivity(url, signal),
|
||||
addComment: (url, body) => remote.reviewComment(url, body),
|
||||
openHostSettings: () => { ctx.get('pluginNavigation')?.openBundle(deps.hostSettings) },
|
||||
actionsFor,
|
||||
changes,
|
||||
copyText,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Choices of the review page that outlive its mount: the change request shown in full, its tab, whether the list column
|
||||
* hides, which list sections fold, the repository the lists are read in, the search text, the conversation the page
|
||||
* hides, which list sections fold, the host or repository the lists are narrowed to, the search text, the conversation the page
|
||||
* started for each change request, and the changes view's choices for each change request.
|
||||
*/
|
||||
|
||||
@@ -8,7 +8,7 @@ import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-sto
|
||||
import type { ForgeViewerFilter } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { changesActions, type ChangesState } from '../changes-store.ts'
|
||||
import { mergeRepositories, type ReviewRepository } from './review-lists.ts'
|
||||
import { mergeRepositories, type ReviewRepository, type ReviewScope } from './review-lists.ts'
|
||||
|
||||
/** A tab of the review page's detail. */
|
||||
export type ReviewTab = 'summary' | 'changes' | 'chat'
|
||||
@@ -26,8 +26,8 @@ export interface ReviewPageState extends ChangesState {
|
||||
listHidden: boolean
|
||||
/** List sections the reader folded. */
|
||||
folded: Partial<Record<ForgeViewerFilter, boolean>>
|
||||
/** Repository the lists are read in, or null for every repository. */
|
||||
repository: { readonly owner: string; readonly name: string } | null
|
||||
/** What the lists are narrowed to: one host, one repository, or null for every repository of every host. */
|
||||
scope: ReviewScope | null
|
||||
/**
|
||||
* Repositories the lists named while they were read in every repository, which the repository menu keeps offering
|
||||
* while the lists are read in one.
|
||||
@@ -62,14 +62,14 @@ const reviewActions = {
|
||||
},
|
||||
toggledList: (state: ReviewPageState) => { state.listHidden = !state.listHidden },
|
||||
folded: (state: ReviewPageState, filter: ForgeViewerFilter) => { state.folded[filter] = state.folded[filter] !== true },
|
||||
scopedTo: (state: ReviewPageState, repository: ReviewPageState['repository']) => { state.repository = repository },
|
||||
scopedTo: (state: ReviewPageState, scope: ReviewScope | null) => { state.scope = scope },
|
||||
/**
|
||||
* Record the repositories the lists read in every repository name: a complete read replaces the record, and a read
|
||||
* still under way or failed in part adds to it.
|
||||
*/
|
||||
listed: (state: ReviewPageState, repositories: ReviewPageState['repositories'], complete: boolean) => {
|
||||
const next = complete ? mergeRepositories(repositories) : mergeRepositories(state.repositories, repositories)
|
||||
const names = (list: ReviewPageState['repositories']): string => list.map(item => `${item.owner}/${item.name}`).join('\n')
|
||||
const names = (list: ReviewPageState['repositories']): string => list.map(item => `${item.host} ${item.owner}/${item.name}`).join('\n')
|
||||
if (names(next) !== names(state.repositories)) state.repositories = [...next]
|
||||
},
|
||||
searched: (state: ReviewPageState, query: string) => { state.query = query },
|
||||
@@ -87,7 +87,7 @@ const reviewActions = {
|
||||
export function createReviewStore(): EngineStoreHandle<ReviewPageState, typeof reviewActions> {
|
||||
return defineStore({
|
||||
init: (): ReviewPageState => ({
|
||||
selected: null, tab: 'summary', listHidden: false, folded: {}, repository: null, repositories: [], query: '', directOnly: false, conversations: {}, view: 'detailed', unseenQuotes: {}, byTab: {},
|
||||
selected: null, tab: 'summary', listHidden: false, folded: {}, scope: null, repositories: [], query: '', directOnly: false, conversations: {}, view: 'detailed', unseenQuotes: {}, byTab: {},
|
||||
}),
|
||||
actions: reviewActions,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/** Copy of the Plugins form that the row pages of the Forge bundle share. */
|
||||
import type { SettingsFormLabels } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ForgePanelKey, NS } from './locales.ts'
|
||||
|
||||
/**
|
||||
* Build the form copy of one row page.
|
||||
* @param t - forge panel copy.
|
||||
* @param unavailable - key of the text shown while the Host does not serve the row's form.
|
||||
* @returns the labels of the shared settings form.
|
||||
*/
|
||||
export function rowFormLabels(t: PropsLocale<typeof NS>['t'], unavailable: ForgePanelKey): SettingsFormLabels {
|
||||
return {
|
||||
unavailable: t(unavailable), readOnly: t('settings.readOnly'), saveFailed: t('settings.saveFailed'),
|
||||
save: t('settings.save'), saving: t('settings.saving'),
|
||||
}
|
||||
}
|
||||
@@ -181,3 +181,23 @@ export function checkDuration(check: ChangeRequestCheck): number | undefined {
|
||||
const elapsed = Date.parse(check.completedAt) - Date.parse(check.startedAt)
|
||||
return Number.isFinite(elapsed) && elapsed >= 0 ? elapsed : undefined
|
||||
}
|
||||
|
||||
/** What stands between an open change request and its merge, in the order a reader resolves them. */
|
||||
const BLOCKERS: readonly { readonly key: ForgePanelKey; readonly applies: (snapshot: ChangeRequestSnapshot) => boolean }[] = [
|
||||
{ key: 'change.blocked.conflict', applies: snapshot => snapshot.mergeability === 'conflicting' },
|
||||
{ key: 'change.blocked.changesRequested', applies: snapshot => snapshot.reviewDecision === 'changes-requested' },
|
||||
{ key: 'change.blocked.reviewRequired', applies: snapshot => snapshot.reviewDecision === 'review-required' },
|
||||
{ key: 'change.blocked.checksFailed', applies: snapshot => snapshot.checksRollup === 'failure' },
|
||||
{ key: 'change.blocked.checksPending', applies: snapshot => snapshot.checksRollup === 'pending' },
|
||||
]
|
||||
|
||||
/**
|
||||
* Name why the code host would not merge an open change request now, from what its snapshot reports.
|
||||
* @param snapshot - the change request's latest snapshot.
|
||||
* @returns the dictionary key of each reason the snapshot shows, or of the general one when it shows none, as for a
|
||||
* user without the right to merge.
|
||||
*/
|
||||
export function mergeBlockers(snapshot: ChangeRequestSnapshot): readonly ForgePanelKey[] {
|
||||
const found = BLOCKERS.filter(blocker => blocker.applies(snapshot)).map(blocker => blocker.key)
|
||||
return found.length > 0 ? found : ['change.blocked.other']
|
||||
}
|
||||
@@ -6,11 +6,12 @@ import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type {} from '@deepseek-ai/dsh-api-remote-access'
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type {
|
||||
BranchUpdateMethod, ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot,
|
||||
ChangeRequestUpdate, ForgeActionFailure, ForgeCommitList,
|
||||
AutoMergeRequest, BranchUpdateMethod, ChangeRequestActivity, ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef,
|
||||
ChangeRequestReviewer,
|
||||
ChangeRequestSnapshot, ChangeRequestUpdate, ForgeActionFailure, ForgeCommitList,
|
||||
ForgeFailure,
|
||||
ForgeLineComment, ForgeRerunRequest, ForgeReviewChange, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult,
|
||||
ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeMethod,
|
||||
ForgeLineComment, ForgeReadiness, ForgeRerunRequest, ForgeReviewChange, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest,
|
||||
ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeMethod,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session'
|
||||
import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types'
|
||||
@@ -19,7 +20,7 @@ import type { Session, SessionEvent, SessionId, UserMessage } from '@deepseek-ai
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import type {} from '@deepseek-ai/dsh-session-projection-cache'
|
||||
import type {} from '@deepseek-ai/dsh-session-query'
|
||||
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
||||
import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
||||
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import { gitIn, hasBranch, inspectCheckout } from './git.ts'
|
||||
@@ -45,7 +46,7 @@ import { Reader, ViewerLists } from './viewer-lists.ts'
|
||||
import type { KeptPanel, PanelConfig } from './panel.ts'
|
||||
import type {
|
||||
Config, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeDiffFile,
|
||||
ForgeReviewChangeRequest, ForgeReviewCountFrame, ForgeReviewFrame,
|
||||
ForgeReviewChangeRequest, ForgeReviewCountFrame, ForgeReviewFrame, ForgeReviewRepository,
|
||||
ForgeExtensionState, ForgeLens, ForgeLensFrame, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope,
|
||||
ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeBases, ForgeWorktreeState,
|
||||
} from './types.ts'
|
||||
@@ -196,6 +197,7 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
sources: () => ctx.forge.viewerSources(),
|
||||
list: async (forge, query, signal) => await ctx.forge.listForViewer(forge, query, signal),
|
||||
count: async (forge, host, signal) => await ctx.forge.countForViewer(forge, host, signal),
|
||||
signIn: async (forge, host, signal) => (await ctx.forge.readiness({ forge, host }, signal)).signIn?.command ?? null,
|
||||
report: (error) => { ctx.logger.warn(`forge-panel: reading a review list failed: ${String(error)}`) },
|
||||
}, {
|
||||
listIntervalMs: resolved.reviewListIntervalMs,
|
||||
@@ -287,15 +289,17 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
/**
|
||||
* Stream the review page's lists of the signed-in user's open change requests on every host a provider lists them on:
|
||||
* the lists read so far first, then a frame after each read settles. Readers of one repository scope share one
|
||||
* reader, which reads every `reviewListIntervalMs` while some stream lasts and backs off after failed rounds up to
|
||||
* `reviewMaxBackoffMs`; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops.
|
||||
* @param repository - one repository to list in, or null for every repository the user can read.
|
||||
* reader, which reads each host every `reviewListIntervalMs` while some stream lasts and reads a host whose read failed
|
||||
* again later each time, up to `reviewMaxBackoffMs`, without delaying the other hosts; nothing is read while no stream
|
||||
* lasts. The stream ends when `signal` aborts or the Remote stops.
|
||||
* @param repository - one repository to list in, read on its host only, or null for every repository the user can
|
||||
* read on every host.
|
||||
* @param signal - ends the stream.
|
||||
* @returns frames, each complete.
|
||||
*/
|
||||
@Remote({ mode: 'stream' })
|
||||
async *reviewLists(
|
||||
repository: { readonly owner: string; readonly name: string } | null, signal: AbortSignal,
|
||||
repository: ForgeReviewRepository | null, signal: AbortSignal,
|
||||
): AsyncIterable<ForgeReviewFrame> {
|
||||
yield* this.viewerLists.lists(repository, signal)
|
||||
}
|
||||
@@ -323,6 +327,28 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
this.viewerLists.refresh()
|
||||
}
|
||||
|
||||
/**
|
||||
* Report whether a provider reaches one of its hosts with the Host's current credentials, for the host list on the
|
||||
* Plugins page of that provider's row. The read names no Session, so, like the review page reads, only callers that
|
||||
* may use the Host's code host credentials reach it.
|
||||
* @param forge - forge family of a registered provider, such as `gitlab`.
|
||||
* @param host - host name as the provider's configuration lists it.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the provider's readiness for the host; `unavailable` with the reason when no provider serves the family,
|
||||
* the probe fails, or it runs past `readinessTimeoutMs`.
|
||||
*/
|
||||
@Remote
|
||||
async hostReadiness(forge: string, host: string, signal: AbortSignal): Promise<ForgeReadiness> {
|
||||
signal.throwIfAborted()
|
||||
try {
|
||||
using timeout = deadline(signal, this.config.readinessTimeoutMs, 'FORGE_PANEL_READINESS_TIMEOUT')
|
||||
return await this.home.forge.readiness({ forge, host: host.toLowerCase() }, timeout.signal)
|
||||
} catch (error) {
|
||||
signal.throwIfAborted()
|
||||
return { state: 'unavailable', message: messageOf(error), signIn: null }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll one change request the review page shows at once; its stream reports the result.
|
||||
* @param url - web URL of the change request.
|
||||
@@ -391,6 +417,41 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the activity of a change request for the review page: its comments, submitted reviews, commits, and changes
|
||||
* of state.
|
||||
* @param url - web URL of the change request.
|
||||
* @param signal - request cancellation.
|
||||
* @returns the activity, or null when the change request's provider reads none.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/activity-failed` with the
|
||||
* host's reason when the host does not provide it.
|
||||
*/
|
||||
@Remote
|
||||
async reviewActivity(url: string, signal: AbortSignal): Promise<ChangeRequestActivity | null> {
|
||||
signal.throwIfAborted()
|
||||
const result = await this.home.forge.readActivity(this.served(url).ref, signal)
|
||||
if (!('code' in result)) return result
|
||||
if (result.code === 'unsupported') return null
|
||||
throw new RemoteError('forgePanel/activity-failed', result.message, {})
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a comment to the conversation of a change request the review page shows.
|
||||
* @param url - web URL of the change request.
|
||||
* @param body - Markdown source of the comment.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` when `body` is
|
||||
* blank, or with the host's reason; `forgePanel/action-unknown` when the host's answer did not confirm the comment.
|
||||
*/
|
||||
@Remote
|
||||
async reviewComment(url: string, body: string, signal: AbortSignal): Promise<void> {
|
||||
signal.throwIfAborted()
|
||||
const { ref } = this.served(url)
|
||||
if (body.trim() === '') throw new RemoteError('forgePanel/action-failed', 'The comment is empty', {})
|
||||
const failure = await this.home.forge.addComment(ref, body, signal)
|
||||
if (failure !== undefined) throw actionError(failure)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read every check of a change request the review page shows.
|
||||
* @param url - web URL of the change request.
|
||||
@@ -560,6 +621,22 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
if (failure !== undefined) throw actionError(failure)
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn the code host's automatic merge of a change request the review page shows on, while its head is still the
|
||||
* request's `headSha`, or off.
|
||||
* @param url - web URL of the change request.
|
||||
* @param request - on with the merge method and the head commit the user confirmed, or off.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`,
|
||||
* `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason.
|
||||
*/
|
||||
@Remote
|
||||
async reviewSetAutoMerge(url: string, request: AutoMergeRequest, signal: AbortSignal): Promise<void> {
|
||||
signal.throwIfAborted()
|
||||
const failure = await this.home.forge.setAutoMerge(this.served(url).ref, request, signal)
|
||||
if (failure !== undefined) throw actionError(failure)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rerun the failed checks of a change request the review page shows.
|
||||
* @param url - web URL of the change request.
|
||||
@@ -1121,6 +1198,25 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
if (failure !== undefined) throw actionError(failure)
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn the code host's automatic merge of a change request of a Session on, while its head is still the request's
|
||||
* `headSha`, or off; the change request is polled again once the host answers.
|
||||
* @param session - Session the change request is bound to.
|
||||
* @param url - binding URL of the change request.
|
||||
* @param request - on with the merge method and the head commit the user confirmed, or off.
|
||||
* @param signal - request cancellation.
|
||||
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
|
||||
* `forgePanel/stale-head` when the head moved past the request's `headSha`; `forgePanel/action-failed` with the
|
||||
* host's reason when the host refuses otherwise, cannot be reached, or sets no automatic merge;
|
||||
* `forgePanel/action-unknown` when the host's answer did not confirm the change.
|
||||
*/
|
||||
@Remote
|
||||
async setAutoMerge(session: Session, url: string, request: AutoMergeRequest, signal: AbortSignal): Promise<void> {
|
||||
signal.throwIfAborted()
|
||||
const failure = await this.home.forge.setAutoMerge(this.bound(session, url).ref, request, signal)
|
||||
if (failure !== undefined) throw actionError(failure)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rerun the failed checks of a change request of a Session while its head is still the commit whose checks the user
|
||||
* saw; the change request is polled again once the host answers.
|
||||
|
||||
@@ -219,6 +219,16 @@ export interface ForgeReviewList {
|
||||
readonly failure: ForgeFailure | null
|
||||
}
|
||||
|
||||
/** One repository on one host, which the review page's lists can be read in. */
|
||||
export interface ForgeReviewRepository {
|
||||
/** Host name of the provider that lists the repository, compared without case. */
|
||||
readonly host: string
|
||||
/** Owner or namespace; nested groups of a GitLab project stay in it. */
|
||||
readonly owner: string
|
||||
/** Repository name. */
|
||||
readonly name: string
|
||||
}
|
||||
|
||||
/** The review page's lists on one host of one provider. */
|
||||
export interface ForgeReviewHost {
|
||||
/** Forge family of the provider. */
|
||||
@@ -227,6 +237,11 @@ export interface ForgeReviewHost {
|
||||
readonly host: string
|
||||
/** Login of the signed-in user the latest successful read named, or null before one. */
|
||||
readonly viewer: string | null
|
||||
/**
|
||||
* The command that signs the provider's CLI in to the host, while the latest read failed for lack of sign-in and the
|
||||
* provider names one; null otherwise.
|
||||
*/
|
||||
readonly signIn: string | null
|
||||
/** Each list the provider offers on the host; a list it does not offer is absent. */
|
||||
readonly lists: Partial<Readonly<Record<ForgeViewerFilter, ForgeReviewList>>>
|
||||
}
|
||||
@@ -648,7 +663,7 @@ export interface Config {
|
||||
reviewListIntervalMs?: number
|
||||
/** Milliseconds between two reads of the review page's navigation count while it is shown. */
|
||||
reviewCountIntervalMs?: number
|
||||
/** Largest delay in milliseconds between two reads of the review page's lists or count after consecutive failures. */
|
||||
/** Largest delay in milliseconds between two reads of the review page's lists or count on one host after its consecutive failed reads. */
|
||||
reviewMaxBackoffMs?: number
|
||||
/** Most change requests one review page list shows, capped by each provider's own limit. */
|
||||
reviewPageSize?: number
|
||||
@@ -719,6 +734,8 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
'forgePanel/reviewers-failed': Record<string, never>
|
||||
/** The code host did not provide a change request's description; the message says why. */
|
||||
'forgePanel/description-failed': Record<string, never>
|
||||
/** The code host did not provide a change request's activity; the message says why. */
|
||||
'forgePanel/activity-failed': Record<string, never>
|
||||
/** The code host's provider cannot read review threads, so the changes view shows none. */
|
||||
'forgePanel/review-unsupported': Record<string, never>
|
||||
/** The code host did not provide the change request's review threads, or its status has not been read yet; the message says why. */
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
/**
|
||||
* The review page's lists of the signed-in user's change requests and its navigation count. Lists are read only while
|
||||
* some reader streams them and the count only while some reader streams it; neither joins the forge's status polling.
|
||||
* Readers of one repository scope share one poller, which reads every list of every host each round, hosts in parallel
|
||||
* and each host's lists one after another, so one host has at most one read in flight. A round with a failure delays
|
||||
* the next round as status polling does after consecutive failures.
|
||||
* Readers of one repository scope share one poller, which reads every list of every due host each round, hosts in
|
||||
* parallel and each host's lists one after another, so one host has at most one read in flight. A host whose read
|
||||
* failed is read again later each time, as status polling waits after consecutive failures, while the other hosts
|
||||
* keep their cadence. A scope that names a repository reads only the host the repository is on.
|
||||
*/
|
||||
|
||||
import type {
|
||||
ForgeFailure, ForgeViewerFilter, ForgeViewerList, ForgeViewerQuery, ForgeViewerSource,
|
||||
} from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { ForgeReviewCountFrame, ForgeReviewFrame, ForgeReviewHost, ForgeReviewList } from './types.ts'
|
||||
import type { ForgeReviewCountFrame, ForgeReviewFrame, ForgeReviewHost, ForgeReviewList, ForgeReviewRepository } from './types.ts'
|
||||
|
||||
/** The lists in the order the page shows them. */
|
||||
const FILTERS: readonly ForgeViewerFilter[] = ['review-requested', 'authored', 'involved']
|
||||
@@ -22,6 +23,8 @@ export interface ViewerListSources {
|
||||
readonly list: (forge: string, query: ForgeViewerQuery, signal: AbortSignal) => Promise<ForgeViewerList | ForgeFailure>
|
||||
/** Read the size of every list on one host. */
|
||||
readonly count: (forge: string, host: string, signal: AbortSignal) => Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>
|
||||
/** The command that signs the provider's CLI in to a host, or null when the provider names none. */
|
||||
readonly signIn: (forge: string, host: string, signal: AbortSignal) => Promise<string | null>
|
||||
/** Report a read that rejected instead of resolving to a failure. */
|
||||
readonly report: (error: unknown) => void
|
||||
}
|
||||
@@ -32,14 +35,14 @@ export interface ViewerListTiming {
|
||||
readonly listIntervalMs: number
|
||||
/** Milliseconds between two rounds of the count poller. */
|
||||
readonly countIntervalMs: number
|
||||
/** Largest delay in milliseconds after consecutive failed rounds. */
|
||||
/** Largest delay in milliseconds before a host is read again after consecutive failed reads. */
|
||||
readonly maxBackoffMs: number
|
||||
/** Most change requests one list read asks for, before each provider's own limit. */
|
||||
readonly pageSize: number
|
||||
}
|
||||
|
||||
/** One repository to list in, or null for every repository. */
|
||||
export type ViewerScope = { readonly owner: string; readonly name: string } | null
|
||||
/** One repository on one host to list in, or null for every repository of every host. */
|
||||
export type ViewerScope = ForgeReviewRepository | null
|
||||
|
||||
/** A stream's latest undelivered frame; a newer frame replaces one the reader has not taken. */
|
||||
export class Reader<T> {
|
||||
@@ -92,15 +95,15 @@ export class Reader<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/** A loop that runs one round, waits, and repeats until stopped; a refresh ends the wait early. */
|
||||
/** A loop that runs one round, waits as long as the round asks, and repeats until stopped; a refresh ends the wait early. */
|
||||
class Poller {
|
||||
private readonly aborter = new AbortController()
|
||||
private wake: (() => void) | undefined
|
||||
private refreshing = false
|
||||
private failures = 0
|
||||
readonly done: Promise<void>
|
||||
|
||||
constructor(private readonly round: (signal: AbortSignal) => Promise<boolean>, private readonly delay: (failures: number) => number) {
|
||||
/** @param round - runs one round, `forced` after a refresh, and resolves to the milliseconds to wait before the next. */
|
||||
constructor(private readonly round: (signal: AbortSignal, forced: boolean) => Promise<number>) {
|
||||
this.done = this.loop()
|
||||
}
|
||||
|
||||
@@ -123,12 +126,12 @@ class Poller {
|
||||
private async loop(): Promise<void> {
|
||||
const { signal } = this.aborter
|
||||
while (!signal.aborted) {
|
||||
const forced = this.refreshing
|
||||
this.refreshing = false
|
||||
const succeeded = await this.round(signal)
|
||||
this.failures = succeeded ? 0 : this.failures + 1
|
||||
const wait = await this.round(signal, forced)
|
||||
if (this.skipsWait(signal)) continue
|
||||
await new Promise<void>((resolve) => {
|
||||
const timer = setTimeout(resolve, this.delay(this.failures))
|
||||
const timer = setTimeout(resolve, wait)
|
||||
this.wake = () => { clearTimeout(timer); resolve() }
|
||||
})
|
||||
this.wake = undefined
|
||||
@@ -136,28 +139,72 @@ class Poller {
|
||||
}
|
||||
}
|
||||
|
||||
/** The readers of one repository scope, the poller they share, and what it read. */
|
||||
/**
|
||||
* When each host of one poller is read next. A host is due at once until its first read settles; after a read it is
|
||||
* due one delay after the start of the round that read it, and the delay grows with its consecutive failed reads.
|
||||
*/
|
||||
class HostSchedule {
|
||||
private readonly hosts = new Map<string, { readonly failures: number; readonly dueAt: number }>()
|
||||
|
||||
/** @param delay - milliseconds between two reads of a host after the given number of consecutive failed reads. */
|
||||
constructor(private readonly delay: (failures: number) => number) {}
|
||||
|
||||
/** Whether a round that starts at `now` reads the host. */
|
||||
due(key: string, now: number): boolean {
|
||||
return (this.hosts.get(key)?.dueAt ?? 0) <= now
|
||||
}
|
||||
|
||||
/** Record whether the read of the host succeeded in the round that started at `started`. */
|
||||
settle(key: string, started: number, succeeded: boolean): void {
|
||||
const failures = succeeded ? 0 : (this.hosts.get(key)?.failures ?? 0) + 1
|
||||
this.hosts.set(key, { failures, dueAt: started + this.delay(failures) })
|
||||
}
|
||||
|
||||
/** Milliseconds from `now` until the first of `keys` is due, or the delay between two successful reads without any key. */
|
||||
wait(keys: readonly string[], now: number): number {
|
||||
if (keys.length === 0) return this.delay(0)
|
||||
return Math.max(0, Math.min(...keys.map(key => this.hosts.get(key)?.dueAt ?? 0)) - now)
|
||||
}
|
||||
}
|
||||
|
||||
/** One host a scope reads, with the provider that lists on it. */
|
||||
interface Target {
|
||||
readonly source: ForgeViewerSource
|
||||
readonly host: string
|
||||
readonly key: string
|
||||
}
|
||||
|
||||
/** The readers of one repository scope, the poller they share, when each host is read next, and what was read. */
|
||||
class Scope {
|
||||
readonly readers = new Set<Reader<ForgeReviewFrame>>()
|
||||
readonly hosts = new Map<string, ForgeReviewHost>()
|
||||
readonly schedule: HostSchedule
|
||||
reading = false
|
||||
readonly poller: Poller
|
||||
|
||||
/**
|
||||
* @param round - reads every list of the scope once; resolves to whether every read succeeded.
|
||||
* @param delay - milliseconds before the next round after the given number of consecutive failed rounds.
|
||||
* @param repository - the repository the scope lists in, or null for every repository of every host.
|
||||
* @param round - reads the scope's due hosts once, every host when `forced`; resolves to the wait before the next round.
|
||||
* @param delay - milliseconds between two reads of a host after the given number of consecutive failed reads.
|
||||
*/
|
||||
constructor(round: (scope: Scope, signal: AbortSignal) => Promise<boolean>, delay: (failures: number) => number) {
|
||||
this.poller = new Poller(signal => round(this, signal), delay)
|
||||
constructor(
|
||||
readonly repository: ViewerScope,
|
||||
round: (scope: Scope, signal: AbortSignal, forced: boolean) => Promise<number>,
|
||||
delay: (failures: number) => number,
|
||||
) {
|
||||
this.schedule = new HostSchedule(delay)
|
||||
this.poller = new Poller((signal, forced) => round(this, signal, forced))
|
||||
}
|
||||
|
||||
/** The hosts the scope reads, in registration and configuration order: every host, or the one its repository is on. */
|
||||
targets(order: readonly ForgeViewerSource[]): Target[] {
|
||||
const only = this.repository?.host.toLowerCase()
|
||||
return order.flatMap(source => source.hosts.filter(host => only === undefined || host === only)
|
||||
.map(host => ({ source, host, key: hostKey(source.forge, host) })))
|
||||
}
|
||||
|
||||
frame(order: readonly ForgeViewerSource[]): ForgeReviewFrame {
|
||||
const hosts: ForgeReviewHost[] = []
|
||||
for (const source of order) {
|
||||
for (const host of source.hosts) {
|
||||
hosts.push(this.hosts.get(hostKey(source.forge, host)) ?? emptyHost(source, host))
|
||||
}
|
||||
}
|
||||
const hosts = this.targets(order).map(({ source, host, key }) => this.hosts.get(key) ?? emptyHost(source, host))
|
||||
return { hosts, reading: this.reading }
|
||||
}
|
||||
}
|
||||
@@ -167,6 +214,7 @@ export class ViewerLists {
|
||||
private readonly scopes = new Map<string, Scope>()
|
||||
private readonly countReaders = new Set<Reader<ForgeReviewCountFrame>>()
|
||||
private readonly counts = new Map<string, number>()
|
||||
private readonly countSchedule = new HostSchedule(failures => this.delay(this.timing.countIntervalMs, failures))
|
||||
private countPoller: Poller | undefined
|
||||
private disposed = false
|
||||
|
||||
@@ -179,18 +227,19 @@ export class ViewerLists {
|
||||
/**
|
||||
* Stream the lists of one repository scope: the lists read so far first, then a frame after each read settles.
|
||||
* The stream ends when `signal` aborts or the hub is disposed; the last stream of a scope stops its reads.
|
||||
* @param scope - one repository, or null for every repository.
|
||||
* @param scope - one repository on its host, or null for every repository of every host.
|
||||
* @param signal - ends the stream.
|
||||
* @returns frames, each complete.
|
||||
*/
|
||||
async *lists(scope: ViewerScope, signal: AbortSignal): AsyncIterable<ForgeReviewFrame> {
|
||||
signal.throwIfAborted()
|
||||
if (this.disposed) return
|
||||
const key = scope === null ? '' : `${scope.owner}/${scope.name}`.toLowerCase()
|
||||
const key = scope === null ? '' : `${scope.host}\n${scope.owner}/${scope.name}`.toLowerCase()
|
||||
let state = this.scopes.get(key)
|
||||
if (state === undefined) {
|
||||
state = new Scope(
|
||||
(created, round) => this.readScope(created, scope, round), failures => this.delay(this.timing.listIntervalMs, failures),
|
||||
scope, (created, round, forced) => this.readScope(created, round, forced),
|
||||
failures => this.delay(this.timing.listIntervalMs, failures),
|
||||
)
|
||||
this.scopes.set(key, state)
|
||||
}
|
||||
@@ -221,7 +270,7 @@ export class ViewerLists {
|
||||
const reader = new Reader<ForgeReviewCountFrame>(signal)
|
||||
this.countReaders.add(reader)
|
||||
reader.push(this.countFrame())
|
||||
this.countPoller ??= new Poller(round => this.readCounts(round), failures => this.delay(this.timing.countIntervalMs, failures))
|
||||
this.countPoller ??= new Poller((round, forced) => this.readCounts(round, forced))
|
||||
try {
|
||||
yield* reader.frames()
|
||||
} finally {
|
||||
@@ -271,45 +320,72 @@ export class ViewerLists {
|
||||
await Promise.all(pollers.map(async (poller) =>{ await poller.stop() }))
|
||||
}
|
||||
|
||||
/** Read every list of every host once; resolves to whether every read succeeded. */
|
||||
private async readScope(scope: Scope, repository: ViewerScope, signal: AbortSignal): Promise<boolean> {
|
||||
const order = this.sources.sources()
|
||||
/**
|
||||
* Read every list of the scope's due hosts once, of every host when `forced`.
|
||||
* @returns milliseconds until the scope's next host is due.
|
||||
*/
|
||||
private async readScope(scope: Scope, signal: AbortSignal, forced: boolean): Promise<number> {
|
||||
const started = Date.now()
|
||||
const targets = scope.targets(this.sources.sources())
|
||||
const repository = scope.repository === null ? null : { owner: scope.repository.owner, name: scope.repository.name }
|
||||
scope.reading = true
|
||||
this.publish(scope)
|
||||
const results = await Promise.all(order.flatMap(source => source.hosts.map(async (host) => {
|
||||
await Promise.all(targets.filter(target => forced || scope.schedule.due(target.key, started)).map(async ({ source, host, key }) => {
|
||||
let succeeded = true
|
||||
let hostFailure: ForgeFailure | undefined
|
||||
for (const filter of FILTERS) {
|
||||
if (!source.filters.has(filter)) continue
|
||||
const query: ForgeViewerQuery = { host, filter, repository, limit: Math.min(source.maxItems, this.timing.pageSize) }
|
||||
const result = hostFailure ?? await this.read(() => this.sources.list(source.forge, query, signal), signal)
|
||||
if (signal.aborted) return false
|
||||
if (signal.aborted) return
|
||||
if ('code' in result && HOST_FAILURES.has(result.code)) hostFailure = result
|
||||
succeeded = this.settle(scope, source, host, filter, result) && succeeded
|
||||
if (repository === null && !('code' in result) && filter === 'review-requested') {
|
||||
this.counts.set(hostKey(source.forge, host), result.total)
|
||||
this.counts.set(key, result.total)
|
||||
this.publishCount()
|
||||
}
|
||||
this.publish(scope)
|
||||
}
|
||||
return succeeded
|
||||
})))
|
||||
const signIn = hostFailure?.code === 'unauthenticated' ? await this.signInOf(scope, source, host, signal) : null
|
||||
if (signal.aborted) return
|
||||
const current = scope.hosts.get(key) ?? emptyHost(source, host)
|
||||
if (current.signIn !== signIn) {
|
||||
scope.hosts.set(key, { ...current, signIn })
|
||||
this.publish(scope)
|
||||
}
|
||||
scope.schedule.settle(key, started, succeeded)
|
||||
}))
|
||||
scope.reading = false
|
||||
if (!signal.aborted) this.publish(scope)
|
||||
return results.every(Boolean)
|
||||
return scope.schedule.wait(targets.map(target => target.key), Date.now())
|
||||
}
|
||||
|
||||
/** Read the count of every host once; resolves to whether every read succeeded. */
|
||||
private async readCounts(signal: AbortSignal): Promise<boolean> {
|
||||
const results = await Promise.all(this.sources.sources().flatMap(source => source.hosts.map(async (host) => {
|
||||
if (!source.filters.has('review-requested')) return true
|
||||
/** The sign-in command the scope already holds for the host, else the one its provider names now, else null. */
|
||||
private async signInOf(scope: Scope, source: ForgeViewerSource, host: string, signal: AbortSignal): Promise<string | null> {
|
||||
const known = scope.hosts.get(hostKey(source.forge, host))?.signIn ?? null
|
||||
if (known !== null) return known
|
||||
const command = await this.read<string | null>(() => this.sources.signIn(source.forge, host, signal), signal)
|
||||
return typeof command === 'string' ? command : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the count of every due host once, of every host when `forced`.
|
||||
* @returns milliseconds until the next host is due.
|
||||
*/
|
||||
private async readCounts(signal: AbortSignal, forced: boolean): Promise<number> {
|
||||
const started = Date.now()
|
||||
const targets = this.sources.sources().filter(source => source.filters.has('review-requested'))
|
||||
.flatMap(source => source.hosts.map(host => ({ source, host, key: hostKey(source.forge, host) })))
|
||||
await Promise.all(targets.filter(target => forced || this.countSchedule.due(target.key, started)).map(async ({ source, host, key }) => {
|
||||
const result = await this.read(() => this.sources.count(source.forge, host, signal), signal)
|
||||
if (signal.aborted || 'code' in result) return false
|
||||
this.counts.set(hostKey(source.forge, host), result.get('review-requested') ?? 0)
|
||||
this.publishCount()
|
||||
return true
|
||||
})))
|
||||
return results.every(Boolean)
|
||||
if (signal.aborted) return
|
||||
if (!('code' in result)) {
|
||||
this.counts.set(key, result.get('review-requested') ?? 0)
|
||||
this.publishCount()
|
||||
}
|
||||
this.countSchedule.settle(key, started, !('code' in result))
|
||||
}))
|
||||
return this.countSchedule.wait(targets.map(target => target.key), Date.now())
|
||||
}
|
||||
|
||||
/** Run one read, turning a rejection into an `unavailable` failure and reporting it unless `signal` aborted. */
|
||||
@@ -371,5 +447,5 @@ function hostKey(forge: string, host: string): string {
|
||||
function emptyHost(source: ForgeViewerSource, host: string): ForgeReviewHost {
|
||||
const lists: Partial<Record<ForgeViewerFilter, ForgeReviewList>> = {}
|
||||
for (const filter of FILTERS) if (source.filters.has(filter)) lists[filter] = EMPTY_LIST
|
||||
return { forge: source.forge, host, viewer: null, lists }
|
||||
return { forge: source.forge, host, viewer: null, signIn: null, lists }
|
||||
}
|
||||
@@ -19,6 +19,8 @@ import './fonts-dom.client.ts'
|
||||
afterEach(cleanup)
|
||||
|
||||
const t = makeTranslate(en)
|
||||
/** The opening action of a change request whose provider names itself GitHub. */
|
||||
const OPEN_ON_GITHUB = t('change.viewOn', { forge: 'GitHub' })
|
||||
const NOW = Date.parse('2026-10-09T12:00:00Z')
|
||||
/** Minus sign (U+2212) the diff size puts before the deleted line count. */
|
||||
const MINUS = '−'
|
||||
@@ -180,7 +182,7 @@ describe('collapsed ChangeRequestCard', () => {
|
||||
expect(within(b.item).queryByText(en['change.row.changes'])).toBeNull()
|
||||
expect(within(b.item).queryByText('+12')).toBeNull()
|
||||
expect(b.menuButton().getAttribute('aria-label')).toBe('Actions for #7')
|
||||
b.choose(en['change.view'])
|
||||
b.choose(OPEN_ON_GITHUB)
|
||||
b.choose(en['change.copy'])
|
||||
b.choose(en['change.remove'])
|
||||
expect(b.openLink).toHaveBeenCalledWith('https://github.com/octo/demo/pull/7')
|
||||
@@ -347,7 +349,7 @@ describe('expanded ChangeRequestCard', () => {
|
||||
expect(within(b.item).getByText('+12,345')).toBeTruthy()
|
||||
expect(within(b.item).getByText(`${MINUS}3`)).toBeTruthy()
|
||||
|
||||
b.choose(en['change.view'])
|
||||
b.choose(OPEN_ON_GITHUB)
|
||||
b.choose(en['change.copy'])
|
||||
b.choose(en['change.remove'])
|
||||
expect(b.openLink).toHaveBeenCalledWith('https://github.com/octo/demo/pull/7#web')
|
||||
@@ -572,7 +574,7 @@ describe('expanded ChangeRequestCard', () => {
|
||||
expect(b.status.textContent).toBe('#1')
|
||||
expect(within(b.item).queryByText(en['change.row.checks'])).toBeNull()
|
||||
expect(within(b.item).queryByText('+12')).toBeNull()
|
||||
expect(b.menuItems()).toEqual([en['change.view'], en['change.copy'], en['change.remove']])
|
||||
expect(b.menuItems()).toEqual([OPEN_ON_GITHUB, en['change.copy'], en['change.remove']])
|
||||
b.choose(en['change.copy'])
|
||||
expect(b.copyLink).toHaveBeenCalledWith('https://github.com/octo/demo/pull/1')
|
||||
})
|
||||
@@ -585,10 +587,23 @@ describe('expanded ChangeRequestCard', () => {
|
||||
expect(b.menuButton().getAttribute('aria-label')).toBe('Actions for Change 3')
|
||||
b.choose(en['change.remove'])
|
||||
expect(b.remove).toHaveBeenCalledOnce()
|
||||
// Without a provider the action names the browser, and carries the leaving arrow.
|
||||
b.choose(en['change.view'])
|
||||
expect(b.openLink).toHaveBeenCalledWith('https://example.test/review/latest#web')
|
||||
})
|
||||
|
||||
it('marks the opening action with the provider\'s mark, and with the arrow for a change request no provider serves', () => {
|
||||
const mark = 'svg[viewBox="-2 -2 28 28"]'
|
||||
const b = card(entry(1, snapshot(1)))
|
||||
fireEvent.click(b.menuButton())
|
||||
expect(screen.getByRole('menuitem', { name: OPEN_ON_GITHUB }).querySelector(mark)).not.toBeNull()
|
||||
cleanup()
|
||||
const other = card(unserved('https://example.test/review/latest'))
|
||||
fireEvent.click(other.menuButton())
|
||||
const open = screen.getByRole('menuitem', { name: en['change.view'] })
|
||||
expect([open.querySelector(mark), open.querySelector('svg') === null]).toEqual([null, false])
|
||||
})
|
||||
|
||||
it('closes the actions menu on Escape', () => {
|
||||
const b = card(entry(1, snapshot(1)))
|
||||
fireEvent.click(b.menuButton())
|
||||
@@ -600,7 +615,7 @@ describe('expanded ChangeRequestCard', () => {
|
||||
|
||||
it('omits removal on a surface without a Session binding', () => {
|
||||
const b = card(entry(1, snapshot(1)), { expanded: true, actions: { remove: undefined } })
|
||||
expect(b.menuItems()).toEqual([en['change.view'], en['change.copy']])
|
||||
expect(b.menuItems()).toEqual([OPEN_ON_GITHUB, en['change.copy']])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -738,6 +753,75 @@ describe('ChangeRequestCard actions', () => {
|
||||
expect(within(b.item).queryByRole('button', { name: en['change.merge'] })).toBeNull()
|
||||
})
|
||||
|
||||
it('offers the automatic merge of a change request the host would not merge yet, with the outlined button and the same menu', async () => {
|
||||
const pending = deferred()
|
||||
const autoMerge = vi.fn<NonNullable<ChangeRequestActions['autoMerge']>>(() => pending.promise)
|
||||
const off = { enabled: false, method: null, enabledBy: null, canEnable: true, canDisable: false }
|
||||
const value = entry(7, snapshot(7, { mergeReady: false, mergeMethods: ['squash', 'merge'], headSha: head, autoMerge: off }))
|
||||
const b = card(value, { expanded: true, actions: { autoMerge } })
|
||||
expect(within(b.item).queryByRole('button', { name: en['change.merge'] })).toBeNull()
|
||||
const button = within(b.item).getByRole('button', { name: en['change.autoMerge'] })
|
||||
expect([button.classList.contains(css.autoMergeAction ?? ''), button.classList.contains(css.mergeAction ?? '')]).toEqual([true, false])
|
||||
fireEvent.click(button)
|
||||
expect(within(screen.getByRole('menu')).getByText('Merge #7 into main once its requirements are met')).toBeTruthy()
|
||||
expect(mergeRows()).toEqual([
|
||||
'Squash and mergeCombine every commit into one ✓', 'Create a merge commitKeep every commit and add a merge commit', 'Enable auto-merge',
|
||||
])
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: 'Enable auto-merge' }))
|
||||
expect(autoMerge).toHaveBeenCalledWith(value, { enabled: true, method: 'squash', headSha: head })
|
||||
expect(button.hasAttribute('disabled')).toBe(true)
|
||||
await act(async () => {
|
||||
pending.resolve()
|
||||
await pending.promise
|
||||
})
|
||||
expect(button.hasAttribute('disabled')).toBe(false)
|
||||
})
|
||||
|
||||
it('shows an automatic merge that is on, and cancels it where the user may', async () => {
|
||||
const autoMerge = vi.fn<NonNullable<ChangeRequestActions['autoMerge']>>(async () => {})
|
||||
const on = { enabled: true, method: 'merge' as const, enabledBy: 'mona', canEnable: false, canDisable: true }
|
||||
const value = entry(7, snapshot(7, { mergeReady: false, autoMerge: on }))
|
||||
const b = card(value, { expanded: true, actions: { autoMerge } })
|
||||
const button = within(b.item).getByRole('button', { name: en['change.autoMergeOn'] })
|
||||
expect(button.getAttribute('data-forge-auto-merge')).toBe('on')
|
||||
fireEvent.click(button)
|
||||
expect(within(screen.getByRole('menu')).getByText('Method: Create a merge commit · Enabled by mona')).toBeTruthy()
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: 'Cancel auto-merge' }))
|
||||
expect(autoMerge).toHaveBeenCalledWith(value, { enabled: false })
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
await act(async () => { await Promise.resolve() })
|
||||
cleanup()
|
||||
|
||||
// A surface that cannot change it, and a user who may not, see the state without the cancellation.
|
||||
for (const [actions, state] of [[{}, on], [{ autoMerge }, { ...on, canDisable: false }]] as const) {
|
||||
const shown = card(entry(7, snapshot(7, { mergeReady: false, autoMerge: state })), { expanded: true, actions })
|
||||
fireEvent.click(within(shown.item).getByRole('button', { name: en['change.autoMergeOn'] }))
|
||||
expect(screen.queryByRole('menuitem', { name: 'Cancel auto-merge' })).toBeNull()
|
||||
fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' })
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('merges now instead of showing the automatic merge once the host would merge', () => {
|
||||
const on = { enabled: true, method: 'merge' as const, enabledBy: null, canEnable: false, canDisable: true }
|
||||
const actions = { merge: vi.fn(async () => {}), autoMerge: vi.fn(async () => {}) }
|
||||
const b = card(entry(7, snapshot(7, { mergeReady: true, autoMerge: on })), { expanded: true, actions })
|
||||
expect(within(b.item).getByRole('button', { name: en['change.merge'] })).toBeTruthy()
|
||||
expect(within(b.item).queryByRole('button', { name: en['change.autoMergeOn'] })).toBeNull()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['the surface cannot turn it on', {}, { mergeMethods: ['merge'] as const }],
|
||||
['the repository allows no merge method', { autoMerge: vi.fn(async () => {}) }, { mergeMethods: [] as const }],
|
||||
])('offers no automatic merge when %s, and no merge it cannot run', (_label, actions, overrides) => {
|
||||
const off = { enabled: false, method: null, enabledBy: null, canEnable: true, canDisable: false }
|
||||
const b = card(entry(7, snapshot(7, { mergeReady: false, autoMerge: off, ...overrides })), { expanded: true, actions })
|
||||
expect(within(b.item).queryByRole('button', { name: en['change.autoMerge'] })).toBeNull()
|
||||
// The card names no merge the host would refuse; the review page does.
|
||||
expect(within(b.item).queryByRole('button', { name: en['change.merge'] })).toBeNull()
|
||||
})
|
||||
|
||||
it('offers neither action on a surface without a Session binding', () => {
|
||||
const actions = { markReady: undefined, merge: undefined }
|
||||
for (const value of [entry(7, snapshot(7, { draft: true })), entry(8, snapshot(8, { mergeReady: true }))]) {
|
||||
|
||||
@@ -41,6 +41,8 @@ import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
const english = makeTranslate(en)
|
||||
/** Copy of a view of a GitHub pull request, which names the code host and the noun. */
|
||||
const t = (key: string, params?: Record<string, unknown>): string => english(key, { forge: 'GitHub', noun: 'PR', ...params })
|
||||
/** The actions that open GitHub, as a view of a change request whose provider names itself GitHub words them. */
|
||||
const ON_GITHUB = { open: t('change.viewOn'), view: t('diff.viewInBrowser'), file: t('diff.openFileInBrowser') }
|
||||
const SESSION = brandString<SessionId>('s1')
|
||||
const TAB = 'tab-changes' as TabId
|
||||
const URL7 = 'https://github.com/octo/demo/pull/7'
|
||||
@@ -1409,7 +1411,7 @@ describe('ChangesTab change requests', () => {
|
||||
expect(m.view.getByRole('img', { name: 'Change request state: Open' })).toBeTruthy()
|
||||
expect(m.view.getByText('Change 7')).toBeTruthy()
|
||||
expect(m.view.getByText('#7')).toBeTruthy()
|
||||
fireEvent.click(m.view.getByRole('button', { name: en['change.view'] }))
|
||||
fireEvent.click(m.view.getByRole('button', { name: ON_GITHUB.open }))
|
||||
expect(m.faces.openLink).toHaveBeenLastCalledWith(URL7)
|
||||
await settle()
|
||||
|
||||
@@ -1434,17 +1436,17 @@ describe('ChangesTab change requests', () => {
|
||||
}
|
||||
expect(menu('docs/notes.txt')).toEqual([en['diff.copyPath']])
|
||||
expect(menu('docs/gone.txt')).toEqual([en['diff.copyPath']])
|
||||
expect(menu('src/app.ts')).toEqual([en['diff.copyPath'], en['diff.openFileInBrowser']])
|
||||
expect(menu('src/app.ts')).toEqual([en['diff.copyPath'], ON_GITHUB.file])
|
||||
fireEvent.click(within(m.section('src/app.ts')).getByRole('button', { name: 'More actions for app.ts' }))
|
||||
fireEvent.click(m.view.getByRole('menuitem', { name: en['diff.openFileInBrowser'] }))
|
||||
fireEvent.click(m.view.getByRole('menuitem', { name: ON_GITHUB.file }))
|
||||
expect(m.faces.openLink).toHaveBeenLastCalledWith(CHANGE.fileUrls['src/app.ts'])
|
||||
})
|
||||
|
||||
it('shows in place that the host did not provide the diff, offering its web page and a retry', async () => {
|
||||
const m = mount({ source, setup: (faces) => { faces.changeRequestDiff.mockResolvedValueOnce(REFUSED.hostRefused) } })
|
||||
await settle()
|
||||
expect(m.view.getByRole('status').textContent).toBe(`${en['diff.error']}${en.retry}${en['diff.viewInBrowser']}`)
|
||||
fireEvent.click(m.view.getByRole('button', { name: en['diff.viewInBrowser'] }))
|
||||
expect(m.view.getByRole('status').textContent).toBe(`${en['diff.error']}${en.retry}${ON_GITHUB.view}`)
|
||||
fireEvent.click(m.view.getByRole('button', { name: ON_GITHUB.view }))
|
||||
expect(m.faces.openLink).toHaveBeenLastCalledWith(URL7)
|
||||
fireEvent.click(m.view.getByRole('button', { name: en.retry }))
|
||||
await settle()
|
||||
@@ -1454,9 +1456,9 @@ describe('ChangesTab change requests', () => {
|
||||
it('says a diff over a size limit is too large to show and offers only its web page', async () => {
|
||||
const m = mount({ source, setup: (faces) => { faces.changeRequestDiff.mockResolvedValue(REFUSED.tooLarge) } })
|
||||
await settle()
|
||||
expect(m.view.getByRole('status').textContent).toBe(`${en['diff.tooLarge']}${en['diff.viewInBrowser']}`)
|
||||
expect(m.view.getByRole('status').textContent).toBe(`${en['diff.tooLarge']}${ON_GITHUB.view}`)
|
||||
expect(m.view.queryByRole('button', { name: en.retry })).toBeNull()
|
||||
fireEvent.click(m.view.getByRole('button', { name: en['diff.viewInBrowser'] }))
|
||||
fireEvent.click(m.view.getByRole('button', { name: ON_GITHUB.view }))
|
||||
expect(m.faces.openLink).toHaveBeenLastCalledWith(URL7)
|
||||
})
|
||||
|
||||
@@ -1551,7 +1553,7 @@ describe('ChangesTab change requests', () => {
|
||||
})
|
||||
await settle()
|
||||
expect(failed.faces.changeRequestDiff).toHaveBeenCalledOnce()
|
||||
expect(within(failed.view.container).getByRole('status').textContent).toBe(`${en['diff.error']}${en.retry}${en['diff.viewInBrowser']}`)
|
||||
expect(within(failed.view.container).getByRole('status').textContent).toBe(`${en['diff.error']}${en.retry}${ON_GITHUB.view}`)
|
||||
})
|
||||
|
||||
it('waits for the first status of a change request whose entry shows a snapshot kept from an earlier panel stream', async () => {
|
||||
@@ -1572,9 +1574,14 @@ describe('ChangesTab change requests', () => {
|
||||
expect(m.view.getByRole('img', { name: 'Change request state: Unknown' })).toBeTruthy()
|
||||
expect(m.view.getByText(URL7)).toBeTruthy()
|
||||
expect(m.view.getByText('#7')).toBeTruthy()
|
||||
fireEvent.click(m.view.getByRole('button', { name: en['change.view'] }))
|
||||
// Before the Session's state names the provider, the action names the host of the URL and carries the leaving arrow.
|
||||
const open = m.view.getByRole('button', { name: t('change.viewOn', { forge: 'github.com' }) })
|
||||
expect(open.querySelector('svg[viewBox="-2 -2 28 28"]')).toBeNull()
|
||||
fireEvent.click(open)
|
||||
expect(m.faces.openLink).toHaveBeenLastCalledWith(URL7)
|
||||
act(() => { m.panel.set({ state: ready({ changeRequests: [entry(7, null)] }), disconnected: false }) })
|
||||
// The provider's family picks the mark: GitHub's for a GitHub change request.
|
||||
expect(m.view.getByRole('button', { name: ON_GITHUB.open }).querySelector('svg[viewBox="-2 -2 28 28"]')).not.toBeNull()
|
||||
expect(m.view.getByText(URL7)).toBeTruthy()
|
||||
await settle()
|
||||
|
||||
|
||||
@@ -2058,6 +2058,32 @@ describe('forgePanel actions', () => {
|
||||
expect(opened.provider.actions).toEqual(['ready 7', `merge 7 squash ${head}`, `merge 7 rebase ${head}`, 'ready 7', `merge 7 merge ${head}`])
|
||||
})
|
||||
|
||||
it('turns the automatic merge of a bound change request on and off through its provider', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
|
||||
const follower = reader(opened)
|
||||
await follower.until(state => ready(state) && polled(state, pullUrl(7)))
|
||||
const on = { enabled: true as const, method: 'merge' as const, headSha: 'a'.repeat(40) }
|
||||
|
||||
await expect(opened.ctx.forgePanel.setAutoMerge(opened.session, pullUrl(7), on, signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'This provider sets no automatic merge' })
|
||||
const setAutoMerge = vi.fn<NonNullable<ForgeProvider['setAutoMerge']>>(() => Promise.resolve(undefined))
|
||||
Object.assign(opened.provider, { setAutoMerge })
|
||||
await opened.ctx.forgePanel.setAutoMerge(opened.session, pullUrl(7), on, signal)
|
||||
await opened.ctx.forgePanel.setAutoMerge(opened.session, pullUrl(7), { enabled: false }, signal)
|
||||
expect(setAutoMerge.mock.calls.map(([target, request]) => [target.number, request])).toEqual([[7, on], [7, { enabled: false }]])
|
||||
setAutoMerge.mockResolvedValueOnce({ code: 'stale', message: 'Head moved' })
|
||||
await expect(opened.ctx.forgePanel.setAutoMerge(opened.session, pullUrl(7), on, signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/stale-head', message: 'Head moved' })
|
||||
// A URL the Session does not bind names no change request to act on.
|
||||
await expect(opened.ctx.forgePanel.setAutoMerge(opened.session, pullUrl(8), on, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' })
|
||||
const aborted = new AbortController()
|
||||
aborted.abort(new Error('closed'))
|
||||
await expect(opened.ctx.forgePanel.setAutoMerge(opened.session, pullUrl(7), on, aborted.signal)).rejects.toThrow('closed')
|
||||
expect(setAutoMerge).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('reads and saves viewed marks of a bound change request through its provider, separating a moved head', async () => {
|
||||
const { repo } = await project()
|
||||
const opened = await open(repo)
|
||||
|
||||
@@ -357,7 +357,8 @@ function annotation(key: string, place: SourcedAnnotation['annotation']['place']
|
||||
/** File threads whose cards share inert actions. */
|
||||
function lineThreads(lines: FileThreads['lines']): FileThreads {
|
||||
const actions: ThreadActions = {
|
||||
author: null, addToInput: () => true, openLink: vi.fn(), readText: vi.fn(), inputFailed: vi.fn(), focused: null, writes: null,
|
||||
author: null, addToInput: () => true, openLink: vi.fn(), forge: 'github', readText: vi.fn(), inputFailed: vi.fn(), focused: null,
|
||||
writes: null,
|
||||
}
|
||||
return { lines, file: [], outdated: [], unresolved: lines.length, actions }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/** `forgePanel.hostReadiness`, which the host list on a provider row's Plugins page reads. */
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type { ForgeReadiness } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type { Config } from '../src/index.ts'
|
||||
import { bench, scratch } from './harness.ts'
|
||||
import type { Bench } from './harness.ts'
|
||||
|
||||
const cleanups: (() => Promise<void>)[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
|
||||
})
|
||||
|
||||
const signal = new AbortController().signal
|
||||
|
||||
/** A panel Remote whose Session directory is no checkout; the read names no Session. */
|
||||
async function opened(config: Config = {}): Promise<Bench> {
|
||||
const { path, remove } = await scratch('dsh-forge-host-readiness-')
|
||||
cleanups.push(remove)
|
||||
const result = await bench(path, config)
|
||||
cleanups.push(() => result.ctx.fiber.dispose())
|
||||
return result
|
||||
}
|
||||
|
||||
describe('forgePanel.hostReadiness', () => {
|
||||
it('reports the provider\'s readiness for the host in lowercase', async () => {
|
||||
const { ctx, provider } = await opened()
|
||||
const signIn: ForgeReadiness = { state: 'unauthenticated', message: 'not signed in', signIn: { command: 'fake auth login --hostname fake.test' } }
|
||||
const probed: string[] = []
|
||||
provider.readinessImpl = (host) => { probed.push(host); return Promise.resolve(signIn) }
|
||||
|
||||
await expect(ctx.forgePanel.hostReadiness('fake', 'Fake.TEST', signal)).resolves.toEqual(signIn)
|
||||
|
||||
expect(probed).toEqual(['fake.test'])
|
||||
})
|
||||
|
||||
it('reports a family no provider serves as unavailable', async () => {
|
||||
const { ctx } = await opened()
|
||||
|
||||
await expect(ctx.forgePanel.hostReadiness('absent', 'absent.test', signal)).resolves.toEqual({
|
||||
state: 'unavailable', message: 'forge: no provider is registered for "absent"', signIn: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports a probe that fails as unavailable with its reason', async () => {
|
||||
const { ctx, provider } = await opened()
|
||||
provider.readinessImpl = () => Promise.reject(new Error('fake: connection refused'))
|
||||
|
||||
await expect(ctx.forgePanel.hostReadiness('fake', 'fake.test', signal)).resolves.toEqual({
|
||||
state: 'unavailable', message: 'fake: connection refused', signIn: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports a probe past readinessTimeoutMs as unavailable', async () => {
|
||||
const { ctx, provider } = await opened({ readinessTimeoutMs: 50 })
|
||||
provider.readinessImpl = (_host, abort) => new Promise((_resolve, reject) => {
|
||||
abort.addEventListener('abort', () => { reject(abort.reason as Error) })
|
||||
})
|
||||
|
||||
await expect(ctx.forgePanel.hostReadiness('fake', 'fake.test', signal)).resolves.toEqual({
|
||||
state: 'unavailable', message: 'FORGE_PANEL_READINESS_TIMEOUT after 50ms', signIn: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects when the caller cancels before or during the probe', async () => {
|
||||
const { ctx, provider } = await opened()
|
||||
const stopped = new Error('caller left')
|
||||
await expect(ctx.forgePanel.hostReadiness('fake', 'fake.test', AbortSignal.abort(stopped))).rejects.toBe(stopped)
|
||||
|
||||
const caller = new AbortController()
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
provider.readinessImpl = (_host, abort) => new Promise((_resolve, reject) => {
|
||||
abort.addEventListener('abort', () => { reject(abort.reason as Error) })
|
||||
entered.resolve(undefined)
|
||||
})
|
||||
const read = ctx.forgePanel.hostReadiness('fake', 'fake.test', caller.signal)
|
||||
await entered.promise
|
||||
caller.abort(stopped)
|
||||
|
||||
await expect(read).rejects.toBe(stopped)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
/** The staged host list of a provider row: what a typed host stages, what is refused, and what one save writes. */
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { HostSettingsForm, typedHost, type HostSettings } from '../src/client/host-settings-form.ts'
|
||||
|
||||
/** A form over a row that serves `gitlab.com`, with the hosts `taken` by other rows. */
|
||||
function mounted(taken: readonly string[] = []) {
|
||||
const scope = stubConfigForm<HostSettings>()
|
||||
scope.publish({ status: 'ready', value: { hosts: ['gitlab.com'] }, base: { hosts: ['gitlab.com'] }, user: {}, writable: true, revision: 4 })
|
||||
const form = new HostSettingsForm(scope.scope, () => taken)
|
||||
const { hooks, ...actions } = form.inject()
|
||||
return { scope, form, state: () => hooks.hostForm.getSnapshot(), ...actions }
|
||||
}
|
||||
|
||||
it.each([
|
||||
[' GitLab.Example.com ', 'gitlab.example.com'],
|
||||
['https://GitLab.example.com:8443/group/app/-/merge_requests/2', 'gitlab.example.com:8443'],
|
||||
['ssh://git@gitlab.example.com/group/app.git', 'gitlab.example.com'],
|
||||
['https://', 'https://'],
|
||||
['a b', 'a b'],
|
||||
['', ''],
|
||||
])('reads %j as the host %j', (text, host) => {
|
||||
expect(typedHost(text)).toBe(host)
|
||||
})
|
||||
|
||||
it('shows no hosts before the Host serves the row', () => {
|
||||
const scope = stubConfigForm<HostSettings>()
|
||||
const form = new HostSettingsForm(scope.scope, () => [])
|
||||
try {
|
||||
expect(form.inject().hooks.hostForm.getSnapshot()).toMatchObject({ available: false, dirty: false, saved: [], draft: [] })
|
||||
} finally { form.dispose() }
|
||||
})
|
||||
|
||||
it('stages added hosts and writes the whole list in one save', async () => {
|
||||
const m = mounted()
|
||||
try {
|
||||
expect(m.state()).toMatchObject({ available: true, dirty: false, saved: ['gitlab.com'], draft: ['gitlab.com'] })
|
||||
|
||||
expect(m.add('https://GitLab.Example.com/group/app/-/merge_requests/2')).toBeUndefined()
|
||||
expect(m.add('git.corp.example:8443')).toBeUndefined()
|
||||
|
||||
expect(m.state()).toMatchObject({ dirty: true, invalid: false, saved: ['gitlab.com'], draft: ['gitlab.com', 'gitlab.example.com', 'git.corp.example:8443'] })
|
||||
expect(m.scope.mutate).not.toHaveBeenCalled()
|
||||
m.save()
|
||||
await vi.waitFor(() => {
|
||||
expect(m.scope.mutate).toHaveBeenCalledWith([{ op: 'set', path: ['hosts'], value: ['gitlab.com', 'gitlab.example.com', 'git.corp.example:8443'] }], 4)
|
||||
})
|
||||
} finally { m.form.dispose() }
|
||||
expect(m.scope.listenerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('stages nothing for blank text, a malformed host, a listed host, or a host another row serves', () => {
|
||||
const m = mounted(['GitHub.com'])
|
||||
try {
|
||||
expect(m.add(' ')).toBeUndefined()
|
||||
expect(m.add('a b')).toEqual({ kind: 'invalid' })
|
||||
expect(m.add('-gitlab.example.com')).toEqual({ kind: 'invalid' })
|
||||
expect(m.add('GITLAB.com')).toEqual({ kind: 'duplicate', host: 'gitlab.com' })
|
||||
expect(m.add('https://github.com/octo/demo/pull/1')).toEqual({ kind: 'taken', host: 'github.com' })
|
||||
|
||||
expect(m.state()).toMatchObject({ dirty: false, draft: ['gitlab.com'] })
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
|
||||
it('stages removals but keeps the last host, and drops the staged list on discard', async () => {
|
||||
const m = mounted()
|
||||
try {
|
||||
m.remove('gitlab.com')
|
||||
expect(m.state()).toMatchObject({ dirty: false, draft: ['gitlab.com'] })
|
||||
|
||||
m.add('gitlab.example.com')
|
||||
m.remove('gitlab.com')
|
||||
expect(m.state()).toMatchObject({ dirty: true, draft: ['gitlab.example.com'] })
|
||||
m.discard()
|
||||
expect(m.state()).toMatchObject({ dirty: false, draft: ['gitlab.com'] })
|
||||
|
||||
m.add('gitlab.example.com')
|
||||
m.remove('gitlab.com')
|
||||
m.save()
|
||||
await vi.waitFor(() => { expect(m.scope.mutate).toHaveBeenCalledWith([{ op: 'set', path: ['hosts'], value: ['gitlab.example.com'] }], 4) })
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
@@ -0,0 +1,212 @@
|
||||
// @vitest-environment jsdom
|
||||
/** A provider row's host page: the list with each host's sign-in state, staged additions and removals, and one save. */
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render, within } from '@testing-library/react'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import { bindSnapshotSelector, makeTranslate, stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { HostSettings, type HostForge, type HostSettingsProps } from '../src/client/HostSettings.tsx'
|
||||
import { HostSettingsForm, type HostSettings as HostSettingsFields } from '../src/client/host-settings-form.ts'
|
||||
import type { HostSignIn } from '../src/client/host-sign-in.ts'
|
||||
import { en } from '../src/client/locales.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const t = makeTranslate(en)
|
||||
const COMMAND = 'glab auth login --hostname gitlab.example.com'
|
||||
|
||||
interface MountOptions {
|
||||
readonly forge?: HostForge
|
||||
readonly view?: 'page' | 'summary'
|
||||
readonly hosts?: string[]
|
||||
readonly taken?: readonly string[]
|
||||
readonly writable?: boolean
|
||||
readonly signIn?: readonly (readonly [string, HostSignIn])[]
|
||||
/** Leave the row's form unserved. */
|
||||
readonly unserved?: boolean
|
||||
}
|
||||
|
||||
/** Render the page of a row that serves `hosts` over a real staged form, with the sign-in states and every face call recorded. */
|
||||
function mount(options: MountOptions = {}) {
|
||||
const scope = stubConfigForm<HostSettingsFields>()
|
||||
const hosts = options.hosts ?? ['gitlab.com']
|
||||
if (options.unserved !== true) {
|
||||
scope.publish({ status: 'ready', value: { hosts }, base: { hosts: ['gitlab.com'] }, user: {}, writable: options.writable ?? true, revision: 2 })
|
||||
}
|
||||
const form = new HostSettingsForm(scope.scope, () => options.taken ?? [])
|
||||
const { hooks, ...actions } = form.inject()
|
||||
const signIn = createSnapshotStore<ReadonlyMap<string, HostSignIn>>(new Map(options.signIn ?? []))
|
||||
const checkSignIn = vi.fn<HostSettingsProps['checkSignIn']>()
|
||||
const copyCommand = vi.fn<HostSettingsProps['copyCommand']>()
|
||||
const props = {
|
||||
view: options.view ?? 'page', forge: options.forge ?? 'gitlab', ...actions,
|
||||
add: vi.fn(actions.add), remove: vi.fn(actions.remove), save: vi.fn(actions.save), discard: vi.fn(actions.discard),
|
||||
useHostForm: bindSnapshotSelector(hooks.hostForm), useSignIn: bindSnapshotSelector(signIn), checkSignIn, copyCommand, t,
|
||||
} as HostSettingsProps
|
||||
const view = render(<HostSettings {...props} />)
|
||||
const row = (host: string): HTMLElement => {
|
||||
const element = view.container.querySelector(`[data-forge-host="${host}"]`)
|
||||
if (!(element instanceof HTMLElement)) throw new Error(`no row for ${host}`)
|
||||
return element
|
||||
}
|
||||
const input = (): HTMLInputElement => {
|
||||
const element = view.getByRole('textbox', { name: 'Host to add' })
|
||||
if (!(element instanceof HTMLInputElement)) throw new Error('no field for the host to add')
|
||||
return element
|
||||
}
|
||||
const type = (text: string): void => { fireEvent.change(input(), { target: { value: text } }) }
|
||||
return { view, scope, form, props, signIn, checkSignIn, copyCommand, row, input, type }
|
||||
}
|
||||
|
||||
describe('HostSettings', () => {
|
||||
it('names the list in the summary view without reading sign-in state', () => {
|
||||
const m = mount({ view: 'summary' })
|
||||
try {
|
||||
expect(m.view.container.textContent).toBe('Hosts')
|
||||
expect(m.checkSignIn).not.toHaveBeenCalled()
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
|
||||
it('says the settings are unavailable while the Host does not serve the row, and reads no sign-in state', () => {
|
||||
const m = mount({ unserved: true })
|
||||
try {
|
||||
expect(m.view.getByRole('status').textContent).toBe('Host settings are unavailable.')
|
||||
expect(m.view.queryByRole('list')).toBeNull()
|
||||
expect(m.checkSignIn).not.toHaveBeenCalled()
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
|
||||
it('lists each saved host with its sign-in state, the command to copy, or why it could not be checked', () => {
|
||||
const m = mount({
|
||||
hosts: ['gitlab.com', 'gitlab.example.com', 'quiet.example.com', 'down.example.com', 'silent.example.com', 'new.example.com'],
|
||||
signIn: [
|
||||
['gitlab.com', { state: 'ready', message: null, signIn: null }],
|
||||
['gitlab.example.com', { state: 'unauthenticated', message: 'not signed in', signIn: { command: COMMAND } }],
|
||||
['quiet.example.com', { state: 'unauthenticated', message: 'the token expired', signIn: null }],
|
||||
['down.example.com', { state: 'unavailable', message: 'glab: connection timed out', signIn: null }],
|
||||
['silent.example.com', { state: 'unavailable', message: '', signIn: null }],
|
||||
],
|
||||
})
|
||||
try {
|
||||
expect(within(m.view.getByRole('list', { name: 'Hosts' })).getAllByRole('listitem')).toHaveLength(6)
|
||||
expect(m.row('gitlab.com').textContent).toBe('gitlab.comSigned in')
|
||||
expect(m.row('gitlab.com').querySelector('[data-state="ready"] [data-state="done"]')).not.toBeNull()
|
||||
expect(m.row('gitlab.example.com').textContent).toBe(`gitlab.example.comNot signed in${COMMAND}Copy`)
|
||||
expect(m.row('quiet.example.com').textContent).toBe('quiet.example.comNot signed inthe token expired')
|
||||
expect(m.row('down.example.com').textContent).toBe('down.example.comCan\'t checkglab: connection timed out')
|
||||
expect(m.row('silent.example.com').textContent).toBe('silent.example.comCan\'t check')
|
||||
expect(m.row('new.example.com').textContent).toBe('new.example.comChecking…')
|
||||
|
||||
fireEvent.click(within(m.row('gitlab.example.com')).getByRole('button', { name: 'Copy sign-in command' }))
|
||||
expect(m.copyCommand).toHaveBeenCalledWith(COMMAND)
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
|
||||
it('reads sign-in state when shown, when the window regains focus, and after the saved hosts change, until it is left', () => {
|
||||
const m = mount()
|
||||
try {
|
||||
expect(m.checkSignIn.mock.calls).toEqual([[['gitlab.com'], false]])
|
||||
fireEvent.focus(window)
|
||||
expect(m.checkSignIn).toHaveBeenCalledTimes(2)
|
||||
|
||||
act(() => { m.signIn.set(new Map([['gitlab.com', { state: 'ready', message: null, signIn: null }]])) })
|
||||
expect(m.row('gitlab.com').textContent).toBe('gitlab.comSigned in')
|
||||
expect(m.checkSignIn).toHaveBeenCalledTimes(2)
|
||||
act(() => { m.scope.publish({ value: { hosts: ['gitlab.com', 'gitlab.example.com'] } }) })
|
||||
expect(m.checkSignIn).toHaveBeenLastCalledWith(['gitlab.com', 'gitlab.example.com'], false)
|
||||
expect(m.checkSignIn).toHaveBeenCalledTimes(3)
|
||||
|
||||
fireEvent.click(m.view.getByRole('button', { name: 'Check sign-in again' }))
|
||||
expect(m.checkSignIn).toHaveBeenLastCalledWith(['gitlab.com', 'gitlab.example.com'], true)
|
||||
|
||||
m.view.unmount()
|
||||
fireEvent.focus(window)
|
||||
expect(m.checkSignIn).toHaveBeenCalledTimes(4)
|
||||
expect(m.props.discard).toHaveBeenCalledOnce()
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
|
||||
it('stages a typed host from the Add button or Enter, marks it as not saved, and writes the list on save', async () => {
|
||||
const m = mount()
|
||||
try {
|
||||
const add = m.view.getByRole('button', { name: 'Add' })
|
||||
expect(add).toHaveProperty('disabled', true)
|
||||
expect(m.input().placeholder).toBe('gitlab.example.com')
|
||||
expect(m.view.getByText('MR links and Git remotes on these hosts are recognized. After adding a host, sign in to it with glab in a terminal.')).toBeTruthy()
|
||||
|
||||
m.type('https://gitlab.example.com/group/app/-/merge_requests/2')
|
||||
fireEvent.click(add)
|
||||
expect(m.input().value).toBe('')
|
||||
expect(m.row('gitlab.example.com').textContent).toBe('gitlab.example.comNot saved')
|
||||
|
||||
m.type('git.corp.example')
|
||||
fireEvent.keyDown(m.input(), { key: 'a' })
|
||||
fireEvent.keyDown(m.input(), { key: 'Enter', isComposing: true })
|
||||
expect(m.props.add).toHaveBeenCalledOnce()
|
||||
fireEvent.keyDown(m.input(), { key: 'Enter' })
|
||||
expect(m.row('git.corp.example').textContent).toBe('git.corp.exampleNot saved')
|
||||
|
||||
fireEvent.click(m.view.getByRole('button', { name: 'Save' }))
|
||||
await vi.waitFor(() => {
|
||||
expect(m.scope.mutate).toHaveBeenCalledWith([{ op: 'set', path: ['hosts'], value: ['gitlab.com', 'gitlab.example.com', 'git.corp.example'] }], 2)
|
||||
})
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
|
||||
it.each([
|
||||
['gitlab', 'a b', 'Enter a host name such as gitlab.example.com'],
|
||||
['gitlab', 'GitLab.com', 'gitlab.com is already in the list'],
|
||||
['gitlab', 'github.com', 'The GitHub component already uses github.com'],
|
||||
['github', 'github.com', 'The GitLab component already uses github.com'],
|
||||
] as const)('on the %s page, refuses %j below the field until the text changes', (forge, text, message) => {
|
||||
const m = mount({ forge, taken: ['github.com'] })
|
||||
try {
|
||||
m.type(text)
|
||||
fireEvent.click(m.view.getByRole('button', { name: 'Add' }))
|
||||
|
||||
expect(m.view.getByRole('alert').textContent).toBe(message)
|
||||
expect(m.input().getAttribute('aria-invalid')).toBe('true')
|
||||
expect(m.input().getAttribute('aria-describedby')).toBe(m.view.getByRole('alert').id)
|
||||
expect(m.input().value).toBe(text)
|
||||
|
||||
m.type(`${text}x`)
|
||||
expect(m.view.queryByRole('alert')).toBeNull()
|
||||
expect(m.input().getAttribute('aria-invalid')).toBeNull()
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
|
||||
it('names pull requests and gh on the GitHub page', () => {
|
||||
const m = mount({ forge: 'github', hosts: ['github.com'] })
|
||||
try {
|
||||
expect(m.input().placeholder).toBe('github.example.com')
|
||||
expect(m.view.getByText('PR links and Git remotes on these hosts are recognized. After adding a host, sign in to it with gh in a terminal.')).toBeTruthy()
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
|
||||
it('removes a host from the staged list, but not the last one', () => {
|
||||
const m = mount({ hosts: ['gitlab.com', 'gitlab.example.com'] })
|
||||
try {
|
||||
const remove = (host: string): HTMLElement => within(m.row(host)).getByRole('button', { name: `Remove ${host}` })
|
||||
expect(remove('gitlab.com').getAttribute('aria-disabled')).toBeNull()
|
||||
|
||||
fireEvent.click(remove('gitlab.com'))
|
||||
expect(m.props.remove).toHaveBeenCalledWith('gitlab.com')
|
||||
expect(m.view.container.querySelector('[data-forge-host="gitlab.com"]')).toBeNull()
|
||||
|
||||
expect(remove('gitlab.example.com').getAttribute('aria-disabled')).toBe('true')
|
||||
fireEvent.click(remove('gitlab.example.com'))
|
||||
expect(m.props.remove).toHaveBeenCalledOnce()
|
||||
expect(m.row('gitlab.example.com')).toBeTruthy()
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
|
||||
it('disables every edit while the document is read-only', () => {
|
||||
const m = mount({ hosts: ['gitlab.com', 'gitlab.example.com'], writable: false })
|
||||
try {
|
||||
expect(m.view.getByText('This deployment stores settings read-only.')).toBeTruthy()
|
||||
expect(m.input()).toHaveProperty('disabled', true)
|
||||
expect(m.view.getByRole('button', { name: 'Add' })).toHaveProperty('disabled', true)
|
||||
expect(within(m.row('gitlab.com')).getByRole('button', { name: 'Remove gitlab.com' })).toHaveProperty('disabled', true)
|
||||
expect(m.view.getByRole('button', { name: 'Check sign-in again' })).toHaveProperty('disabled', false)
|
||||
} finally { m.form.dispose() }
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
/** The sign-in states a provider row's page keeps for its hosts. */
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import type { ForgeReadiness } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { HostSignInStates, type HostReadinessRead } from '../src/client/host-sign-in.ts'
|
||||
|
||||
const READY: ForgeReadiness = { state: 'ready', message: null, signIn: null }
|
||||
const SIGN_IN: ForgeReadiness = { state: 'unauthenticated', message: 'not signed in', signIn: { command: 'glab auth login --hostname gitlab.example.com' } }
|
||||
|
||||
/** One readiness read the test answers by hand. */
|
||||
interface PendingRead {
|
||||
readonly host: string
|
||||
readonly signal: AbortSignal
|
||||
readonly answer: (result: RemoteResult<ForgeReadiness>) => void
|
||||
}
|
||||
|
||||
/** Readiness reads the test answers by hand, in call order. */
|
||||
function reads() {
|
||||
const calls: PendingRead[] = []
|
||||
const read = vi.fn<HostReadinessRead>((host, signal) => new Promise((resolve) => { calls.push({ host, signal, answer: resolve }) }))
|
||||
return { calls, read }
|
||||
}
|
||||
|
||||
/** Let answered reads reach the store. */
|
||||
async function settle(): Promise<void> {
|
||||
await new Promise((resolve) => { setTimeout(resolve, 0) })
|
||||
}
|
||||
|
||||
it('shows every host as being checked, then each answer as it arrives', async () => {
|
||||
const { calls, read } = reads()
|
||||
const signIn = new HostSignInStates(read)
|
||||
expect(signIn.states.getSnapshot().size).toBe(0)
|
||||
|
||||
signIn.check(['gitlab.com', 'gitlab.example.com'], true)
|
||||
|
||||
expect(calls.map(call => call.host)).toEqual(['gitlab.com', 'gitlab.example.com'])
|
||||
expect([...signIn.states.getSnapshot()]).toEqual([['gitlab.com', { state: 'checking' }], ['gitlab.example.com', { state: 'checking' }]])
|
||||
calls[1]?.answer({ ok: true, value: SIGN_IN })
|
||||
await settle()
|
||||
expect([...signIn.states.getSnapshot()]).toEqual([['gitlab.com', { state: 'checking' }], ['gitlab.example.com', SIGN_IN]])
|
||||
calls[0]?.answer({ ok: true, value: READY })
|
||||
await settle()
|
||||
expect(signIn.states.getSnapshot().get('gitlab.com')).toEqual(READY)
|
||||
})
|
||||
|
||||
it('reports a refused read as a host it could not check, with the reason', async () => {
|
||||
const { calls, read } = reads()
|
||||
const signIn = new HostSignInStates(read)
|
||||
signIn.check(['gitlab.com'], true)
|
||||
|
||||
calls[0]?.answer({ ok: false, error: new RemoteError('gateway/internal', 'The Host did not answer the sign-in read', {}) })
|
||||
await settle()
|
||||
|
||||
expect(signIn.states.getSnapshot().get('gitlab.com')).toEqual({
|
||||
state: 'unavailable', message: 'The Host did not answer the sign-in read', signIn: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the states it has during a quiet check, shows only new hosts as being checked, and forgets hosts no longer named', async () => {
|
||||
const { calls, read } = reads()
|
||||
const signIn = new HostSignInStates(read)
|
||||
signIn.check(['gitlab.com', 'old.example.com'], true)
|
||||
calls[0]?.answer({ ok: true, value: READY })
|
||||
calls[1]?.answer({ ok: true, value: SIGN_IN })
|
||||
await settle()
|
||||
|
||||
signIn.check(['gitlab.com', 'gitlab.example.com'], false)
|
||||
|
||||
expect([...signIn.states.getSnapshot()]).toEqual([['gitlab.com', READY], ['gitlab.example.com', { state: 'checking' }]])
|
||||
calls[2]?.answer({ ok: true, value: SIGN_IN })
|
||||
await settle()
|
||||
expect(signIn.states.getSnapshot().get('gitlab.com')).toEqual(SIGN_IN)
|
||||
})
|
||||
|
||||
it('ends the reads of an earlier check and drops their answers', async () => {
|
||||
const { calls, read } = reads()
|
||||
const signIn = new HostSignInStates(read)
|
||||
signIn.check(['gitlab.com'], true)
|
||||
|
||||
signIn.check(['gitlab.com'], true)
|
||||
|
||||
expect(calls[0]?.signal.aborted).toBe(true)
|
||||
expect(calls[1]?.signal.aborted).toBe(false)
|
||||
calls[0]?.answer({ ok: true, value: SIGN_IN })
|
||||
await settle()
|
||||
expect(signIn.states.getSnapshot().get('gitlab.com')).toEqual({ state: 'checking' })
|
||||
|
||||
signIn.dispose()
|
||||
expect(calls[1]?.signal.aborted).toBe(true)
|
||||
calls[1]?.answer({ ok: true, value: READY })
|
||||
await settle()
|
||||
expect(signIn.states.getSnapshot().get('gitlab.com')).toEqual({ state: 'checking' })
|
||||
})
|
||||
@@ -13,7 +13,10 @@ import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type { SidebarRightTabDefinition, TabId } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
|
||||
import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {
|
||||
ChangeRequestDescription, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeCommitList, ForgeRerunRequest, ForgeReviewData,
|
||||
AutoMergeRequest, ChangeRequestActivity, ChangeRequestDescription, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeCommitList,
|
||||
ForgeReadiness,
|
||||
ForgeRerunRequest,
|
||||
ForgeReviewData,
|
||||
ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, ForgeViewedFiles,
|
||||
ForgeViewedRequest,
|
||||
} from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
@@ -31,8 +34,10 @@ import { ChangesTabTitle } from '../src/client/ChangesTabTitle.tsx'
|
||||
import {
|
||||
CheckoutRow, ConnectionRow, LocalChangesRow, type CheckoutRowInjected, type ConnectionRowInjected, type LocalChangesRowInjected,
|
||||
} from '../src/client/EnvironmentRows.tsx'
|
||||
import { HostSettings, type HostSettingsInjected } from '../src/client/HostSettings.tsx'
|
||||
import type { HostSettings as HostSettingsFields } from '../src/client/host-settings-form.ts'
|
||||
import { en, NS, zh } from '../src/client/locales.ts'
|
||||
import { inject, mountForgePanel, WORKTREE_NS, WORKTREE_ROW_KEY } from '../src/client/mount.ts'
|
||||
import { FORGE_BUNDLE, HOST_ROWS, inject, mountForgePanel, WORKTREE_NS, WORKTREE_ROW_KEY } from '../src/client/mount.ts'
|
||||
import type { SessionListInjected } from '../src/client/session-list.ts'
|
||||
import { SessionHoverForge } from '../src/client/SessionHoverForge.tsx'
|
||||
import { SessionRowForge } from '../src/client/SessionRowForge.tsx'
|
||||
@@ -96,6 +101,8 @@ function stream<F = ForgePanelState>(signal: AbortSignal) {
|
||||
}
|
||||
|
||||
const OK: RemoteResult<void> = { ok: true, value: undefined }
|
||||
/** The automatic merge turned on for a confirmed head. */
|
||||
const AUTO_ON = { enabled: true as const, method: 'squash' as const, headSha: 'b'.repeat(40) }
|
||||
|
||||
/** What a Remote read resolves to. */
|
||||
type Read<T> = Promise<RemoteResult<T>>
|
||||
@@ -162,6 +169,10 @@ function isReviewPageFace(value: Record<string, unknown>): value is Record<strin
|
||||
return typeof value.openLists === 'function' && typeof value.actionsFor === 'function'
|
||||
}
|
||||
|
||||
function isHostFace(value: Record<string, unknown>): value is Record<string, unknown> & HostSettingsInjected {
|
||||
return typeof value.add === 'function' && typeof value.checkSignIn === 'function'
|
||||
}
|
||||
|
||||
function isReviewCountFace(value: Record<string, unknown>): value is Record<string, unknown> & ReviewNavCountInjected {
|
||||
return typeof value.hooks === 'object' && value.hooks !== null && 'count' in value.hooks
|
||||
}
|
||||
@@ -215,6 +226,7 @@ async function base() {
|
||||
dismiss: vi.fn(async (_sessionId: SessionId, _url: string): Promise<RemoteResult<void>> => OK),
|
||||
markReady: vi.fn(async (_sessionId: SessionId, _url: string): Promise<RemoteResult<void>> => OK),
|
||||
merge: vi.fn(async (_sessionId: SessionId, _url: string, _method: string, _headSha: string): Promise<RemoteResult<void>> => OK),
|
||||
setAutoMerge: vi.fn(async (_sessionId: SessionId, _url: string, _request: AutoMergeRequest): Promise<RemoteResult<void>> => OK),
|
||||
rerunChecks: vi.fn(async (_sessionId: SessionId, _url: string, _request: ForgeRerunRequest): Promise<RemoteResult<void>> => OK),
|
||||
requestReviews: vi.fn(async (
|
||||
_sessionId: SessionId, _url: string, _reviewers: readonly Pick<ChangeRequestReviewer, 'kind' | 'login'>[],
|
||||
@@ -270,9 +282,12 @@ async function base() {
|
||||
reviewRefresh: vi.fn(async (): Promise<RemoteResult<void>> => OK),
|
||||
reviewDescription: vi.fn(async (_url: string, _signal: AbortSignal): Read<ChangeRequestDescription> =>
|
||||
({ ok: true, value: description('Body') })),
|
||||
reviewActivity: vi.fn(async (_url: string, _signal: AbortSignal): Read<ChangeRequestActivity | null> => ({ ok: true, value: null })),
|
||||
reviewComment: vi.fn(async (_url: string, _body: string): Promise<RemoteResult<void>> => OK),
|
||||
reviewPoll: vi.fn(async (_url: string): Promise<RemoteResult<void>> => OK),
|
||||
reviewMarkReady: vi.fn(async (_url: string): Promise<RemoteResult<void>> => OK),
|
||||
reviewMerge: vi.fn(async (_url: string, _method: string, _headSha: string): Promise<RemoteResult<void>> => OK),
|
||||
reviewSetAutoMerge: vi.fn(async (_url: string, _request: AutoMergeRequest): Promise<RemoteResult<void>> => OK),
|
||||
reviewChecks: vi.fn(async (_url: string, _headSha: string, _signal: AbortSignal): Read<ChangeRequestSnapshot> =>
|
||||
({ ok: true, value: snapshot(7) })),
|
||||
reviewRerunChecks: vi.fn(async (_url: string, _request: ForgeRerunRequest): Promise<RemoteResult<void>> => OK),
|
||||
@@ -298,6 +313,8 @@ async function base() {
|
||||
reviewSubmit: vi.fn(async (_url: string, _request: ForgeReviewRequest): Read<ForgeReviewResult> =>
|
||||
({ ok: true, value: { ok: true, url: 'https://github.com/review/2' } })),
|
||||
reviewStage: vi.fn(async (_sessionId: SessionId, _url: string | null): Promise<RemoteResult<void>> => OK),
|
||||
hostReadiness: vi.fn(async (_forge: string, _host: string, _signal: AbortSignal): Read<ForgeReadiness> =>
|
||||
({ ok: true, value: { state: 'ready', message: null, signIn: null } })),
|
||||
}
|
||||
ctx.provide('remote.forgePanel', forgePanel)
|
||||
ctx.provide('locale', new LocaleRuntime(ctx))
|
||||
@@ -319,7 +336,14 @@ async function base() {
|
||||
}
|
||||
ctx.provide('sessions', sessions)
|
||||
const worktreeForm = stubConfigForm<WorktreeSettingsFields>()
|
||||
ctx.provide('configForms', { get: (name: string) => { expect(name).toBe(WORKTREE_NS); return worktreeForm.scope } } as never)
|
||||
const hostForms = { 'forge-github': stubConfigForm<HostSettingsFields>(), 'forge-gitlab': stubConfigForm<HostSettingsFields>() }
|
||||
ctx.provide('configForms', {
|
||||
get: (name: string) => {
|
||||
if (name === WORKTREE_NS) return worktreeForm.scope
|
||||
if (name === 'forge-github' || name === 'forge-gitlab') return hostForms[name].scope
|
||||
throw new Error(`no form expected for the entry ${name}`)
|
||||
},
|
||||
} as never)
|
||||
ctx.provide('sidebarRight', sidebarRight)
|
||||
const remoteAccess = {
|
||||
whenAccess: vi.fn((_action: string, callback: () => Iterable<() => unknown>) => {
|
||||
@@ -358,7 +382,7 @@ async function base() {
|
||||
} as never, () => null)
|
||||
return {
|
||||
ctx, remote, unmount, streams, stateStreams, extensionStreams, countStreams, forgePanel, sidebarRightTabs, unregisterTab, sidebarRight,
|
||||
sessions, scopes, worktreeForm, remoteAccess, workspaces, uiWorkspace,
|
||||
sessions, scopes, worktreeForm, hostForms, remoteAccess, workspaces, uiWorkspace,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -992,6 +1016,21 @@ describe('mountForgePanel change request actions', () => {
|
||||
expect(f.notice()).toMatchObject(notice)
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['turns it on and confirms it', AUTO_ON, OK, { key: 'toast.autoMergeEnabled', tone: 'success', params: { name: '#7' } }],
|
||||
['turns it off and confirms it', { enabled: false as const }, OK, { key: 'toast.autoMergeCancelled', tone: 'success', params: { name: '#7' } }],
|
||||
['says a moved head needs another look', AUTO_ON, REFUSED.stale, { key: 'toast.autoMergeStale', tone: 'failure', params: { name: '#7' } }],
|
||||
['reports why the host refused', AUTO_ON, REFUSED.refused,
|
||||
{ key: 'toast.autoMergeFailed', tone: 'failure', params: { message: 'Pull Request is not mergeable' } }],
|
||||
])('sets the automatic merge through the Remote and %s', async (_label, request, result, notice) => {
|
||||
const f = await fixture()
|
||||
f.forgePanel.setAutoMerge.mockResolvedValueOnce(result)
|
||||
await f.section(S1).autoMerge(entry(7, snapshot(7)), request)
|
||||
expect(f.forgePanel.setAutoMerge).toHaveBeenCalledWith(S1, 'https://github.com/octo/demo/pull/7', request)
|
||||
expect(f.notice()).toMatchObject(notice)
|
||||
await f.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('mountForgePanel overview actions', () => {
|
||||
@@ -1349,6 +1388,115 @@ describe('worktree row settings', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('provider row host settings', () => {
|
||||
/** The host page faces of the GitHub and GitLab rows. */
|
||||
function hostPages(f: Awaited<ReturnType<typeof fixture>>): Record<'github' | 'gitlab', HostSettingsInjected> {
|
||||
const rows = f.ctx.slots.entries('plugins.row.config').filter(candidate => candidate.component === HostSettings)
|
||||
expect(rows.map(row => row.options)).toMatchObject([{ key: `${FORGE_BUNDLE}#forge-github` }, { key: `${FORGE_BUNDLE}#forge-gitlab` }])
|
||||
const [github, gitlab] = rows.map(row => row.inject?.())
|
||||
assert(github !== undefined && isHostFace(github) && gitlab !== undefined && isHostFace(gitlab))
|
||||
return { github, gitlab }
|
||||
}
|
||||
|
||||
/** Serve a row's form with `hosts`. */
|
||||
function serve(f: Awaited<ReturnType<typeof fixture>>, row: 'forge-github' | 'forge-gitlab', hosts: string[]): void {
|
||||
f.hostForms[row].publish({ status: 'ready', value: { hosts }, base: { hosts }, user: {}, writable: true, revision: 1 })
|
||||
}
|
||||
|
||||
it('registers a host page for each provider row over the entry of the same id and writes the staged list on save', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
expect(HOST_ROWS).toEqual([{ forge: 'github', row: 'forge-github' }, { forge: 'gitlab', row: 'forge-gitlab' }])
|
||||
const pages = hostPages(f)
|
||||
expect([pages.github.forge, pages.gitlab.forge]).toEqual(['github', 'gitlab'])
|
||||
serve(f, 'forge-gitlab', ['gitlab.com'])
|
||||
expect(pages.gitlab.hooks.hostForm.getSnapshot()).toMatchObject({ available: true, dirty: false, saved: ['gitlab.com'], draft: ['gitlab.com'] })
|
||||
expect(pages.github.hooks.hostForm.getSnapshot()).toMatchObject({ available: false, saved: [] })
|
||||
|
||||
expect(pages.gitlab.add('gitlab.example.com')).toBeUndefined()
|
||||
pages.gitlab.save()
|
||||
|
||||
await vi.waitFor(() => { expect(f.hostForms['forge-gitlab'].mutate).toHaveBeenCalledOnce() })
|
||||
expect(f.hostForms['forge-gitlab'].mutate.mock.calls[0]?.[0]).toEqual([{ op: 'set', path: ['hosts'], value: ['gitlab.com', 'gitlab.example.com'] }])
|
||||
expect(f.hostForms['forge-github'].mutate).not.toHaveBeenCalled()
|
||||
} finally { await f.ctx.fiber.dispose() }
|
||||
})
|
||||
|
||||
it('refuses a host the other provider row serves now', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
const pages = hostPages(f)
|
||||
serve(f, 'forge-gitlab', ['gitlab.com'])
|
||||
// The GitHub row is not served yet, so it holds no host.
|
||||
expect(pages.gitlab.add('ghe.corp.example')).toBeUndefined()
|
||||
pages.gitlab.discard()
|
||||
|
||||
serve(f, 'forge-github', ['github.com', 'ghe.corp.example'])
|
||||
|
||||
expect(pages.gitlab.add('ghe.corp.example')).toEqual({ kind: 'taken', host: 'ghe.corp.example' })
|
||||
expect(pages.github.add('gitlab.com')).toEqual({ kind: 'taken', host: 'gitlab.com' })
|
||||
expect(pages.github.add('ghe.corp.example')).toEqual({ kind: 'duplicate', host: 'ghe.corp.example' })
|
||||
} finally { await f.ctx.fiber.dispose() }
|
||||
})
|
||||
|
||||
it('reads sign-in state through the Remote under the row\'s forge family', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
const pages = hostPages(f)
|
||||
const signIn: ForgeReadiness = { state: 'unauthenticated', message: 'not signed in', signIn: { command: 'glab auth login --hostname gitlab.example.com' } }
|
||||
f.forgePanel.hostReadiness.mockResolvedValueOnce({ ok: true, value: signIn })
|
||||
|
||||
pages.gitlab.checkSignIn(['gitlab.example.com'], true)
|
||||
|
||||
expect(f.forgePanel.hostReadiness).toHaveBeenCalledWith('gitlab', 'gitlab.example.com', expect.any(AbortSignal))
|
||||
expect(pages.gitlab.hooks.signIn.getSnapshot().get('gitlab.example.com')).toEqual({ state: 'checking' })
|
||||
await settle()
|
||||
expect(pages.gitlab.hooks.signIn.getSnapshot().get('gitlab.example.com')).toEqual(signIn)
|
||||
expect(pages.github.hooks.signIn.getSnapshot().size).toBe(0)
|
||||
|
||||
pages.github.checkSignIn(['github.com'], false)
|
||||
expect(f.forgePanel.hostReadiness).toHaveBeenLastCalledWith('github', 'github.com', expect.any(AbortSignal))
|
||||
} finally { await f.ctx.fiber.dispose() }
|
||||
})
|
||||
|
||||
it('copies a sign-in command and confirms it', async () => {
|
||||
const f = await fixture()
|
||||
const writeText = vi.fn(async (_text: string) => {})
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
|
||||
try {
|
||||
hostPages(f).gitlab.copyCommand('glab auth login --hostname gitlab.example.com')
|
||||
await settle()
|
||||
|
||||
expect(writeText).toHaveBeenCalledWith('glab auth login --hostname gitlab.example.com')
|
||||
expect(f.notice()).toMatchObject({ key: 'toast.commandCopied', tone: 'success' })
|
||||
} finally { await f.ctx.fiber.dispose() }
|
||||
})
|
||||
|
||||
it('withdraws both host pages, releases their forms, and ends the sign-in reads under way with its fiber', async () => {
|
||||
const b = await base()
|
||||
const fiber = b.ctx.plugin({ inject: [...inject], apply: (plugin: Context) => mountForgePanel(plugin, REMOTE) })
|
||||
await fiber
|
||||
const rows = () => b.ctx.slots.entries('plugins.row.config').filter(candidate => candidate.component === HostSettings)
|
||||
expect(rows()).toHaveLength(2)
|
||||
const github = rows()[0]?.inject?.()
|
||||
assert(github !== undefined && isHostFace(github))
|
||||
const signals: AbortSignal[] = []
|
||||
b.forgePanel.hostReadiness.mockImplementation((_forge, _host, signal) => {
|
||||
signals.push(signal)
|
||||
return new Promise(() => {})
|
||||
})
|
||||
github.checkSignIn(['github.com'], true)
|
||||
expect(b.hostForms['forge-github'].listenerCount()).toBe(1)
|
||||
|
||||
await fiber.dispose()
|
||||
|
||||
expect(rows()).toHaveLength(0)
|
||||
expect(signals.map(signal => signal.aborted)).toEqual([true])
|
||||
expect(b.hostForms['forge-github'].listenerCount()).toBe(0)
|
||||
expect(b.hostForms['forge-gitlab'].listenerCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('archive notices', () => {
|
||||
it('uses the scheduled cleanup notice and reports a later failure', async () => {
|
||||
const f = await fixture()
|
||||
@@ -1507,18 +1655,22 @@ describe('mountForgePanel review page', () => {
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
it('reads the lists of every repository or one, the change request, and its description through the Remote', async () => {
|
||||
it('reads the lists, the change request, its description and activity, and adds a comment through the Remote', async () => {
|
||||
const f = await fixture()
|
||||
const page = reviewPage(f)
|
||||
const signal = new AbortController().signal
|
||||
page.openLists('', signal)
|
||||
page.openLists(null, signal)
|
||||
expect(f.forgePanel.reviewLists).toHaveBeenLastCalledWith(null, signal)
|
||||
page.openLists('octo/demo', signal)
|
||||
expect(f.forgePanel.reviewLists).toHaveBeenLastCalledWith({ owner: 'octo', name: 'demo' }, signal)
|
||||
page.openLists({ host: 'gitlab.example', owner: 'group/sub', name: 'app' }, signal)
|
||||
expect(f.forgePanel.reviewLists).toHaveBeenLastCalledWith({ host: 'gitlab.example', owner: 'group/sub', name: 'app' }, signal)
|
||||
page.openChangeRequest(url, signal)
|
||||
expect(f.forgePanel.reviewChangeRequest).toHaveBeenCalledWith(url, signal)
|
||||
expect(await page.readDescription(url, signal)).toEqual({ ok: true, value: description('Body') })
|
||||
expect(f.forgePanel.reviewDescription).toHaveBeenCalledWith(url, signal)
|
||||
expect(await page.readActivity(url, signal)).toEqual({ ok: true, value: null })
|
||||
expect(f.forgePanel.reviewActivity).toHaveBeenCalledWith(url, signal)
|
||||
expect(await page.addComment(url, 'Thanks')).toEqual({ ok: true, value: undefined })
|
||||
expect(f.forgePanel.reviewComment).toHaveBeenCalledWith(url, 'Thanks')
|
||||
expect(page.hooks.locale.getSnapshot()).toBe(f.ctx.locale.getLocale().active)
|
||||
const reset = vi.fn()
|
||||
const unsubscribe = page.subscribeReset(reset)
|
||||
@@ -1530,6 +1682,25 @@ describe('mountForgePanel review page', () => {
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
it('opens the Forge bundle on the Plugins page for the host lists while the Plugins page provides its navigation', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
const page = reviewPage(f)
|
||||
expect(page.hooks.pluginNavigation.getSnapshot()).toBe(false)
|
||||
expect(() => { page.openHostSettings() }).not.toThrow()
|
||||
const openBundle = vi.fn()
|
||||
const navigation = f.ctx.plugin({ apply: (ctx: Context) => { ctx.provide('pluginNavigation', { openBundle } as never) } })
|
||||
await navigation
|
||||
await vi.waitFor(() => { expect(page.hooks.pluginNavigation.getSnapshot()).toBe(true) })
|
||||
|
||||
page.openHostSettings()
|
||||
|
||||
expect(openBundle).toHaveBeenCalledWith(FORGE_BUNDLE)
|
||||
await navigation.dispose()
|
||||
expect(page.hooks.pluginNavigation.getSnapshot()).toBe(false)
|
||||
} finally { await f.ctx.fiber.dispose() }
|
||||
})
|
||||
|
||||
it('reads every list again and reports only a failure', async () => {
|
||||
const f = await fixture()
|
||||
await reviewPage(f).refresh()
|
||||
@@ -1567,12 +1738,11 @@ describe('mountForgePanel review page card actions', () => {
|
||||
f.actions.viewChanges?.(entry(7, snapshot(7)))
|
||||
expect(f.showChanges).toHaveBeenCalledOnce()
|
||||
|
||||
f.actions.retry()
|
||||
await settle()
|
||||
// The read settles with the Host's answer, so a surface can show the refresh while it runs.
|
||||
await f.actions.retry()
|
||||
expect(f.forgePanel.reviewPoll).toHaveBeenCalledWith(url)
|
||||
f.forgePanel.reviewPoll.mockResolvedValueOnce(REFUSED.failed)
|
||||
f.actions.retry()
|
||||
await settle()
|
||||
await f.actions.retry()
|
||||
expect(f.notice()).toMatchObject({ key: 'toast.refreshFailed', tone: 'failure' })
|
||||
await f.dispose()
|
||||
})
|
||||
@@ -1608,6 +1778,21 @@ describe('mountForgePanel review page card actions', () => {
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['turns it on and confirms it', AUTO_ON, OK, { key: 'toast.autoMergeEnabled', tone: 'success', params: { name: '#7' } }],
|
||||
['turns it off and confirms it', { enabled: false as const }, OK, { key: 'toast.autoMergeCancelled', tone: 'success', params: { name: '#7' } }],
|
||||
['says a moved head needs another look', AUTO_ON, REFUSED.stale, { key: 'toast.autoMergeStale', tone: 'failure', params: { name: '#7' } }],
|
||||
['tells the reader to check an outcome the host did not confirm', AUTO_ON, REFUSED.unknown,
|
||||
{ key: 'toast.actionUnknown', tone: 'failure', params: { name: '#7' } }],
|
||||
])('sets the automatic merge by its URL and %s', async (_label, request, result, notice) => {
|
||||
const f = await card()
|
||||
f.forgePanel.reviewSetAutoMerge.mockResolvedValueOnce(result)
|
||||
await f.actions.autoMerge?.(entry(7, snapshot(7)), request)
|
||||
expect(f.forgePanel.reviewSetAutoMerge).toHaveBeenCalledWith(url, request)
|
||||
expect(f.notice()).toMatchObject(notice)
|
||||
await f.dispose()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['confirms it', OK, { key: 'toast.rerunRequested', tone: 'success', params: { name: '#7' } }],
|
||||
['says a moved head needs another look', REFUSED.stale, { key: 'toast.rerunStale', tone: 'failure', params: { name: '#7' } }],
|
||||
|
||||
@@ -239,7 +239,7 @@ describe('ChangeRequestsSection', () => {
|
||||
const value = entry(7, snapshot(7))
|
||||
const b = section(ready({ changeRequests: [value, entry(8, { code: 'unavailable', message: 'down' })] }))
|
||||
const card = b.view.container.querySelector('[data-forge-change="https://github.com/octo/demo/pull/7"]') as HTMLElement
|
||||
chooseAction(card, '#7', en['change.view'])
|
||||
chooseAction(card, '#7', 'Open on GitHub')
|
||||
chooseAction(card, '#7', en['change.copy'])
|
||||
chooseAction(card, '#7', en['change.viewChanges'])
|
||||
chooseAction(card, '#7', en['change.remove'])
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* The summary tab's activity: its rows with runs of commits as one, each kind of line and card, the reads that follow
|
||||
* the change request, and the field that adds a comment.
|
||||
*/
|
||||
import { act, cleanup, fireEvent, render, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { ChangeRequestActivity, ChangeRequestActivityItem, ForgeCommentAuthor } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { en } from '../src/client/locales.ts'
|
||||
import { activityEntries, longBody } from '../src/client/review-page/review-activity.ts'
|
||||
import { ReviewActivity, type ReviewActivityProps } from '../src/client/review-page/ReviewActivity.tsx'
|
||||
import css from '../src/client/review-page/ReviewPage.module.css'
|
||||
import { prUrl } from './review-fixtures.client.ts'
|
||||
|
||||
afterEach(() => { cleanup() })
|
||||
|
||||
const t = makeTranslate(en)
|
||||
const NOW = Date.parse('2026-10-09T02:00:00Z')
|
||||
const URL7 = prUrl(7)
|
||||
const MARKDOWN = { code: { copyLabel: 'Copy', copiedLabel: 'Copied', toolbarLabels: { codeLabel: 'Code', wrapLabel: 'Wrap', unwrapLabel: 'Unwrap' } }, footnotes: 'Footnotes' }
|
||||
|
||||
const mona: ForgeCommentAuthor = { login: 'mona', avatarUrl: null, bot: false }
|
||||
const robot: ForgeCommentAuthor = { login: 'ci-bot', avatarUrl: null, bot: true }
|
||||
|
||||
/** An hour before {@link NOW}, plus `minutes`. */
|
||||
function at(minutes = 0): string {
|
||||
return new Date(NOW - 3_600_000 + minutes * 60_000).toISOString()
|
||||
}
|
||||
|
||||
function commit(sha: string, title: string, minutes = 0): ChangeRequestActivityItem {
|
||||
return { kind: 'commit', at: at(minutes), actor: mona, sha: sha.repeat(40), title }
|
||||
}
|
||||
|
||||
function activity(items: readonly ChangeRequestActivityItem[], overrides: Partial<ChangeRequestActivity> = {}): ChangeRequestActivity {
|
||||
return { items, truncated: false, viewerCanComment: false, ...overrides }
|
||||
}
|
||||
|
||||
function ok<T>(value: T): RemoteResult<T> {
|
||||
return { ok: true, value }
|
||||
}
|
||||
|
||||
function failed(code: 'forgePanel/activity-failed' | 'forgePanel/action-failed' | 'forgePanel/action-unknown', message: string): RemoteResult<never> {
|
||||
return { ok: false, error: new RemoteError(code, message, {}) }
|
||||
}
|
||||
|
||||
/** A promise the test settles by hand. */
|
||||
function deferred<T>() {
|
||||
let settle: (value: T) => void = () => {}
|
||||
const promise = new Promise<T>((resolve) => { settle = resolve })
|
||||
return { promise, settle }
|
||||
}
|
||||
|
||||
/** Let the reads in flight settle. */
|
||||
async function settle(): Promise<void> {
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)) })
|
||||
}
|
||||
|
||||
/** Render the activity of #7 on GitHub with every handler recorded; the read answers `value`. */
|
||||
async function renderActivity(value: ChangeRequestActivity | null, overrides: Partial<ReviewActivityProps> = {}) {
|
||||
const props: ReviewActivityProps = {
|
||||
url: URL7, revision: 'r1', forge: 'GitHub', read: vi.fn(async () => ok(value)), comment: vi.fn(async () => ok(undefined)),
|
||||
onOpenChanges: vi.fn(), openLink: vi.fn(), now: NOW, markdown: MARKDOWN, t, ...overrides,
|
||||
}
|
||||
const view = render(<ReviewActivity {...props} />)
|
||||
await settle()
|
||||
const rerender = (next: Partial<ReviewActivityProps>): void => { view.rerender(<ReviewActivity {...props} {...next} />) }
|
||||
const lines = (): (string | null)[] => [...view.container.querySelectorAll('[data-forge-review-line]')].map(line => line.textContent)
|
||||
return { view, props, rerender, lines }
|
||||
}
|
||||
|
||||
describe('activityEntries', () => {
|
||||
it('keeps the order and makes one row of every run of commits', () => {
|
||||
const comment: ChangeRequestActivityItem = { kind: 'comment', at: at(2), actor: mona, body: 'Thanks', url: null }
|
||||
const merged: ChangeRequestActivityItem = { kind: 'merged', at: at(5), actor: mona }
|
||||
const entries = activityEntries([commit('a', 'One'), commit('b', 'Two', 1), comment, commit('c', 'Three', 3), merged])
|
||||
expect(entries.map(entry => entry.kind === 'commits' ? entry.commits.map(item => item.title) : entry.item.kind))
|
||||
.toEqual([['One', 'Two'], 'comment', ['Three'], 'merged'])
|
||||
expect(activityEntries([])).toEqual([])
|
||||
})
|
||||
|
||||
it('names every row apart, also two of one kind, time, and actor', () => {
|
||||
const requested = (reviewer: string): ChangeRequestActivityItem => ({ kind: 'review-requested', at: at(), actor: mona, reviewer })
|
||||
const closed: ChangeRequestActivityItem = { kind: 'closed', at: at(), actor: null }
|
||||
const keys = activityEntries([requested('lin'), requested('zhou'), requested('wang'), closed, commit('a', 'One'), closed])
|
||||
.map(entry => entry.key)
|
||||
expect(keys).toEqual([
|
||||
`review-requested:${at()}:mona`, `review-requested:${at()}:mona#1`, `review-requested:${at()}:mona#2`, `closed:${at()}:`,
|
||||
`commits:${'a'.repeat(40)}`, `closed:${at()}:#1`,
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('longBody', () => {
|
||||
it('cuts a comment over 400 characters or 6 lines short', () => {
|
||||
expect(longBody('x'.repeat(400))).toBe(false)
|
||||
expect(longBody('x'.repeat(401))).toBe(true)
|
||||
expect(longBody(Array.from({ length: 6 }, () => 'line').join('\n'))).toBe(false)
|
||||
expect(longBody(Array.from({ length: 7 }, () => 'line').join('\n'))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReviewActivity', () => {
|
||||
it('shows nothing for a provider that reads no activity', async () => {
|
||||
const b = await renderActivity(null)
|
||||
expect(b.view.container.innerHTML).toBe('')
|
||||
expect(b.props.read).toHaveBeenCalledWith(URL7, expect.any(AbortSignal))
|
||||
})
|
||||
|
||||
it('waits for the first read, then says when there is no activity', async () => {
|
||||
const read = deferred<RemoteResult<ChangeRequestActivity | null>>()
|
||||
const b = await renderActivity(null, { read: vi.fn(() => read.promise) })
|
||||
const region = b.view.getByRole('region', { name: 'Activity' })
|
||||
expect(region.querySelector('[data-forge-review-skeleton="activity"]')).not.toBeNull()
|
||||
expect(region.textContent).toBe('Activity')
|
||||
read.settle(ok(activity([])))
|
||||
await settle()
|
||||
expect(region.querySelector('[data-forge-review-skeleton]')).toBeNull()
|
||||
expect(region.textContent).toBe('ActivityNo activity yet')
|
||||
expect(b.view.queryByRole('textbox')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows one commit as its title and several as one line that unfolds them', async () => {
|
||||
const b = await renderActivity(activity([
|
||||
commit('a', 'Fix the parser'), { kind: 'reopened', at: at(1), actor: mona }, commit('b', 'Add a test', 2), commit('c', 'Rename it', 3),
|
||||
]))
|
||||
expect(b.lines()).toEqual(['Fix the parser1 h agoaaaaaaa', 'mona reopened this59 min ago', 'Commits: 257 min ago'])
|
||||
const fold = b.view.getByRole('button', { name: 'Commits: 2' })
|
||||
expect(fold.getAttribute('aria-expanded')).toBe('false')
|
||||
fireEvent.click(fold)
|
||||
expect(fold.getAttribute('aria-expanded')).toBe('true')
|
||||
expect(b.lines().slice(3)).toEqual(['Add a test58 min agobbbbbbb', 'Rename it57 min agoccccccc'])
|
||||
expect(b.view.container.querySelectorAll(`.${css.activityNested}`)).toHaveLength(2)
|
||||
fireEvent.click(fold)
|
||||
expect(b.lines()).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('shows each review decision, and opens the changes tab from a review that left inline comments', async () => {
|
||||
const review = (verdict: 'approved' | 'changes-requested' | 'commented' | 'dismissed', comments: number, body = ''): ChangeRequestActivityItem =>
|
||||
({ kind: 'review', at: at(), actor: mona, verdict, body, comments, url: null })
|
||||
const b = await renderActivity(activity([
|
||||
review('approved', 0), review('changes-requested', 2), review('commented', 0, 'Please rename `x`'), review('dismissed', 0, ' \n'),
|
||||
{ ...review('commented', 1), actor: null },
|
||||
]))
|
||||
expect(b.lines()).toEqual([
|
||||
'mona approved these changes1 h ago', 'mona requested changes · Inline comments: 21 h agoView in Changes', 'mona reviewed1 h ago',
|
||||
'mona\'s review was dismissed1 h ago', 'Deleted account reviewed · Inline comments: 11 h agoView in Changes',
|
||||
])
|
||||
const glyphs = [...b.view.container.querySelectorAll(`.${css.activityGlyph}`)].map(glyph => glyph.getAttribute('data-tone'))
|
||||
expect(glyphs).toEqual(['success', 'error', null, null, null])
|
||||
// Only the reviews with inline comments act.
|
||||
expect(b.view.getAllByRole('button').map(button => button.getAttribute('aria-label'))).toEqual([
|
||||
'mona requested changes · Inline comments: 2, View in Changes', 'Deleted account reviewed · Inline comments: 1, View in Changes',
|
||||
])
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'mona requested changes · Inline comments: 2, View in Changes' }))
|
||||
expect(b.props.onOpenChanges).toHaveBeenCalledTimes(1)
|
||||
// A review's own text shows as a card under its line; a blank one shows none.
|
||||
const cards = b.view.container.querySelectorAll('[data-forge-review-comment]')
|
||||
expect(cards).toHaveLength(1)
|
||||
expect(cards[0]?.textContent).toBe('Mmona1 h agoPlease rename x')
|
||||
})
|
||||
|
||||
it('shows a comment as a card with its author, and a long one cut short until it is expanded', async () => {
|
||||
const long = Array.from({ length: 14 }, (_value, index) => `Line ${index + 1}`).join('\n\n')
|
||||
const b = await renderActivity(activity([
|
||||
{ kind: 'comment', at: at(), actor: robot, body: 'Coverage is **92%**', url: null },
|
||||
{ kind: 'comment', at: at(1), actor: null, body: long, url: null },
|
||||
]))
|
||||
const [short, cut] = [...b.view.container.querySelectorAll('[data-forge-review-comment]')] as [HTMLElement, HTMLElement]
|
||||
expect(short.textContent).toBe('Cci-botbot1 h agoCoverage is 92%')
|
||||
expect(short.querySelector('strong')?.textContent).toBe('92%')
|
||||
expect(within(short).queryByRole('button')).toBeNull()
|
||||
expect(cut.textContent?.startsWith('?Deleted account59 min agoLine 1')).toBe(true)
|
||||
expect(cut.querySelector(`.${css.activityClamp}`)).not.toBeNull()
|
||||
const more = within(cut).getByRole('button', { name: 'Expand' })
|
||||
expect(more.getAttribute('aria-expanded')).toBe('false')
|
||||
fireEvent.click(more)
|
||||
expect(cut.querySelector(`.${css.activityClamp}`)).toBeNull()
|
||||
fireEvent.click(within(cut).getByRole('button', { name: 'Collapse' }))
|
||||
expect(cut.querySelector(`.${css.activityClamp}`)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('words every change of state after the account it is by', async () => {
|
||||
const event = (kind: 'merged' | 'closed' | 'reopened' | 'ready-for-review' | 'converted-to-draft' | 'force-pushed' | 'auto-merge-enabled'
|
||||
| 'auto-merge-disabled'): ChangeRequestActivityItem => ({ kind, at: at(), actor: mona })
|
||||
const b = await renderActivity(activity([
|
||||
event('ready-for-review'), event('converted-to-draft'), event('force-pushed'), event('auto-merge-enabled'), event('auto-merge-disabled'),
|
||||
event('closed'), event('reopened'), event('merged'),
|
||||
{ kind: 'review-requested', at: at(), actor: mona, reviewer: 'octo/core' },
|
||||
{ kind: 'review-requested', at: at(), actor: mona, reviewer: null },
|
||||
{ kind: 'renamed', at: at(), actor: mona, from: 'Old', to: 'New' },
|
||||
{ kind: 'other', at: at(), actor: mona, text: 'changed the description' },
|
||||
{ kind: 'merged', at: 'not a time', actor: null },
|
||||
]))
|
||||
expect(b.lines()).toEqual([
|
||||
'mona marked this ready for review1 h ago', 'mona converted this to a draft1 h ago', 'mona force-pushed the branch1 h ago',
|
||||
'mona enabled auto-merge1 h ago', 'mona disabled auto-merge1 h ago', 'mona closed this1 h ago', 'mona reopened this1 h ago',
|
||||
'mona merged this1 h ago', 'mona requested a review from octo/core1 h ago', 'mona requested a review1 h ago',
|
||||
'mona changed the title from “Old” to “New”1 h ago', 'mona changed the description1 h ago', 'Deleted account merged this',
|
||||
])
|
||||
expect(b.view.queryByRole('button')).toBeNull()
|
||||
})
|
||||
|
||||
it('says when earlier activity is not listed and opens the change request for it', async () => {
|
||||
const b = await renderActivity(activity([commit('a', 'One')], { truncated: true }))
|
||||
expect(b.view.getByText('Earlier activity is not listed')).toBeTruthy()
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Open on GitHub' }))
|
||||
expect(b.props.openLink).toHaveBeenCalledWith(URL7)
|
||||
// Once the provider left, the link names the browser.
|
||||
b.rerender({ forge: null })
|
||||
expect(b.view.getByRole('button', { name: 'Open in browser' })).toBeTruthy()
|
||||
})
|
||||
|
||||
it('reports a read that failed, reads again on Retry, and keeps the rows of an earlier read', async () => {
|
||||
const read = vi.fn<ReviewActivityProps['read']>()
|
||||
read.mockResolvedValueOnce(failed('forgePanel/activity-failed', 'slow down'))
|
||||
.mockResolvedValueOnce(ok(activity([commit('a', 'One')])))
|
||||
.mockResolvedValueOnce(failed('forgePanel/activity-failed', 'down'))
|
||||
const b = await renderActivity(null, { read })
|
||||
const notice = b.view.getByRole('status')
|
||||
expect(notice.textContent).toBe('Couldn\'t read the activity: slow downRetry')
|
||||
expect(b.view.container.querySelector('[data-state="ongoing"]')).toBeNull()
|
||||
fireEvent.click(within(notice).getByRole('button', { name: 'Retry' }))
|
||||
await settle()
|
||||
expect(b.view.queryByRole('status')).toBeNull()
|
||||
expect(b.lines()).toEqual(['One1 h agoaaaaaaa'])
|
||||
// A later read that fails keeps what the earlier one listed.
|
||||
b.rerender({ revision: 'r2' })
|
||||
await settle()
|
||||
expect(b.view.getByRole('status').textContent).toBe('Couldn\'t read the activity: downRetry')
|
||||
expect(b.lines()).toEqual(['One1 h agoaaaaaaa'])
|
||||
expect(read).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('reads again when the change request changed, and drops the answer of a read it no longer waits for', async () => {
|
||||
const first = deferred<RemoteResult<ChangeRequestActivity | null>>()
|
||||
const read = vi.fn<ReviewActivityProps['read']>()
|
||||
read.mockReturnValueOnce(first.promise).mockResolvedValueOnce(ok(activity([commit('b', 'Two')])))
|
||||
.mockResolvedValueOnce(ok(activity([commit('c', 'Three')])))
|
||||
const b = await renderActivity(null, { read })
|
||||
b.rerender({ revision: 'r2' })
|
||||
await settle()
|
||||
expect(read.mock.calls[0]?.[1].aborted).toBe(true)
|
||||
first.settle(ok(activity([commit('a', 'One')])))
|
||||
await settle()
|
||||
expect(b.lines()).toEqual(['Two1 h agobbbbbbb'])
|
||||
// Another change request starts without the rows of this one.
|
||||
const next = deferred<RemoteResult<ChangeRequestActivity | null>>()
|
||||
read.mockReset()
|
||||
read.mockReturnValueOnce(next.promise)
|
||||
b.rerender({ url: prUrl(8), revision: 'r2' })
|
||||
await settle()
|
||||
expect(b.lines()).toEqual([])
|
||||
expect(read).toHaveBeenLastCalledWith(prUrl(8), expect.any(AbortSignal))
|
||||
next.settle(failed('forgePanel/activity-failed', 'down'))
|
||||
await settle()
|
||||
expect(b.lines()).toEqual([])
|
||||
expect(b.view.getByRole('status').textContent).toBe('Couldn\'t read the activity: downRetry')
|
||||
})
|
||||
|
||||
it('adds a comment, clears the field, and reads the activity again', async () => {
|
||||
const sent = deferred<RemoteResult<void>>()
|
||||
const comment = vi.fn<ReviewActivityProps['comment']>(() => sent.promise)
|
||||
const read = vi.fn<ReviewActivityProps['read']>(async () => ok(activity([], { viewerCanComment: true })))
|
||||
const b = await renderActivity(null, { read, comment })
|
||||
const field = b.view.getByRole('textbox', { name: 'Leave a comment' }) as HTMLTextAreaElement
|
||||
const button = b.view.getByRole('button', { name: 'Comment' }) as HTMLButtonElement
|
||||
expect(button.disabled).toBe(true)
|
||||
fireEvent.change(field, { target: { value: ' \n' } })
|
||||
expect(button.disabled).toBe(true)
|
||||
fireEvent.change(field, { target: { value: 'Thanks for the fix' } })
|
||||
expect(button.disabled).toBe(false)
|
||||
fireEvent.click(button)
|
||||
expect(comment).toHaveBeenCalledWith(URL7, 'Thanks for the fix')
|
||||
// While the comment is sent, the field keeps its text read-only and neither the button nor the keys send another.
|
||||
expect([field.readOnly, button.disabled, button.textContent]).toEqual([true, true, 'Posting…'])
|
||||
expect(field.closest('[aria-busy="true"]')).not.toBeNull()
|
||||
fireEvent.keyDown(field, { key: 'Enter', ctrlKey: true })
|
||||
expect(comment).toHaveBeenCalledOnce()
|
||||
sent.settle(ok(undefined))
|
||||
await settle()
|
||||
expect(field.value).toBe('')
|
||||
expect([field.readOnly, button.textContent]).toEqual([false, 'Comment'])
|
||||
expect(read).toHaveBeenCalledTimes(2)
|
||||
expect(b.view.queryByRole('alert')).toBeNull()
|
||||
})
|
||||
|
||||
it('says where the comment goes and which keys send it', async () => {
|
||||
const b = await renderActivity(activity([], { viewerCanComment: true }))
|
||||
const composer = b.view.getByRole('textbox', { name: 'Leave a comment' }).parentElement as HTMLElement
|
||||
expect(composer.textContent).toBe('Posts to GitHub · Markdown supportedCtrl+EnterComment')
|
||||
expect((b.view.getByRole('textbox', { name: 'Leave a comment' }) as HTMLTextAreaElement).rows).toBe(3)
|
||||
cleanup()
|
||||
// The desktop shell names an Apple platform on the document; without a provider the hint names no code host.
|
||||
document.documentElement.dataset['platform'] = 'darwin'
|
||||
try {
|
||||
const apple = await renderActivity(activity([], { viewerCanComment: true }), { forge: null })
|
||||
const field = apple.view.getByRole('textbox', { name: 'Leave a comment' })
|
||||
expect(field.parentElement?.textContent).toBe('Markdown supported⌘EnterComment')
|
||||
} finally {
|
||||
delete document.documentElement.dataset['platform']
|
||||
}
|
||||
})
|
||||
|
||||
it('sends on Command or Control with Enter, and not on Enter alone, while composing, or for a blank text', async () => {
|
||||
const comment = vi.fn<ReviewActivityProps['comment']>(async () => ok(undefined))
|
||||
const b = await renderActivity(activity([], { viewerCanComment: true }), { comment })
|
||||
const field = b.view.getByRole('textbox', { name: 'Leave a comment' }) as HTMLTextAreaElement
|
||||
fireEvent.keyDown(field, { key: 'Enter', metaKey: true })
|
||||
fireEvent.change(field, { target: { value: 'First' } })
|
||||
fireEvent.keyDown(field, { key: 'Enter' })
|
||||
fireEvent.keyDown(field, { key: 'a', ctrlKey: true })
|
||||
fireEvent.keyDown(field, { key: 'Enter', ctrlKey: true, isComposing: true })
|
||||
expect(comment).not.toHaveBeenCalled()
|
||||
fireEvent.keyDown(field, { key: 'Enter', ctrlKey: true })
|
||||
await settle()
|
||||
expect(comment).toHaveBeenCalledWith(URL7, 'First')
|
||||
fireEvent.change(field, { target: { value: 'Second' } })
|
||||
fireEvent.keyDown(field, { key: 'Enter', metaKey: true })
|
||||
await settle()
|
||||
expect(comment).toHaveBeenLastCalledWith(URL7, 'Second')
|
||||
})
|
||||
|
||||
it('keeps the text of a comment the host did not save and says why', async () => {
|
||||
const comment = vi.fn<ReviewActivityProps['comment']>()
|
||||
comment.mockResolvedValueOnce(failed('forgePanel/action-failed', 'refused'))
|
||||
.mockResolvedValueOnce(failed('forgePanel/action-unknown', 'no answer'))
|
||||
const read = vi.fn<ReviewActivityProps['read']>(async () => ok(activity([], { viewerCanComment: true })))
|
||||
const b = await renderActivity(null, { read, comment })
|
||||
const field = b.view.getByRole('textbox', { name: 'Leave a comment' }) as HTMLTextAreaElement
|
||||
fireEvent.change(field, { target: { value: 'Thanks' } })
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Comment' }))
|
||||
await settle()
|
||||
expect(b.view.getByRole('alert').textContent).toBe('The comment was not posted: refused')
|
||||
expect(field.value).toBe('Thanks')
|
||||
// An outcome the host did not confirm names where to check before another attempt.
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Comment' }))
|
||||
await settle()
|
||||
expect(b.view.getByRole('alert').textContent).toBe('The submission outcome is unknown. Check GitHub before publishing again.')
|
||||
expect(field.value).toBe('Thanks')
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
// Once the provider left, the page has no product name to point at.
|
||||
comment.mockResolvedValueOnce(failed('forgePanel/action-unknown', 'no answer'))
|
||||
b.rerender({ read, comment, forge: null })
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Comment' }))
|
||||
await settle()
|
||||
expect(b.view.getByRole('alert').textContent).toBe('The comment was not posted: no answer')
|
||||
})
|
||||
})
|
||||
@@ -6,7 +6,7 @@
|
||||
import { act, cleanup, fireEvent, render, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { ChangeRequestDescription, ChangeRequestSnapshot } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { ChangeRequestActivity, ChangeRequestDescription, ChangeRequestSnapshot } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { ChangeRequestActions } from '../src/client/ChangeRequestCard.tsx'
|
||||
@@ -26,6 +26,8 @@ afterEach(() => {
|
||||
const t = makeTranslate(en)
|
||||
const NOW = Date.parse('2026-10-09T02:00:00Z')
|
||||
const URL7 = prUrl(7)
|
||||
/** A site mark, as the link icon draws the marks of known hosts. */
|
||||
const SITE_MARK = 'svg[viewBox="-2 -2 28 28"]'
|
||||
|
||||
function ok<T>(value: T): RemoteResult<T> {
|
||||
return { ok: true, value }
|
||||
@@ -64,7 +66,8 @@ function renderDetail(overrides: Partial<ReviewDetailProps> = {}) {
|
||||
const read = stream(reviewed(7))
|
||||
const props: ReviewDetailProps = {
|
||||
url: URL7, read, tab: 'summary', onTab: vi.fn(), listHidden: false, onToggleList: vi.fn(), onBack: vi.fn(), now: NOW, locale: 'en',
|
||||
actions, readDescription: vi.fn(async () => ok(description('Body'))),
|
||||
actions, readDescription: vi.fn(async () => ok(description('Body'))), readActivity: vi.fn(async () => ok(null)),
|
||||
addComment: vi.fn(async () => ok(undefined)), onAddHost: undefined,
|
||||
renderChanges: vi.fn(() => <p>changes body</p>), renderChat: vi.fn(() => <p>chat body</p>), unseenQuotes: 0, t, ...overrides,
|
||||
}
|
||||
const view = render(<ReviewDetail {...props} />)
|
||||
@@ -77,11 +80,25 @@ function changed(overrides: Partial<ChangeRequestSnapshot>): ForgeReviewChangeRe
|
||||
}
|
||||
|
||||
describe('ReviewDetail before a status', () => {
|
||||
it('waits for the first status, leaving the list from the back button and the list toggle', () => {
|
||||
it('draws the detail as a skeleton until the first status, with the list toggle and the link actions already working', () => {
|
||||
const b = renderDetail({ read: stream(undefined) })
|
||||
const status = b.view.getByRole('status')
|
||||
expect(status.querySelector('[data-state="ongoing"]')).not.toBeNull()
|
||||
expect(status.textContent).toBe('')
|
||||
const detail = b.view.container.querySelector('[data-forge-review-detail]') as HTMLElement
|
||||
expect(detail.getAttribute('aria-busy')).toBe('true')
|
||||
expect(b.view.getByRole('status').textContent).toBe('Reading the change request')
|
||||
expect([...detail.querySelectorAll('[data-forge-review-skeleton]')].map(part => part.getAttribute('data-forge-review-skeleton')))
|
||||
.toEqual(['description', 'activity', 'status'])
|
||||
// The captions of the two sections are fixed text; the title, the tabs, and the status column are not read yet.
|
||||
expect(b.view.getAllByRole('region').map(region => region.getAttribute('aria-label'))).toEqual(['Description', 'Activity'])
|
||||
expect(b.view.queryByRole('heading', { level: 1 })).toBeNull()
|
||||
expect(b.view.queryAllByRole('tab')).toEqual([])
|
||||
expect(b.view.queryByRole('complementary')).toBeNull()
|
||||
// Opening, copying, and reading again need only the URL. No frame has named the provider yet.
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Open in browser' }))
|
||||
expect(b.actions.openLink).toHaveBeenCalledWith(URL7)
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Copy link' }))
|
||||
expect(b.actions.copyLink).toHaveBeenCalledWith(URL7)
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Refresh status' }))
|
||||
expect(b.actions.retry).toHaveBeenCalledOnce()
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Back to list' }))
|
||||
expect(b.props.onBack).toHaveBeenCalledOnce()
|
||||
const toggle = b.view.getByRole('button', { name: 'Hide list' })
|
||||
@@ -92,28 +109,43 @@ describe('ReviewDetail before a status', () => {
|
||||
expect(b.view.getByRole('button', { name: 'Show list' }).getAttribute('aria-pressed')).toBe('false')
|
||||
})
|
||||
|
||||
it('waits while the latest poll has not returned a status yet', () => {
|
||||
it('keeps the skeleton while the latest poll has not returned a status yet, naming the code host once a frame did', () => {
|
||||
const b = renderDetail({ read: stream(reviewed(7, null)) })
|
||||
expect(b.view.getByRole('status').textContent).toBe('')
|
||||
expect(b.view.getByRole('status').textContent).toBe('Reading the change request')
|
||||
expect(b.view.getByRole('button', { name: 'Open on GitHub' })).toBeTruthy()
|
||||
cleanup()
|
||||
const polled = renderDetail({ read: stream({ ...reviewed(7), snapshot: null }) })
|
||||
expect(polled.view.getByRole('status').textContent).toBe('')
|
||||
expect(polled.view.getByRole('status').textContent).toBe('Reading the change request')
|
||||
expect(polled.view.container.querySelector('[data-forge-review-skeleton="status"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('explains a link no enabled code host serves', () => {
|
||||
it('explains a link whose host no code host component serves', () => {
|
||||
const b = renderDetail({ read: stream(undefined, { code: 'forgePanel/unrecognized-url', message: 'no provider' }) })
|
||||
expect(b.view.getByRole('status').textContent).toBe(`${en['reviewPage.unrecognized']}${en['reviewPage.unrecognizedHint']}`)
|
||||
expect(b.view.getByRole('status').textContent).toBe('Unknown code hostThis link\'s host has not been added to a code host component.')
|
||||
expect(b.view.queryByRole('button', { name: 'Retry' })).toBeNull()
|
||||
expect(b.view.queryByRole('button', { name: 'Add host…' })).toBeNull()
|
||||
})
|
||||
|
||||
it('offers the host lists for such a link while they can be opened', () => {
|
||||
const onAddHost = vi.fn()
|
||||
const b = renderDetail({ read: stream(undefined, { code: 'forgePanel/unrecognized-url', message: 'no provider' }), onAddHost })
|
||||
fireEvent.click(within(b.view.getByRole('status')).getByRole('button', { name: 'Add host…' }))
|
||||
expect(onAddHost).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('offers to open the stream again or the browser once the stream stopped', () => {
|
||||
const b = renderDetail({ read: stream(undefined, { code: 'ended', message: '' }) })
|
||||
expect(within(b.view.getByRole('status')).getByText('Couldn\'t read the change request')).toBeTruthy()
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Retry' }))
|
||||
const status = b.view.getByRole('status')
|
||||
fireEvent.click(within(status).getByRole('button', { name: 'Retry' }))
|
||||
expect(b.props.read.retry).toHaveBeenCalledOnce()
|
||||
expect(b.actions.retry).not.toHaveBeenCalled()
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Open in browser' }))
|
||||
fireEvent.click(within(status).getByRole('button', { name: 'Open in browser' }))
|
||||
expect(b.actions.openLink).toHaveBeenCalledWith(URL7)
|
||||
// The header's refresh opens the stream again as well, since a poll cannot reach a stopped stream.
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Refresh status' }))
|
||||
expect(b.props.read.retry).toHaveBeenCalledTimes(2)
|
||||
expect(b.actions.retry).not.toHaveBeenCalled()
|
||||
expect(b.view.container.querySelector('[data-forge-review-skeleton]')).toBeNull()
|
||||
})
|
||||
|
||||
it('names why the poll failed and polls again, or reopens the stream once it also stopped', () => {
|
||||
@@ -171,16 +203,48 @@ describe('ReviewDetail header', () => {
|
||||
expect(b.view.getByRole('button', { name: 'More actions' })).toBeTruthy()
|
||||
})
|
||||
|
||||
it('offers the primary action, and opens, copies, or reads the status from the More menu', () => {
|
||||
it('offers the primary action before the three link actions, which open GitHub, copy with a mark, and read the status again', async () => {
|
||||
vi.useFakeTimers()
|
||||
const b = renderDetail({ read: stream(changed({ draft: true })) })
|
||||
const primary = b.view.getByRole('button', { name: 'Ready for review' })
|
||||
expect(primary.closest(`.${css.primary}`)).not.toBeNull()
|
||||
fireEvent.click(primary)
|
||||
expect(b.actions.markReady).toHaveBeenCalledOnce()
|
||||
|
||||
const links = b.view.container.querySelector('[data-forge-review-actions]') as HTMLElement
|
||||
expect(primary.compareDocumentPosition(links) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0)
|
||||
expect(within(links).getAllByRole('button').map(button => button.getAttribute('aria-label'))).toEqual(['Open on GitHub', 'Copy link', 'Refresh status'])
|
||||
const open = within(links).getByRole('button', { name: 'Open on GitHub' })
|
||||
expect(open.querySelector(SITE_MARK)).not.toBeNull()
|
||||
fireEvent.click(open)
|
||||
expect(b.actions.openLink).toHaveBeenCalledWith(URL7)
|
||||
|
||||
// Copying shows a mark for a moment.
|
||||
const copy = within(links).getByRole('button', { name: 'Copy link' })
|
||||
fireEvent.click(copy)
|
||||
expect(b.actions.copyLink).toHaveBeenCalledWith(URL7)
|
||||
expect(copy.querySelector(`.${css.copied}`)).not.toBeNull()
|
||||
await tick(1500)
|
||||
expect(copy.querySelector(`.${css.copied}`)).toBeNull()
|
||||
|
||||
// The refresh glyph turns until the read it started ends.
|
||||
const read = deferred<undefined>()
|
||||
b.actions.retry.mockReturnValueOnce(read.promise)
|
||||
const refresh = within(links).getByRole('button', { name: 'Refresh status' })
|
||||
fireEvent.click(refresh)
|
||||
expect(b.actions.retry).toHaveBeenCalledOnce()
|
||||
expect(refresh.querySelector('[data-turning]')).not.toBeNull()
|
||||
read.settle(undefined)
|
||||
await tick(0)
|
||||
expect(refresh.querySelector('[data-turning]')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the same three actions in the More menu, which a narrow header shows in their place', () => {
|
||||
const b = renderDetail()
|
||||
const more = b.view.getByRole('button', { name: 'More actions' })
|
||||
expect(more.closest(`.${css.moreAction}`)).not.toBeNull()
|
||||
for (const [row, check] of [
|
||||
['Open in browser', () => { expect(b.actions.openLink).toHaveBeenCalledWith(URL7) }],
|
||||
['Open on GitHub', () => { expect(b.actions.openLink).toHaveBeenCalledWith(URL7) }],
|
||||
['Copy change request link', () => { expect(b.actions.copyLink).toHaveBeenCalledWith(URL7) }],
|
||||
['Refresh status', () => { expect(b.actions.retry).toHaveBeenCalledOnce() }],
|
||||
] as const) {
|
||||
@@ -197,6 +261,76 @@ describe('ReviewDetail header', () => {
|
||||
fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' })
|
||||
expect(more.getAttribute('aria-expanded')).toBe('false')
|
||||
})
|
||||
|
||||
it('marks the opening action with the mark of the provider\'s family, whatever the host name, and with the arrow without one', () => {
|
||||
const gitlab = { forge: 'gitlab', label: 'GitLab', changeRequestNoun: 'merge-request' as const }
|
||||
const b = renderDetail({ read: stream({ ...reviewed(7), forge: gitlab }) })
|
||||
expect(b.view.getByRole('button', { name: 'Open on GitLab' }).querySelector(SITE_MARK)).not.toBeNull()
|
||||
b.rerender({ read: stream({ ...reviewed(7), forge: { ...gitlab, forge: 'gitea', label: 'Gitea' } }) })
|
||||
expect(b.view.getByRole('button', { name: 'Open on Gitea' }).querySelector(SITE_MARK)).toBeNull()
|
||||
b.rerender({ read: stream({ ...reviewed(7), forge: null }) })
|
||||
expect(b.view.getByRole('button', { name: 'Open in browser' }).querySelector(SITE_MARK)).toBeNull()
|
||||
})
|
||||
|
||||
it('cuts a long repository name and keeps its number', () => {
|
||||
const b = renderDetail()
|
||||
const link = b.view.container.querySelector(`.${css.repository}`) as HTMLElement
|
||||
expect([...link.children].map(part => [part.className, part.textContent])).toEqual([[css.repositoryName, 'octo/demo'], [css.number, '#7']])
|
||||
})
|
||||
|
||||
it('offers the automatic merge of a change request the host would not merge yet, and its cancellation once it is on', async () => {
|
||||
const autoMerge = vi.fn<NonNullable<ChangeRequestActions['autoMerge']>>(async () => {})
|
||||
const off = { enabled: false, method: null, enabledBy: null, canEnable: true, canDisable: false }
|
||||
const b = renderDetail({ read: stream(changed({ mergeReady: false, mergeMethods: ['merge', 'squash'], autoMerge: off })) })
|
||||
b.rerender({ actions: { ...b.actions, autoMerge } })
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Auto-merge' }))
|
||||
expect(within(document.body).getByText('Merge #7 into main once its requirements are met')).toBeTruthy()
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: /Squash and merge/ }))
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: 'Enable auto-merge' }))
|
||||
expect(autoMerge).toHaveBeenLastCalledWith(expect.objectContaining({ url: URL7 }), { enabled: true, method: 'squash', headSha: 'a'.repeat(40) })
|
||||
await settle()
|
||||
|
||||
const on = { enabled: true, method: 'squash' as const, enabledBy: 'mona', canEnable: false, canDisable: true }
|
||||
b.rerender({ actions: { ...b.actions, autoMerge }, read: stream(changed({ mergeReady: false, mergeMethods: ['merge', 'squash'], autoMerge: on })) })
|
||||
const status = b.view.getByRole('button', { name: 'Auto-merge enabled' })
|
||||
expect(b.view.queryByRole('button', { name: 'Auto-merge' })).toBeNull()
|
||||
fireEvent.click(status)
|
||||
expect(within(document.body).getByText('Merges into main once its requirements are met')).toBeTruthy()
|
||||
expect(within(document.body).getByText('Method: Squash and merge · Enabled by mona')).toBeTruthy()
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: 'Cancel auto-merge' }))
|
||||
expect(autoMerge).toHaveBeenLastCalledWith(expect.objectContaining({ url: URL7 }), { enabled: false })
|
||||
expect(status.getAttribute('aria-expanded')).toBe('false')
|
||||
await settle()
|
||||
|
||||
// An automatic merge the host names neither the method nor the account of, and that the user may not cancel.
|
||||
const bare = { enabled: true, method: null, enabledBy: null, canEnable: false, canDisable: false }
|
||||
b.rerender({ actions: { ...b.actions, autoMerge }, read: stream(changed({ mergeReady: false, autoMerge: bare })) })
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Auto-merge enabled' }))
|
||||
expect(within(document.body).queryByText(/Method:|Enabled by/)).toBeNull()
|
||||
expect(within(document.body).queryByRole('menuitem', { name: 'Cancel auto-merge' })).toBeNull()
|
||||
fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' })
|
||||
})
|
||||
|
||||
it('shows the merge the host would refuse as unavailable and names why', async () => {
|
||||
vi.useFakeTimers()
|
||||
const blocked = changed({ mergeReady: false, mergeability: 'conflicting', reviewDecision: 'changes-requested', checksRollup: 'failure' })
|
||||
const b = renderDetail({ read: stream(blocked) })
|
||||
const merge = b.view.getByRole('button', { name: 'Merge' })
|
||||
expect(merge.getAttribute('aria-disabled')).toBe('true')
|
||||
expect(merge.getAttribute('aria-haspopup')).toBeNull()
|
||||
fireEvent.pointerEnter(merge)
|
||||
await tick(0)
|
||||
expect(within(document.body).getByRole('tooltip').textContent).toBe('Has merge conflicts, Changes were requested, Checks failed')
|
||||
fireEvent.pointerLeave(merge)
|
||||
// A surface that cannot turn the automatic merge on shows the same button for a change request that allows it.
|
||||
const allowed = { enabled: false, method: null, enabledBy: null, canEnable: true, canDisable: false }
|
||||
b.rerender({ read: stream(changed({ mergeReady: false, autoMerge: allowed })) })
|
||||
expect(b.view.getByRole('button', { name: 'Merge' }).getAttribute('aria-disabled')).toBe('true')
|
||||
expect(b.view.queryByRole('button', { name: 'Auto-merge' })).toBeNull()
|
||||
// A merged change request has no merge action.
|
||||
b.rerender({ read: stream(changed({ state: 'merged', mergeReady: false })) })
|
||||
expect(b.view.queryByRole('button', { name: 'Merge' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReviewDetail tabs', () => {
|
||||
@@ -237,13 +371,61 @@ describe('ReviewDetail tabs', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReviewDetail activity', () => {
|
||||
it('shows the activity under the description, reads it again when the change request or its reviews change, and opens the changes tab', async () => {
|
||||
const activity: ChangeRequestActivity = {
|
||||
items: [{ kind: 'review', at: '2026-10-09T01:00:00Z', actor: { login: 'mona', avatarUrl: null, bot: false }, verdict: 'commented', body: '',
|
||||
comments: 1, url: null }],
|
||||
truncated: false, viewerCanComment: true,
|
||||
}
|
||||
const readActivity = vi.fn<ReviewDetailProps['readActivity']>(async () => ok(activity))
|
||||
const addComment = vi.fn<ReviewDetailProps['addComment']>(async () => ok(undefined))
|
||||
const b = renderDetail({ readActivity, addComment })
|
||||
await settle()
|
||||
const region = b.view.getByRole('region', { name: 'Activity' })
|
||||
expect(region.compareDocumentPosition(b.view.getByRole('region', { name: 'Description' })) & Node.DOCUMENT_POSITION_PRECEDING).not.toBe(0)
|
||||
expect(readActivity).toHaveBeenCalledWith(URL7, expect.any(AbortSignal))
|
||||
fireEvent.click(within(region).getByRole('button', { name: 'mona reviewed · Inline comments: 1, View in Changes' }))
|
||||
expect(b.props.onTab).toHaveBeenCalledWith('changes')
|
||||
|
||||
// A comment goes to the change request the detail shows, and the activity is read again after it.
|
||||
fireEvent.change(within(region).getByRole('textbox', { name: 'Leave a comment' }), { target: { value: 'Thanks' } })
|
||||
fireEvent.click(within(region).getByRole('button', { name: 'Comment' }))
|
||||
await settle()
|
||||
expect(addComment).toHaveBeenCalledWith(URL7, 'Thanks')
|
||||
expect(readActivity).toHaveBeenCalledTimes(2)
|
||||
|
||||
b.rerender({ read: stream(changed({ updatedAt: '2026-10-09T01:30:00Z' })) })
|
||||
await settle()
|
||||
expect(readActivity).toHaveBeenCalledTimes(3)
|
||||
b.rerender({ read: stream({ ...changed({ updatedAt: '2026-10-09T01:30:00Z' }), reviewRevision: 4 }) })
|
||||
await settle()
|
||||
expect(readActivity).toHaveBeenCalledTimes(4)
|
||||
// The link in the activity opens through the detail's own link action.
|
||||
readActivity.mockResolvedValueOnce(ok({ ...activity, truncated: true }))
|
||||
b.rerender({ read: stream({ ...changed({ updatedAt: '2026-10-09T01:30:00Z' }), reviewRevision: 5 }) })
|
||||
await settle()
|
||||
fireEvent.click(within(region).getByRole('button', { name: 'Open on GitHub' }))
|
||||
expect(b.actions.openLink).toHaveBeenCalledWith(URL7)
|
||||
|
||||
// Once the provider left, a comment whose outcome is unknown has no product name to point at.
|
||||
addComment.mockResolvedValueOnce({ ok: false, error: new RemoteError('forgePanel/action-unknown', 'no answer', {}) })
|
||||
b.rerender({ read: stream({ ...changed({ updatedAt: '2026-10-09T01:30:00Z' }), reviewRevision: 5, forge: null }) })
|
||||
fireEvent.change(within(region).getByRole('textbox', { name: 'Leave a comment' }), { target: { value: 'Again' } })
|
||||
fireEvent.click(within(region).getByRole('button', { name: 'Comment' }))
|
||||
await settle()
|
||||
expect(within(region).getByRole('alert').textContent).toBe('The comment was not posted: no answer')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReviewDetail description', () => {
|
||||
it('waits for the description, renders its Markdown, and names an empty one', async () => {
|
||||
const read = deferred<RemoteResult<ChangeRequestDescription>>()
|
||||
const readDescription = vi.fn((_url: string, _signal: AbortSignal) => read.promise)
|
||||
const b = renderDetail({ readDescription })
|
||||
const region = b.view.getByRole('region', { name: 'Description' })
|
||||
expect(region.querySelector('[data-state="ongoing"]')).not.toBeNull()
|
||||
expect(region.getAttribute('aria-busy')).toBeNull()
|
||||
expect(region.querySelector('[data-forge-review-skeleton="description"]')).not.toBeNull()
|
||||
expect(region.textContent).toBe('Description')
|
||||
read.settle(ok(description('Hello **world** <img alt="shot" src="https://example.test/a.png">')))
|
||||
await settle()
|
||||
|
||||
@@ -16,7 +16,7 @@ export function prUrl(number: number): string {
|
||||
|
||||
/**
|
||||
* Open pull request `number` in `octo/demo` by `octo` with passed checks and no review, updated `2026-10-09T00:00:00Z`,
|
||||
* that asks nothing of the signed-in user and closes no issue.
|
||||
* that asks nothing of the signed-in user.
|
||||
*/
|
||||
export function summary(number: number, overrides: Partial<ChangeRequestSummary> = {}): ChangeRequestSummary {
|
||||
return {
|
||||
@@ -30,8 +30,6 @@ export function summary(number: number, overrides: Partial<ChangeRequestSummary>
|
||||
reviewDecision: 'none',
|
||||
viewerReview: null,
|
||||
viewerRequest: null,
|
||||
closingIssues: [],
|
||||
closingIssuesTruncated: false,
|
||||
updatedAt: '2026-10-09T00:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
@@ -51,7 +49,7 @@ export function failedList(code: ForgeFailure['code'], message = 'down'): ForgeR
|
||||
export function host(
|
||||
lists: Partial<Record<ForgeViewerFilter, ForgeReviewList>>, overrides: Partial<ForgeReviewHost> = {},
|
||||
): ForgeReviewHost {
|
||||
return { forge: 'github', host: 'github.com', viewer: 'octo', lists, ...overrides }
|
||||
return { forge: 'github', host: 'github.com', viewer: 'octo', signIn: null, lists, ...overrides }
|
||||
}
|
||||
|
||||
/** A frame of `hosts` with no read in flight. */
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* The review page's list column, its navigation row, and the label line: sections with their items, empty states, and
|
||||
* failures, the search box and pasted links, the filter menu, the navigation count, and labels folding into a chip.
|
||||
* The review page's list column, its navigation row, and the label line: sections with their items and empty states,
|
||||
* the notices of hosts that could not be read, the search box and pasted links, the filter menu of hosts and repositories,
|
||||
* the navigation count, and labels folding into a chip.
|
||||
*/
|
||||
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ChangeRequestIssue, ChangeRequestLabel, ChangeRequestSummary } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { ChangeRequestLabel, ChangeRequestSummary } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import { en } from '../src/client/locales.ts'
|
||||
import { fittingLabels, ReviewLabels } from '../src/client/review-page/ReviewLabels.tsx'
|
||||
import { ReviewList, type ReviewListProps } from '../src/client/review-page/ReviewList.tsx'
|
||||
@@ -31,10 +32,10 @@ const NOW = Date.parse('2026-10-09T00:05:00Z')
|
||||
/** Render the list column with every handler recorded and no choice made, unless `overrides` makes one. */
|
||||
function renderList(overrides: Partial<ReviewListProps> = {}) {
|
||||
const props: ReviewListProps = {
|
||||
frame: undefined, stopped: null, selected: null, query: '', repository: null, repositories: [], directOnly: false, folded: {}, refreshing: false,
|
||||
frame: undefined, stopped: null, selected: null, query: '', scope: null, repositories: [], directOnly: false, folded: {}, refreshing: false,
|
||||
now: NOW, view: 'detailed',
|
||||
onSelect: vi.fn(), onSearch: vi.fn(), onScope: vi.fn(), onToggleDirect: vi.fn(), onView: vi.fn(), onFold: vi.fn(), onRefresh: vi.fn(),
|
||||
onRetry: vi.fn(), copyText: vi.fn(), t, ...overrides,
|
||||
onRetry: vi.fn(), copyText: vi.fn(), onOpenSettings: undefined, t, ...overrides,
|
||||
}
|
||||
const view = render(<ReviewList {...props} />)
|
||||
/** The section of one list. */
|
||||
@@ -52,11 +53,6 @@ function renderList(overrides: Partial<ReviewListProps> = {}) {
|
||||
return { view, props, section, item }
|
||||
}
|
||||
|
||||
function issue(number: number): ChangeRequestIssue {
|
||||
const url = `https://github.com/octo/demo/issues/${number}`
|
||||
return { repository: ref(number).repository, number, title: `Issue ${number}`, state: 'open', url }
|
||||
}
|
||||
|
||||
function inRepository(number: number, owner: string, name: string, overrides: Partial<ChangeRequestSummary> = {}): ChangeRequestSummary {
|
||||
return summary(number, { ref: { ...ref(number), repository: { ...ref(number).repository, owner, name } }, ...overrides })
|
||||
}
|
||||
@@ -158,74 +154,149 @@ describe('ReviewList sections', () => {
|
||||
expect(b.view.queryByText(/more not listed/)).toBeNull()
|
||||
})
|
||||
|
||||
it('shows skeleton rows for a list no host has read yet, and only the failure once a read failed', () => {
|
||||
const b = renderList({ frame: frame(host({ authored: list(null), involved: failedList('unavailable', 'GitHub is down') })) })
|
||||
it('shows skeleton rows for a list no host has read yet while a read runs, and none once every read settled', () => {
|
||||
const lists = frame(host({ authored: list(null), involved: list([summary(1)]) }))
|
||||
const b = renderList({ frame: { ...lists, reading: true } })
|
||||
expect(b.section('authored').querySelectorAll(`[aria-busy="true"] .${css.skeletonItem}`)).toHaveLength(3)
|
||||
expect(within(b.section('authored')).queryByRole('button', { name: /\d/ })).toBeNull()
|
||||
const involved = b.section('involved')
|
||||
expect(involved.querySelector('[aria-busy="true"]')).toBeNull()
|
||||
expect(within(involved).getByRole('status').textContent).toBe('Couldn\'t read the list on github.com: GitHub is down')
|
||||
cleanup()
|
||||
const settled = renderList({ frame: lists })
|
||||
expect(settled.section('authored').querySelector('[aria-busy="true"]')).toBeNull()
|
||||
expect(settled.section('authored').textContent).toBe('Created by me')
|
||||
})
|
||||
|
||||
it('asks the user to sign in to a GitHub host with a command to copy, and to other hosts without one', () => {
|
||||
const b = renderList({ frame: frame(
|
||||
host({ authored: failedList('unauthenticated') }, { host: 'ghe.example' }),
|
||||
it('keeps one skeleton row under the rows of the hosts that answered while another host still reads the list', () => {
|
||||
const slow = { forge: 'gitlab', host: 'gitlab.com' }
|
||||
const lists = frame(
|
||||
host({ authored: list([summary(1)]), involved: list([]) }), host({ authored: list(null), involved: list(null) }, slow),
|
||||
)
|
||||
const b = renderList({ frame: { ...lists, reading: true } })
|
||||
// The count and the empty text wait for the host that has not answered.
|
||||
expect(b.section('authored').querySelectorAll('[data-forge-review-item]')).toHaveLength(1)
|
||||
expect(b.section('authored').querySelectorAll(`[aria-busy="true"] .${css.skeletonItem}`)).toHaveLength(1)
|
||||
expect(within(b.section('authored')).getByRole('button', { name: /Created by me/ }).textContent).toBe('Created by me')
|
||||
expect(b.section('involved').querySelectorAll(`[aria-busy="true"] .${css.skeletonItem}`)).toHaveLength(3)
|
||||
expect(within(b.section('involved')).queryByText('No change requests')).toBeNull()
|
||||
cleanup()
|
||||
// A host that failed is not waited for: its notice reports it.
|
||||
const failed = frame(host({ authored: list([summary(1)]) }), host({ authored: failedList('unavailable') }, slow))
|
||||
const c = renderList({ frame: { ...failed, reading: true } })
|
||||
expect(c.section('authored').querySelector('[aria-busy="true"]')).toBeNull()
|
||||
expect(within(c.section('authored')).getByRole('button', { name: /Created by me/ }).textContent).toBe('Created by me1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReviewList hosts that could not be read', () => {
|
||||
it('reports each host once after the sections, with its sign-in command and the way to the settings', () => {
|
||||
const onOpenSettings = vi.fn()
|
||||
const b = renderList({ onOpenSettings, frame: frame(
|
||||
host({ 'authored': list([summary(1)]), 'review-requested': failedList('rate-limited'), 'involved': list([]) }),
|
||||
host({ authored: failedList('unauthenticated'), involved: failedList('unauthenticated') }, { host: 'ghe.example', signIn: 'gh auth login --hostname ghe.example' }),
|
||||
host({ involved: failedList('unauthenticated') }, { forge: 'gitlab', host: 'gitlab.example' }),
|
||||
host({ 'review-requested': failedList('rate-limited') }),
|
||||
host({ involved: failedList('unavailable', 'glab could not start') }, { forge: 'gitlab', host: 'gitlab.com' }),
|
||||
) })
|
||||
const github = within(b.section('authored')).getByRole('status')
|
||||
expect(github.textContent).toContain('Sign in to ghe.example to list your change requests')
|
||||
expect(within(github).getByText('gh auth login --hostname ghe.example')).toBeTruthy()
|
||||
fireEvent.click(within(github).getByRole('button', { name: 'Copy sign-in command' }))
|
||||
const notices = b.view.getAllByRole('status')
|
||||
expect(notices.map(notice => notice.getAttribute('data-forge-review-failure'))).toEqual(['github.com', 'ghe.example', 'gitlab.example', 'gitlab.com'])
|
||||
// The notices follow the last section instead of repeating inside each one.
|
||||
expect(b.section('involved').parentElement?.lastElementChild?.contains(notices[0] ?? null)).toBe(true)
|
||||
expect(b.view.container.querySelector('[data-forge-review-section] [role="status"]')).toBeNull()
|
||||
const [limited, enterprise, gitlab, down] = notices as [HTMLElement, HTMLElement, HTMLElement, HTMLElement]
|
||||
expect(limited.textContent).toBe(`Couldn't read the list on github.com: ${en['change.failure.rateLimited']}Open settings`)
|
||||
expect(enterprise.textContent).toContain('Sign in to ghe.example to list your change requests')
|
||||
expect(within(enterprise).getByText('gh auth login --hostname ghe.example')).toBeTruthy()
|
||||
fireEvent.click(within(enterprise).getByRole('button', { name: 'Copy sign-in command' }))
|
||||
expect(b.props.copyText).toHaveBeenCalledWith('gh auth login --hostname ghe.example')
|
||||
const gitlab = within(b.section('involved')).getByRole('status')
|
||||
expect(gitlab.textContent).toBe('Sign in to gitlab.example to list your change requests')
|
||||
expect(within(gitlab).queryByRole('button')).toBeNull()
|
||||
expect(within(b.section('review-requested')).getByRole('status').textContent).toBe(en['change.failure.rateLimited'])
|
||||
// A provider that names no sign-in command leaves the notice without one.
|
||||
expect(gitlab.textContent).toBe('Sign in to gitlab.example to list your change requestsOpen settings')
|
||||
expect(within(gitlab).queryByRole('button', { name: 'Copy sign-in command' })).toBeNull()
|
||||
expect(down.textContent).toBe('Couldn\'t read the list on gitlab.com: glab could not startOpen settings')
|
||||
fireEvent.click(within(down).getByRole('button', { name: 'Open settings' }))
|
||||
expect(onOpenSettings).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('shows only the notices once no host listed anything, without a settings button while the settings cannot be opened', () => {
|
||||
const lists = frame(
|
||||
host({ 'authored': failedList('unauthenticated'), 'review-requested': failedList('unauthenticated') }, { signIn: 'gh auth login --hostname github.com' }),
|
||||
host({ involved: failedList('unavailable', 'down') }, { forge: 'gitlab', host: 'gitlab.com' }),
|
||||
)
|
||||
const b = renderList({ frame: lists })
|
||||
expect(b.view.container.querySelector('[data-forge-review-section]')).toBeNull()
|
||||
const notices = b.view.getAllByRole('status') as [HTMLElement, HTMLElement]
|
||||
expect(notices).toHaveLength(2)
|
||||
expect(within(notices[0]).getAllByRole('button').map(button => button.textContent)).toEqual(['Copy sign-in command'])
|
||||
expect(notices[1].textContent).toBe('Couldn\'t read the list on gitlab.com: down')
|
||||
expect(within(notices[1]).queryByRole('button')).toBeNull()
|
||||
cleanup()
|
||||
// A later read of the hosts that failed changes nothing on the page until one answers.
|
||||
const reading = renderList({ frame: { ...lists, reading: true } })
|
||||
expect(reading.view.container.querySelector('[data-forge-review-section]')).toBeNull()
|
||||
expect(reading.view.getAllByRole('status')).toHaveLength(2)
|
||||
cleanup()
|
||||
// A host still to answer keeps the sections, with their skeletons above the notices.
|
||||
const first = renderList({ frame: { hosts: [...lists.hosts, host({ authored: list(null) }, { host: 'ghe.example' })], reading: true } })
|
||||
expect(first.section('authored').querySelector('[aria-busy="true"]')).not.toBeNull()
|
||||
expect(first.view.getAllByRole('status')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('leaves out the notices and the lists of hosts other than the one the lists are narrowed to', () => {
|
||||
const b = renderList({ scope: { host: 'github.com' }, frame: frame(
|
||||
host({ authored: list([summary(1)]) }), host({ involved: failedList('unauthenticated') }, { forge: 'gitlab', host: 'gitlab.com' }),
|
||||
) })
|
||||
expect(b.view.queryByRole('status')).toBeNull()
|
||||
expect([...b.view.container.querySelectorAll('[data-forge-review-section]')].map(section => section.getAttribute('data-forge-review-section'))).toEqual(['authored'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReviewList items', () => {
|
||||
it('names an item by its number, author, update time, closing issues, and the hint the user acts on', () => {
|
||||
it('names an item by its number and author with the short update time beside them, then the hint the user acts on', () => {
|
||||
const b = renderList({ frame: frame(host({
|
||||
'review-requested': list([
|
||||
summary(1, {
|
||||
viewerReview: { verdict: 'changes-requested', reviewedSha: null }, viewerRequest: { team: null }, closingIssues: [issue(5)],
|
||||
}),
|
||||
summary(2, { author: null, updatedAt: 'not a time', checksRollup: 'none', closingIssues: [issue(5), issue(6), issue(8)] }),
|
||||
summary(3, {
|
||||
viewerReview: { verdict: 'approved', reviewedSha: 'a'.repeat(40) }, closingIssues: [issue(5)], closingIssuesTruncated: true,
|
||||
}),
|
||||
summary(1, { viewerReview: { verdict: 'changes-requested', reviewedSha: null }, viewerRequest: { team: null } }),
|
||||
summary(2, { author: null, updatedAt: 'not a time', checksRollup: 'none' }),
|
||||
summary(3, { viewerReview: { verdict: 'approved', reviewedSha: 'a'.repeat(40) } }),
|
||||
summary(4, { viewerRequest: { team: 'octo/core' }, checksRollup: 'failure' }),
|
||||
]),
|
||||
})) })
|
||||
const first = b.item(prUrl(1))
|
||||
expect(first.querySelector(`.${css.itemMeta}`)?.textContent).toBe('#1·octo·5 min ago·⊙#5·You requested changes · Requested again')
|
||||
expect(first.querySelector(`.${css.itemMeta} .${css.itemHint}`)?.textContent).toBe('You requested changes · Requested again')
|
||||
expect(first.querySelector(`.${css.itemLine}`)?.textContent).toBe('#1·octo')
|
||||
expect(first.querySelector(`.${css.itemMeta} > .${css.itemTime}`)?.textContent).toBe('5min')
|
||||
// The hint stands beside the number and the author, so it shares their line where it fits and wraps below it where it does not.
|
||||
expect(first.querySelector(`.${css.itemFacts} > .${css.itemHint}`)?.textContent).toBe('Re-review requested')
|
||||
expect(first.querySelector(`.${css.itemHint}`)?.getAttribute('data-tone')).toBe('error')
|
||||
expect(first.querySelector('[data-forge-glyph]')?.getAttribute('data-tone')).toBe('open')
|
||||
expect(first.querySelector('[data-checks]')?.getAttribute('data-checks')).toBe('success')
|
||||
|
||||
const second = b.item(prUrl(2))
|
||||
expect(second.querySelector(`.${css.itemMeta}`)?.textContent).toBe('#2·⊙#5and 2 more')
|
||||
expect(second.querySelector(`.${css.itemMeta}`)?.textContent).toBe('#2')
|
||||
expect(second.querySelector(`.${css.itemTime}`)).toBeNull()
|
||||
expect(second.querySelector(`.${css.itemHint}`)).toBeNull()
|
||||
expect(second.querySelector('[data-checks]')).toBeNull()
|
||||
|
||||
const third = b.item(prUrl(3))
|
||||
expect(third.querySelector(`.${css.itemIssues}`)?.textContent).toBe('⊙#5and 1+ more')
|
||||
expect(third.querySelector(`.${css.itemHint}`)?.textContent).toBe('You approved')
|
||||
expect(third.querySelector(`.${css.itemHint}`)?.getAttribute('data-tone')).toBe('success')
|
||||
|
||||
const fourth = b.item(prUrl(4))
|
||||
expect(fourth.querySelector(`.${css.itemMeta}`)?.textContent).toBe('#4·octo·5 min ago·Team octo/core')
|
||||
expect(fourth.querySelector(`.${css.itemFacts}`)?.textContent).toBe('#4·octoTeam octo/core')
|
||||
expect(fourth.querySelector(`.${css.itemHint}`)?.textContent).toBe('Team octo/core')
|
||||
expect(fourth.querySelector(`.${css.itemHint}`)?.hasAttribute('data-tone')).toBe(false)
|
||||
expect(fourth.querySelector('[data-forge-glyph]')?.getAttribute('data-tone')).toBe('blocked')
|
||||
})
|
||||
|
||||
it('names each item\'s repository once the lists span more than one', () => {
|
||||
it('names each item\'s repository before its number once the lists span more than one', () => {
|
||||
const b = renderList({ frame: frame(host({ authored: list([summary(1), inRepository(2, 'acme', 'widgets')]) })) })
|
||||
expect(b.item(prUrl(1)).querySelector(`.${css.itemMeta}`)?.firstChild?.textContent).toBe('demo#1')
|
||||
expect(b.item(prUrl(2)).querySelector(`.${css.itemMeta}`)?.firstChild?.textContent).toBe('widgets#2')
|
||||
expect(b.item(prUrl(1)).querySelector(`.${css.itemName}`)?.textContent).toBe('demo#1')
|
||||
expect(b.item(prUrl(2)).querySelector(`.${css.itemName} > .${css.itemRepository}`)?.textContent).toBe('widgets')
|
||||
expect(b.item(prUrl(2)).querySelector(`.${css.itemName} > .${css.itemNumber}`)?.textContent).toBe('#2')
|
||||
cleanup()
|
||||
const single = renderList({ frame: frame(host({ authored: list([summary(1)]) })) })
|
||||
expect(single.item(prUrl(1)).querySelector(`.${css.itemRepository}`)).toBeNull()
|
||||
cleanup()
|
||||
// Narrowed to one host, the lists span the repositories of that host only.
|
||||
const narrowed = renderList({ scope: { host: 'github.com' }, frame: frame(
|
||||
host({ authored: list([summary(1)]) }), host({ authored: list([inRepository(2, 'acme', 'widgets')]) }, { forge: 'gitlab', host: 'gitlab.example' }),
|
||||
) })
|
||||
expect(narrowed.item(prUrl(1)).querySelector(`.${css.itemRepository}`)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -256,9 +327,7 @@ describe('ReviewList compact view', () => {
|
||||
it('names the full title and every fact of the detailed item in a hover card that copies the title', () => {
|
||||
vi.useFakeTimers()
|
||||
const b = renderList({ view: 'compact', frame: frame(host({ 'review-requested': list([
|
||||
summary(1, {
|
||||
viewerReview: { verdict: 'changes-requested', reviewedSha: null }, viewerRequest: { team: null }, closingIssues: [issue(5)],
|
||||
}),
|
||||
summary(1, { viewerReview: { verdict: 'changes-requested', reviewedSha: null }, viewerRequest: { team: null } }),
|
||||
inRepository(2, 'acme', 'widgets', { author: null, updatedAt: 'not a time' }),
|
||||
]) })) })
|
||||
fireEvent.pointerEnter(b.item(prUrl(1)))
|
||||
@@ -268,11 +337,11 @@ describe('ReviewList compact view', () => {
|
||||
act(() => { vi.advanceTimersByTime(1) })
|
||||
const first = screen.getByRole('button', { name: 'Copy title: Change 1' })
|
||||
expect(first.querySelector(`.${css.compactCardTitle}`)?.textContent).toBe('Change 1')
|
||||
expect(first.querySelector(`.${css.itemMeta}`)?.textContent).toBe('octo/demo#1·octo·5 min ago·⊙#5')
|
||||
expect(first.querySelector(`.${css.itemHint}`)?.textContent).toBe('You requested changes · Requested again')
|
||||
expect(first.querySelector(`.${css.cardMeta}`)?.textContent).toBe('octo/demo#1·octo·5 min ago')
|
||||
expect(first.querySelector(`.${css.itemHint}`)?.textContent).toBe('Re-review requested')
|
||||
expect(first.querySelector(`.${css.itemHint}`)?.getAttribute('data-tone')).toBe('error')
|
||||
const second = screen.getByRole('button', { name: 'Copy title: Change 2' })
|
||||
expect(second.querySelector(`.${css.itemMeta}`)?.textContent).toBe('acme/widgets#2')
|
||||
expect(second.querySelector(`.${css.cardMeta}`)?.textContent).toBe('acme/widgets#2')
|
||||
expect(second.querySelector(`.${css.itemHint}`)).toBeNull()
|
||||
cleanup()
|
||||
|
||||
@@ -281,7 +350,17 @@ describe('ReviewList compact view', () => {
|
||||
fireEvent.pointerEnter(single.item(prUrl(3)))
|
||||
act(() => { vi.advanceTimersByTime(800) })
|
||||
const card = screen.getByRole('button', { name: 'Copy title: Change 3' })
|
||||
expect(card.querySelector(`.${css.itemMeta}`)?.textContent).toBe('#3·octo·5 min ago')
|
||||
expect(card.querySelector(`.${css.cardMeta}`)?.textContent).toBe('#3·octo·5 min ago')
|
||||
cleanup()
|
||||
|
||||
// Once the lists span more than one host, the card starts with the host.
|
||||
const hosts = renderList({ view: 'compact', frame: frame(
|
||||
host({ authored: list([summary(4)]) }), host({ authored: list([inRepository(5, 'group/sub', 'app')]) }, { forge: 'gitlab', host: 'gitlab.example' }),
|
||||
) })
|
||||
fireEvent.pointerEnter(hosts.item(prUrl(5)))
|
||||
act(() => { vi.advanceTimersByTime(800) })
|
||||
expect(screen.getByRole('button', { name: 'Copy title: Change 5' }).querySelector(`.${css.cardMeta}`)?.textContent)
|
||||
.toBe('gitlab.example·group/sub/app#5·octo·5 min ago')
|
||||
})
|
||||
|
||||
it('marquees a clipped title while the item is hovered and returns it on leave', () => {
|
||||
@@ -382,7 +461,7 @@ describe('ReviewList filter menu', () => {
|
||||
const button = open(b)
|
||||
expect(repositories()).toEqual(['All repositories', 'acme/widgets', 'octo/demo'])
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: 'acme/widgets' }))
|
||||
expect(b.props.onScope).toHaveBeenCalledWith({ owner: 'acme', name: 'widgets' })
|
||||
expect(b.props.onScope).toHaveBeenCalledWith({ host: 'github.com', owner: 'acme', name: 'widgets' })
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false')
|
||||
open(b)
|
||||
repositories()
|
||||
@@ -397,40 +476,71 @@ describe('ReviewList filter menu', () => {
|
||||
})
|
||||
|
||||
it('keeps offering a chosen repository whose lists are empty, and names the chosen repository on its row', () => {
|
||||
const b = renderList({ frame: lists, repository: { owner: 'zeta', name: 'empty' } })
|
||||
const b = renderList({ frame: lists, scope: { host: 'github.com', owner: 'zeta', name: 'empty' } })
|
||||
const button = open(b)
|
||||
expect(button.matches(`.${css.iconButtonActive}`)).toBe(true)
|
||||
expect(within(document.body).getByRole('menuitem', { name: /^Repository/ }).textContent).toBe('Repositoryzeta/empty')
|
||||
expect(repositories()).toEqual(['All repositories', 'acme/widgets', 'octo/demo', 'zeta/empty'])
|
||||
cleanup()
|
||||
|
||||
const listed = renderList({ frame: lists, repository: { owner: 'acme', name: 'widgets' } })
|
||||
const listed = renderList({ frame: lists, scope: { host: 'github.com', owner: 'acme', name: 'widgets' } })
|
||||
open(listed)
|
||||
expect(within(document.body).getByRole('menuitem', { name: /^Repository/ }).textContent).toBe('Repositoryacme/widgets')
|
||||
expect(repositories()).toEqual(['All repositories', 'acme/widgets', 'octo/demo'])
|
||||
})
|
||||
|
||||
it('keeps offering the repositories remembered from every repository while the lists are read in one, marking the chosen one', () => {
|
||||
const remembered = [{ owner: 'acme', name: 'widgets' }, { owner: 'octo', name: 'demo' }, { owner: 'zeta', name: 'tools' }]
|
||||
const remembered = ['acme/widgets', 'octo/demo', 'zeta/tools'].map((path) => {
|
||||
const [owner = '', name = ''] = path.split('/')
|
||||
return { host: 'github.com', owner, name }
|
||||
})
|
||||
// Lists read in octo/demo name only that repository.
|
||||
const scoped = frame(host({ authored: list([summary(1)]) }))
|
||||
const b = renderList({ frame: scoped, repository: { owner: 'octo', name: 'demo' }, repositories: remembered })
|
||||
const b = renderList({ frame: scoped, scope: { host: 'github.com', owner: 'octo', name: 'demo' }, repositories: remembered })
|
||||
open(b)
|
||||
expect(repositories()).toEqual(['All repositories', 'acme/widgets', 'octo/demo', 'zeta/tools'])
|
||||
const child = within(document.body).getAllByRole('menu').at(-1) as HTMLElement
|
||||
expect(within(child).getAllByRole('menuitem').map(row => row.querySelector(CHECK) !== null)).toEqual([false, false, true, false])
|
||||
// Another repository is one choice away, without returning to every repository first.
|
||||
fireEvent.click(within(child).getByRole('menuitem', { name: 'zeta/tools' }))
|
||||
expect(b.props.onScope).toHaveBeenCalledWith({ owner: 'zeta', name: 'tools' })
|
||||
expect(b.props.onScope).toHaveBeenCalledWith({ host: 'github.com', owner: 'zeta', name: 'tools' })
|
||||
cleanup()
|
||||
|
||||
// The offer also survives the wait for the chosen repository's first frame.
|
||||
const waiting = renderList({ repository: { owner: 'octo', name: 'demo' }, repositories: remembered })
|
||||
const waiting = renderList({ scope: { host: 'github.com', owner: 'octo', name: 'demo' }, repositories: remembered })
|
||||
open(waiting)
|
||||
expect(repositories()).toEqual(['All repositories', 'acme/widgets', 'octo/demo', 'zeta/tools'])
|
||||
expect(within(document.body).queryByText('Reading the lists', { selector: '[role="menu"] *' })).toBeNull()
|
||||
})
|
||||
|
||||
it('offers each host with its repositories below it once the lists name repositories on more than one host', () => {
|
||||
const two = frame(
|
||||
host({ authored: list([summary(1), inRepository(2, 'acme', 'widgets')]) }),
|
||||
host({ involved: list([inRepository(3, 'group/sub', 'app')]) }, { forge: 'gitlab', host: 'gitlab.example' }),
|
||||
)
|
||||
const b = renderList({ frame: two })
|
||||
open(b)
|
||||
expect(repositories()).toEqual(['All repositories', 'github.com', 'acme/widgets', 'octo/demo', 'gitlab.example', 'group/sub/app'])
|
||||
const offered = within(within(document.body).getAllByRole('menu').at(-1) as HTMLElement).getAllByRole('menuitem')
|
||||
// A repository stands below the row of its host.
|
||||
expect(offered.map(row => row.querySelector(`.${css.menuNested}`) !== null)).toEqual([false, false, true, true, false, true])
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: 'gitlab.example' }))
|
||||
expect(b.props.onScope).toHaveBeenCalledWith({ host: 'gitlab.example' })
|
||||
cleanup()
|
||||
|
||||
const narrowed = renderList({ frame: two, scope: { host: 'gitlab.example' } })
|
||||
const button = open(narrowed)
|
||||
expect(button.matches(`.${css.iconButtonActive}`)).toBe(true)
|
||||
expect(within(document.body).getByRole('menuitem', { name: /^Repository/ }).textContent).toBe('Repositorygitlab.example')
|
||||
repositories()
|
||||
const rows = within(within(document.body).getAllByRole('menu').at(-1) as HTMLElement).getAllByRole('menuitem')
|
||||
expect(rows.map(row => row.querySelector(CHECK) !== null)).toEqual([false, false, false, false, true, false])
|
||||
// Only the chosen host's change requests show, and a nested group's project is one choice.
|
||||
expect([...narrowed.view.container.querySelectorAll('[data-forge-review-item]')].map(item => item.getAttribute('data-forge-review-item'))).toEqual([prUrl(3)])
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: 'group/sub/app' }))
|
||||
expect(narrowed.props.onScope).toHaveBeenCalledWith({ host: 'gitlab.example', owner: 'group/sub', name: 'app' })
|
||||
})
|
||||
|
||||
it('says that the lists are still read while no repository was remembered and a read is under way', () => {
|
||||
const reading = (): boolean => within(document.body).getAllByRole('menu').at(-1)?.textContent?.includes('Reading the lists') === true
|
||||
const first = renderList()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* The review page's list helpers and store: list sections and their search, the repositories the lists name, item hints
|
||||
* and tones, pasted links, description Markdown, and the page's choices.
|
||||
* The review page's list helpers and store: list sections and their search, the hosts that failed, the repositories and
|
||||
* scopes the lists name, item hints and tones, pasted links, description Markdown, and the page's choices.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
@@ -8,8 +8,8 @@ import type { ChangeRequestSummary } from '@deepseek-ai/dsh-experimental-forge/t
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { TextSearchIndex } from '@deepseek-ai/dsh-util-text-search'
|
||||
import {
|
||||
descriptionMarkdown, mergeRepositories, pastedUrl, REVIEW_FILTERS, reviewHint, reviewListsComplete, reviewRepositories, reviewSearchKeys,
|
||||
reviewSections, summaryTone,
|
||||
descriptionMarkdown, mergeRepositories, pastedUrl, REVIEW_FILTERS, reviewFailures, reviewHint, reviewListsComplete, reviewRepositories,
|
||||
reviewSearchKeys, reviewSections, sameScope, scopeRepository, summaryTone,
|
||||
} from '../src/client/review-page/review-lists.ts'
|
||||
import { createReviewStore } from '../src/client/review-page/review-store.ts'
|
||||
import { ref } from './client-fixtures.client.ts'
|
||||
@@ -27,7 +27,7 @@ function urls(sections: ReturnType<typeof reviewSections>): Record<string, reado
|
||||
|
||||
describe('reviewSections', () => {
|
||||
it('shows no section before the first frame', () => {
|
||||
expect(reviewSections(undefined, false)).toEqual([])
|
||||
expect(reviewSections(undefined, false, null)).toEqual([])
|
||||
})
|
||||
|
||||
it('shows one section per offered list in page order, newest first, summing totals over hosts and marking cut lists', () => {
|
||||
@@ -35,32 +35,53 @@ describe('reviewSections', () => {
|
||||
const newer = summary(2, { updatedAt: '2026-10-05T00:00:00Z' })
|
||||
const middle = summary(4, { updatedAt: '2026-10-03T00:00:00Z' })
|
||||
const requested = summary(3)
|
||||
const sections = reviewSections(frame(
|
||||
const lists = frame(
|
||||
host({ 'authored': list([older, newer], { total: 5 }), 'review-requested': list([requested]) }),
|
||||
host({ authored: list([middle]) }, { forge: 'gitlab', host: 'gitlab.example' }),
|
||||
), false)
|
||||
)
|
||||
const sections = reviewSections(lists, false, null)
|
||||
expect(REVIEW_FILTERS).toEqual(['review-requested', 'authored', 'involved'])
|
||||
expect(sections.map(section => section.filter)).toEqual(['review-requested', 'authored'])
|
||||
expect(sections[1]?.items?.map(item => [item.summary.ref.number, item.forge, item.host])).toEqual([
|
||||
[2, 'github', 'github.com'], [4, 'gitlab', 'gitlab.example'], [1, 'github', 'github.com'],
|
||||
])
|
||||
expect(sections[1]).toMatchObject({ total: 6, truncated: true, failure: null })
|
||||
expect(sections[0]).toMatchObject({ total: 1, truncated: false, failure: null })
|
||||
expect(sections[1]).toEqual(expect.objectContaining({ total: 6, truncated: true }))
|
||||
expect(sections[0]).toEqual(expect.objectContaining({ total: 1, truncated: false }))
|
||||
})
|
||||
|
||||
it('reports the first failure of any host, keeping the items a host read and null items before any host read the list', () => {
|
||||
it('marks a list some host has neither read nor failed to read, and no list whose hosts all answered or failed', () => {
|
||||
const lists = frame(
|
||||
host({ 'authored': list([summary(1)]), 'review-requested': list(null), 'involved': list([]) }),
|
||||
host({ authored: list(null), involved: failedList('unavailable') }, { forge: 'gitlab', host: 'gitlab.example' }),
|
||||
)
|
||||
expect(reviewSections(lists, false, null).map(section => [section.filter, section.items?.length ?? null, section.pending])).toEqual([
|
||||
['review-requested', null, true], ['authored', 1, true], ['involved', 0, false],
|
||||
])
|
||||
// The host that has not answered is out of a reader's narrowed lists.
|
||||
expect(reviewSections(lists, false, 'github.com').map(section => section.pending)).toEqual([true, false, false])
|
||||
})
|
||||
|
||||
it('shows only the lists of the host the reader narrowed them to', () => {
|
||||
const lists = frame(
|
||||
host({ 'authored': list([summary(1), summary(2)], { total: 5 }), 'review-requested': list([summary(3)]) }),
|
||||
host({ authored: list([summary(4)]) }, { forge: 'gitlab', host: 'gitlab.example' }),
|
||||
)
|
||||
expect(reviewSections(lists, false, 'gitlab.example')).toEqual([
|
||||
{ filter: 'authored', items: [{ summary: summary(4), forge: 'gitlab', host: 'gitlab.example' }], total: 1, truncated: false, pending: false },
|
||||
])
|
||||
expect(reviewSections(lists, false, 'github.com').map(section => [section.filter, section.total])).toEqual([['review-requested', 1], ['authored', 5]])
|
||||
expect(reviewSections(lists, false, 'other.example')).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps the items a host read while its latest read failed, and null items before any host read the list', () => {
|
||||
const sections = reviewSections(frame(
|
||||
host({
|
||||
involved: list([summary(1)], { failure: { code: 'rate-limited', message: 'slow down' } }), authored: failedList('unauthenticated'),
|
||||
}),
|
||||
host({ involved: failedList('unavailable'), authored: failedList('unavailable') }, { host: 'ghe.example' }),
|
||||
), false)
|
||||
), false, null)
|
||||
expect(urls(sections)).toEqual({ authored: null, involved: ['https://github.com/octo/demo/pull/1'] })
|
||||
expect(sections.map(section => section.failure)).toEqual([
|
||||
{ host: 'github.com', forge: 'github', failure: { code: 'unauthenticated', message: 'down' } },
|
||||
{ host: 'github.com', forge: 'github', failure: { code: 'rate-limited', message: 'slow down' } },
|
||||
])
|
||||
expect(sections[0]).toMatchObject({ total: 0, truncated: false })
|
||||
expect(sections[0]).toEqual({ filter: 'authored', items: null, total: 0, truncated: false, pending: false })
|
||||
})
|
||||
|
||||
it('leaves out review requests made only of one of the user\'s teams from the review-requested list when asked', () => {
|
||||
@@ -68,20 +89,23 @@ describe('reviewSections', () => {
|
||||
const direct = summary(2, { viewerRequest: { team: null }, updatedAt: '2026-10-08T00:00:00Z' })
|
||||
const none = summary(3, { updatedAt: '2026-10-07T00:00:00Z' })
|
||||
const lists = frame(host({ 'review-requested': list([team, direct, none]), 'authored': list([team]) }))
|
||||
expect(urls(reviewSections(lists, true))).toEqual({
|
||||
expect(urls(reviewSections(lists, true, null))).toEqual({
|
||||
'review-requested': ['https://github.com/octo/demo/pull/2', 'https://github.com/octo/demo/pull/3'],
|
||||
'authored': ['https://github.com/octo/demo/pull/1'],
|
||||
})
|
||||
expect(reviewSections(lists, false)[0]?.items).toHaveLength(3)
|
||||
expect(reviewSections(lists, false, null)[0]?.items).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('offers the title, the number, the repository, and the author to the shared list search', () => {
|
||||
it('offers the title, the number, the repository, the author, and the host to the shared list search', () => {
|
||||
const parser = summary(11, { title: 'Fix the Parser' })
|
||||
const widgets = inRepository(22, 'Acme', 'Widgets', { title: 'Tidy up' })
|
||||
const mona = summary(33, { title: 'Docs', author: { login: 'Mona', avatarUrl: null, bot: true } })
|
||||
const hidden = summary(44, { title: 'Hidden author', author: null })
|
||||
const lists = frame(host({ involved: list([parser, widgets, mona, hidden]) }))
|
||||
const [section] = reviewSections(lists, false)
|
||||
const elsewhere = summary(55, { title: 'Elsewhere' })
|
||||
const lists = frame(
|
||||
host({ involved: list([parser, widgets, mona, hidden]) }), host({ involved: list([elsewhere]) }, { forge: 'gitlab', host: 'gitlab.example' }),
|
||||
)
|
||||
const [section] = reviewSections(lists, false, null)
|
||||
const index = new TextSearchIndex(section?.items ?? [], reviewSearchKeys)
|
||||
const search = (query: string): number[] => index.search(query).map(item => item.summary.ref.number)
|
||||
expect(search(' PARSER ')).toEqual([11])
|
||||
@@ -89,14 +113,54 @@ describe('reviewSections', () => {
|
||||
expect(search('22')).toEqual([22])
|
||||
expect(search('acme/wid')).toEqual([22])
|
||||
expect(search('mon')).toEqual([33])
|
||||
expect(search('gitlab')).toEqual([55])
|
||||
expect(search('github.com')).toEqual([11, 22, 33, 44])
|
||||
// A fuzzy subsequence from a word start finds a title, as the client search rule lets it.
|
||||
expect(search('tdy')).toEqual([22])
|
||||
expect(search('fix docs')).toEqual([])
|
||||
expect(search('zzz')).toEqual([])
|
||||
expect(search(' ')).toEqual([11, 22, 33, 44])
|
||||
expect(search(' ')).toEqual([11, 22, 33, 44, 55])
|
||||
// The section keeps every item and the whole list's size; the search only narrows what shows.
|
||||
expect(section).toMatchObject({ total: 4 })
|
||||
expect(section?.items).toHaveLength(4)
|
||||
expect(section?.total).toBe(5)
|
||||
expect(section?.items).toHaveLength(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('reviewFailures', () => {
|
||||
it('reports each host whose read failed once, with the first failure among its lists and its sign-in command', () => {
|
||||
const lists = frame(
|
||||
host({
|
||||
involved: list([summary(1)], { failure: { code: 'rate-limited', message: 'slow down' } }), authored: failedList('unauthenticated'),
|
||||
}, { signIn: 'gh auth login --hostname github.com' }),
|
||||
host({ involved: list([summary(2)]) }, { host: 'ghe.example' }),
|
||||
host({ involved: failedList('unavailable') }, { forge: 'gitlab', host: 'gitlab.example' }),
|
||||
)
|
||||
expect(reviewFailures(undefined, null)).toEqual([])
|
||||
expect(reviewFailures(lists, null)).toEqual([
|
||||
{ forge: 'github', host: 'github.com', failure: { code: 'unauthenticated', message: 'down' }, signIn: 'gh auth login --hostname github.com' },
|
||||
{ forge: 'gitlab', host: 'gitlab.example', failure: { code: 'unavailable', message: 'down' }, signIn: null },
|
||||
])
|
||||
expect(reviewFailures(lists, 'gitlab.example').map(failure => failure.host)).toEqual(['gitlab.example'])
|
||||
expect(reviewFailures(lists, 'ghe.example')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('review scopes', () => {
|
||||
it('names the repository of a scope and tells two scopes apart by host and repository', () => {
|
||||
const repository = { host: 'github.com', owner: 'octo', name: 'demo' }
|
||||
expect(scopeRepository(null)).toBeNull()
|
||||
expect(scopeRepository({ host: 'github.com' })).toBeNull()
|
||||
expect(scopeRepository(repository)).toBe(repository)
|
||||
expect(sameScope(null, null)).toBe(true)
|
||||
expect(sameScope(null, repository)).toBe(false)
|
||||
expect(sameScope({ host: 'github.com' }, null)).toBe(false)
|
||||
expect(sameScope({ host: 'github.com' }, { host: 'github.com' })).toBe(true)
|
||||
expect(sameScope({ host: 'github.com' }, { host: 'ghe.example' })).toBe(false)
|
||||
expect(sameScope({ host: 'github.com' }, repository)).toBe(false)
|
||||
expect(sameScope(repository, { ...repository })).toBe(true)
|
||||
expect(sameScope(repository, { ...repository, host: 'ghe.example' })).toBe(false)
|
||||
expect(sameScope(repository, { ...repository, owner: 'acme' })).toBe(false)
|
||||
expect(sameScope(repository, { ...repository, name: 'other' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -111,22 +175,26 @@ describe('reviewListsComplete', () => {
|
||||
})
|
||||
|
||||
describe('mergeRepositories', () => {
|
||||
it('merges lists without duplicates, whatever their case, by owner then name', () => {
|
||||
it('merges lists without duplicates, whatever their case, by host, then owner, then name', () => {
|
||||
const on = (host: string, owner: string, name: string): { host: string; owner: string; name: string } => ({ host, owner, name })
|
||||
expect(mergeRepositories()).toEqual([])
|
||||
expect(mergeRepositories(
|
||||
[{ owner: 'octo', name: 'demo' }, { owner: 'acme', name: 'widgets' }], [{ owner: 'Octo', name: 'Demo' }], [{ owner: 'acme', name: 'gears' }],
|
||||
)).toEqual([{ owner: 'acme', name: 'gears' }, { owner: 'acme', name: 'widgets' }, { owner: 'Octo', name: 'Demo' }])
|
||||
[on('github.com', 'octo', 'demo'), on('github.com', 'acme', 'widgets')], [on('github.com', 'Octo', 'Demo')],
|
||||
[on('gitlab.example', 'acme', 'gears'), on('github.com', 'acme', 'gears')],
|
||||
)).toEqual([
|
||||
on('github.com', 'acme', 'gears'), on('github.com', 'acme', 'widgets'), on('github.com', 'Octo', 'Demo'), on('gitlab.example', 'acme', 'gears'),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('reviewRepositories', () => {
|
||||
it('lists each repository the lists name once, by owner then name, skipping lists not read yet', () => {
|
||||
it('lists each repository the lists name once with its host, by host, then owner, then name, skipping lists not read yet', () => {
|
||||
expect(reviewRepositories(undefined)).toEqual([])
|
||||
const repositories = reviewRepositories(frame(
|
||||
host({ authored: list([summary(1), inRepository(2, 'Octo', 'Demo')]), involved: failedList('unavailable') }),
|
||||
host({ 'review-requested': list([inRepository(3, 'acme', 'widgets')]) }, { host: 'ghe.example' }),
|
||||
))
|
||||
expect(repositories).toEqual([{ owner: 'acme', name: 'widgets' }, { owner: 'Octo', name: 'Demo' }])
|
||||
expect(repositories).toEqual([{ host: 'ghe.example', owner: 'acme', name: 'widgets' }, { host: 'github.com', owner: 'Octo', name: 'Demo' }])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -201,7 +269,7 @@ describe('createReviewStore', () => {
|
||||
const store = createReviewStore().create()
|
||||
const { actions } = store
|
||||
expect(store.getSnapshot()).toEqual({
|
||||
selected: null, tab: 'summary', listHidden: false, folded: {}, repository: null, repositories: [], query: '', directOnly: false,
|
||||
selected: null, tab: 'summary', listHidden: false, folded: {}, scope: null, repositories: [], query: '', directOnly: false,
|
||||
conversations: {}, view: 'detailed', unseenQuotes: {}, byTab: {},
|
||||
})
|
||||
actions.tabbed('chat')
|
||||
@@ -210,18 +278,20 @@ describe('createReviewStore', () => {
|
||||
actions.tabbed('changes')
|
||||
actions.toggledList()
|
||||
actions.folded('authored')
|
||||
actions.scopedTo({ owner: 'octo', name: 'demo' })
|
||||
actions.scopedTo({ host: 'github.com', owner: 'octo', name: 'demo' })
|
||||
actions.searched('parser')
|
||||
actions.toggledDirect()
|
||||
expect(store.getSnapshot()).toMatchObject({
|
||||
tab: 'changes', listHidden: true, folded: { authored: true }, repository: { owner: 'octo', name: 'demo' }, query: 'parser',
|
||||
tab: 'changes', listHidden: true, folded: { authored: true }, scope: { host: 'github.com', owner: 'octo', name: 'demo' }, query: 'parser',
|
||||
directOnly: true,
|
||||
})
|
||||
actions.folded('authored')
|
||||
actions.toggledList()
|
||||
actions.toggledDirect()
|
||||
actions.scopedTo({ host: 'gitlab.example' })
|
||||
expect(store.getSnapshot().scope).toEqual({ host: 'gitlab.example' })
|
||||
actions.scopedTo(null)
|
||||
expect(store.getSnapshot()).toMatchObject({ listHidden: false, folded: { authored: false }, repository: null, directOnly: false })
|
||||
expect(store.getSnapshot()).toMatchObject({ listHidden: false, folded: { authored: false }, scope: null, directOnly: false })
|
||||
|
||||
const first = brandString<SessionId>('s1')
|
||||
const second = brandString<SessionId>('s2')
|
||||
@@ -238,8 +308,8 @@ describe('createReviewStore', () => {
|
||||
it('records the repositories of every repository\'s lists: a read under way adds to the record, a complete read replaces it', () => {
|
||||
const store = createReviewStore().create()
|
||||
const { actions } = store
|
||||
const demo = { owner: 'octo', name: 'demo' }
|
||||
const widgets = { owner: 'acme', name: 'widgets' }
|
||||
const demo = { host: 'github.com', owner: 'octo', name: 'demo' }
|
||||
const widgets = { host: 'github.com', owner: 'acme', name: 'widgets' }
|
||||
actions.listed([demo], false)
|
||||
actions.listed([widgets], false)
|
||||
expect(store.getSnapshot().repositories).toEqual([widgets, demo])
|
||||
@@ -249,8 +319,9 @@ describe('createReviewStore', () => {
|
||||
expect(store.getSnapshot().repositories).toBe(recorded)
|
||||
actions.listed([demo], true)
|
||||
expect(store.getSnapshot().repositories).toEqual([demo])
|
||||
actions.listed([{ owner: 'octo', name: 'other' }], true)
|
||||
expect(store.getSnapshot().repositories).toEqual([{ owner: 'octo', name: 'other' }])
|
||||
// The same repository on another host is another repository.
|
||||
actions.listed([{ ...demo, host: 'ghe.example' }], true)
|
||||
expect(store.getSnapshot().repositories).toEqual([{ host: 'ghe.example', owner: 'octo', name: 'demo' }])
|
||||
})
|
||||
|
||||
it('shows the list in the view the reader chose', () => {
|
||||
|
||||
@@ -14,7 +14,7 @@ import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-tes
|
||||
import type { SessionAreaProps } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ChangeRequestSnapshot, ForgeCommitList, ForgeReviewThread, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { ChangeRequestActions } from '../src/client/ChangeRequestCard.tsx'
|
||||
import type { ViewAnnotations } from '../src/client/annotations.ts'
|
||||
@@ -34,7 +34,8 @@ import type {
|
||||
ForgeChangeRequestDiff, ForgeDiffFile, ForgeExtensionState, ForgeReviewChangeRequest, ForgeReviewFrame,
|
||||
} from '../src/types.ts'
|
||||
import { entry, ready, ref, snapshot } from './client-fixtures.client.ts'
|
||||
import { description, fed, frame, host, list, prUrl, reviewed, summary, type Fed } from './review-fixtures.client.ts'
|
||||
import { description, failedList, fed, frame, host, list, prUrl, reviewed, summary, type Fed } from './review-fixtures.client.ts'
|
||||
import type { ReviewRepository } from '../src/client/review-page/review-lists.ts'
|
||||
import { reviewThread } from './thread-fixtures.client.ts'
|
||||
|
||||
const t = makeTranslate(en)
|
||||
@@ -136,6 +137,7 @@ function renderPage(threads: readonly ForgeReviewThread[] = []) {
|
||||
openInMain: vi.fn<ReviewChatFace['openInMain']>(),
|
||||
requestWorktree: vi.fn<ReviewChatFace['requestWorktree']>(),
|
||||
}
|
||||
const pluginNavigation = createSnapshotStore(false)
|
||||
const conversations: ForgeReviewConversationProps[] = []
|
||||
const renderSlot = ((_key: string, owner: ForgeReviewConversationProps) => {
|
||||
conversations.push(owner)
|
||||
@@ -146,8 +148,9 @@ function renderPage(threads: readonly ForgeReviewThread[] = []) {
|
||||
}
|
||||
const props: ReviewPageProps = {
|
||||
useLocale: bindSnapshotSelector(createSnapshotStore('en')),
|
||||
openLists: vi.fn((scope: string, signal: AbortSignal) => {
|
||||
const stream = fed<ForgeReviewFrame>(scope, signal)
|
||||
usePluginNavigation: bindSnapshotSelector(pluginNavigation),
|
||||
openLists: vi.fn((repository: ReviewRepository | null, signal: AbortSignal) => {
|
||||
const stream = fed<ForgeReviewFrame>(repository === null ? '' : `${repository.host} ${repository.owner}/${repository.name}`, signal)
|
||||
lists.push(stream)
|
||||
return stream
|
||||
}),
|
||||
@@ -163,6 +166,9 @@ function renderPage(threads: readonly ForgeReviewThread[] = []) {
|
||||
return refresh.promise
|
||||
}),
|
||||
readDescription: vi.fn(async () => ok(description('Body'))),
|
||||
readActivity: vi.fn(async () => ok(null)),
|
||||
addComment: vi.fn(async () => ok(undefined)),
|
||||
openHostSettings: vi.fn(),
|
||||
actionsFor: vi.fn((_url: string, showChanges: () => void): ChangeRequestActions => {
|
||||
shown.push(showChanges)
|
||||
return { openLink: vi.fn(), copyLink: vi.fn(), retry: vi.fn(), viewChanges: () => { showChanges() } }
|
||||
@@ -190,7 +196,7 @@ function renderPage(threads: readonly ForgeReviewThread[] = []) {
|
||||
return element
|
||||
}
|
||||
return {
|
||||
view, props, store, lists, details, refreshes, shown, changes, chat, conversations, page,
|
||||
view, props, store, lists, details, refreshes, shown, changes, chat, conversations, page, pluginNavigation,
|
||||
list: () => last(lists), detail: () => last(details),
|
||||
}
|
||||
}
|
||||
@@ -228,7 +234,7 @@ async function quoteComment(section: HTMLElement, body: string): Promise<void> {
|
||||
describe('ReviewPage lists', () => {
|
||||
it('lists the change requests of every repository beside a placeholder until one is chosen', async () => {
|
||||
const b = renderPage()
|
||||
expect(b.props.openLists).toHaveBeenCalledWith('', b.list().signal)
|
||||
expect(b.props.openLists).toHaveBeenCalledWith(null, b.list().signal)
|
||||
expect(b.props.openChangeRequest).not.toHaveBeenCalled()
|
||||
expect(b.view.getByText('Select a change request')).toBeTruthy()
|
||||
b.list().push(frame(host({ authored: list([summary(7)]) })))
|
||||
@@ -243,9 +249,9 @@ describe('ReviewPage lists', () => {
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Filter' }))
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: /^Repository/ }))
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: 'octo/demo' }))
|
||||
expect(b.store.getSnapshot().repository).toEqual({ owner: 'octo', name: 'demo' })
|
||||
expect(b.store.getSnapshot().scope).toEqual({ host: 'github.com', owner: 'octo', name: 'demo' })
|
||||
expect(b.lists[0]?.disposed).toHaveBeenCalledOnce()
|
||||
expect(b.list().key).toBe('octo/demo')
|
||||
expect(b.props.openLists).toHaveBeenLastCalledWith({ host: 'github.com', owner: 'octo', name: 'demo' }, b.list().signal)
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Filter' }))
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: 'Only requests made of me' }))
|
||||
expect(b.store.getSnapshot().directOnly).toBe(true)
|
||||
@@ -277,14 +283,14 @@ describe('ReviewPage lists', () => {
|
||||
// A read under way adds what it has read so far; the settled read is the record.
|
||||
b.list().push({ ...frame(host({ 'review-requested': list([summary(7)]), 'authored': list(null) })), reading: true })
|
||||
await settle()
|
||||
expect(b.store.getSnapshot().repositories).toEqual([{ owner: 'octo', name: 'demo' }])
|
||||
expect(b.store.getSnapshot().repositories).toEqual([{ host: 'github.com', owner: 'octo', name: 'demo' }])
|
||||
b.list().push(frame(host({ 'review-requested': list([summary(7)]), 'authored': list([other]) })))
|
||||
await settle()
|
||||
expect(offered()).toEqual(['All repositories', 'acme/widgets', 'octo/demo'])
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: 'acme/widgets' }))
|
||||
|
||||
// The chosen repository's lists name only it, before and after its first frame.
|
||||
expect(b.list().key).toBe('acme/widgets')
|
||||
expect(b.list().key).toBe('github.com acme/widgets')
|
||||
expect(offered()).toEqual(['All repositories', 'acme/widgets', 'octo/demo'])
|
||||
fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' })
|
||||
fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' })
|
||||
@@ -298,7 +304,30 @@ describe('ReviewPage lists', () => {
|
||||
expect(b.store.getSnapshot().repositories).toHaveLength(2)
|
||||
b.list().push(frame(host({ 'review-requested': list([summary(7)]), 'authored': list([]) })))
|
||||
await settle()
|
||||
expect(b.store.getSnapshot().repositories).toEqual([{ owner: 'octo', name: 'demo' }])
|
||||
expect(b.store.getSnapshot().repositories).toEqual([{ host: 'github.com', owner: 'octo', name: 'demo' }])
|
||||
})
|
||||
|
||||
it('narrows the lists to one host on the page, without another stream, and offers the settings from a host that failed while they can be opened', async () => {
|
||||
const b = renderPage()
|
||||
b.list().push(frame(
|
||||
host({ 'review-requested': list([summary(7)]) }),
|
||||
host({ authored: list([summary(8)]) }, { forge: 'gitlab', host: 'gitlab.example' }),
|
||||
host({ involved: failedList('unauthenticated') }, { forge: 'gitlab', host: 'gitlab.com' }),
|
||||
))
|
||||
await settle()
|
||||
expect(b.view.getByRole('status').textContent).toBe('Sign in to gitlab.com to list your change requests')
|
||||
act(() => { b.pluginNavigation.set(true) })
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Open settings' }))
|
||||
expect(b.props.openHostSettings).toHaveBeenCalledOnce()
|
||||
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Filter' }))
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: /^Repository/ }))
|
||||
fireEvent.click(within(document.body).getByRole('menuitem', { name: 'gitlab.example' }))
|
||||
expect(b.store.getSnapshot().scope).toEqual({ host: 'gitlab.example' })
|
||||
expect(b.lists).toHaveLength(1)
|
||||
expect(b.lists[0]?.disposed).not.toHaveBeenCalled()
|
||||
expect([...b.view.container.querySelectorAll('[data-forge-review-item]')].map(item => item.getAttribute('data-forge-review-item'))).toEqual([prUrl(8)])
|
||||
expect(b.view.queryByRole('status')).toBeNull()
|
||||
})
|
||||
|
||||
it('reads every list again once at a time, showing the refresh until it settles', async () => {
|
||||
@@ -327,13 +356,29 @@ describe('ReviewPage lists', () => {
|
||||
b.list().push(frame(host({ authored: list([summary(7)]) })))
|
||||
await settle()
|
||||
const meta = (): string | null | undefined => b.view.container.querySelector(`.${css.itemMeta}`)?.textContent
|
||||
expect(meta()).toBe('#7·octo·5 min ago')
|
||||
expect(meta()).toBe('#7·octo5min')
|
||||
act(() => { vi.advanceTimersByTime(60_000) })
|
||||
expect(meta()).toBe('#7·octo·6 min ago')
|
||||
expect(meta()).toBe('#7·octo6min')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReviewPage detail', () => {
|
||||
it('offers the host lists for a link no provider serves only while the Plugins page can be opened', async () => {
|
||||
const b = renderPage()
|
||||
b.list().push(frame(host({ 'review-requested': list([summary(7)]) })))
|
||||
await settle()
|
||||
fireEvent.click(b.view.container.querySelector(`[data-forge-review-item="${URL7}"]`) ?? document.body)
|
||||
b.detail().fail(new RemoteError('forgePanel/unrecognized-url', 'no provider serves it', {}))
|
||||
await settle()
|
||||
expect(b.view.getByText('Unknown code host')).toBeTruthy()
|
||||
expect(b.view.queryByRole('button', { name: 'Add host…' })).toBeNull()
|
||||
|
||||
act(() => { b.pluginNavigation.set(true) })
|
||||
fireEvent.click(b.view.getByRole('button', { name: 'Add host…' }))
|
||||
|
||||
expect(b.props.openHostSettings).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('shows the chosen change request with its card actions, and goes back to the list', async () => {
|
||||
const b = renderPage()
|
||||
await select(b)
|
||||
|
||||
@@ -4,7 +4,8 @@ import type { Context } from '@deepseek-ai/cordis'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type {
|
||||
ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeProvider,
|
||||
ChangeRequestActivity, ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure,
|
||||
ForgeFailure, ForgeProvider,
|
||||
ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, ForgeViewerFilter,
|
||||
ForgeViewerList, ForgeViewerQuery,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
@@ -279,6 +280,30 @@ describe('forgePanel review page reads', () => {
|
||||
Object.assign(opened.provider, { readDescription: () => Promise.resolve(description) })
|
||||
await expect(panel.reviewDescription(url, signal)).resolves.toEqual(description)
|
||||
|
||||
// A provider that reads no activity has none to show; a read the host refused names the host's reason.
|
||||
await expect(panel.reviewActivity(url, signal)).resolves.toBeNull()
|
||||
const activity: ChangeRequestActivity = {
|
||||
items: [{ kind: 'comment', at: '2026-11-02T00:00:00Z', actor: { login: 'mona', avatarUrl: null, bot: false }, body: 'Looks good', url: null }],
|
||||
truncated: false, viewerCanComment: true,
|
||||
}
|
||||
const readActivity = vi.fn<() => Promise<ChangeRequestActivity | ForgeFailure>>(() => Promise.resolve(activity))
|
||||
Object.assign(opened.provider, { readActivity })
|
||||
await expect(panel.reviewActivity(url, signal)).resolves.toEqual(activity)
|
||||
readActivity.mockResolvedValueOnce({ code: 'rate-limited', message: 'slow down' })
|
||||
await expect(panel.reviewActivity(url, signal)).rejects.toMatchObject({ code: 'forgePanel/activity-failed', message: 'slow down' })
|
||||
|
||||
// A comment reaches the provider as written; a blank one is refused before the host is asked.
|
||||
await expect(panel.reviewComment(url, 'Thanks', signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'This provider adds no comments' })
|
||||
const addComment = vi.fn<() => Promise<ForgeActionFailure | undefined>>(() => Promise.resolve(undefined))
|
||||
Object.assign(opened.provider, { addComment })
|
||||
await expect(panel.reviewComment(url, ' Thanks\n', signal)).resolves.toBeUndefined()
|
||||
expect(addComment).toHaveBeenCalledWith(ref(7), ' Thanks\n', expect.any(AbortSignal))
|
||||
await expect(panel.reviewComment(url, ' \n', signal)).rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'The comment is empty' })
|
||||
expect(addComment).toHaveBeenCalledTimes(1)
|
||||
addComment.mockResolvedValueOnce({ code: 'unknown', message: 'no answer' })
|
||||
await expect(panel.reviewComment(url, 'Thanks', signal)).rejects.toMatchObject({ code: 'forgePanel/action-unknown', message: 'no answer' })
|
||||
|
||||
await expect(panel.reviewChecks(url, HEAD, signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/checks-failed', message: 'This provider does not support complete check reads' })
|
||||
Object.assign(opened.provider, { fetchChecks: () => Promise.resolve(snapshot(ref(7))) })
|
||||
@@ -374,6 +399,20 @@ describe('forgePanel review page actions', () => {
|
||||
await expect(panel.reviewMarkReady(url, signal)).rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'Not a draft' })
|
||||
expect(opened.provider.actions).toEqual(['ready 7', `merge 7 squash ${HEAD}`, `merge 7 rebase ${HEAD}`, 'ready 7'])
|
||||
|
||||
// The automatic merge reaches the provider as asked; one that sets none fails without asking the host.
|
||||
const on = { enabled: true as const, method: 'squash' as const, headSha: HEAD }
|
||||
await expect(panel.reviewSetAutoMerge(url, on, signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'This provider sets no automatic merge' })
|
||||
const setAutoMerge = vi.fn<NonNullable<ForgeProvider['setAutoMerge']>>(() => Promise.resolve(undefined))
|
||||
Object.assign(opened.provider, { setAutoMerge })
|
||||
await expect(panel.reviewSetAutoMerge(url, on, signal)).resolves.toBeUndefined()
|
||||
await expect(panel.reviewSetAutoMerge(url, { enabled: false }, signal)).resolves.toBeUndefined()
|
||||
expect(setAutoMerge.mock.calls.map(([target, request]) => [target, request])).toEqual([[ref(7), on], [ref(7), { enabled: false }]])
|
||||
setAutoMerge.mockResolvedValueOnce({ code: 'stale', message: 'Head moved' })
|
||||
await expect(panel.reviewSetAutoMerge(url, on, signal)).rejects.toMatchObject({ code: 'forgePanel/stale-head', message: 'Head moved' })
|
||||
setAutoMerge.mockResolvedValueOnce({ code: 'unknown', message: 'no answer' })
|
||||
await expect(panel.reviewSetAutoMerge(url, on, signal)).rejects.toMatchObject({ code: 'forgePanel/action-unknown', message: 'no answer' })
|
||||
|
||||
await expect(panel.reviewRerunChecks(url, { headSha: HEAD }, signal))
|
||||
.rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'This provider reruns no checks' })
|
||||
await expect(panel.reviewReviewerCandidates(url, '', signal))
|
||||
@@ -435,6 +474,8 @@ describe('forgePanel review page actions', () => {
|
||||
() => panel.reviewPoll(UNSERVED, signal),
|
||||
() => changeRequest(opened, UNSERVED).pull(),
|
||||
() => panel.reviewDescription(UNSERVED, signal),
|
||||
() => panel.reviewActivity(UNSERVED, signal),
|
||||
() => panel.reviewComment(UNSERVED, 'Thanks', signal),
|
||||
() => panel.reviewChecks(UNSERVED, HEAD, signal),
|
||||
() => panel.reviewThreads(UNSERVED, HEAD, false, signal),
|
||||
() => panel.reviewThreadWrite(UNSERVED, write, signal),
|
||||
@@ -446,6 +487,7 @@ describe('forgePanel review page actions', () => {
|
||||
() => panel.reviewSetViewed(UNSERVED, { path: 'src/a.ts', viewed: true, headSha: HEAD }, signal),
|
||||
() => panel.reviewMarkReady(UNSERVED, signal),
|
||||
() => panel.reviewMerge(UNSERVED, 'merge', HEAD, signal),
|
||||
() => panel.reviewSetAutoMerge(UNSERVED, { enabled: false }, signal),
|
||||
() => panel.reviewRerunChecks(UNSERVED, { headSha: HEAD }, signal),
|
||||
() => panel.reviewRequestReviews(UNSERVED, [{ kind: 'user', login: 'mona' }], signal),
|
||||
() => panel.reviewReviewerCandidates(UNSERVED, '', signal),
|
||||
@@ -472,6 +514,8 @@ describe('forgePanel review page actions', () => {
|
||||
() => panel.reviewRefresh(aborted),
|
||||
() => panel.reviewPoll(url, aborted),
|
||||
() => panel.reviewDescription(url, aborted),
|
||||
() => panel.reviewActivity(url, aborted),
|
||||
() => panel.reviewComment(url, 'Thanks', aborted),
|
||||
() => panel.reviewChecks(url, HEAD, aborted),
|
||||
() => panel.reviewThreads(url, HEAD, false, aborted),
|
||||
() => panel.reviewDiff(url, null, aborted),
|
||||
@@ -479,6 +523,7 @@ describe('forgePanel review page actions', () => {
|
||||
() => panel.reviewText(url, HEAD, 'src/a.ts', aborted),
|
||||
() => panel.reviewViewed(url, HEAD, false, aborted),
|
||||
() => panel.reviewMarkReady(url, aborted),
|
||||
() => panel.reviewSetAutoMerge(url, { enabled: false }, aborted),
|
||||
() => panel.reviewStage(opened.session.id, url, aborted),
|
||||
]
|
||||
|
||||
@@ -535,7 +580,7 @@ describe('forgePanel review lists', () => {
|
||||
const { provider, registration } = await registerViewer(opened)
|
||||
const read = await lists.until(frame => !frame.reading && frame.hosts[0]?.viewer === 'mona')
|
||||
const listed = { items: [], total: 2, fetchedAt: ANY_TIME, failure: null }
|
||||
expect(read.hosts).toEqual([{ forge: 'viewer', host: 'view.test', viewer: 'mona', lists: { 'review-requested': listed, authored: listed } }])
|
||||
expect(read.hosts).toEqual([{ forge: 'viewer', host: 'view.test', viewer: 'mona', signIn: null, lists: { 'review-requested': listed, authored: listed } }])
|
||||
expect(provider.queries).toEqual([
|
||||
{ host: 'view.test', filter: 'review-requested', repository: null, limit: 10 },
|
||||
{ host: 'view.test', filter: 'authored', repository: null, limit: 10 },
|
||||
@@ -552,7 +597,7 @@ describe('forgePanel review lists', () => {
|
||||
const { provider } = await registerViewer(opened)
|
||||
provider.list = () => Promise.reject(new Error('gh crashed'))
|
||||
const warn = vi.spyOn(opened.ctx.logger, 'warn').mockImplementation(() => undefined)
|
||||
const lists = streamed<ForgeReviewFrame>(stop => opened.ctx.forgePanel.reviewLists({ owner: 'octo', name: 'demo' }, stop))
|
||||
const lists = streamed<ForgeReviewFrame>(stop => opened.ctx.forgePanel.reviewLists({ host: 'view.test', owner: 'octo', name: 'demo' }, stop))
|
||||
|
||||
const failed = await lists.until(frame => !frame.reading && (frame.hosts[0]?.lists.authored?.failure ?? null) !== null)
|
||||
expect(failed.hosts[0]?.lists['review-requested']?.failure).toEqual({ code: 'unavailable', message: 'gh crashed' })
|
||||
@@ -560,6 +605,21 @@ describe('forgePanel review lists', () => {
|
||||
expect(warn).toHaveBeenCalledWith('forge-panel: reading a review list failed: Error: gh crashed')
|
||||
})
|
||||
|
||||
it('names the provider\'s sign-in command beside the lists of a host that refuses the viewer', async () => {
|
||||
const opened = await page()
|
||||
const { provider } = await registerViewer(opened)
|
||||
provider.list = () => Promise.resolve({ code: 'unauthenticated', message: 'sign in' })
|
||||
const lists = streamed<ForgeReviewFrame>(stop => opened.ctx.forgePanel.reviewLists(null, stop))
|
||||
|
||||
// A provider that names no command leaves the host without one.
|
||||
const unnamed = await lists.until(frame => !frame.reading && (frame.hosts[0]?.lists.authored?.failure ?? null) !== null)
|
||||
expect(unnamed.hosts[0]?.signIn).toBeNull()
|
||||
provider.readiness = () => Promise.resolve({ state: 'unauthenticated', message: 'sign in', signIn: { command: 'viewer auth login' } })
|
||||
await opened.ctx.forgePanel.reviewRefresh(signal)
|
||||
const refused = await lists.until(frame => !frame.reading && (frame.hosts[0]?.signIn ?? null) !== null)
|
||||
expect(refused.hosts[0]).toEqual(expect.objectContaining({ host: 'view.test', viewer: null, signIn: 'viewer auth login' }))
|
||||
})
|
||||
|
||||
it('streams the review request count from count reads and from lists of every repository', async () => {
|
||||
const opened = await page()
|
||||
const { registration } = await registerViewer(opened)
|
||||
|
||||
@@ -29,7 +29,7 @@ afterEach(() => {
|
||||
|
||||
function actions(overrides: Partial<ThreadActions> = {}): ThreadActions {
|
||||
return {
|
||||
author: 'octo', focused: null,
|
||||
author: 'octo', focused: null, forge: 'github',
|
||||
addToInput: vi.fn(() => true), openLink: vi.fn(), readText: vi.fn(async (): Promise<RemoteResult<string>> => ({ ok: true, value: 'a\nb\nc' })),
|
||||
inputFailed: vi.fn(),
|
||||
writes: null,
|
||||
@@ -270,7 +270,10 @@ describe('ThreadCard', () => {
|
||||
fireEvent.click(view.getByRole('button', { name: en['review.addToInput'] }))
|
||||
expect(shared.addToInput).toHaveBeenCalledWith(thread, 'R3')
|
||||
expect(shared.inputFailed).toHaveBeenCalledOnce()
|
||||
fireEvent.click(view.getByRole('button', { name: hostCopy('thread.openOnHost') }))
|
||||
// The action that opens the thread on its code host carries that host's mark.
|
||||
const open = view.getByRole('button', { name: hostCopy('thread.openOnHost') })
|
||||
expect(open.querySelector('svg[viewBox="-2 -2 28 28"]')).not.toBeNull()
|
||||
fireEvent.click(open)
|
||||
expect(shared.openLink).toHaveBeenCalledWith(thread.comments[0]?.url)
|
||||
})
|
||||
|
||||
@@ -368,7 +371,7 @@ describe('ThreadList', () => {
|
||||
function list(overrides: Partial<ThreadListProps> = {}) {
|
||||
const props: ThreadListProps = {
|
||||
entries: [], files: [], truncated: false, url: 'https://github.com/octo/demo/pull/7', filter: 'all', claim: false,
|
||||
claimed: vi.fn(), choose: vi.fn(), open: vi.fn(), openLink: vi.fn(), close: vi.fn(), t, ...overrides,
|
||||
claimed: vi.fn(), choose: vi.fn(), open: vi.fn(), openLink: vi.fn(), forge: 'github', close: vi.fn(), t, ...overrides,
|
||||
}
|
||||
return { props, view: render(<ThreadList {...props} />) }
|
||||
}
|
||||
@@ -378,7 +381,9 @@ describe('ThreadList', () => {
|
||||
cleanup()
|
||||
const { view } = list({ entries: [{ thread: reviewThread(), place: { kind: 'line', side: 'R', startLine: 3, endLine: 3 } }], filter: 'resolved' })
|
||||
expect(view.getByText(en['thread.none'])).toBeDefined()
|
||||
expect(view.getByRole('button', { name: hostCopy('thread.openAll') }).parentElement?.textContent).toBe(hostCopy('thread.openAll'))
|
||||
const all = view.getByRole('button', { name: hostCopy('thread.openAll') })
|
||||
expect(all.parentElement?.textContent).toBe(hostCopy('thread.openAll'))
|
||||
expect(all.querySelector('svg[viewBox="-2 -2 28 28"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('orders each file\'s threads from file threads to lines to outdated ones and describes each', () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
checkCounts, checkDuration, ciSummary, flagOf, needsAttention, numberOf, toneOf,
|
||||
checkCounts, checkDuration, ciSummary, flagOf, mergeBlockers, needsAttention, numberOf, toneOf,
|
||||
} from '../src/client/status.ts'
|
||||
import { check, entry, ref, snapshot, unserved } from './client-fixtures.client.ts'
|
||||
|
||||
@@ -147,3 +147,16 @@ describe('checkDuration', () => {
|
||||
expect(checkDuration(check('test', overrides))).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('mergeBlockers', () => {
|
||||
it('names each reason the snapshot shows, the conflict first', () => {
|
||||
const blocked = snapshot(7, { mergeability: 'conflicting', reviewDecision: 'changes-requested', checksRollup: 'failure' })
|
||||
expect(mergeBlockers(blocked)).toEqual(['change.blocked.conflict', 'change.blocked.changesRequested', 'change.blocked.checksFailed'])
|
||||
expect(mergeBlockers(snapshot(7, { reviewDecision: 'review-required', checksRollup: 'pending' })))
|
||||
.toEqual(['change.blocked.reviewRequired', 'change.blocked.checksPending'])
|
||||
})
|
||||
|
||||
it('names the general reason when the snapshot shows none, as for a user without the right to merge', () => {
|
||||
expect(mergeBlockers(snapshot(7, { mergeability: 'mergeable', reviewDecision: 'approved', checksRollup: 'success' }))).toEqual(['change.blocked.other'])
|
||||
})
|
||||
})
|
||||
@@ -22,8 +22,6 @@ function summary(number: number, repository = 'demo'): ChangeRequestSummary {
|
||||
reviewDecision: 'none',
|
||||
viewerReview: null,
|
||||
viewerRequest: null,
|
||||
closingIssues: [],
|
||||
closingIssuesTruncated: false,
|
||||
updatedAt: '2026-11-10T09:00:00Z',
|
||||
}
|
||||
}
|
||||
@@ -32,9 +30,11 @@ function summary(number: number, repository = 'demo'): ChangeRequestSummary {
|
||||
interface RegistryFake extends ViewerListSources {
|
||||
readonly calls: ForgeViewerQuery[]
|
||||
readonly counts: string[]
|
||||
readonly signIns: string[]
|
||||
readonly reported: unknown[]
|
||||
answer: (query: ForgeViewerQuery, signal: AbortSignal) => Promise<ForgeViewerList | ForgeFailure>
|
||||
answerCount: (host: string) => Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>
|
||||
answerCount: (host: string, signal: AbortSignal) => Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure>
|
||||
answerSignIn: (host: string, signal: AbortSignal) => Promise<string | null>
|
||||
sourcesNow: ForgeViewerSource[]
|
||||
}
|
||||
|
||||
@@ -42,20 +42,26 @@ function registry(sources: ForgeViewerSource[]): RegistryFake {
|
||||
const fake: RegistryFake = {
|
||||
calls: [],
|
||||
counts: [],
|
||||
signIns: [],
|
||||
reported: [],
|
||||
sourcesNow: sources,
|
||||
answer: async (query: ForgeViewerQuery): Promise<ForgeViewerList | ForgeFailure> =>
|
||||
await Promise.resolve({ viewer: 'octo', items: [summary(query.filter === 'authored' ? 2 : 1)], total: 3 }),
|
||||
answerCount: async (): Promise<ReadonlyMap<ForgeViewerFilter, number> | ForgeFailure> =>
|
||||
await Promise.resolve(new Map([['review-requested', 7]])),
|
||||
answerSignIn: async host => await Promise.resolve(`gh auth login --hostname ${host}`),
|
||||
sources: () => fake.sourcesNow,
|
||||
list: async (_forge: string, query: ForgeViewerQuery, signal: AbortSignal) => {
|
||||
fake.calls.push(query)
|
||||
return await fake.answer(query, signal)
|
||||
},
|
||||
count: async (_forge: string, host: string) => {
|
||||
count: async (_forge: string, host: string, signal: AbortSignal) => {
|
||||
fake.counts.push(host)
|
||||
return await fake.answerCount(host)
|
||||
return await fake.answerCount(host, signal)
|
||||
},
|
||||
signIn: async (_forge: string, host: string, signal: AbortSignal) => {
|
||||
fake.signIns.push(host)
|
||||
return await fake.answerSignIn(host, signal)
|
||||
},
|
||||
report: (error: unknown) => { fake.reported.push(error) },
|
||||
}
|
||||
@@ -64,6 +70,14 @@ function registry(sources: ForgeViewerSource[]): RegistryFake {
|
||||
|
||||
const github: ForgeViewerSource = { forge: 'github', hosts: ['github.com'], filters: ALL, maxItems: 50 }
|
||||
|
||||
const gitlab: ForgeViewerSource = { forge: 'gitlab', hosts: ['gitlab.example'], filters: ALL, maxItems: 10 }
|
||||
|
||||
const refused = async (): Promise<ForgeFailure> => await Promise.resolve({ code: 'unauthenticated', message: 'sign in' })
|
||||
|
||||
/** A read that settles only when its signal aborts, as a provider's read does. */
|
||||
const pending = async (_host: string, signal: AbortSignal): Promise<never> =>
|
||||
await new Promise<never>((_resolve, reject) => { signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) })
|
||||
|
||||
const hubs: ViewerLists[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -136,9 +150,9 @@ describe('ViewerLists', () => {
|
||||
const fake = registry([github])
|
||||
const lists = hub(fake, { ...timing, listIntervalMs: 60_000 })
|
||||
const controller = new AbortController()
|
||||
const read = follow(lists.lists({ owner: 'octo', name: 'demo' }, controller.signal))
|
||||
const read = follow(lists.lists({ host: 'github.com', owner: 'octo', name: 'demo' }, controller.signal))
|
||||
await until(read, frame => !frame.reading && frame.hosts[0]?.lists.involved?.items !== null)
|
||||
fake.answer = async () => await Promise.resolve({ code: 'unauthenticated', message: 'sign in' })
|
||||
fake.answer = refused
|
||||
fake.calls.length = 0
|
||||
lists.refresh()
|
||||
const failed = await until(read, frame => (frame.hosts[0]?.lists.involved?.failure ?? null) !== null)
|
||||
@@ -194,7 +208,7 @@ describe('ViewerLists', () => {
|
||||
await read.done
|
||||
})
|
||||
|
||||
it('shares one reader per repository scope, waits between rounds, backs off after failures, and stops with its last stream', async () => {
|
||||
it('shares one reader per repository scope, reads a failing host again later each time, and stops with its last stream', async () => {
|
||||
vi.useFakeTimers()
|
||||
const fake = registry([github])
|
||||
fake.answer = async () => await Promise.resolve({ code: 'not-found', message: 'gone' })
|
||||
@@ -223,6 +237,152 @@ describe('ViewerLists', () => {
|
||||
expect(fake.calls).toHaveLength(15)
|
||||
})
|
||||
|
||||
it('keeps the cadence of the other hosts while it reads a failing host again later each time, and reads every host on a refresh', async () => {
|
||||
vi.useFakeTimers()
|
||||
const fake = registry([github, { ...gitlab, filters: new Set(['authored']) }])
|
||||
fake.answer = async query => await Promise.resolve(query.host === 'gitlab.example'
|
||||
? { code: 'unavailable', message: 'down' } : { viewer: 'octo', items: [], total: 0 })
|
||||
const lists = hub(fake)
|
||||
const controller = new AbortController()
|
||||
const read = follow(lists.lists(null, controller.signal))
|
||||
const reads = (): number[] => ['github.com', 'gitlab.example'].map(host => fake.calls.filter(call => call.host === host).length)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(reads()).toEqual([3, 1])
|
||||
// github.com is read every second; gitlab.example after two seconds, then four, then the largest delay of five.
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(reads()).toEqual([6, 1])
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(reads()).toEqual([9, 2])
|
||||
await vi.advanceTimersByTimeAsync(3_999)
|
||||
expect(reads()).toEqual([18, 2])
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(reads()).toEqual([21, 3])
|
||||
lists.refresh()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(reads()).toEqual([24, 4])
|
||||
controller.abort()
|
||||
await read.done
|
||||
})
|
||||
|
||||
it('reads a repository scope only on the host the repository is on, whatever case names it', async () => {
|
||||
vi.useFakeTimers()
|
||||
const fake = registry([github, gitlab])
|
||||
const lists = hub(fake)
|
||||
const controller = new AbortController()
|
||||
const read = follow(lists.lists({ host: 'GitLab.Example', owner: 'group/sub', name: 'app' }, controller.signal))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(read.frames.at(-1)?.hosts.map(host => host.host)).toEqual(['gitlab.example'])
|
||||
expect(fake.calls.map(call => [call.host, call.filter, call.repository])).toEqual([
|
||||
['gitlab.example', 'review-requested', { owner: 'group/sub', name: 'app' }],
|
||||
['gitlab.example', 'authored', { owner: 'group/sub', name: 'app' }],
|
||||
['gitlab.example', 'involved', { owner: 'group/sub', name: 'app' }],
|
||||
])
|
||||
controller.abort()
|
||||
await read.done
|
||||
})
|
||||
|
||||
it('keeps the sign-in command of a host that refuses the viewer, without asking for it again, until a read succeeds', async () => {
|
||||
vi.useFakeTimers()
|
||||
const fake = registry([github])
|
||||
const accepted = fake.answer
|
||||
fake.answer = refused
|
||||
const lists = hub(fake)
|
||||
const controller = new AbortController()
|
||||
const read = follow(lists.lists(null, controller.signal))
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(read.frames.at(-1)?.hosts[0]).toEqual(expect.objectContaining({ signIn: 'gh auth login --hostname github.com', viewer: null }))
|
||||
lists.refresh()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(fake.signIns).toEqual(['github.com'])
|
||||
fake.answer = accepted
|
||||
lists.refresh()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(read.frames.at(-1)?.hosts[0]).toEqual(expect.objectContaining({ signIn: null, viewer: 'octo' }))
|
||||
controller.abort()
|
||||
await read.done
|
||||
})
|
||||
|
||||
it('lists a refused host without a sign-in command when its provider names none or cannot be asked', async () => {
|
||||
vi.useFakeTimers()
|
||||
const fake = registry([github])
|
||||
fake.answer = refused
|
||||
fake.answerSignIn = async () => await Promise.resolve(null)
|
||||
const lists = hub(fake)
|
||||
const controller = new AbortController()
|
||||
const read = follow(lists.lists(null, controller.signal))
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(read.frames.at(-1)?.hosts[0]?.signIn).toBeNull()
|
||||
fake.answerSignIn = async () => await Promise.reject(new Error('no provider'))
|
||||
lists.refresh()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(read.frames.at(-1)?.hosts[0]?.signIn).toBeNull()
|
||||
expect(fake.signIns).toEqual(['github.com', 'github.com'])
|
||||
expect(fake.reported).toEqual([new Error('no provider')])
|
||||
controller.abort()
|
||||
await read.done
|
||||
})
|
||||
|
||||
it('ends a stream whose sign-in command or count is still being read, without recording or reporting that read', async () => {
|
||||
vi.useFakeTimers()
|
||||
const fake = registry([github])
|
||||
fake.answer = refused
|
||||
fake.answerSignIn = pending
|
||||
fake.answerCount = pending
|
||||
const lists = hub(fake)
|
||||
const listing = new AbortController()
|
||||
const counting = new AbortController()
|
||||
const read = follow(lists.lists(null, listing.signal))
|
||||
const counts = follow<ForgeReviewCountFrame>(lists.count(counting.signal))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(fake.signIns).toEqual(['github.com'])
|
||||
expect(fake.counts).toEqual(['github.com'])
|
||||
listing.abort()
|
||||
counting.abort()
|
||||
await Promise.all([read.done, counts.done])
|
||||
expect(read.frames.at(-1)?.hosts[0]?.signIn).toBeNull()
|
||||
expect(counts.frames).toEqual([{ reviewRequested: null }])
|
||||
expect(fake.reported).toEqual([])
|
||||
})
|
||||
|
||||
it('lists a host whose provider offers no list with no lists and reads nothing on it', async () => {
|
||||
vi.useFakeTimers()
|
||||
const fake = registry([{ ...gitlab, filters: new Set() }])
|
||||
const lists = hub(fake)
|
||||
const controller = new AbortController()
|
||||
const read = follow(lists.lists(null, controller.signal))
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(read.frames.at(-1)).toEqual({ hosts: [{ forge: 'gitlab', host: 'gitlab.example', viewer: null, signIn: null, lists: {} }], reading: false })
|
||||
expect(fake.calls).toEqual([])
|
||||
controller.abort()
|
||||
await read.done
|
||||
})
|
||||
|
||||
it('reads the count of a failing host again later each time while the other hosts keep their cadence', async () => {
|
||||
vi.useFakeTimers()
|
||||
const fake = registry([github, gitlab])
|
||||
fake.answerCount = async host => await Promise.resolve(host === 'gitlab.example'
|
||||
? { code: 'unavailable', message: 'down' } : new Map<ForgeViewerFilter, number>([['review-requested', 7]]))
|
||||
const lists = hub(fake)
|
||||
const controller = new AbortController()
|
||||
const counts = follow<ForgeReviewCountFrame>(lists.count(controller.signal))
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(fake.counts).toEqual(['github.com', 'gitlab.example'])
|
||||
expect(counts.frames.at(-1)).toEqual({ reviewRequested: 7 })
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
expect(fake.counts).toEqual(['github.com', 'gitlab.example', 'github.com'])
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
expect(fake.counts).toEqual(['github.com', 'gitlab.example', 'github.com', 'github.com', 'gitlab.example'])
|
||||
lists.refresh()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(fake.counts).toHaveLength(7)
|
||||
controller.abort()
|
||||
await counts.done
|
||||
})
|
||||
|
||||
it('counts review requests from its own reads and from lists of every repository', async () => {
|
||||
vi.useFakeTimers()
|
||||
const fake = registry([github, { forge: 'other', hosts: ['other.example'], filters: new Set(['authored']), maxItems: 5 }])
|
||||
@@ -268,7 +428,7 @@ describe('ViewerLists', () => {
|
||||
})
|
||||
|
||||
it('forgets hosts whose provider left, publishes that, and reads the hosts that remain', async () => {
|
||||
const fake = registry([github, { forge: 'gitlab', hosts: ['gitlab.example'], filters: ALL, maxItems: 10 }])
|
||||
const fake = registry([github, gitlab])
|
||||
const lists = hub(fake)
|
||||
const controller = new AbortController()
|
||||
const read = follow(lists.lists(null, controller.signal))
|
||||
|
||||
@@ -30,8 +30,8 @@
|
||||
en: 0192ab064b8000a7
|
||||
zh: 1a1de04f87631b9a
|
||||
/deepseek-ai-dsh-experimental-forge-bundle/known-limitations-and-deferred-work:
|
||||
en: 0c681a81348e10e3
|
||||
zh: 40d04b43b23e4259
|
||||
en: 7446ae5ff50a9540
|
||||
zh: 05b3b00cc35b32db
|
||||
/deepseek-ai-dsh-experimental-forge-bundle/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -63,7 +63,7 @@ Enabling or disabling the bundle changes the model's tool schema list. Calls app
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- The bundle serves github.com and gitlab.com only; a GitHub Enterprise or self-managed GitLab host needs a profile patch that lists it in the `forge-github` row's [`hosts`](../forge-github/README.md#use-this-package) or the `forge-gitlab` row's [`hosts`](../forge-gitlab/README.md#use-this-package). No provider recognizes other code hosts.
|
||||
- The bundle serves github.com and gitlab.com until another host is added: the page of its GitHub or GitLab row on the Plugins page adds a GitHub Enterprise or self-managed GitLab host and writes it to the profile patch, in the `forge-github` row's [`hosts`](../forge-github/README.md#use-this-package) or the `forge-gitlab` row's [`hosts`](../forge-gitlab/README.md#use-this-package). No provider recognizes other code hosts.
|
||||
- The model has no tool for bound change requests yet.
|
||||
|
||||
-----
|
||||
|
||||
@@ -63,7 +63,7 @@ kind: "package-bundle"
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- 本 Bundle 只服务 github.com 和 gitlab.com;GitHub Enterprise 或自建 GitLab 主机需要用 profile patch 把它列入 `forge-github` 行的 [`hosts`](../forge-github/README.zh.md#use-this-package) 或 `forge-gitlab` 行的 [`hosts`](../forge-gitlab/README.zh.md#use-this-package)。没有提供方识别其他代码托管平台。
|
||||
- 在添加其他主机之前,本 Bundle 只服务 github.com 和 gitlab.com:插件页上本 Bundle 的 GitHub 行或 GitLab 行的页面可以添加 GitHub Enterprise 或自建 GitLab 主机,并把它写入 profile patch 中 `forge-github` 行的 [`hosts`](../forge-github/README.zh.md#use-this-package) 或 `forge-gitlab` 行的 [`hosts`](../forge-gitlab/README.zh.md#use-this-package)。没有提供方识别其他代码托管平台。
|
||||
- 模型目前还没有读取已绑定变更请求的工具。
|
||||
|
||||
-----
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-forge-github/use-this-package:
|
||||
en: 16acf338dc8ff67f
|
||||
zh: 1a70559dc1892545
|
||||
en: 97ac1c449b48c2cd
|
||||
zh: 4db7ec82246edfcb
|
||||
/deepseek-ai-dsh-experimental-forge-github/understand-the-implementation:
|
||||
en: ed8edec5c90cc1eb
|
||||
zh: e3a5b74f75dfc17d
|
||||
en: d7aaa48b140ce680
|
||||
zh: b3a1ce07e514b9b0
|
||||
/deepseek-ai-dsh-experimental-forge-github/further-exploration:
|
||||
en: d377d5fd9d9f190e
|
||||
zh: 920bcbfdb8c993f2
|
||||
@@ -30,8 +30,8 @@
|
||||
en: 26b946af4b742e17
|
||||
zh: 00b34f0721ac72f6
|
||||
/deepseek-ai-dsh-experimental-forge-github/known-limitations-and-deferred-work:
|
||||
en: aa6f410a7f265d2f
|
||||
zh: ecd80b54fd5c0a59
|
||||
en: 31d5924b08580218
|
||||
zh: 47793fc2edb668c8
|
||||
/deepseek-ai-dsh-experimental-forge-github/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
@@ -25,7 +25,7 @@ Read GitHub and GitHub Enterprise pull requests for `ctx.forge` with the GitHub
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
Mount the provider after the forge registry and list every GitHub Enterprise host explicitly.
|
||||
Mount the provider after the forge registry and list every GitHub Enterprise host explicitly. `hosts` lists at least one host name, each with an optional port, and is editable while the provider runs: the [forge panel](../client-ui-forge/README.md) draws the list on this row's page on the Plugins page, and a saved list replaces the registered provider without mounting the plugin again. A list that names a host the GitLab provider serves is not registered: the Loader logs the refusal and the previous list keeps being served until a restart, where the provider that mounts second fails to load.
|
||||
|
||||
```yaml
|
||||
- name: '@deepseek-ai/dsh-experimental-forge'
|
||||
@@ -50,6 +50,8 @@ Unfinished check runs and completed runs with stale, missing, or unrecognized co
|
||||
|
||||
A pull request is `mergeReady` when it is open, not a draft, GitHub reports its merge state as `CLEAN`, `HAS_HOOKS`, or `UNSTABLE`, and the signed-in user has write, maintain, or admin permission. `mergeMethods` lists the squash, merge-commit, and rebase methods the repository allows, the user's default merge method first. Marking ready runs `gh pr ready <number> --repo <host>/<owner>/<name>`. Merging calls `PUT repos/<owner>/<name>/pulls/<number>/merge` through `gh api` with the method and the expected head SHA, so GitHub refuses once new commits arrived, which is reported as `stale`. Unlike `gh pr merge`, it never enables auto-merge, never joins a merge queue, and never deletes the head branch. A refused action reports GitHub's message, and a diagnostic that mentions authentication becomes `unauthenticated`.
|
||||
|
||||
Every snapshot carries `autoMerge`, read from four fields of the snapshot query. `enabled` is true while the pull request has an `autoMergeRequest`, whose `mergeMethod` and `enabledBy` login give `method` and `enabledBy`; a merge method other than squash, merge, and rebase reads as null. `canDisable` is GitHub's `viewerCanDisableAutoMerge`, and `canEnable` its `viewerCanEnableAutoMerge`, except that `canEnable` is false on a base branch with a merge queue (`isMergeQueueEnabled`). Read with admin permission on 150 open pull requests of this repository, `viewerCanEnableAutoMerge` was false for all 71 drafts, all 4 with auto-merge on, and the only one in merge state `CLEAN`, and true for 72 of the other 74. `setAutoMerge` first reads the pull request's node id and head. Turning it on returns `stale` without a mutation when the head is not `request.headSha`, then calls `enablePullRequestAutoMerge` with the merge method and `expectedHeadOid`, so GitHub refuses once new commits arrived; turning it off calls `disablePullRequestAutoMerge` at any head. The mutation goes through the sender `writeReview` uses and is never retried: a refusal becomes `failed` and an answer that does not confirm the outcome `unknown`, each with GitHub's message. A GraphQL refusal carries no HTTP status that names a moved head, so a refusal to turn it on is followed by one more read of the head and becomes `stale` when the head is another commit by then.
|
||||
|
||||
`diff` reads `headRefOid` and `baseRefOid` in one GraphQL query and returns `stale` when the head is not the requested commit, which must be a full 40- or 64-digit hexadecimal commit. Otherwise it reads `repos/<owner>/<name>/compare/<baseRefOid>...<headSha>` through `gh api --allow-escape-sequences` with the diff media type, the patch from the merge base of both commits, so neither end follows a moving branch. Each status snapshot carries `baseRefOid` as `baseSha`, and leaves it out when GitHub reports no full commit there; given it, `diff` starts this comparison while the GraphQL query confirms the head, and a stale head or another base commit cancels the early comparison and waits for it to end before `diff` returns. For every open and merged pull request measured, this patch is byte-identical to `gh pr diff`, which takes no commit argument. Unlike the pull request diff, the compare endpoint returns diffs over 300 files, so only output over `maxOutputBytes` or GitHub's own refusal makes such a diff `too-large`. `--allow-escape-sequences` keeps terminal escape sequences that file contents hold, which `gh` 2.97 and newer otherwise refuse to print; an older `gh` rejects the option with `unknown flag` before sending a request and prints such sequences unchanged, so that rejection repeats the read without it. `fileText` reads `repos/<owner>/<name>/contents/<path>?ref=<commit>` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://<host>/<owner>/<name>/blob/<commit>/<path>`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head and commit count of the first one and a cursor no earlier page returned, else the listing is `unavailable`. `compare` reads the patch from the merge base of two full commits to the second through the same compare request as `diff`. `mergeBase` reads `merge_base_commit.sha` from `repos/<owner>/<name>/compare/<base>...<head>?page=2&per_page=1`, a page of the comparison that lists no files, and returns `unavailable` when the answer is not a full commit. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's HTTP 406 refusal or `too_large` error, which a diff or file over its size limit draws, `rate-limited` for HTTP 429 or a message that names a primary or secondary rate limit, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`.
|
||||
|
||||
Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. GitHub refuses a single comment while the user has a pending review, so the changes view offers one only while there is none. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints.
|
||||
@@ -64,7 +66,9 @@ Every status read also reads the overview of each pull request: up to 25 review
|
||||
|
||||
`viewedFiles` lists the pull request's files through GraphQL, 100 per page, up to `maxViewedFiles` (default 3,000) files, and sets `truncated` when GitHub counts more; GitHub's `VIEWED`, `UNVIEWED`, and `DISMISSED` map to `viewed`, `unviewed`, and `dismissed`, and an unknown state to `unviewed`. A page whose head is not the requested commit makes the read `stale`, and a page that does not advance makes it `unavailable`. `setViewed` checks the head, then calls `markFileAsViewed` or `unmarkFileAsViewed`; GitHub keeps one viewed mark per file and user, whatever the commit. `rerunChecks` reads the complete checks, returns `stale` when the head moved, and posts `repos/<owner>/<name>/actions/runs/<run>/rerun-failed-jobs` once for each workflow run with a failed check and no pending one, as GitHub offers no rerun of a run in progress; it tries every such run, reports the refused ones together, and stops early only for missing credentials. GitHub reruns the failed jobs with the jobs that depend on them. `requestReviews` resolves user logins and `organization/slug` team names to node ids in one GraphQL query and calls `requestReviews` with `union: true`, so existing requests stay; bot logins, given the `[bot]` suffix, go to `requestReviewsByLogin` afterwards, which GitHub Enterprise Server 3.19 and 3.20 lack. `reviewerCandidates` lists up to 20 assignable users whose login or name contains the query, and with an empty query GitHub's suggested reviewers first; the author is left out. `updateBranch` checks the head, then calls `updatePullRequestBranch` with the update method and `expectedHeadOid`, so GitHub refuses once new commits arrived. These mutations go through the sender `writeReview` uses, with their GraphQL document and variables as JSON on stdin, and are never retried: a refusal becomes `failed` and an answer that does not confirm the outcome becomes `unknown`, each with GitHub's message.
|
||||
|
||||
`viewer` offers the `review-requested`, `authored`, and `involved` lists on every configured host, up to `maxViewerItems` (default 50) pull requests per read. `listForViewer` reads one list through one GraphQL `search` of open pull requests in unarchived repositories, most recently updated first: `review-requested:@me`, which also matches a request to one of the user's teams, `author:@me`, or `involves:@me -author:@me -review-requested:@me`, so the lists share no pull request; a repository adds `repo:<owner>/<name>`, and a name that is not a valid owner or repository segment returns `not-found` without a request. GitHub answers one document that searches several lists with a gateway error, so each list is its own request. Each item carries the viewer's latest submitted review, the review request that asks the viewer or one of the viewer's teams, the head commit's combined check state, and up to three closing issues; results that are not pull requests are left out. `countForViewer` reads every list's `issueCount` in one request. Search reads a search index, so a pull request can appear in or leave a list some minutes after the change. `readDescription` reads `body`, `bodyHTML`, `createdAt`, and up to 100 labels in one GraphQL query. On a private repository an uploaded image's Markdown address, `https://<host>/user-attachments/assets/<uuid>`, answers only with the user's GitHub session, while `bodyHTML` names the same upload at a signed `private-user-images` address that loads without one for five minutes; `images` maps each Markdown address to the signed address of the same upload, and `imagesExpireAt` is the earliest `exp` of their tokens. `bodyHTML` is read for these addresses only.
|
||||
`viewer` offers the `review-requested`, `authored`, and `involved` lists on every configured host, up to `maxViewerItems` (default 50) pull requests per read. `listForViewer` reads one list through one GraphQL `search` of open pull requests in unarchived repositories, most recently updated first: `review-requested:@me`, which also matches a request to one of the user's teams, `author:@me`, or `involves:@me -author:@me -review-requested:@me`, so the lists share no pull request; a repository adds `repo:<owner>/<name>`, and a name that is not a valid owner or repository segment returns `not-found` without a request. GitHub answers one document that searches several lists with a gateway error, so each list is its own request. Each item carries the viewer's latest submitted review, the review request that asks the viewer or one of the viewer's teams, and the head commit's combined check state; results that are not pull requests are left out. `countForViewer` reads every list's `issueCount` in one request. Search reads a search index, so a pull request can appear in or leave a list some minutes after the change. `readDescription` reads `body`, `bodyHTML`, `createdAt`, and up to 100 labels in one GraphQL query. On a private repository an uploaded image's Markdown address, `https://<host>/user-attachments/assets/<uuid>`, answers only with the user's GitHub session, while `bodyHTML` names the same upload at a signed `private-user-images` address that loads without one for five minutes; `images` maps each Markdown address to the signed address of the same upload, and `imagesExpireAt` is the earliest `exp` of their tokens. `bodyHTML` is read for these addresses only.
|
||||
|
||||
`readActivity` reads the latest 100 entries of the pull request's timeline in one GraphQL query, `timelineItems(last: 100)` restricted to the item types it maps, and sets `truncated` from `pageInfo.hasPreviousPage`. Entries keep GitHub's order, which is oldest first by a commit's committer date, a review's `submittedAt`, and every other entry's `createdAt`. `PullRequestCommit` maps to `commit`, with `messageHeadline` as its title, which GitHub shortens with an ellipsis, and the GitHub account of the commit's author as its actor, or none when the author has no account; `IssueComment` maps to `comment`; `PullRequestReview` maps to `review` with its verdict and the number of comments it left on lines and files, and a `PENDING` review is left out; `ReviewRequestedEvent` maps to `review-requested` with the requested account's login or the team's `organization/slug`; `RenamedTitleEvent` maps to `renamed`; `MergedEvent`, `ClosedEvent`, `ReopenedEvent`, `ReadyForReviewEvent`, `ConvertToDraftEvent`, `HeadRefForcePushedEvent`, `AutoMergeEnabledEvent`, and `AutoMergeDisabledEvent` map to the kinds of the same meaning. GitHub records a `ClosedEvent` with every merge, so on a merged pull request a `ClosedEvent` that no `ReopenedEvent` follows is left out. An account is a bot when GitHub types it `Bot` or its login ends in `[bot]`, as GitHub spells an app that authored a commit. GitHub's schema has no field that tells whether the viewer may comment on a pull request, so `viewerCanComment` applies the rule of `readReview`: false for an archived repository, and for a locked conversation without `ADMIN`, `MAINTAIN`, or `WRITE` permission. `addComment` posts to `repos/<owner>/<name>/issues/<number>/comments` once through `gh api`, with the text as JSON on stdin, and is never retried: a diagnostic that mentions authentication returns `unauthenticated`; an HTTP 400, 403, 404, 409, or 422 refusal and a `gh` that cannot start return `failed`; a `gh` timeout, a server error, a request cancelled after it was sent, and an answer without the saved comment's `id` return `unknown`, each with GitHub's message or the diagnostic.
|
||||
|
||||
-----
|
||||
|
||||
@@ -88,7 +92,8 @@ A snapshot fetch and a brief read each group references by host, build a `gh api
|
||||
| [`src/mutation.ts`](src/mutation.ts) | Sending one GraphQL mutation and classifying its outcome |
|
||||
| [`src/gh.ts`](src/gh.ts) | Host `gh` execution with environment scrubbing and limits |
|
||||
| [`src/viewed.ts`](src/viewed.ts) | Viewed file reads and writes |
|
||||
| [`src/overview.ts`](src/overview.ts) | Review requests, reviewer search, and branch updates |
|
||||
| [`src/overview.ts`](src/overview.ts) | Review requests, reviewer search, branch updates, and auto-merge |
|
||||
| [`src/activity.ts`](src/activity.ts) | Timeline read and its mapping onto activity entries |
|
||||
| [`src/pull-request-node.ts`](src/pull-request-node.ts) | Pull request node id at a checked head, for mutations |
|
||||
| [`src/urls.ts`](src/urls.ts) | Remote URL and pull request URL parsing, and validation of inlined names and commits |
|
||||
|
||||
@@ -124,8 +129,10 @@ None. Provider output reaches only host-side watchers.
|
||||
- **Brief check outcome** — a brief reports GitHub's combined check state, while a snapshot with a complete check list derives its own; nothing reconciles the two when they differ for one pull request.
|
||||
- **Rewritten base branch** — the diff starts from the merge base of the head and the base commit GitHub recorded at the pull request's last update. After the base branch is force-pushed, that merge base can differ from the one GitHub's pull request view uses, so the patch can include or omit commits until the pull request is updated.
|
||||
- **No fork discovery** — head lookups exclude pull requests whose head is in another repository.
|
||||
- **Rate limits** — every brief poll costs one GraphQL query per `briefBatchSize` pull requests of a host; every snapshot poll costs one per `snapshotBatchSize` pull requests of a host, plus one query per further page of 100 review threads, and a complete check read one more query per further page of 100 check records; every diff read costs one GraphQL query and one REST request, and a second REST request when the base commit changed after the latest status. All count against the signed-in account’s rate limit. A review read costs one GraphQL query per page of 100 threads and one more per further page of 100 comments in a thread. A review write costs one GraphQL query for the head check and one mutation, or two for a pending reply that starts the pending review.
|
||||
- **No merge queue** — a base branch that requires a merge queue refuses a direct merge, and the provider never queues one.
|
||||
- **Rate limits** — every brief poll costs one GraphQL query per `briefBatchSize` pull requests of a host; every snapshot poll costs one per `snapshotBatchSize` pull requests of a host, plus one query per further page of 100 review threads, and a complete check read one more query per further page of 100 check records; every diff read costs one GraphQL query and one REST request, and a second REST request when the base commit changed after the latest status. All count against the signed-in account’s rate limit. A review read costs one GraphQL query per page of 100 threads and one more per further page of 100 comments in a thread. A review write costs one GraphQL query for the head check and one mutation, or two for a pending reply that starts the pending review. An activity read costs one GraphQL query, and an added comment one REST request. Setting auto-merge costs one GraphQL query and one mutation, and one more query after a refusal to turn it on.
|
||||
- **No merge queue** — a base branch that requires a merge queue refuses a direct merge, and `merge` never queues one. On a base branch with a merge queue `autoMerge.canEnable` is false, since GitHub ignores the merge method of an auto-merge request there; `setAutoMerge` itself does not check for a queue, and auto-merge that was turned on on GitHub is still reported.
|
||||
- **Activity bound** — an activity read lists only the latest 100 timeline entries of the types it maps, and `truncated` marks a pull request with older ones, which no read reaches. Label changes, assignments, references from other issues and pull requests, and every other kind of timeline record are not listed. The read is one request, so entries that together print over `maxOutputBytes` fail it as `too-large`.
|
||||
- **Comment permission** — GitHub reports no field for whether the viewer may comment, so `viewerCanComment` stays true for a user whom the repository owner blocked or an interaction limit excludes; GitHub refuses that user's comment only when it is sent.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
@@ -25,7 +25,7 @@ kind: "package-reference"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
在 forge 注册表之后挂载提供方,并显式列出每个 GitHub Enterprise 主机。
|
||||
在 forge 注册表之后挂载提供方,并显式列出每个 GitHub Enterprise 主机。`hosts` 至少列出一个主机名,每个可带端口,并且可以在提供方运行期间修改:[forge 面板](../client-ui-forge/README.zh.md)在插件页上这一行的页面里绘制该列表,保存后的列表会替换已注册的提供方,无需重新挂载插件。列出 GitLab 提供方所服务主机的列表不会被注册:Loader 记录这次拒绝,之前的列表继续服务,直到重启;重启时后挂载的提供方加载失败。
|
||||
|
||||
```yaml
|
||||
- name: '@deepseek-ai/dsh-experimental-forge'
|
||||
@@ -50,6 +50,8 @@ kind: "package-reference"
|
||||
|
||||
pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready <number> --repo <host>/<owner>/<name>`。合并经 `gh api` 调用 `PUT repos/<owner>/<name>/pulls/<number>/merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。
|
||||
|
||||
每个快照都带有 `autoMerge`,取自快照查询的四个字段。pull request 有 `autoMergeRequest` 时 `enabled` 为 true,其 `mergeMethod` 与 `enabledBy` 的登录名给出 `method` 与 `enabledBy`;压缩合并、合并提交与变基合并之外的合并方式读作 null。`canDisable` 即 GitHub 的 `viewerCanDisableAutoMerge`,`canEnable` 即其 `viewerCanEnableAutoMerge`,但在带合并队列的基准分支上(`isMergeQueueEnabled`)`canEnable` 为 false。以 admin 权限读取本仓库 150 个 open pull request 时,全部 71 个草稿、全部 4 个已启用自动合并的,以及唯一一个合并状态为 `CLEAN` 的,`viewerCanEnableAutoMerge` 都为 false;其余 74 个中有 72 个为 true。`setAutoMerge` 先读取 pull request 的节点 id 与 head。启用时,head 不是 `request.headSha` 则不发送 mutation,直接返回 `stale`;否则以合并方式与 `expectedHeadOid` 调用 `enablePullRequestAutoMerge`,因此新提交到来后 GitHub 会拒绝;关闭时调用 `disablePullRequestAutoMerge`,与 head 无关。mutation 与 `writeReview` 使用同一个发送方式,且从不重试:拒绝为 `failed`,无法确认结果的答复为 `unknown`,都附 GitHub 的原因。GraphQL 的拒绝不带能说明 head 已移动的 HTTP 状态,因此启用被拒绝后会再读一次 head,此时 head 已是另一个提交则返回 `stale`。
|
||||
|
||||
`diff` 在一次 GraphQL 查询中读取 `headRefOid` 与 `baseRefOid`,head 不是请求的提交时返回 `stale`;请求的提交必须是完整的 40 位或 64 位十六进制提交。否则经 `gh api --allow-escape-sequences` 以 diff 媒体类型读取 `repos/<owner>/<name>/compare/<baseRefOid>...<headSha>`,即两个提交的合并基准到 head 的补丁,两端都不跟随移动的分支。每个状态快照把 `baseRefOid` 作为 `baseSha` 携带(GitHub 返回的不是完整提交时省略);拿到它时,`diff` 在 GraphQL 查询确认 head 的同时就开始这次比较,head 已过时或基准提交不同时会取消提前开始的比较并等它结束,然后才返回。实测的所有 open 与已合并 pull request 上,该补丁与不接受提交参数的 `gh pr diff` 逐字节一致。与 pull request diff 不同,compare 接口会返回超过 300 个文件的 diff,因此这类 diff 只有在输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才为 `too-large`。`--allow-escape-sequences` 保留文件内容中的终端转义序列;否则 `gh` 2.97 及以上版本拒绝输出。更早的 `gh` 在发出请求前就以 `unknown flag` 拒绝该选项,且原样输出这类序列,因此遇到这一拒绝时去掉该选项重读一次。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos/<owner>/<name>/contents/<path>?ref=<commit>`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://<host>/<owner>/<name>/blob/<commit>/<path>`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 与提交总数必须与第一页相同,游标也不能与之前任何一页重复,否则返回 `unavailable`。`compare` 用与 `diff` 相同的 compare 请求读取两个完整提交的合并基准到第二个提交的补丁。`mergeBase` 从 `repos/<owner>/<name>/compare/<base>...<head>?page=2&per_page=1` 读取 `merge_base_commit.sha`;这一页比较结果不列文件。返回值不是完整提交时为 `unavailable`。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 以 HTTP 406 拒绝或报告 `too_large` 错误时(diff 或文件超过其大小上限即会如此)为 `too-large`,HTTP 429 或提到主限流、次级限流的消息为 `rate-limited`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。
|
||||
|
||||
提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。用户有待提交评审时 GitHub 会拒绝单条评论,因此更改视图只在没有待提交评审时提供单条评论。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。
|
||||
@@ -64,7 +66,9 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为
|
||||
|
||||
`viewedFiles` 经 GraphQL 每页 100 个列出 pull request 的文件,最多 `maxViewedFiles`(默认 3,000)个,GitHub 统计到更多时设置 `truncated`;GitHub 的 `VIEWED`、`UNVIEWED` 与 `DISMISSED` 分别映射为 `viewed`、`unviewed` 与 `dismissed`,未知状态映射为 `unviewed`。某页的 head 不是请求的提交时读取为 `stale`,分页不前进时为 `unavailable`。`setViewed` 先检查 head,再调用 `markFileAsViewed` 或 `unmarkFileAsViewed`;GitHub 对每个文件和用户只保存一个已审阅标记,与提交无关。`rerunChecks` 读取完整检查,head 已移动时返回 `stale`,再对每个含失败检查且没有进行中检查的工作流运行 POST 一次 `repos/<owner>/<name>/actions/runs/<run>/rerun-failed-jobs`,因为 GitHub 不提供运行中工作流的重跑;它会尝试每个这样的运行,汇总报告被拒绝的运行,只在缺少凭据时提前停止。GitHub 会重跑失败的 job 及依赖它们的 job。`requestReviews` 在一次 GraphQL 查询中把用户登录名与 `organization/slug` 形式的团队名解析为节点 id,再以 `union: true` 调用 `requestReviews`,保留已有请求;bot 登录名加上 `[bot]` 后缀后,随后交给 `requestReviewsByLogin`,GitHub Enterprise Server 3.19 与 3.20 没有该 mutation。`reviewerCandidates` 列出登录名或名称包含查询文本的最多 20 个可指派用户,查询为空时 GitHub 建议的评审者排在最前;作者被略去。`updateBranch` 先检查 head,再以更新方式与 `expectedHeadOid` 调用 `updatePullRequestBranch`,因此新提交到来后 GitHub 会拒绝。这些写操作与 `writeReview` 使用同一个发送方式,把 GraphQL 文档与变量作为 JSON 经标准输入发送,且从不重试:拒绝为 `failed`,无法确认结果的答复为 `unknown`,都附 GitHub 的原因。
|
||||
|
||||
`viewer` 在每个已配置主机上提供 `review-requested`、`authored` 与 `involved` 三个列表,每次读取最多 `maxViewerItems`(默认 50)个拉取请求。`listForViewer` 用一次 GraphQL `search` 读取一个列表:未归档仓库中打开的拉取请求,按最近更新在前;三个列表的限定词分别为 `review-requested:@me`(也匹配请求给用户所在团队的评审)、`author:@me` 与 `involves:@me -author:@me -review-requested:@me`,因此互不重叠;限定仓库时追加 `repo:<owner>/<name>`,owner 或仓库名不是合法片段时不发请求,直接返回 `not-found`。GitHub 对在一个文档里搜索多个列表的请求返回网关错误,所以每个列表单独请求。每项带有当前用户最近提交的评审、请求当前用户或其所在团队评审的那条请求、head 提交的检查汇总,以及最多三个会关闭的 issue;不是拉取请求的结果被忽略。`countForViewer` 在一次请求中读取每个列表的 `issueCount`。search 读的是搜索索引,所以拉取请求在变化后可能要过几分钟才进入或离开列表。`readDescription` 用一次 GraphQL 查询读取 `body`、`bodyHTML`、`createdAt` 与最多 100 个标签。私有仓库中,上传图片在 Markdown 里的地址 `https://<host>/user-attachments/assets/<uuid>` 只在带有用户 GitHub 会话时才返回图片,而 `bodyHTML` 为同一上传给出带签名的 `private-user-images` 地址,五分钟内无需会话即可加载;`images` 把每个 Markdown 地址映射到同一上传的签名地址,`imagesExpireAt` 为这些令牌中最早的 `exp`。读取 `bodyHTML` 只为得到这些地址。
|
||||
`viewer` 在每个已配置主机上提供 `review-requested`、`authored` 与 `involved` 三个列表,每次读取最多 `maxViewerItems`(默认 50)个拉取请求。`listForViewer` 用一次 GraphQL `search` 读取一个列表:未归档仓库中打开的拉取请求,按最近更新在前;三个列表的限定词分别为 `review-requested:@me`(也匹配请求给用户所在团队的评审)、`author:@me` 与 `involves:@me -author:@me -review-requested:@me`,因此互不重叠;限定仓库时追加 `repo:<owner>/<name>`,owner 或仓库名不是合法片段时不发请求,直接返回 `not-found`。GitHub 对在一个文档里搜索多个列表的请求返回网关错误,所以每个列表单独请求。每项带有当前用户最近提交的评审、请求当前用户或其所在团队评审的那条请求,以及 head 提交的检查汇总;不是拉取请求的结果被忽略。`countForViewer` 在一次请求中读取每个列表的 `issueCount`。search 读的是搜索索引,所以拉取请求在变化后可能要过几分钟才进入或离开列表。`readDescription` 用一次 GraphQL 查询读取 `body`、`bodyHTML`、`createdAt` 与最多 100 个标签。私有仓库中,上传图片在 Markdown 里的地址 `https://<host>/user-attachments/assets/<uuid>` 只在带有用户 GitHub 会话时才返回图片,而 `bodyHTML` 为同一上传给出带签名的 `private-user-images` 地址,五分钟内无需会话即可加载;`images` 把每个 Markdown 地址映射到同一上传的签名地址,`imagesExpireAt` 为这些令牌中最早的 `exp`。读取 `bodyHTML` 只为得到这些地址。
|
||||
|
||||
`readActivity` 用一次 GraphQL 查询读取 pull request 时间线上最近的 100 条记录,即只含所映射条目类型的 `timelineItems(last: 100)`,并由 `pageInfo.hasPreviousPage` 得出 `truncated`。记录保持 GitHub 的顺序,即按时间从早到晚:提交取提交者日期,评审取 `submittedAt`,其余记录取 `createdAt`。`PullRequestCommit` 映射为 `commit`,标题取 `messageHeadline`(过长时 GitHub 会以省略号截短),actor 为提交作者的 GitHub 账号,作者没有账号时为空;`IssueComment` 映射为 `comment`;`PullRequestReview` 映射为 `review`,带有结论以及它在行和文件上留下的评论数,`PENDING` 评审被略去;`ReviewRequestedEvent` 映射为 `review-requested`,带有被请求账号的登录名或 `organization/slug` 形式的团队名;`RenamedTitleEvent` 映射为 `renamed`;`MergedEvent`、`ClosedEvent`、`ReopenedEvent`、`ReadyForReviewEvent`、`ConvertToDraftEvent`、`HeadRefForcePushedEvent`、`AutoMergeEnabledEvent` 与 `AutoMergeDisabledEvent` 映射为含义相同的类型。GitHub 每次合并都会同时记录一个 `ClosedEvent`,因此在已合并的 pull request 上,之后没有 `ReopenedEvent` 的 `ClosedEvent` 被略去。GitHub 把账号的类型标为 `Bot`,或账号的登录名以 `[bot]` 结尾(GitHub 对作为提交作者的应用如此拼写)时,该账号是 bot。GitHub 的 schema 没有说明当前登录用户能否在 pull request 上评论的字段,因此 `viewerCanComment` 沿用 `readReview` 的规则:仓库已归档,或对话已锁定且用户没有 `ADMIN`、`MAINTAIN` 或 `WRITE` 权限时为 false。`addComment` 经 `gh api` 向 `repos/<owner>/<name>/issues/<number>/comments` POST 一次,评论文本以 JSON 形式经 stdin 传入,且从不重试:提到认证的诊断信息返回 `unauthenticated`;HTTP 400、403、404、409 或 422 拒绝以及 `gh` 无法启动返回 `failed`;`gh` 超时、服务端错误、发送后被取消的请求以及没有已保存评论 `id` 的答复返回 `unknown`,都附 GitHub 的原因或诊断信息。
|
||||
|
||||
-----
|
||||
|
||||
@@ -88,7 +92,8 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为
|
||||
| [`src/mutation.ts`](src/mutation.ts) | 发送单个 GraphQL mutation 并判定其结果 |
|
||||
| [`src/gh.ts`](src/gh.ts) | 在宿主上执行 `gh`,清理环境变量并施加限制 |
|
||||
| [`src/viewed.ts`](src/viewed.ts) | 读取与写入已审阅文件 |
|
||||
| [`src/overview.ts`](src/overview.ts) | 评审请求、评审者搜索与分支更新 |
|
||||
| [`src/overview.ts`](src/overview.ts) | 评审请求、评审者搜索、分支更新与自动合并 |
|
||||
| [`src/activity.ts`](src/activity.ts) | 读取时间线,并映射为活动记录 |
|
||||
| [`src/pull-request-node.ts`](src/pull-request-node.ts) | 在核对过的 head 上读取 pull request 节点 id,供写操作使用 |
|
||||
| [`src/urls.ts`](src/urls.ts) | 解析远端 URL 与 pull request URL,并校验写入请求的名称与提交 |
|
||||
|
||||
@@ -124,8 +129,10 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为
|
||||
- **简报的检查结果**——简报报告 GitHub 的检查汇总状态,检查列表完整的快照则自行得出结果;同一个 pull request 的两个结果不一致时,没有机制去对齐它们。
|
||||
- **基准分支被改写**——diff 从 head 与 GitHub 在 pull request 最后一次更新时记录的基准提交的合并基准开始。基准分支被强制推送后,该合并基准可能不同于 GitHub pull request 页面使用的合并基准,因此在 pull request 更新前,补丁可能多出或缺少提交。
|
||||
- **不发现 fork**——按 head 分支查找时,不包含 head 位于其他仓库的 pull request。
|
||||
- **速率限制**——每次简报轮询为每个主机的每 `briefBatchSize` 个 pull request 消耗一次 GraphQL 查询;每次快照轮询为每个主机的每 `snapshotBatchSize` 个 pull request 消耗一次,评审讨论每多一页(100 个)再消耗一次;完整检查读取时检查记录每多一页(100 条)再消耗一次;每次 diff 读取消耗一次 GraphQL 查询与一次 REST 请求;最新状态之后基准提交有变化时再多一次 REST 请求。这些都计入已登录账号的速率配额。每次评审读取每页 100 个讨论消耗一次 GraphQL 查询,单个讨论的评论每多一页(100 条)再消耗一次。每次评审写入消耗一次用于检查 head 的 GraphQL 查询和一个 mutation;开始待提交评审的待提交回复需要两个 mutation。
|
||||
- **不支持合并队列**——要求合并队列的基准分支会拒绝直接合并,提供方也不会把变更请求加入队列。
|
||||
- **速率限制**——每次简报轮询为每个主机的每 `briefBatchSize` 个 pull request 消耗一次 GraphQL 查询;每次快照轮询为每个主机的每 `snapshotBatchSize` 个 pull request 消耗一次,评审讨论每多一页(100 个)再消耗一次;完整检查读取时检查记录每多一页(100 条)再消耗一次;每次 diff 读取消耗一次 GraphQL 查询与一次 REST 请求;最新状态之后基准提交有变化时再多一次 REST 请求。这些都计入已登录账号的速率配额。每次评审读取每页 100 个讨论消耗一次 GraphQL 查询,单个讨论的评论每多一页(100 条)再消耗一次。每次评审写入消耗一次用于检查 head 的 GraphQL 查询和一个 mutation;开始待提交评审的待提交回复需要两个 mutation。每次活动读取消耗一次 GraphQL 查询,每次添加评论消耗一次 REST 请求。每次设置自动合并消耗一次 GraphQL 查询和一个 mutation;启用被拒绝后再多一次查询。
|
||||
- **不支持合并队列**——要求合并队列的基准分支会拒绝直接合并,`merge` 也不会把变更请求加入队列。在带合并队列的基准分支上 `autoMerge.canEnable` 为 false,因为 GitHub 在那里忽略自动合并请求的合并方式;`setAutoMerge` 本身不检查是否有合并队列,在 GitHub 上启用的自动合并仍会如实报告。
|
||||
- **活动记录上限**——每次活动读取只列出所映射类型中最近的 100 条时间线记录,`truncated` 标出还有更早记录的 pull request,更早的记录无法读取。标签变更、指派、来自其他 issue 与 pull request 的引用,以及其他各类时间线记录都不列出。读取只有一次请求,因此这些记录的输出合计超过 `maxOutputBytes` 时,读取以 `too-large` 失败。
|
||||
- **评论权限**——GitHub 没有说明当前登录用户能否评论的字段,因此对被仓库所有者屏蔽、或被互动限制排除的用户,`viewerCanComment` 仍为 true;GitHub 只在评论发出时才拒绝该用户的评论。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
@@ -42,18 +42,28 @@
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/dsh-experimental-forge": "workspace:*",
|
||||
"@deepseek-ai/dsh-experimental-forge-session": "workspace:*",
|
||||
"@deepseek-ai/dsh-subprocess": "workspace:*"
|
||||
"@deepseek-ai/dsh-subprocess": "workspace:*",
|
||||
"@deepseek-ai/cordis-plugin-loader": "workspace:~",
|
||||
"@deepseek-ai/dsh-settings": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/dsh-brand": "workspace:*",
|
||||
"@deepseek-ai/dsh-experimental-forge": "workspace:*",
|
||||
"@deepseek-ai/dsh-experimental-forge-session": "workspace:*",
|
||||
"@deepseek-ai/dsh-subprocess": "workspace:*"
|
||||
"@deepseek-ai/dsh-subprocess": "workspace:*",
|
||||
"@deepseek-ai/cordis-plugin-loader": "workspace:~",
|
||||
"@deepseek-ai/dsh-settings": "workspace:*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@deepseek-ai/dsh-experimental-forge-session": {
|
||||
"optional": true
|
||||
},
|
||||
"@deepseek-ai/cordis-plugin-loader": {
|
||||
"optional": true
|
||||
},
|
||||
"@deepseek-ai/dsh-settings": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/** Pull request activity through GraphQL: the latest timeline entries as comments, reviews, commits, and changes of state. */
|
||||
|
||||
import type {
|
||||
ChangeRequestActivity, ChangeRequestActivityItem, ChangeRequestRef, ForgeCommentAuthor, ForgeFailure,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
import { z } from 'zod'
|
||||
import type { GraphqlReader } from './commits.ts'
|
||||
import { VERDICTS } from './graphql.ts'
|
||||
import { viewerMayComment } from './threads.ts'
|
||||
import { checkedRepository } from './urls.ts'
|
||||
|
||||
/** Most entries one read lists, GitHub's connection maximum. */
|
||||
const ENTRIES = 100
|
||||
|
||||
const ACCOUNT = '__typename login avatarUrl(size: 48)'
|
||||
|
||||
/** Timeline events that carry only their time and the account that caused them. */
|
||||
const STATE_EVENTS = [
|
||||
'MergedEvent', 'ClosedEvent', 'ReopenedEvent', 'ReadyForReviewEvent', 'ConvertToDraftEvent', 'HeadRefForcePushedEvent',
|
||||
'AutoMergeEnabledEvent', 'AutoMergeDisabledEvent',
|
||||
] as const
|
||||
|
||||
/**
|
||||
* The latest timeline entries of one pull request, with the fields that decide whether the viewer may comment; variables
|
||||
* `owner` and `name` are strings, `number` is an integer.
|
||||
*/
|
||||
export const ACTIVITY_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
|
||||
repository(owner: $owner, name: $name) {
|
||||
isArchived viewerPermission
|
||||
pullRequest(number: $number) {
|
||||
locked merged
|
||||
timelineItems(last: ${ENTRIES}, itemTypes: [
|
||||
PULL_REQUEST_COMMIT, ISSUE_COMMENT, PULL_REQUEST_REVIEW, REVIEW_REQUESTED_EVENT, RENAMED_TITLE_EVENT, MERGED_EVENT, CLOSED_EVENT,
|
||||
REOPENED_EVENT, READY_FOR_REVIEW_EVENT, CONVERT_TO_DRAFT_EVENT, HEAD_REF_FORCE_PUSHED_EVENT, AUTO_MERGE_ENABLED_EVENT,
|
||||
AUTO_MERGE_DISABLED_EVENT
|
||||
]) {
|
||||
pageInfo { hasPreviousPage }
|
||||
nodes {
|
||||
__typename
|
||||
... on PullRequestCommit { commit { oid messageHeadline committedDate author { user { ${ACCOUNT} } } } }
|
||||
... on IssueComment { createdAt url body author { ${ACCOUNT} } }
|
||||
... on PullRequestReview { createdAt submittedAt url body state author { ${ACCOUNT} } comments { totalCount } }
|
||||
... on ReviewRequestedEvent {
|
||||
createdAt actor { ${ACCOUNT} } requestedReviewer { ... on Actor { login } ... on Team { combinedSlug } }
|
||||
}
|
||||
... on RenamedTitleEvent { createdAt actor { ${ACCOUNT} } previousTitle currentTitle }
|
||||
${STATE_EVENTS.map(type => `... on ${type} { createdAt actor { ${ACCOUNT} } }`).join('\n ')}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
const accountSchema = z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() })
|
||||
|
||||
const entrySchema = z.discriminatedUnion('__typename', [
|
||||
z.object({
|
||||
__typename: z.literal('PullRequestCommit'),
|
||||
commit: z.object({
|
||||
oid: z.string(),
|
||||
messageHeadline: z.string(),
|
||||
committedDate: z.string(),
|
||||
author: z.object({ user: accountSchema.nullable() }).nullable(),
|
||||
}),
|
||||
}),
|
||||
z.object({
|
||||
__typename: z.literal('IssueComment'),
|
||||
createdAt: z.string(),
|
||||
url: z.string(),
|
||||
body: z.string(),
|
||||
author: accountSchema.nullable(),
|
||||
}),
|
||||
z.object({
|
||||
__typename: z.literal('PullRequestReview'),
|
||||
createdAt: z.string(),
|
||||
submittedAt: z.string().nullable(),
|
||||
url: z.string(),
|
||||
body: z.string(),
|
||||
state: z.string(),
|
||||
author: accountSchema.nullable(),
|
||||
comments: z.object({ totalCount: z.number().int().nonnegative() }),
|
||||
}),
|
||||
z.object({
|
||||
__typename: z.literal('ReviewRequestedEvent'),
|
||||
createdAt: z.string(),
|
||||
actor: accountSchema.nullable(),
|
||||
requestedReviewer: z.object({ login: z.string().optional(), combinedSlug: z.string().optional() }).nullable(),
|
||||
}),
|
||||
z.object({
|
||||
__typename: z.literal('RenamedTitleEvent'),
|
||||
createdAt: z.string(),
|
||||
actor: accountSchema.nullable(),
|
||||
previousTitle: z.string(),
|
||||
currentTitle: z.string(),
|
||||
}),
|
||||
z.object({ __typename: z.enum(STATE_EVENTS), createdAt: z.string(), actor: accountSchema.nullable() }),
|
||||
])
|
||||
|
||||
const activitySchema = z.object({
|
||||
data: z.object({
|
||||
repository: z.object({
|
||||
isArchived: z.boolean(),
|
||||
viewerPermission: z.string().nullable(),
|
||||
pullRequest: z.object({
|
||||
locked: z.boolean(),
|
||||
merged: z.boolean(),
|
||||
timelineItems: z.object({
|
||||
pageInfo: z.object({ hasPreviousPage: z.boolean() }),
|
||||
// GitHub answers null for an entry it does not show the viewer.
|
||||
nodes: z.array(entrySchema.nullable()),
|
||||
}),
|
||||
}).nullable(),
|
||||
}).nullable(),
|
||||
}),
|
||||
})
|
||||
|
||||
type Entry = z.infer<typeof entrySchema>
|
||||
|
||||
/**
|
||||
* Read the latest 100 entries of a pull request's timeline in one request. They keep GitHub's order, which is oldest
|
||||
* first by the time each entry reports: a commit's committer date, a review's submission, and the creation of every
|
||||
* other entry. A pending review is left out, and so is the close GitHub records with a merge. GitHub's schema has no
|
||||
* field that tells whether the viewer may comment, so `viewerCanComment` follows {@link viewerMayComment}; GitHub can
|
||||
* still refuse the comment of a user it blocks or limits.
|
||||
* @param read - runs one GraphQL request.
|
||||
* @param ref - pull request.
|
||||
* @param signal - cancellation of the read.
|
||||
* @returns the activity, or why GitHub did not provide it.
|
||||
*/
|
||||
export async function readActivity(
|
||||
read: GraphqlReader, ref: ChangeRequestRef, signal: AbortSignal,
|
||||
): Promise<ChangeRequestActivity | ForgeFailure> {
|
||||
const { host, owner, name } = checkedRepository(ref)
|
||||
const output = await read(['api', 'graphql', '--hostname', host, '-f', `query=${ACTIVITY_QUERY}`, '-f', `owner=${owner}`,
|
||||
'-f', `name=${name}`, '-F', `number=${ref.number}`], signal)
|
||||
if (!output.ok) return output.failure
|
||||
const parsed = activitySchema.safeParse(output.body)
|
||||
if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the activity read' }
|
||||
const repository = parsed.data.data.repository
|
||||
const pull = repository?.pullRequest
|
||||
if (repository == null || pull == null) return { code: 'not-found', message: `pull request ${ref.number} was not found` }
|
||||
const { nodes, pageInfo } = pull.timelineItems
|
||||
// A pull request is open when it merges, so on a merged one a close that no reopening follows is the one the merge recorded.
|
||||
const impliedAfter = pull.merged ? nodes.findLastIndex(node => node?.__typename === 'ReopenedEvent') : nodes.length
|
||||
const items: ChangeRequestActivityItem[] = []
|
||||
for (const [index, node] of nodes.entries()) {
|
||||
if (node === null || (node.__typename === 'ClosedEvent' && index > impliedAfter)) continue
|
||||
const item = itemOf(node)
|
||||
if (item !== undefined) items.push(item)
|
||||
}
|
||||
return { items, truncated: pageInfo.hasPreviousPage, viewerCanComment: viewerMayComment(repository, pull.locked) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Map one timeline entry.
|
||||
* @param node - the entry as GitHub returned it.
|
||||
* @returns the activity item, or undefined for a review that is not submitted.
|
||||
*/
|
||||
function itemOf(node: Entry): ChangeRequestActivityItem | undefined {
|
||||
switch (node.__typename) {
|
||||
case 'PullRequestCommit': {
|
||||
const { commit } = node
|
||||
// A commit whose author has no GitHub account names no account. GitHub shortens a long `messageHeadline` with an ellipsis.
|
||||
const actor = accountOf(commit.author?.user ?? null)
|
||||
return { kind: 'commit', at: commit.committedDate, actor, sha: commit.oid, title: commit.messageHeadline }
|
||||
}
|
||||
case 'IssueComment':
|
||||
return { kind: 'comment', at: node.createdAt, actor: accountOf(node.author), body: node.body, url: node.url }
|
||||
case 'PullRequestReview': {
|
||||
const verdict = VERDICTS[node.state]
|
||||
if (verdict === undefined) return undefined
|
||||
const { body, url, comments: { totalCount: comments } } = node
|
||||
return { kind: 'review', at: node.submittedAt ?? node.createdAt, actor: accountOf(node.author), verdict, body, comments, url }
|
||||
}
|
||||
case 'ReviewRequestedEvent': {
|
||||
// A team is named `organization/slug`, as the snapshot's reviewers and a review request name it.
|
||||
const reviewer = node.requestedReviewer?.combinedSlug ?? node.requestedReviewer?.login ?? null
|
||||
return { kind: 'review-requested', at: node.createdAt, actor: accountOf(node.actor), reviewer }
|
||||
}
|
||||
case 'RenamedTitleEvent':
|
||||
return { kind: 'renamed', at: node.createdAt, actor: accountOf(node.actor), from: node.previousTitle, to: node.currentTitle }
|
||||
case 'MergedEvent': return { kind: 'merged', at: node.createdAt, actor: accountOf(node.actor) }
|
||||
case 'ClosedEvent': return { kind: 'closed', at: node.createdAt, actor: accountOf(node.actor) }
|
||||
case 'ReopenedEvent': return { kind: 'reopened', at: node.createdAt, actor: accountOf(node.actor) }
|
||||
case 'ReadyForReviewEvent': return { kind: 'ready-for-review', at: node.createdAt, actor: accountOf(node.actor) }
|
||||
case 'ConvertToDraftEvent': return { kind: 'converted-to-draft', at: node.createdAt, actor: accountOf(node.actor) }
|
||||
case 'HeadRefForcePushedEvent': return { kind: 'force-pushed', at: node.createdAt, actor: accountOf(node.actor) }
|
||||
case 'AutoMergeEnabledEvent': return { kind: 'auto-merge-enabled', at: node.createdAt, actor: accountOf(node.actor) }
|
||||
case 'AutoMergeDisabledEvent': return { kind: 'auto-merge-disabled', at: node.createdAt, actor: accountOf(node.actor) }
|
||||
/* v8 ignore next -- closed timeline entry union exhaustiveness guard */
|
||||
default: return assertNever(node, 'GitHub timeline entry')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map one account. A commit's author is always typed `User`, so an app that authored a commit is told by the `[bot]`
|
||||
* suffix GitHub gives its login there.
|
||||
*/
|
||||
function accountOf(account: z.infer<typeof accountSchema> | null): ForgeCommentAuthor | null {
|
||||
if (account === null) return null
|
||||
return { login: account.login, avatarUrl: account.avatarUrl, bot: account.__typename === 'Bot' || account.login.endsWith('[bot]') }
|
||||
}
|
||||
@@ -3,8 +3,8 @@
|
||||
import type { Branded } from '@deepseek-ai/dsh-brand'
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type {
|
||||
ChangeRequestBrief, ChangeRequestCheck, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, CheckState,
|
||||
ChecksRollup,
|
||||
ChangeRequestAutoMerge, ChangeRequestBrief, ChangeRequestCheck, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer,
|
||||
ChangeRequestSnapshot, CheckState, ChecksRollup,
|
||||
ForgeCheckId, ForgeFailure, ForgeRepository, Mergeability, MergeMethod, ReviewDecision, ReviewVerdict,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { z } from 'zod'
|
||||
@@ -40,6 +40,7 @@ function pullRequestFields(threads: number): string {
|
||||
author { login }
|
||||
headRefName headRefOid baseRefName baseRefOid additions deletions mergeable mergeStateStatus reviewDecision viewerCanUpdateBranch
|
||||
canBeRebased
|
||||
viewerCanEnableAutoMerge viewerCanDisableAutoMerge isMergeQueueEnabled autoMergeRequest { mergeMethod enabledBy { login } }
|
||||
reviewThreads(first: ${threads}) { ${THREAD_FIELDS} }
|
||||
reviewRequests(first: ${OVERVIEW_PAGE}) { totalCount nodes { asCodeOwner requestedReviewer {
|
||||
__typename ... on User { login avatarUrl } ... on Bot { login avatarUrl } ... on Team { combinedSlug avatarUrl }
|
||||
@@ -142,8 +143,8 @@ export interface SnapshotPages {
|
||||
|
||||
const actorSchema = z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() })
|
||||
|
||||
/** The closing issues references of a pull request, the snapshot's and a viewer list item's. */
|
||||
export const closingIssuesSchema = z.object({
|
||||
/** The closing issues references of a pull request snapshot. */
|
||||
const closingIssuesSchema = z.object({
|
||||
totalCount: z.number().int().nonnegative(),
|
||||
nodes: z.array(z.object({
|
||||
number: z.number().int().positive(),
|
||||
@@ -180,6 +181,10 @@ const pullRequestSchema = z.object({
|
||||
reviewDecision: z.string().nullable(),
|
||||
viewerCanUpdateBranch: z.boolean(),
|
||||
canBeRebased: z.boolean(),
|
||||
viewerCanEnableAutoMerge: z.boolean(),
|
||||
viewerCanDisableAutoMerge: z.boolean(),
|
||||
isMergeQueueEnabled: z.boolean(),
|
||||
autoMergeRequest: z.object({ mergeMethod: z.string(), enabledBy: z.object({ login: z.string() }).nullable() }).nullable(),
|
||||
reviewThreads: threadPageSchema,
|
||||
reviewRequests: z.object({
|
||||
totalCount: z.number().int().nonnegative(),
|
||||
@@ -276,15 +281,17 @@ export const VERDICTS: Readonly<Record<string, ReviewVerdict>> = {
|
||||
APPROVED: 'approved', CHANGES_REQUESTED: 'changes-requested', COMMENTED: 'commented', DISMISSED: 'dismissed',
|
||||
}
|
||||
|
||||
/** Merge methods in menu order, with the repository setting that allows each and GitHub's name for it. */
|
||||
/** GitHub's `PullRequestMergeMethod` value of each merge method. */
|
||||
export const MERGE_METHOD_NAMES: Readonly<Record<MergeMethod, string>> = { squash: 'SQUASH', merge: 'MERGE', rebase: 'REBASE' }
|
||||
|
||||
/** Merge methods in menu order, with the repository setting that allows each. */
|
||||
const METHODS: readonly {
|
||||
readonly method: MergeMethod
|
||||
readonly allowed: 'squashMergeAllowed' | 'mergeCommitAllowed' | 'rebaseMergeAllowed'
|
||||
readonly name: string
|
||||
}[] = [
|
||||
{ method: 'squash', allowed: 'squashMergeAllowed', name: 'SQUASH' },
|
||||
{ method: 'merge', allowed: 'mergeCommitAllowed', name: 'MERGE' },
|
||||
{ method: 'rebase', allowed: 'rebaseMergeAllowed', name: 'REBASE' },
|
||||
{ method: 'squash', allowed: 'squashMergeAllowed' },
|
||||
{ method: 'merge', allowed: 'mergeCommitAllowed' },
|
||||
{ method: 'rebase', allowed: 'rebaseMergeAllowed' },
|
||||
]
|
||||
|
||||
/** One batched status query and the change request behind each alias. */
|
||||
@@ -634,6 +641,7 @@ function toSnapshot(
|
||||
mergeReady: settings !== undefined && MERGERS.has(settings.viewerPermission ?? '') && node.state === 'OPEN' && !node.isDraft
|
||||
&& MERGEABLE_NOW.has(node.mergeStateStatus),
|
||||
mergeMethods: settings === undefined ? [] : mergeMethods(settings),
|
||||
autoMerge: autoMergeOf(node),
|
||||
// GitHub's `viewerCanUpdateBranch` is false while the head is up to date as well as when the viewer may not update
|
||||
// it; `mergeStateStatus` cannot tell a head behind its base, as BLOCKED and the other states take precedence over
|
||||
// BEHIND. `canBeRebased` reports whether the pull request can be rebase merged, which follows the repository's rebase
|
||||
@@ -718,10 +726,25 @@ export function actionsRunOf(id: ForgeCheckId): number | undefined {
|
||||
/** The methods the repository allows, the viewer's default first. */
|
||||
function mergeMethods(settings: RepositoryNode): MergeMethod[] {
|
||||
const allowed = METHODS.filter(entry => settings[entry.allowed])
|
||||
const usual = allowed.filter(entry => entry.name === settings.viewerDefaultMergeMethod)
|
||||
const usual = allowed.filter(entry => MERGE_METHOD_NAMES[entry.method] === settings.viewerDefaultMergeMethod)
|
||||
return [...usual, ...allowed.filter(entry => !usual.includes(entry))].map(entry => entry.method)
|
||||
}
|
||||
|
||||
/**
|
||||
* How the pull request stands with GitHub's auto-merge. Turning it on is not offered on a base branch with a merge
|
||||
* queue, where GitHub ignores the merge method of the request; a merge method GitHub adds later reads as null.
|
||||
*/
|
||||
function autoMergeOf(node: PullRequestNode): ChangeRequestAutoMerge {
|
||||
const request = node.autoMergeRequest
|
||||
return {
|
||||
enabled: request !== null,
|
||||
method: METHODS.find(entry => MERGE_METHOD_NAMES[entry.method] === request?.mergeMethod)?.method ?? null,
|
||||
enabledBy: request?.enabledBy?.login ?? null,
|
||||
canEnable: node.viewerCanEnableAutoMerge && !node.isMergeQueueEnabled,
|
||||
canDisable: node.viewerCanDisableAutoMerge,
|
||||
}
|
||||
}
|
||||
|
||||
function changeRequestState(state: PullRequestNode['state']): ChangeRequestSnapshot['state'] {
|
||||
switch (state) {
|
||||
case 'OPEN': return 'open'
|
||||
|
||||
@@ -3,10 +3,13 @@
|
||||
* forge-session runs, the `gh` commands that bind pull requests to a Session.
|
||||
*/
|
||||
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { Context, Volatile } from '@deepseek-ai/cordis'
|
||||
// Type-only: the Loader's `loader/volatile-update` event and the optional `settings` service.
|
||||
import type {} from '@deepseek-ai/cordis-plugin-loader'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import type {} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type {} from '@deepseek-ai/dsh-experimental-forge-session'
|
||||
import type {} from '@deepseek-ai/dsh-settings'
|
||||
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
|
||||
import { GH_COMMANDS } from './commands.ts'
|
||||
import { ghRunner } from './gh.ts'
|
||||
@@ -19,8 +22,11 @@ export const inject = ['forge']
|
||||
export interface Config {
|
||||
/** GitHub CLI executable name or absolute host path. */
|
||||
ghCommand?: string
|
||||
/** Host names this provider serves; list GitHub Enterprise hosts explicitly. */
|
||||
hosts?: string[]
|
||||
/**
|
||||
* Host names this provider serves, at least one; list GitHub Enterprise hosts explicitly. Editable live: the
|
||||
* provider registers again with the new list.
|
||||
*/
|
||||
hosts: Volatile<string[]>
|
||||
/** Deadline in milliseconds for one `gh` invocation. */
|
||||
timeoutMs?: number
|
||||
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */
|
||||
@@ -45,9 +51,12 @@ export interface Config {
|
||||
maxViewerItems?: number
|
||||
}
|
||||
|
||||
export const Config: z<Config> = z.object({
|
||||
/** A host name with an optional port, as `hosts` lists it. */
|
||||
const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i
|
||||
|
||||
export const Config = z.object({
|
||||
ghCommand: z.string().default('gh'),
|
||||
hosts: z.array(z.string()).default(['github.com']),
|
||||
hosts: z.array(z.string().pattern(HOST)).min(1).default(['github.com']).volatile(),
|
||||
timeoutMs: z.number().default(30_000),
|
||||
maxOutputBytes: z.number().default(8_388_608),
|
||||
maxReviewThreads: z.number().default(1_000),
|
||||
@@ -61,15 +70,9 @@ export const Config: z<Config> = z.object({
|
||||
/** Most results one GitHub search page returns. */
|
||||
const SEARCH_PAGE = 100
|
||||
|
||||
const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i
|
||||
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
const resolved = config as Required<Config>
|
||||
if (resolved.ghCommand.trim().length === 0) throw new Error('forge-github: ghCommand must not be empty')
|
||||
if (resolved.hosts.length === 0) throw new Error('forge-github: hosts must list at least one host')
|
||||
for (const host of resolved.hosts) {
|
||||
if (!HOST.test(host)) throw new Error(`forge-github: invalid host ${JSON.stringify(host)}`)
|
||||
}
|
||||
if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) {
|
||||
throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`)
|
||||
}
|
||||
@@ -79,7 +82,14 @@ export function apply(ctx: Context, config: Config): void {
|
||||
if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`)
|
||||
}
|
||||
if (resolved.maxViewerItems > SEARCH_PAGE) throw new Error(`forge-github: maxViewerItems must be no greater than ${SEARCH_PAGE}`)
|
||||
ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved))
|
||||
const gh = ghRunner(resolved)
|
||||
const provider = (): GitHubProvider => new GitHubProvider(gh, resolved.hosts.get(), resolved)
|
||||
const registration = ctx.forge.register(provider())
|
||||
// A list the registry refuses, because the GitLab provider serves one of its hosts, throws here: the Loader logs it
|
||||
// and the previous list keeps being served.
|
||||
ctx.on('loader/volatile-update', () => { registration.replace(provider()) })
|
||||
// The Forge panel draws the host list on this row's Plugins page.
|
||||
ctx.inject(['settings'], (scope) => { scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber)) })
|
||||
ctx.inject(['forgeSession'], (scope) => {
|
||||
scope.forgeSession.registerCommands(GH_COMMANDS)
|
||||
})
|
||||
|
||||
@@ -4,8 +4,8 @@ import type { ForgeActionFailure } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { z } from 'zod'
|
||||
import { GhUnavailableError, type GhOutput, type GhRunner } from './gh.ts'
|
||||
|
||||
/** HTTP statuses that mean GitHub refused the request, so it changed nothing. */
|
||||
const REFUSED = /\(HTTP (?:400|401|403|404|409|422)\)/
|
||||
/** HTTP statuses that mean GitHub refused the request, so it changed nothing, as `gh api` names them in its diagnostic. */
|
||||
export const REFUSED = /\(HTTP (?:400|401|403|404|409|422)\)/
|
||||
|
||||
/**
|
||||
* GraphQL error types that mean GitHub refused a mutation before applying it. An error without one of them, such as
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
/** GitHub writes and reads of the change request overview: review requests, reviewer candidates, and branch updates. */
|
||||
/** GitHub writes and reads of the change request overview: review requests, reviewer candidates, branch updates, and auto-merge. */
|
||||
|
||||
import type {
|
||||
BranchUpdateRequest, ChangeRequestRef, ForgeActionFailure, ForgeFailure, ForgeReviewerCandidate, ForgeReviewersRequest,
|
||||
AutoMergeRequest, BranchUpdateRequest, ChangeRequestRef, ForgeActionFailure, ForgeFailure, ForgeReviewerCandidate, ForgeReviewersRequest,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { z } from 'zod'
|
||||
import type { GraphqlReader } from './commits.ts'
|
||||
import { MERGE_METHOD_NAMES } from './graphql.ts'
|
||||
import type { GraphqlWriter } from './mutation.ts'
|
||||
import { pullRequestNode } from './pull-request-node.ts'
|
||||
import { checkedRepository, isCommit } from './urls.ts'
|
||||
@@ -38,6 +39,16 @@ export const UPDATE_BRANCH_MUTATION = `mutation($input: UpdatePullRequestBranchI
|
||||
updatePullRequestBranch(input: $input) { clientMutationId }
|
||||
}`
|
||||
|
||||
/** Turn auto-merge on with a merge method for an expected head; variable `input` is an `EnablePullRequestAutoMergeInput`. */
|
||||
export const ENABLE_AUTO_MERGE_MUTATION = `mutation($input: EnablePullRequestAutoMergeInput!) {
|
||||
enablePullRequestAutoMerge(input: $input) { clientMutationId }
|
||||
}`
|
||||
|
||||
/** Turn auto-merge off; variable `input` is a `DisablePullRequestAutoMergeInput`. */
|
||||
export const DISABLE_AUTO_MERGE_MUTATION = `mutation($input: DisablePullRequestAutoMergeInput!) {
|
||||
disablePullRequestAutoMerge(input: $input) { clientMutationId }
|
||||
}`
|
||||
|
||||
/** Most accounts one candidate listing returns. */
|
||||
const CANDIDATES = 20
|
||||
|
||||
@@ -162,6 +173,43 @@ export async function updateGitHubBranch(
|
||||
} }, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a pull request's auto-merge on with `enablePullRequestAutoMerge`, or off with `disablePullRequestAutoMerge`.
|
||||
* Turning it on reads the head first and sends no mutation once it is another commit; GitHub also checks
|
||||
* `expectedHeadOid` itself. A refusal of turning it on is followed by one more read of the head, and is `stale` when
|
||||
* the head is another commit by then. Turning it off reads the pull request at any head.
|
||||
* @param read - runs one GraphQL query.
|
||||
* @param write - runs one GraphQL mutation.
|
||||
* @param ref - pull request address.
|
||||
* @param request - on with the merge method and the head commit the user confirmed, or off.
|
||||
* @param signal - cancellation of every request.
|
||||
* @returns undefined once GitHub accepted the change, `stale` when the head moved, or why GitHub refused or did not
|
||||
* confirm it.
|
||||
* @throws when the head commit of a request that turns auto-merge on is not a full commit object name.
|
||||
*/
|
||||
export async function setGitHubAutoMerge(
|
||||
read: GraphqlReader, write: GraphqlWriter, ref: ChangeRequestRef, request: AutoMergeRequest, signal: AbortSignal,
|
||||
): Promise<ForgeActionFailure | undefined> {
|
||||
const { host } = ref.repository
|
||||
if (!request.enabled) {
|
||||
const id = await pullRequestNode(read, ref, null, signal)
|
||||
if (typeof id !== 'string') return id
|
||||
return await write(host, { query: DISABLE_AUTO_MERGE_MUTATION, field: 'disablePullRequestAutoMerge',
|
||||
variables: { input: { pullRequestId: id } } }, signal)
|
||||
}
|
||||
const { headSha } = request
|
||||
if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`)
|
||||
const id = await pullRequestNode(read, ref, headSha, signal)
|
||||
if (typeof id !== 'string') return id
|
||||
const failure = await write(host, { query: ENABLE_AUTO_MERGE_MUTATION, field: 'enablePullRequestAutoMerge', variables: {
|
||||
input: { pullRequestId: id, mergeMethod: MERGE_METHOD_NAMES[request.method], expectedHeadOid: headSha },
|
||||
} }, signal)
|
||||
if (failure?.code !== 'failed') return failure
|
||||
// A refusal carries no HTTP status that names a moved head, as the REST merge's 409 does.
|
||||
const moved = await pullRequestNode(read, ref, headSha, signal)
|
||||
return typeof moved !== 'string' && moved.code === 'stale' ? moved : failure
|
||||
}
|
||||
|
||||
/**
|
||||
* List accounts a review can be requested from: GitHub's suggestions for the pull request when `query` is empty, then
|
||||
* the accounts that can be assigned in the repository whose login or name matches `query`, without the author.
|
||||
|
||||
@@ -2,15 +2,15 @@
|
||||
|
||||
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
|
||||
import type {
|
||||
BranchUpdateRequest, ChangeRequestBrief, ChangeRequestDescription, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot,
|
||||
ForgeActionFailure,
|
||||
AutoMergeRequest, BranchUpdateRequest, ChangeRequestActivity, ChangeRequestBrief, ChangeRequestDescription, ChangeRequestKey,
|
||||
ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure,
|
||||
ForgeCommitList, ForgeFailure, ForgeViewerCapability, ForgeViewerFilter, ForgeViewerList, ForgeViewerQuery,
|
||||
ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewersRequest,
|
||||
ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeRequest,
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { listCommits } from './commits.ts'
|
||||
import type { GraphqlReader } from './commits.ts'
|
||||
import { sendMutation, type GraphqlWriter } from './mutation.ts'
|
||||
import { REFUSED, sendMutation, type GraphqlWriter } from './mutation.ts'
|
||||
import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from './gh.ts'
|
||||
import type { GhOutput, GhRunner } from './gh.ts'
|
||||
import { readComparison } from './compare.ts'
|
||||
@@ -22,10 +22,11 @@ import type { PageResult, SnapshotPages, SnapshotQuery, StatusQuery } from './gr
|
||||
import { checkedRepository, isCommit, parsePullRequestUrl, parseRemoteUrl } from './urls.ts'
|
||||
import { submitGitHubReview } from './review.ts'
|
||||
import { readViewed, writeViewed } from './viewed.ts'
|
||||
import { gitHubReviewerCandidates, requestGitHubReviews, updateGitHubBranch } from './overview.ts'
|
||||
import { gitHubReviewerCandidates, requestGitHubReviews, setGitHubAutoMerge, updateGitHubBranch } from './overview.ts'
|
||||
import { writeGitHubReview } from './review-writes.ts'
|
||||
import { readReviewThreads } from './threads.ts'
|
||||
import { readDescription } from './description.ts'
|
||||
import { readActivity } from './activity.ts'
|
||||
import { countViewerLists, readViewerList, VIEWER_FILTERS } from './viewer.ts'
|
||||
|
||||
const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i
|
||||
@@ -154,6 +155,46 @@ export class GitHubProvider implements ForgeProvider {
|
||||
return await readDescription(this.graphql, ref, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the latest entries of a pull request's timeline through one GraphQL request.
|
||||
* @see readActivity
|
||||
*/
|
||||
async readActivity(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestActivity | ForgeFailure> {
|
||||
const failure = this.hostFailure(ref.repository.host)
|
||||
if (failure !== undefined) return failure
|
||||
return await readActivity(this.graphql, ref, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a comment through one `POST repos/<owner>/<name>/issues/<number>/comments` request, with the text as JSON on
|
||||
* standard input. The request is never retried. Missing or rejected credentials are `unauthenticated`; a refusal GitHub
|
||||
* reports by its HTTP status, and a `gh` that cannot start, are `failed`; every other run that does not end with the
|
||||
* saved comment, a cancelled one included, is `unknown`.
|
||||
* @throws with `signal.reason` when the signal aborted before the request was sent.
|
||||
*/
|
||||
async addComment(ref: ChangeRequestRef, body: string, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
|
||||
const { host, owner, name } = checkedRepository(ref)
|
||||
const failure = this.hostFailure(host)
|
||||
if (failure !== undefined) return { code: 'failed', message: failure.message }
|
||||
signal.throwIfAborted()
|
||||
let output: GhOutput
|
||||
try {
|
||||
output = await this.gh(
|
||||
['api', '--hostname', host, '--method', 'POST', `repos/${owner}/${name}/issues/${ref.number}/comments`, '--input', '-'],
|
||||
signal, JSON.stringify({ body }))
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return { code: error instanceof GhUnavailableError ? 'failed' : 'unknown', message }
|
||||
}
|
||||
if (output.exitCode === 0) {
|
||||
if (isSavedComment(parseJson(output.stdout))) return undefined
|
||||
return { code: 'unknown', message: 'unexpected GitHub response to the comment' }
|
||||
}
|
||||
const { message } = refusal(output)
|
||||
if (AUTHENTICATION.test(output.stderr)) return { code: 'unauthenticated', message }
|
||||
return { code: REFUSED.test(output.stderr) ? 'failed' : 'unknown', message }
|
||||
}
|
||||
|
||||
repositoryFromRemote(url: string): ForgeRepository | undefined {
|
||||
const location = parseRemoteUrl(url)
|
||||
if (location === undefined || !this.served.has(location.host)) return undefined
|
||||
@@ -270,6 +311,17 @@ export class GitHubProvider implements ForgeProvider {
|
||||
], signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn GitHub's auto-merge of a pull request on, with the merge method and the confirmed head as `expectedHeadOid`,
|
||||
* or off, through one GraphQL mutation that is never retried.
|
||||
* @see setGitHubAutoMerge
|
||||
*/
|
||||
async setAutoMerge(ref: ChangeRequestRef, request: AutoMergeRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined> {
|
||||
const failure = this.hostFailure(checkedRepository(ref).host)
|
||||
if (failure !== undefined) return { code: 'failed', message: failure.message }
|
||||
return await setGitHubAutoMerge(this.graphql, this.mutate, ref, request, signal)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the pull request's diff at `headSha`. One GraphQL read names the
|
||||
* current head and the base commit GitHub recorded with it; a head other
|
||||
@@ -661,6 +713,11 @@ function hostMessage(stdout: string): string | undefined {
|
||||
return body.message.trim().length > 0 ? body.message : undefined
|
||||
}
|
||||
|
||||
/** Whether a REST answer is a saved issue comment, which GitHub returns with its numeric id. */
|
||||
function isSavedComment(body: unknown): boolean {
|
||||
return typeof body === 'object' && body !== null && 'id' in body && typeof body.id === 'number'
|
||||
}
|
||||
|
||||
/** A repository path with each segment percent-encoded, for an API path or a web URL. */
|
||||
function encodedPath(path: string): string {
|
||||
return path.split('/').map(segment => encodeURIComponent(segment)).join('/')
|
||||
|
||||
@@ -178,8 +178,7 @@ export async function readReviewThreads(
|
||||
// GitHub lists a pending review only to its author; reading up to 100 finds the viewer's even if others were listed first.
|
||||
const pending = pull.reviews.nodes.find(review => review.viewerDidAuthor)
|
||||
const pendingReview = pending === undefined ? null : { id: pending.id as ForgeReviewId, comments: pending.comments.totalCount }
|
||||
// GitHub refuses every write to an archived repository, and comments on a locked conversation from anyone without write access.
|
||||
const viewerCanReview = !repository.isArchived && (!pull.locked || WRITERS.has(repository.viewerPermission ?? ''))
|
||||
const viewerCanReview = viewerMayComment(repository, pull.locked)
|
||||
// GitHub lets the author of a pull request comment on it but not approve it or request changes.
|
||||
const reviewEvents: readonly ForgeReviewEvent[] = !viewerCanReview ? [] : pull.viewerDidAuthor ? ['comment'] : ['comment', 'approve', 'request-changes']
|
||||
const result = (truncated: boolean): ForgeReviewData => ({
|
||||
@@ -223,6 +222,19 @@ export async function readReviewThreads(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether GitHub's two general refusals leave the signed-in user free to comment on a pull request: it refuses every
|
||||
* write to an archived repository, and comments on a locked conversation from anyone without write access.
|
||||
* @param repository - the repository's `isArchived` and `viewerPermission`.
|
||||
* @param locked - the pull request's `locked`.
|
||||
* @returns false when either refusal applies.
|
||||
*/
|
||||
export function viewerMayComment(
|
||||
repository: { readonly isArchived: boolean; readonly viewerPermission: string | null }, locked: boolean,
|
||||
): boolean {
|
||||
return !repository.isArchived && (!locked || WRITERS.has(repository.viewerPermission ?? ''))
|
||||
}
|
||||
|
||||
/**
|
||||
* Map one thread. GitHub keeps a thread's `line` on the commit of its first comment, which stays an older commit for
|
||||
* a comment written on a commit the head no longer is; such a thread, like one GitHub marks outdated or leaves
|
||||
|
||||
@@ -5,15 +5,12 @@ import type {
|
||||
} from '@deepseek-ai/dsh-experimental-forge'
|
||||
import { z } from 'zod'
|
||||
import type { GraphqlReader } from './commits.ts'
|
||||
import { checksRollup, closingIssuesSchema, reviewDecision, VERDICTS } from './graphql.ts'
|
||||
import { checksRollup, reviewDecision, VERDICTS } from './graphql.ts'
|
||||
import { isSegment } from './urls.ts'
|
||||
|
||||
/** The lists GitHub search reads, each the same search the GitHub pull request page offers. */
|
||||
export const VIEWER_FILTERS: ReadonlySet<ForgeViewerFilter> = new Set(['review-requested', 'authored', 'involved'])
|
||||
|
||||
/** Most closing issues one list item names. */
|
||||
const CLOSING_ISSUES = 3
|
||||
|
||||
/**
|
||||
* Search qualifiers of each list. `involved` leaves out the other two lists, so the three never share a pull request;
|
||||
* `review-requested:@me` also matches a request to one of the user's teams.
|
||||
@@ -29,8 +26,7 @@ const ROW_FIELDS = `number title url isDraft updatedAt headRefOid reviewDecision
|
||||
author { __typename login avatarUrl }
|
||||
commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
|
||||
viewerLatestReview { state commit { oid } }
|
||||
viewerLatestReviewRequest { requestedReviewer { __typename ... on Team { combinedSlug } } }
|
||||
closingIssuesReferences(first: ${CLOSING_ISSUES}) { totalCount nodes { number title state url repository { name owner { login } } } }`
|
||||
viewerLatestReviewRequest { requestedReviewer { __typename ... on Team { combinedSlug } } }`
|
||||
|
||||
/** One page of one list with the signed-in user; variables `q` and the integer `first`. */
|
||||
export const VIEWER_LIST_QUERY = `query($q: String!, $first: Int!) {
|
||||
@@ -63,7 +59,6 @@ const rowSchema = z.object({
|
||||
viewerLatestReviewRequest: z.object({
|
||||
requestedReviewer: z.object({ __typename: z.string(), combinedSlug: z.string().optional() }).nullable(),
|
||||
}).nullable(),
|
||||
closingIssuesReferences: closingIssuesSchema,
|
||||
})
|
||||
|
||||
const listSchema = z.object({
|
||||
@@ -168,18 +163,6 @@ function summaryOf(host: string, row: z.infer<typeof rowSchema>): ChangeRequestS
|
||||
reviewDecision: reviewDecision(row.reviewDecision),
|
||||
viewerReview: review === null || verdict === undefined ? null : { verdict, reviewedSha: review.commit?.oid ?? null },
|
||||
viewerRequest: reviewer == null ? null : { team: reviewer.__typename === 'Team' ? reviewer.combinedSlug ?? null : null },
|
||||
closingIssues: row.closingIssuesReferences.nodes.flatMap((issue) => {
|
||||
const { owner: { login: issueOwner }, name: issueName } = issue.repository
|
||||
if (!isSegment(issueOwner) || !isSegment(issueName)) return []
|
||||
return [{
|
||||
repository: { forge: 'github', host, owner: issueOwner, name: issueName },
|
||||
number: issue.number,
|
||||
title: issue.title,
|
||||
state: issue.state === 'OPEN' ? 'open' as const : 'closed' as const,
|
||||
url: issue.url,
|
||||
}]
|
||||
}),
|
||||
closingIssuesTruncated: row.closingIssuesReferences.totalCount > row.closingIssuesReferences.nodes.length,
|
||||
updatedAt: row.updatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ACTIVITY_QUERY } from '../src/activity.ts'
|
||||
import { GhTimeoutError, GhUnavailableError } from '../src/gh.ts'
|
||||
import type { GhOutput, GhRunner } from '../src/gh.ts'
|
||||
import { GitHubProvider } from '../src/provider.ts'
|
||||
import type { GitHubLimits } from '../src/provider.ts'
|
||||
import { demo, pull } from './fixtures.ts'
|
||||
|
||||
const signal = new AbortController().signal
|
||||
|
||||
const limits: GitHubLimits = {
|
||||
maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, snapshotBatchSize: 8, briefBatchSize: 50,
|
||||
maxCommits: 250, maxViewedFiles: 3_000, maxViewerItems: 50,
|
||||
}
|
||||
|
||||
/** One `gh` run: its arguments and what it received on standard input. */
|
||||
interface Call {
|
||||
readonly args: readonly string[]
|
||||
readonly input: string | undefined
|
||||
}
|
||||
|
||||
function fakeGh(handler: () => GhOutput | Promise<GhOutput>): { run: GhRunner; calls: Call[] } {
|
||||
const calls: Call[] = []
|
||||
return { calls, run: async (args, _signal, input) => { calls.push({ args: [...args], input }); return await handler() } }
|
||||
}
|
||||
|
||||
function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput {
|
||||
return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr }
|
||||
}
|
||||
|
||||
function provider(run: GhRunner): GitHubProvider {
|
||||
return new GitHubProvider(run, ['github.com'], limits)
|
||||
}
|
||||
|
||||
const octo = { __typename: 'User', login: 'octo', avatarUrl: 'https://avatars.example/octo' }
|
||||
const actions = { __typename: 'Bot', login: 'github-actions', avatarUrl: 'https://avatars.example/actions' }
|
||||
const octoActor = { login: 'octo', avatarUrl: 'https://avatars.example/octo', bot: false }
|
||||
const actionsActor = { login: 'github-actions', avatarUrl: 'https://avatars.example/actions', bot: true }
|
||||
|
||||
/** One timeline event that carries only its time and actor. */
|
||||
function event(type: string, createdAt: string, actor: unknown = octo): Record<string, unknown> {
|
||||
return { __typename: type, createdAt, actor }
|
||||
}
|
||||
|
||||
function commit(oid: string, committedDate: string, author: unknown, messageHeadline = `Commit ${oid}`): Record<string, unknown> {
|
||||
return { __typename: 'PullRequestCommit', commit: { oid, messageHeadline, committedDate, author } }
|
||||
}
|
||||
|
||||
function review(state: string, overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
__typename: 'PullRequestReview', createdAt: '2026-11-02T08:00:00Z', submittedAt: '2026-11-02T09:00:00Z',
|
||||
url: `https://github.com/octo/demo/pull/7#pullrequestreview-${state}`, body: '', state, author: octo, comments: { totalCount: 0 },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** Fields of an activity answer that differ from an open, unlocked pull request a reader sees whole. */
|
||||
interface Overrides {
|
||||
readonly merged?: boolean
|
||||
readonly locked?: boolean
|
||||
readonly isArchived?: boolean
|
||||
readonly viewerPermission?: string | null
|
||||
readonly hasPreviousPage?: boolean
|
||||
}
|
||||
|
||||
/** An activity answer for a pull request with `nodes` as its latest timeline entries. */
|
||||
function activityBody(nodes: readonly unknown[], overrides: Overrides = {}): Record<string, unknown> {
|
||||
return { data: { repository: {
|
||||
isArchived: overrides.isArchived ?? false,
|
||||
viewerPermission: overrides.viewerPermission === undefined ? 'READ' : overrides.viewerPermission,
|
||||
pullRequest: {
|
||||
locked: overrides.locked ?? false,
|
||||
merged: overrides.merged ?? false,
|
||||
timelineItems: { pageInfo: { hasPreviousPage: overrides.hasPreviousPage ?? false }, nodes },
|
||||
},
|
||||
} } }
|
||||
}
|
||||
|
||||
async function kinds(body: unknown): Promise<unknown> {
|
||||
const result = await provider(fakeGh(() => output(body)).run).readActivity(pull(7), signal)
|
||||
return 'code' in result ? result : result.items.map(item => item.kind)
|
||||
}
|
||||
|
||||
describe('GitHub activity reads', () => {
|
||||
it('reads the latest timeline entries in one request and maps each to the activity kind of the same meaning', async () => {
|
||||
const gh = fakeGh(() => output(activityBody([
|
||||
commit('a'.repeat(40), '2026-11-01T08:00:00Z', { user: octo }, 'feat: add the panel'),
|
||||
commit('b'.repeat(40), '2026-11-01T08:01:00Z', { user: { __typename: 'User', login: 'dependabot[bot]', avatarUrl: null } }),
|
||||
commit('c'.repeat(40), '2026-11-01T08:02:00Z', { user: null }),
|
||||
commit('d'.repeat(40), '2026-11-01T08:03:00Z', null),
|
||||
{ __typename: 'IssueComment', createdAt: '2026-11-01T09:00:00Z', url: 'https://github.com/octo/demo/pull/7#issuecomment-1',
|
||||
body: 'Coverage **92%**', author: actions },
|
||||
{ __typename: 'IssueComment', createdAt: '2026-11-01T09:01:00Z', url: 'https://github.com/octo/demo/pull/7#issuecomment-2',
|
||||
body: 'from a deleted account', author: null },
|
||||
{ ...event('RenamedTitleEvent', '2026-11-01T10:00:00Z'), previousTitle: 'Old title', currentTitle: 'New title' },
|
||||
event('ReadyForReviewEvent', '2026-11-01T10:01:00Z'),
|
||||
event('ConvertToDraftEvent', '2026-11-01T10:02:00Z'),
|
||||
{ ...event('ReviewRequestedEvent', '2026-11-01T10:03:00Z'), requestedReviewer: { login: 'hubot' } },
|
||||
{ ...event('ReviewRequestedEvent', '2026-11-01T10:04:00Z'), requestedReviewer: { combinedSlug: 'octo/reviewers' } },
|
||||
{ ...event('ReviewRequestedEvent', '2026-11-01T10:05:00Z'), requestedReviewer: null },
|
||||
{ ...event('ReviewRequestedEvent', '2026-11-01T10:06:00Z', null), requestedReviewer: {} },
|
||||
review('COMMENTED', { body: 'Two notes', comments: { totalCount: 2 } }),
|
||||
review('CHANGES_REQUESTED'),
|
||||
review('DISMISSED'),
|
||||
review('APPROVED', { createdAt: '2026-11-02T10:00:00Z', submittedAt: null, author: null }),
|
||||
event('HeadRefForcePushedEvent', '2026-11-03T08:00:00Z'),
|
||||
event('AutoMergeEnabledEvent', '2026-11-03T08:01:00Z'),
|
||||
event('AutoMergeDisabledEvent', '2026-11-03T08:02:00Z'),
|
||||
event('ClosedEvent', '2026-11-03T08:03:00Z'),
|
||||
event('ReopenedEvent', '2026-11-03T08:04:00Z'),
|
||||
event('MergedEvent', '2026-11-03T08:05:00Z'),
|
||||
])))
|
||||
|
||||
const result = await provider(gh.run).readActivity(pull(7), signal)
|
||||
|
||||
expect(gh.calls).toEqual([{ input: undefined, args: ['api', 'graphql', '--hostname', 'github.com', '-f', `query=${ACTIVITY_QUERY}`,
|
||||
'-f', 'owner=octo', '-f', 'name=demo', '-F', 'number=7'] }])
|
||||
const reviewUrl = (state: string): string => `https://github.com/octo/demo/pull/7#pullrequestreview-${state}`
|
||||
expect(result).toEqual({
|
||||
truncated: false,
|
||||
viewerCanComment: true,
|
||||
items: [
|
||||
{ kind: 'commit', at: '2026-11-01T08:00:00Z', actor: octoActor, sha: 'a'.repeat(40), title: 'feat: add the panel' },
|
||||
{ kind: 'commit', at: '2026-11-01T08:01:00Z', actor: { login: 'dependabot[bot]', avatarUrl: null, bot: true }, sha: 'b'.repeat(40),
|
||||
title: `Commit ${'b'.repeat(40)}` },
|
||||
{ kind: 'commit', at: '2026-11-01T08:02:00Z', actor: null, sha: 'c'.repeat(40), title: `Commit ${'c'.repeat(40)}` },
|
||||
{ kind: 'commit', at: '2026-11-01T08:03:00Z', actor: null, sha: 'd'.repeat(40), title: `Commit ${'d'.repeat(40)}` },
|
||||
{ kind: 'comment', at: '2026-11-01T09:00:00Z', actor: actionsActor, body: 'Coverage **92%**',
|
||||
url: 'https://github.com/octo/demo/pull/7#issuecomment-1' },
|
||||
{ kind: 'comment', at: '2026-11-01T09:01:00Z', actor: null, body: 'from a deleted account',
|
||||
url: 'https://github.com/octo/demo/pull/7#issuecomment-2' },
|
||||
{ kind: 'renamed', at: '2026-11-01T10:00:00Z', actor: octoActor, from: 'Old title', to: 'New title' },
|
||||
{ kind: 'ready-for-review', at: '2026-11-01T10:01:00Z', actor: octoActor },
|
||||
{ kind: 'converted-to-draft', at: '2026-11-01T10:02:00Z', actor: octoActor },
|
||||
{ kind: 'review-requested', at: '2026-11-01T10:03:00Z', actor: octoActor, reviewer: 'hubot' },
|
||||
{ kind: 'review-requested', at: '2026-11-01T10:04:00Z', actor: octoActor, reviewer: 'octo/reviewers' },
|
||||
{ kind: 'review-requested', at: '2026-11-01T10:05:00Z', actor: octoActor, reviewer: null },
|
||||
{ kind: 'review-requested', at: '2026-11-01T10:06:00Z', actor: null, reviewer: null },
|
||||
{ kind: 'review', at: '2026-11-02T09:00:00Z', actor: octoActor, verdict: 'commented', body: 'Two notes', comments: 2,
|
||||
url: reviewUrl('COMMENTED') },
|
||||
{ kind: 'review', at: '2026-11-02T09:00:00Z', actor: octoActor, verdict: 'changes-requested', body: '', comments: 0,
|
||||
url: reviewUrl('CHANGES_REQUESTED') },
|
||||
{ kind: 'review', at: '2026-11-02T09:00:00Z', actor: octoActor, verdict: 'dismissed', body: '', comments: 0,
|
||||
url: reviewUrl('DISMISSED') },
|
||||
{ kind: 'review', at: '2026-11-02T10:00:00Z', actor: null, verdict: 'approved', body: '', comments: 0, url: reviewUrl('APPROVED') },
|
||||
{ kind: 'force-pushed', at: '2026-11-03T08:00:00Z', actor: octoActor },
|
||||
{ kind: 'auto-merge-enabled', at: '2026-11-03T08:01:00Z', actor: octoActor },
|
||||
{ kind: 'auto-merge-disabled', at: '2026-11-03T08:02:00Z', actor: octoActor },
|
||||
{ kind: 'closed', at: '2026-11-03T08:03:00Z', actor: octoActor },
|
||||
{ kind: 'reopened', at: '2026-11-03T08:04:00Z', actor: octoActor },
|
||||
{ kind: 'merged', at: '2026-11-03T08:05:00Z', actor: octoActor },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('asks GitHub for the latest 100 entries of every timeline type it maps', () => {
|
||||
expect(ACTIVITY_QUERY).toContain('timelineItems(last: 100, itemTypes: [')
|
||||
const types = ['PullRequestCommit', 'IssueComment', 'PullRequestReview', 'ReviewRequestedEvent', 'RenamedTitleEvent', 'MergedEvent',
|
||||
'ClosedEvent', 'ReopenedEvent', 'ReadyForReviewEvent', 'ConvertToDraftEvent', 'HeadRefForcePushedEvent', 'AutoMergeEnabledEvent',
|
||||
'AutoMergeDisabledEvent']
|
||||
for (const type of types) {
|
||||
expect(ACTIVITY_QUERY).toContain(`... on ${type} {`)
|
||||
expect(ACTIVITY_QUERY).toMatch(new RegExp(String.raw`\b${type.replaceAll(/(?<!^)[A-Z]/g, letter => `_${letter}`).toUpperCase()}\b`))
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves out a pending review and an entry GitHub does not show', async () => {
|
||||
await expect(kinds(activityBody([review('PENDING', { submittedAt: null }), null, review('APPROVED')]))).resolves.toEqual(['review'])
|
||||
})
|
||||
|
||||
it('leaves out the close a merge records, and keeps a close the pull request was reopened after', async () => {
|
||||
const closed = event('ClosedEvent', '2026-11-03T08:00:00Z')
|
||||
const reopened = event('ReopenedEvent', '2026-11-03T08:01:00Z')
|
||||
const merged = event('MergedEvent', '2026-11-03T08:02:00Z')
|
||||
const implied = event('ClosedEvent', '2026-11-03T08:03:00Z')
|
||||
await expect(kinds(activityBody([merged, implied], { merged: true }))).resolves.toEqual(['merged'])
|
||||
await expect(kinds(activityBody([implied, merged], { merged: true }))).resolves.toEqual(['merged'])
|
||||
await expect(kinds(activityBody([closed, reopened, merged, implied], { merged: true })))
|
||||
.resolves.toEqual(['closed', 'reopened', 'merged'])
|
||||
// The merge is older than the latest 100 entries, and its close is among them.
|
||||
await expect(kinds(activityBody([implied, review('APPROVED')], { merged: true, hasPreviousPage: true }))).resolves.toEqual(['review'])
|
||||
await expect(kinds(activityBody([closed, reopened, implied]))).resolves.toEqual(['closed', 'reopened', 'closed'])
|
||||
})
|
||||
|
||||
it('marks the activity truncated when the pull request has older entries', async () => {
|
||||
const read = async (hasPreviousPage: boolean): Promise<unknown> =>
|
||||
await provider(fakeGh(() => output(activityBody([], { hasPreviousPage }))).run).readActivity(pull(7), signal)
|
||||
await expect(read(true)).resolves.toEqual({ items: [], truncated: true, viewerCanComment: true })
|
||||
await expect(read(false)).resolves.toEqual({ items: [], truncated: false, viewerCanComment: true })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['an open conversation for a reader', {}, true],
|
||||
['an archived repository', { isArchived: true, viewerPermission: 'ADMIN' }, false],
|
||||
['a locked conversation for a reader', { locked: true }, false],
|
||||
['a locked conversation for a user without a permission', { locked: true, viewerPermission: null }, false],
|
||||
['a locked conversation for a writer', { locked: true, viewerPermission: 'WRITE' }, true],
|
||||
] as const)('tells whether the viewer may comment on %s', async (_label, overrides, viewerCanComment) => {
|
||||
await expect(provider(fakeGh(() => output(activityBody([], overrides))).run).readActivity(pull(7), signal))
|
||||
.resolves.toMatchObject({ viewerCanComment })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a missing pull request', output({ data: { repository: { isArchived: false, viewerPermission: 'READ', pullRequest: null } } }),
|
||||
{ code: 'not-found', message: 'pull request 7 was not found' }],
|
||||
['a missing repository', output({ data: { repository: null } }), { code: 'not-found', message: 'pull request 7 was not found' }],
|
||||
['an entry of a type it did not ask for', output(activityBody([event('LockedEvent', '2026-11-03T08:00:00Z')])),
|
||||
{ code: 'unavailable', message: 'unexpected GitHub response to the activity read' }],
|
||||
['an entry without its fields', output(activityBody([{ __typename: 'IssueComment' }])),
|
||||
{ code: 'unavailable', message: 'unexpected GitHub response to the activity read' }],
|
||||
['a refusal', output('', 1, 'gh: Something went wrong (HTTP 502)'),
|
||||
{ code: 'unavailable', message: 'gh: Something went wrong (HTTP 502)' }],
|
||||
])('reports %s', async (_label, answer, failure) => {
|
||||
await expect(provider(fakeGh(() => answer).run).readActivity(pull(7), signal)).resolves.toEqual(failure)
|
||||
})
|
||||
|
||||
it('refuses an unconfigured host without asking GitHub', async () => {
|
||||
const gh = fakeGh(() => output(''))
|
||||
await expect(provider(gh.run).readActivity(pull(1, { ...demo, host: 'other.example' }), signal))
|
||||
.resolves.toEqual({ code: 'unavailable', message: 'forge-github: host "other.example" is not configured' })
|
||||
expect(gh.calls).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('GitHub comments', () => {
|
||||
const saved = { id: 6939417101, html_url: 'https://github.com/octo/demo/pull/7#issuecomment-6939417101', body: 'Looks right' }
|
||||
|
||||
it('posts the comment once with its text as JSON on standard input', async () => {
|
||||
const gh = fakeGh(() => output(saved))
|
||||
const body = 'Looks right\n\n- [ ] one "quoted" `-F field=@file`'
|
||||
|
||||
await expect(provider(gh.run).addComment(pull(7), body, signal)).resolves.toBeUndefined()
|
||||
|
||||
expect(gh.calls).toEqual([{
|
||||
args: ['api', '--hostname', 'github.com', '--method', 'POST', 'repos/octo/demo/issues/7/comments', '--input', '-'],
|
||||
input: JSON.stringify({ body }),
|
||||
}])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a locked conversation', output({ message: 'The conversation is locked.' }, 1, 'gh: The conversation is locked. (HTTP 403)'),
|
||||
{ code: 'failed', message: 'The conversation is locked.' }],
|
||||
['a pull request GitHub does not have', output({ message: 'Not Found' }, 1, 'gh: Not Found (HTTP 404)'),
|
||||
{ code: 'failed', message: 'Not Found' }],
|
||||
['text GitHub does not accept', output({ message: 'Validation Failed' }, 1, 'gh: Validation Failed (HTTP 422)'),
|
||||
{ code: 'failed', message: 'Validation Failed' }],
|
||||
['rejected credentials', output({ message: 'Bad credentials' }, 1, 'gh: Bad credentials (HTTP 401)'),
|
||||
{ code: 'unauthenticated', message: 'Bad credentials' }],
|
||||
['a gh that is not signed in', output('', 4, 'To get started with GitHub CLI, please run: gh auth login'),
|
||||
{ code: 'unauthenticated', message: 'To get started with GitHub CLI, please run: gh auth login' }],
|
||||
])('reports %s as a refusal that changed nothing', async (_label, answer, failure) => {
|
||||
await expect(provider(fakeGh(() => answer).run).addComment(pull(7), 'Looks right', signal)).resolves.toEqual(failure)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a server error', (): GhOutput => output('', 1, 'gh: Something went wrong (HTTP 502)'), 'gh: Something went wrong (HTTP 502)'],
|
||||
['an answer without the saved comment', (): GhOutput => output({ message: 'accepted' }), 'unexpected GitHub response to the comment'],
|
||||
['an answer that is not JSON', (): GhOutput => output('<html>'), 'unexpected GitHub response to the comment'],
|
||||
['a gh that times out', (): GhOutput => { throw new GhTimeoutError('gh api timed out after 30000ms') },
|
||||
'gh api timed out after 30000ms'],
|
||||
// A runner rejects with the reason of the signal that cancelled it, which need not be an error.
|
||||
['a request cancelled after it was sent', (): GhOutput => { throw 'the user left the page' }, 'the user left the page'],
|
||||
])('reports %s as an unknown outcome without sending the comment again', async (_label, answer, message) => {
|
||||
const gh = fakeGh(answer)
|
||||
await expect(provider(gh.run).addComment(pull(7), 'Looks right', signal)).resolves.toEqual({ code: 'unknown', message })
|
||||
expect(gh.calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('reports a gh that cannot start as a failure', async () => {
|
||||
const run: GhRunner = () => Promise.reject(new GhUnavailableError('gh could not start: spawn gh ENOENT'))
|
||||
await expect(provider(run).addComment(pull(7), 'Looks right', signal))
|
||||
.resolves.toEqual({ code: 'failed', message: 'gh could not start: spawn gh ENOENT' })
|
||||
})
|
||||
|
||||
it('sends nothing once the request is cancelled, for an unconfigured host, or for a repository name that cannot be a path', async () => {
|
||||
const gh = fakeGh(() => output(saved))
|
||||
const subject = provider(gh.run)
|
||||
const cancelled = new AbortController()
|
||||
cancelled.abort(new Error('cancelled before the request'))
|
||||
|
||||
await expect(subject.addComment(pull(7), 'Looks right', cancelled.signal)).rejects.toThrow('cancelled before the request')
|
||||
await expect(subject.addComment(pull(7, { ...demo, host: 'other.example' }), 'Looks right', signal))
|
||||
.resolves.toEqual({ code: 'failed', message: 'forge-github: host "other.example" is not configured' })
|
||||
await expect(subject.addComment(pull(7, { ...demo, name: 'de/mo' }), 'Looks right', signal))
|
||||
.rejects.toThrow('forge-github: invalid repository "octo/de/mo"')
|
||||
expect(gh.calls).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -79,6 +79,10 @@ export function pullRequestNode(number: number, overrides: Record<string, unknow
|
||||
reviewDecision: null,
|
||||
viewerCanUpdateBranch: false,
|
||||
canBeRebased: false,
|
||||
viewerCanEnableAutoMerge: false,
|
||||
viewerCanDisableAutoMerge: false,
|
||||
isMergeQueueEnabled: false,
|
||||
autoMergeRequest: null,
|
||||
reviewThreads: threadPage([true, false, false]),
|
||||
reviewRequests: { totalCount: 0, nodes: [] },
|
||||
latestReviews: { totalCount: 0, nodes: [] },
|
||||
|
||||
@@ -70,6 +70,7 @@ describe('snapshot mapping', () => {
|
||||
mergeability: 'mergeable',
|
||||
mergeReady: true,
|
||||
mergeMethods: ['merge', 'squash'],
|
||||
autoMerge: { enabled: false, method: null, enabledBy: null, canEnable: false, canDisable: false },
|
||||
branchUpdates: [],
|
||||
reviewDecision: 'none',
|
||||
reviewers: [],
|
||||
@@ -280,6 +281,32 @@ describe('snapshot mapping', () => {
|
||||
expect((await single(pullRequestNode(1), { squashMergeAllowed: 'yes' }))).toMatchObject({ mergeReady: false, mergeMethods: [] })
|
||||
})
|
||||
|
||||
it('reads the auto-merge fields of every pull request with its snapshot', () => {
|
||||
expect(snapshotQuery([pull(1)], MAX_THREADS).document).toContain(
|
||||
'viewerCanEnableAutoMerge viewerCanDisableAutoMerge isMergeQueueEnabled autoMergeRequest { mergeMethod enabledBy { login } }')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['off where the viewer can turn it on', { mergeStateStatus: 'BLOCKED', viewerCanEnableAutoMerge: true },
|
||||
{ enabled: false, method: null, enabledBy: null, canEnable: true, canDisable: false }],
|
||||
['on by an account, where the viewer can turn it off',
|
||||
{ viewerCanDisableAutoMerge: true, autoMergeRequest: { mergeMethod: 'SQUASH', enabledBy: { login: 'mona' } } },
|
||||
{ enabled: true, method: 'squash', enabledBy: 'mona', canEnable: false, canDisable: true }],
|
||||
['on by an account GitHub does not name, for a viewer who cannot turn it off',
|
||||
{ autoMergeRequest: { mergeMethod: 'MERGE', enabledBy: null } },
|
||||
{ enabled: true, method: 'merge', enabledBy: null, canEnable: false, canDisable: false }],
|
||||
['off and not offered on a base branch with a merge queue', { viewerCanEnableAutoMerge: true, isMergeQueueEnabled: true },
|
||||
{ enabled: false, method: null, enabledBy: null, canEnable: false, canDisable: false }],
|
||||
])('reports auto-merge %s', async (_label, node, autoMerge) => {
|
||||
expect((await single(pullRequestNode(1, node))).autoMerge).toEqual(autoMerge)
|
||||
})
|
||||
|
||||
it.each([['SQUASH', 'squash'], ['MERGE', 'merge'], ['REBASE', 'rebase'], ['FUTURE_METHOD', null]])(
|
||||
'reads the auto-merge method %s as %s', async (mergeMethod, method) => {
|
||||
const snapshot = await single(pullRequestNode(1, { autoMergeRequest: { mergeMethod, enabledBy: { login: 'mona' } } }))
|
||||
expect(snapshot.autoMerge?.method).toBe(method)
|
||||
})
|
||||
|
||||
it('keeps a hidden author, drafts, and a commit without rollup', async () => {
|
||||
expect(await single(pullRequestNode(1, { isDraft: true, author: null }))).toMatchObject({ draft: true, author: null })
|
||||
expect(await single(pullRequestNode(1, { commits: { nodes: [] } }))).toMatchObject({ checks: [], checksRollup: 'none', checksTruncated: false })
|
||||
|
||||
@@ -2,8 +2,8 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
import type { GraphqlReader } from '../src/commits.ts'
|
||||
import type { GraphqlWriter } from '../src/mutation.ts'
|
||||
import {
|
||||
CANDIDATES_QUERY, gitHubReviewerCandidates, REQUEST_BOT_REVIEWS_MUTATION, REQUEST_REVIEWS_MUTATION, requestGitHubReviews,
|
||||
UPDATE_BRANCH_MUTATION, updateGitHubBranch,
|
||||
CANDIDATES_QUERY, DISABLE_AUTO_MERGE_MUTATION, ENABLE_AUTO_MERGE_MUTATION, gitHubReviewerCandidates, REQUEST_BOT_REVIEWS_MUTATION,
|
||||
REQUEST_REVIEWS_MUTATION, requestGitHubReviews, setGitHubAutoMerge, UPDATE_BRANCH_MUTATION, updateGitHubBranch,
|
||||
} from '../src/overview.ts'
|
||||
import { pullRequestNode } from '../src/pull-request-node.ts'
|
||||
import { pull } from './fixtures.ts'
|
||||
@@ -141,6 +141,65 @@ describe('branch updates', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('auto-merge', () => {
|
||||
const MOVED = 'e'.repeat(40)
|
||||
const on = { enabled: true, method: 'squash', headSha: HEAD } as const
|
||||
const refusal = { code: 'failed', message: 'Pull request Pull request is in clean status' } as const
|
||||
const stale = { code: 'stale', message: `the pull request head moved from ${HEAD} to ${MOVED}` } as const
|
||||
|
||||
it.each([['squash', 'SQUASH'], ['merge', 'MERGE'], ['rebase', 'REBASE']] as const)(
|
||||
'turns it on by %s for the confirmed head as GitHub expects it, after one read', async (method, mergeMethod) => {
|
||||
const write = vi.fn<GraphqlWriter>(async () => undefined)
|
||||
const lookup = reader(node())
|
||||
await expect(setGitHubAutoMerge(lookup.read, write, pull(7), { ...on, method }, signal)).resolves.toBeUndefined()
|
||||
expect(write.mock.calls).toEqual([['github.com', { query: ENABLE_AUTO_MERGE_MUTATION, field: 'enablePullRequestAutoMerge',
|
||||
variables: { input: { pullRequestId: 'PR_7', mergeMethod, expectedHeadOid: HEAD } } }, signal]])
|
||||
expect(lookup.calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('turns it off at any head, and passes on a refusal without another read', async () => {
|
||||
const write = vi.fn<GraphqlWriter>(async () => undefined)
|
||||
await expect(setGitHubAutoMerge(reader(node(MOVED)).read, write, pull(7), { enabled: false }, signal)).resolves.toBeUndefined()
|
||||
expect(write.mock.calls).toEqual([['github.com', { query: DISABLE_AUTO_MERGE_MUTATION, field: 'disablePullRequestAutoMerge',
|
||||
variables: { input: { pullRequestId: 'PR_7' } } }, signal]])
|
||||
const refused = reader(node())
|
||||
await expect(setGitHubAutoMerge(refused.read, vi.fn<GraphqlWriter>(async () => refusal), pull(7), { enabled: false }, signal))
|
||||
.resolves.toEqual(refusal)
|
||||
expect(refused.calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('refuses a moved head and a failed read without writing, and an invalid head without reading', async () => {
|
||||
const write = vi.fn<GraphqlWriter>()
|
||||
await expect(setGitHubAutoMerge(reader(node(MOVED)).read, write, pull(7), on, signal)).resolves.toEqual(stale)
|
||||
await expect(setGitHubAutoMerge(reader(new Error('signed out')).read, write, pull(7), { enabled: false }, signal))
|
||||
.resolves.toEqual({ code: 'unauthenticated', message: 'signed out' })
|
||||
const none = reader()
|
||||
await expect(setGitHubAutoMerge(none.read, write, pull(7), { ...on, headSha: 'main' }, signal))
|
||||
.rejects.toThrow('forge-github: invalid head commit "main"')
|
||||
expect(none.calls).toEqual([])
|
||||
expect(write).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['as stale once the head moved after the first read', node(MOVED), stale],
|
||||
['as GitHub worded it while the head stays', node(), refusal],
|
||||
['as GitHub worded it when the head cannot be read again', new Error('down'), refusal],
|
||||
])('reports a refusal to turn it on %s, without sending it again', async (_label, second, failure) => {
|
||||
const write = vi.fn<GraphqlWriter>(async () => refusal)
|
||||
const lookup = reader(node(), second)
|
||||
await expect(setGitHubAutoMerge(lookup.read, write, pull(7), on, signal)).resolves.toEqual(failure)
|
||||
expect(lookup.calls).toHaveLength(2)
|
||||
expect(write).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('leaves an outcome GitHub did not confirm unknown, without reading the head again', async () => {
|
||||
const unknown = { code: 'unknown', message: 'Something went wrong' } as const
|
||||
const lookup = reader(node())
|
||||
await expect(setGitHubAutoMerge(lookup.read, vi.fn<GraphqlWriter>(async () => unknown), pull(7), on, signal)).resolves.toEqual(unknown)
|
||||
expect(lookup.calls).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('reviewer candidates', () => {
|
||||
const account = (login: string, name: string | null = null) => ({ login, name, avatarUrl: null })
|
||||
const listing = (suggested: readonly unknown[], users: readonly unknown[], author: unknown = { login: 'Octo' }) => ({ data: { repository: {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { GH_COMMANDS } from '../src/commands.ts'
|
||||
import * as ForgeGitHub from '../src/index.ts'
|
||||
import { briefNode, pull, pullRequestNode } from './fixtures.ts'
|
||||
import { liveConfig, omitsGeneratedPage } from '../../../settings/settings/tests/live-config.ts'
|
||||
|
||||
let ctx: Context | undefined
|
||||
|
||||
@@ -93,8 +94,8 @@ describe('forge-github plugin', () => {
|
||||
|
||||
it.each([
|
||||
[{ ghCommand: ' ' }, 'forge-github: ghCommand must not be empty'],
|
||||
[{ hosts: [] }, 'forge-github: hosts must list at least one host'],
|
||||
[{ hosts: ['https://github.com'] }, 'forge-github: invalid host "https://github.com"'],
|
||||
[{ hosts: [] }, '$.hosts expected array length >= 1 but got 0'],
|
||||
[{ hosts: ['https://github.com'] }, '$.hosts[0] expect string to match regexp'],
|
||||
[{ timeoutMs: 0 }, 'forge-github: timeoutMs must be a positive integer no greater than 2147483647'],
|
||||
[{ timeoutMs: 2_147_483_648 }, 'forge-github: timeoutMs must be a positive integer no greater than 2147483647'],
|
||||
[{ timeoutMs: 1.5 }, 'forge-github: timeoutMs must be a positive integer no greater than 2147483647'],
|
||||
@@ -117,6 +118,43 @@ describe('forge-github plugin', () => {
|
||||
await expect(context.plugin(ForgeGitHub, config)).rejects.toThrow(message)
|
||||
})
|
||||
|
||||
it('serves the host list a live edit sets without mounting again', async () => {
|
||||
const context = await forge()
|
||||
const live = await liveConfig(context, ForgeGitHub)
|
||||
expect(context.forge.repositoryFromRemote('https://ghe.corp.example/team/svc.git')).toBeUndefined()
|
||||
|
||||
await live.update({ hosts: ['github.com', 'ghe.corp.example'] })
|
||||
|
||||
expect(context.forge.repositoryFromRemote('https://ghe.corp.example/team/svc.git')).toEqual({ forge: 'github', host: 'ghe.corp.example', owner: 'team', name: 'svc' })
|
||||
expect(context.forge.repositoryFromRemote('https://github.com/octo/demo.git')).toBeDefined()
|
||||
// Identity only: printing a Fiber walks Context proxies.
|
||||
expect(Object.is(live.entry.fiber, live.fiber)).toBe(true)
|
||||
|
||||
await live.update({ hosts: ['github.com'] })
|
||||
expect(context.forge.repositoryFromRemote('https://ghe.corp.example/team/svc.git')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps serving its previous hosts when a live edit adds one another provider serves', async () => {
|
||||
const context = await forge()
|
||||
context.forge.register({ ...otherProvider(), hosts: ['code.example.test'] })
|
||||
const live = await liveConfig(context, ForgeGitHub)
|
||||
const warned = vi.spyOn(context.logger, 'warn').mockImplementation(() => {})
|
||||
|
||||
await live.update({ hosts: ['github.com', 'code.example.test'] })
|
||||
|
||||
expect(context.forge.repositoryFromRemote('https://github.com/octo/demo.git')).toMatchObject({ forge: 'github', host: 'github.com' })
|
||||
expect(context.forge.changeRequestFromUrl('https://code.example.test/octo/demo/pull/1')).toBeUndefined()
|
||||
expect(warned.mock.calls.map((call): unknown => call[0]))
|
||||
.toContainEqual(new Error('forge: host "code.example.test" is already served by the "gitlab" provider'))
|
||||
})
|
||||
|
||||
it('keeps its own instance off the generated Settings pages', async () => {
|
||||
await omitsGeneratedPage(async (context) => {
|
||||
await context.plugin(ForgeService)
|
||||
return context.plugin(ForgeGitHub, {})
|
||||
})
|
||||
})
|
||||
|
||||
it('does not apply timer limits to the output byte budget', async () => {
|
||||
const context = await forge()
|
||||
await context.plugin(ForgeGitHub, { maxOutputBytes: 2_147_483_648 })
|
||||
@@ -124,6 +162,16 @@ describe('forge-github plugin', () => {
|
||||
})
|
||||
})
|
||||
|
||||
/** A provider of the `gitlab` family that serves nothing it is asked. */
|
||||
function otherProvider(): Parameters<Context['forge']['register']>[0] {
|
||||
const never = (): never => { throw new Error('not called') }
|
||||
return {
|
||||
forge: 'gitlab', hosts: [], label: 'GitLab', changeRequestNoun: 'merge-request',
|
||||
repositoryFromRemote: () => undefined, changeRequestFromUrl: () => undefined, changeRequestUrl: never, fetch: never,
|
||||
findByHead: never, readiness: never, markReady: never, merge: never, diff: never, fileText: never, fileUrl: never,
|
||||
}
|
||||
}
|
||||
|
||||
// The recording `gh` is a POSIX shell script, as in gh.spec.ts.
|
||||
describe.skipIf(process.platform === 'win32')('forge-github plugin status queries', () => {
|
||||
const cleanups: (() => Promise<void>)[] = []
|
||||
|
||||
@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from '../src/gh.ts'
|
||||
import type { GhOutput, GhRunner } from '../src/gh.ts'
|
||||
import { PULL_REQUEST_COMMITS_QUERY, THREADS_QUERY } from '../src/graphql.ts'
|
||||
import { CANDIDATES_QUERY } from '../src/overview.ts'
|
||||
import { CANDIDATES_QUERY, DISABLE_AUTO_MERGE_MUTATION, ENABLE_AUTO_MERGE_MUTATION } from '../src/overview.ts'
|
||||
import { VIEWED_QUERY } from '../src/viewed.ts'
|
||||
import { GitHubProvider } from '../src/provider.ts'
|
||||
import type { GitHubLimits } from '../src/provider.ts'
|
||||
@@ -941,6 +941,56 @@ describe('GitHub provider overview and viewed marks', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('turns auto-merge on for the confirmed head and off, each through one mutation on standard input', async () => {
|
||||
const gh = double(() => node)
|
||||
const subject = provider(gh.run)
|
||||
await expect(subject.setAutoMerge(pull(1), { enabled: true, method: 'rebase', headSha: HEAD }, signal)).resolves.toBeUndefined()
|
||||
await expect(subject.setAutoMerge(pull(1), { enabled: false }, signal)).resolves.toBeUndefined()
|
||||
expect(gh.inputs).toEqual([
|
||||
{ query: ENABLE_AUTO_MERGE_MUTATION, variables: { input: { pullRequestId: 'PR_1', mergeMethod: 'REBASE', expectedHeadOid: HEAD } } },
|
||||
{ query: DISABLE_AUTO_MERGE_MUTATION, variables: { input: { pullRequestId: 'PR_1' } } },
|
||||
])
|
||||
const mutation = ['api', 'graphql', '--hostname', 'github.com', '--input', '-']
|
||||
expect(gh.calls.filter(args => args.includes('--input'))).toEqual([mutation, mutation])
|
||||
})
|
||||
|
||||
const MOVED = 'e'.repeat(40)
|
||||
const squash = { enabled: true, method: 'squash', headSha: HEAD } as const
|
||||
/** GitHub's answer to a mutation it refuses, as `gh api graphql` prints it. */
|
||||
const refused = (message: string): GhOutput =>
|
||||
output({ data: { enablePullRequestAutoMerge: null }, errors: [{ type: 'UNPROCESSABLE', message }] }, 1, `gh: ${message}`)
|
||||
|
||||
it.each([
|
||||
['a refusal while the head stays', HEAD, refused('Pull request Pull request is in clean status'),
|
||||
{ code: 'failed', message: 'Pull request Pull request is in clean status' }, 2],
|
||||
['a refusal after the head moved', MOVED, refused('Head moved'),
|
||||
{ code: 'stale', message: `the pull request head moved from ${HEAD} to ${MOVED}` }, 2],
|
||||
['an error that does not name a refusal', HEAD, output({ data: null, errors: [{ message: 'Something went wrong' }] }, 1),
|
||||
{ code: 'unknown', message: 'Something went wrong' }, 1],
|
||||
['a server error', HEAD, output('', 1, 'gh: HTTP 502'), { code: 'unknown', message: 'gh: HTTP 502' }, 1],
|
||||
['a timeout', HEAD, new GhTimeoutError('gh timed out'), { code: 'unknown', message: 'gh timed out' }, 1],
|
||||
['a gh that cannot start', HEAD, new GhUnavailableError('gh could not start'), { code: 'failed', message: 'gh could not start' }, 2],
|
||||
])('reports turning auto-merge on answered with %s, sending the mutation once', async (_label, later, answer, failure, reads) => {
|
||||
let read = 0
|
||||
const gh = double(() => read++ === 0 ? node : { data: { repository: { pullRequest: { id: 'PR_1', headRefOid: later } } } }, () => {
|
||||
if (answer instanceof Error) throw answer
|
||||
return answer
|
||||
})
|
||||
await expect(provider(gh.run).setAutoMerge(pull(1), squash, signal)).resolves.toEqual(failure)
|
||||
expect(gh.inputs).toHaveLength(1)
|
||||
expect(read).toBe(reads)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a head that moved', () => output({ data: { repository: { pullRequest: { id: 'PR_1', headRefOid: MOVED } } } }), 'stale'],
|
||||
['missing credentials', () => output('', 1, 'gh: HTTP 401: Bad credentials'), 'unauthenticated'],
|
||||
['a pull request GitHub does not show', () => output({ data: { repository: { pullRequest: null } } }), 'failed'],
|
||||
] as const)('refuses to turn auto-merge on after %s, without a mutation', async (_label, answer, code) => {
|
||||
const gh = fakeGh(answer)
|
||||
await expect(provider(gh.run).setAutoMerge(pull(1), squash, signal)).resolves.toMatchObject({ code })
|
||||
expect(gh.calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('reruns each workflow run with a failed Actions job once, after confirming the head', async () => {
|
||||
const actions = (name: string, conclusion: string, run: number | null) => ({ ...checkRun(name, 'COMPLETED', conclusion),
|
||||
checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: run, event: 'pull_request', workflow: { id: name, name } } } })
|
||||
@@ -1006,6 +1056,7 @@ describe('GitHub provider overview and viewed marks', () => {
|
||||
await expect(subject.requestReviews(unconfigured, { reviewers: [{ kind: 'user', login: 'mona' }] }, signal)).resolves.toEqual(failure)
|
||||
await expect(subject.reviewerCandidates(unconfigured, '', signal)).resolves.toEqual({ ...failure, code: 'unavailable' })
|
||||
await expect(subject.updateBranch(unconfigured, { method: 'merge', headSha: HEAD }, signal)).resolves.toEqual(failure)
|
||||
await expect(subject.setAutoMerge(unconfigured, { enabled: false }, signal)).resolves.toEqual(failure)
|
||||
expect(gh.calls).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -40,7 +40,6 @@ function row(number: number, overrides: Record<string, unknown> = {}): Record<st
|
||||
commits: { nodes: [{ commit: { statusCheckRollup: { state: 'FAILURE' } } }] },
|
||||
viewerLatestReview: null,
|
||||
viewerLatestReviewRequest: { requestedReviewer: { __typename: 'User' } },
|
||||
closingIssuesReferences: { totalCount: 0, nodes: [] },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
@@ -69,16 +68,7 @@ describe('GitHub viewer lists', () => {
|
||||
|
||||
it('reads one list through one search on the queried host and maps each pull request', async () => {
|
||||
const gh = fakeGh(() => output(listBody([
|
||||
row(8225, {
|
||||
closingIssuesReferences: {
|
||||
totalCount: 4,
|
||||
nodes: [
|
||||
{ number: 8224, title: 'Identify the client', state: 'OPEN', url: 'https://github.com/octo/demo/issues/8224', repository: { name: 'demo', owner: { login: 'octo' } } },
|
||||
{ number: 9, title: 'Closed elsewhere', state: 'CLOSED', url: 'https://github.com/octo/other/issues/9', repository: { name: 'other', owner: { login: 'octo' } } },
|
||||
{ number: 10, title: 'Bad repository', state: 'OPEN', url: 'https://github.com/x/y/issues/10', repository: { name: 'a b', owner: { login: 'x' } } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
row(8225),
|
||||
row(7155, {
|
||||
isDraft: true,
|
||||
reviewDecision: 'CHANGES_REQUESTED',
|
||||
@@ -114,11 +104,6 @@ describe('GitHub viewer lists', () => {
|
||||
reviewDecision: 'none',
|
||||
viewerReview: null,
|
||||
viewerRequest: { team: null },
|
||||
closingIssues: [
|
||||
{ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 8224, title: 'Identify the client', state: 'open', url: 'https://github.com/octo/demo/issues/8224' },
|
||||
{ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'other' }, number: 9, title: 'Closed elsewhere', state: 'closed', url: 'https://github.com/octo/other/issues/9' },
|
||||
],
|
||||
closingIssuesTruncated: true,
|
||||
updatedAt: '2026-11-10T09:29:00Z',
|
||||
},
|
||||
expect.objectContaining({
|
||||
@@ -128,7 +113,6 @@ describe('GitHub viewer lists', () => {
|
||||
reviewDecision: 'changes-requested',
|
||||
viewerReview: { verdict: 'changes-requested', reviewedSha: '2'.repeat(40) },
|
||||
viewerRequest: { team: 'octo/core' },
|
||||
closingIssuesTruncated: false,
|
||||
}),
|
||||
expect.objectContaining({ title: 'Change 6', author: null, viewerReview: null, viewerRequest: null }),
|
||||
expect.objectContaining({ title: 'Change 7', viewerReview: { verdict: 'commented', reviewedSha: null }, viewerRequest: { team: null } }),
|
||||
|
||||
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user