dsh-remote-vs 0.15.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,428 @@
1
+ /**
2
+ * "Review this diff with AI" (F6): the pure half — byte accounting, the size
3
+ * tier decision and the prompt builder. No React, no DOM, no host access: the
4
+ * button in `scm/DiffView.tsx` calls these and hands the result to
5
+ * `appendToDraft` (`composer.ts`), the ONE delivery channel v1 uses.
6
+ *
7
+ * Why the byte accounting is not optional
8
+ * ---------------------------------------
9
+ * `git diff` runs through `capped()` in `git-ops.ts`: `| head -c GIT_CAP`, and
10
+ * `RemoteExecResult` carries no `truncated` flag — the cut is SILENT. Sending
11
+ * such a prefix as "the diff" produces a confident review of half a patch: a
12
+ * wrong answer with no marker anywhere. So the caller compares BYTES against
13
+ * `GIT_CAP`, and `pickReviewMode` refuses `full` for a capped diff even when the
14
+ * prefix would fit the inline budget: a truncated diff can never be reviewed as
15
+ * if it were complete.
16
+ *
17
+ * Two thresholds, two different jobs:
18
+ * - `GIT_CAP` (2,000,000 B, `git-ops.ts`): the read was CUT, so the prompt's
19
+ * FIRST line has to say so.
20
+ * - `AI_REVIEW_MAX_BYTES` (32 KiB ≈ 8–10k tokens): above it the diff is not
21
+ * inlined at all. The prompt carries the file, the scope and the `@@` hunk
22
+ * headers, and tells the model to fetch the diff itself (a read or a
23
+ * `git diff` on the remote host) instead of spending a whole context window
24
+ * on one message — 2 MB would be ~550–700k tokens and could never be sent.
25
+ *
26
+ * The fence length is computed, never hardcoded: a file that CONTAINS ``` would
27
+ * close a 3-backtick fence early and the rest of the patch would be read as
28
+ * prose. One backtick more than the longest run inside makes that impossible.
29
+ */
30
+ import { GIT_CAP } from '../git-ops.ts'
31
+
32
+ /** Largest complete diff we inline into the prompt, in BYTES (≈8–10k tokens). */
33
+ export const AI_REVIEW_MAX_BYTES = 32 * 1024
34
+
35
+ /** How many `@@` headers a summary prompt enumerates before it stops. */
36
+ export const AI_REVIEW_MAX_HUNKS = 40
37
+
38
+ /** How much of the diff the prompt carries. */
39
+ export type ReviewMode = 'full' | 'summary' | 'pathOnly'
40
+
41
+ /** Which revision range the diff describes (the SCM view's three diff tabs). */
42
+ export type ReviewScope = 'worktree' | 'staged' | 'commit'
43
+
44
+ /** Prompt language. Follows the UI language (`store.lang`), no separate setting. */
45
+ export type ReviewLang = 'zh' | 'en'
46
+
47
+ /** Everything the prompt template needs, all of it already in the caller's hands. */
48
+ export interface ReviewPromptInput {
49
+ /** SSH host alias the diff was read from (named in the prompt, no secrets). */
50
+ alias: string
51
+ /** Repository root on that host (absolute POSIX path). */
52
+ root: string
53
+ /** Repository-relative path of the file. */
54
+ rel: string
55
+ /** Absolute remote path of the file. */
56
+ fullPath: string
57
+ scope: ReviewScope
58
+ /** The commit the diff was drilled down from, for `scope: 'commit'`. */
59
+ commitRef?: string
60
+ /** Unified diff text (`tab.diff.diff`), possibly empty for untracked/binary. */
61
+ diff: string
62
+ mode: ReviewMode
63
+ /** The diff is a `GIT_CAP`-capped PREFIX (the host truncated it silently). */
64
+ capped: boolean
65
+ lang: ReviewLang
66
+ }
67
+
68
+ /** UTF-8 byte length — the unit `head -c` and therefore `GIT_CAP` count. */
69
+ export function diffByteLength(diff: string): number {
70
+ return new TextEncoder().encode(diff).length
71
+ }
72
+
73
+ /**
74
+ * Which revision range a diff tab shows.
75
+ *
76
+ * `ref` wins over `staged`, and that order is load-bearing: a commit drill-down
77
+ * tab is BOTH `staged: true` and `ref: hash` (`store.openCommitFile`), so asking
78
+ * `staged` first would label a commit's diff as "staged changes" and point the
79
+ * model at the index instead of the commit.
80
+ */
81
+ export function reviewScopeOf(staged: boolean, ref: string | undefined): ReviewScope {
82
+ if (ref !== undefined) return 'commit'
83
+ if (staged) return 'staged'
84
+ return 'worktree'
85
+ }
86
+
87
+ /**
88
+ * Which prompt shape this diff gets.
89
+ *
90
+ * Order matters. `pathOnly` answers "there is no diff text at all" (untracked /
91
+ * binary / failed read) and outranks the rest because it needs no budget.
92
+ * `capped` outranks the size test: a 1 KiB prefix of a 2 MB patch is not a
93
+ * small diff, it is a CUT one. Only a complete, small diff earns `full`.
94
+ */
95
+ export function pickReviewMode(input: { bytes: number; hasDiff: boolean; capped: boolean }): ReviewMode {
96
+ if (!input.hasDiff) return 'pathOnly'
97
+ if (input.capped) return 'summary'
98
+ if (input.bytes <= AI_REVIEW_MAX_BYTES) return 'full'
99
+ return 'summary'
100
+ }
101
+
102
+ /** Longest unbroken run of backticks in `text` (0 when there is none). */
103
+ export function longestBacktickRun(text: string): number {
104
+ let longest = 0
105
+ for (const run of text.matchAll(/`+/g)) {
106
+ if (run[0].length > longest) longest = run[0].length
107
+ }
108
+ return longest
109
+ }
110
+
111
+ /**
112
+ * A code fence `diff` itself cannot close: one backtick longer than the longest
113
+ * run inside it, never shorter than the usual three.
114
+ */
115
+ export function diffFence(diff: string): string {
116
+ return '`'.repeat(Math.max(3, longestBacktickRun(diff) + 1))
117
+ }
118
+
119
+ /**
120
+ * The `@@ … @@` hunk headers of a unified diff, in order.
121
+ *
122
+ * A line starting with `@@` can only be a header: every content line of a
123
+ * unified diff begins with ' ', '+' or '-', and the file-level lines begin with
124
+ * `diff --git`, `index`, `---`, `+++`, `new file` or `deleted file`.
125
+ */
126
+ export function hunkHeaders(diff: string): string[] {
127
+ return diff.split('\n').filter(line => line.startsWith('@@'))
128
+ }
129
+
130
+ /** How the prompt names the revision range. */
131
+ const SCOPE_LABEL: Record<ReviewLang, Record<ReviewScope, string>> = {
132
+ zh: { worktree: '工作区未暂存的更改', staged: '已暂存的更改', commit: '提交' },
133
+ en: { worktree: 'unstaged working-tree changes', staged: 'staged changes', commit: 'commit' },
134
+ }
135
+
136
+ function scopeLabel(scope: ReviewScope, commitRef: string | undefined, lang: ReviewLang): string {
137
+ const base = SCOPE_LABEL[lang][scope]
138
+ if (scope !== 'commit' || commitRef === undefined) return base
139
+ return `${base} ${commitRef}`
140
+ }
141
+
142
+ /**
143
+ * The warning that must be the prompt's FIRST line when the diff was capped.
144
+ *
145
+ * The number comes from `GIT_CAP` itself, so the prompt cannot drift from the
146
+ * command that did the cut. The language is the reviewer's, like the rest.
147
+ */
148
+ function cappedWarning(lang: ReviewLang): string {
149
+ if (lang === 'zh') {
150
+ return `⚠ 这份 diff 在 ${GIT_CAP} 字节处被静默截断:下面只是前缀,后面的文件与代码块可能缺失,请以远端实际内容为准。`
151
+ }
152
+ return `⚠ This diff was silently truncated at ${GIT_CAP} bytes: only a prefix is shown, so later files and hunks may be missing — rely on the real remote content.`
153
+ }
154
+
155
+ /** The file/scope facts every prompt carries, right after the headline. */
156
+ function contextLines(input: ReviewPromptInput): string[] {
157
+ const scope = scopeLabel(input.scope, input.commitRef, input.lang)
158
+ if (input.lang === 'zh') {
159
+ return [
160
+ `目标文件:${input.fullPath}(仓库内相对路径 ${input.rel})`,
161
+ `主机:${input.alias}`,
162
+ `仓库根:${input.root}`,
163
+ `差异范围:${scope}`,
164
+ ]
165
+ }
166
+ return [
167
+ `Target file: ${input.fullPath} (repository-relative path ${input.rel})`,
168
+ `Host: ${input.alias}`,
169
+ `Repository root: ${input.root}`,
170
+ `Diff scope: ${scope}`,
171
+ ]
172
+ }
173
+
174
+ /**
175
+ * The review instructions every prompt carries.
176
+ *
177
+ * Phrased as RULES rather than a persona because the receiver is a coding agent
178
+ * with write access to the same host: this text lands in a normal draft and can
179
+ * be sent as-is, so "change nothing" has to be explicit.
180
+ */
181
+ function reviewRules(lang: ReviewLang): string[] {
182
+ if (lang === 'zh') {
183
+ return [
184
+ '1. 只做审查:不要修改、暂存、提交或删除任何文件,也不要运行会改变工作区的命令。',
185
+ '2. 重点看正确性、边界条件(空值 / 超大输入 / 异常路径)与错误处理(是否吞掉失败),以及与仓库既有约定不一致的地方(命名、分层、注释风格)。',
186
+ '3. 每条问题用「文件:行号」定位(变更后的行号),说明为什么是问题、建议怎么改。',
187
+ '4. 不要复述 diff 内容,直接给结论;没有发现问题就明确说「未发现问题」。',
188
+ ]
189
+ }
190
+ return [
191
+ '1. Review only: do not modify, stage, commit or delete any file, and do not run commands that change the working tree.',
192
+ '2. Focus on correctness, boundary conditions (empty / huge input / unusual paths), swallowed failures, and anything that breaks the repository conventions (naming, layering, comment style).',
193
+ '3. Locate every finding as "file:line" (line numbers AFTER the change) and say why it is a problem and how you would fix it.',
194
+ '4. Do not restate the diff; give conclusions only, and say "no issues found" explicitly when there are none.',
195
+ ]
196
+ }
197
+
198
+ /** The fenced, verbatim diff of a completed read. */
199
+ function fullBlock(input: ReviewPromptInput): string[] {
200
+ const intro = input.lang === 'zh' ? '完整 diff:' : 'Complete diff:'
201
+ // A trailing newline would put a blank line before the closing fence; drop
202
+ // exactly one so the block stays tight.
203
+ const body = input.diff.endsWith('\n') ? input.diff.slice(0, -1) : input.diff
204
+ const fence = diffFence(input.diff)
205
+ return [intro, `${fence}diff`, body, fence]
206
+ }
207
+
208
+ /**
209
+ * The size-reduced prompt: no diff body, but the anchors a reviewer needs.
210
+ *
211
+ * The `@@` headers are the part of a large diff that is cheap and useful — they
212
+ * say WHERE the changes are, so the model can read those regions instead of the
213
+ * whole patch. The body is deliberately absent: shipping it would defeat the
214
+ * budget this branch exists for.
215
+ */
216
+ function summaryBlock(input: ReviewPromptInput): string[] {
217
+ const headers = hunkHeaders(input.diff)
218
+ const listed = headers.slice(0, AI_REVIEW_MAX_HUNKS)
219
+ const omitted = headers.length - listed.length
220
+ const lines: string[] = []
221
+ if (input.lang === 'zh') {
222
+ lines.push(`diff 大小:${diffByteLength(input.diff)} 字节;超过 ${AI_REVIEW_MAX_BYTES} 字节的内嵌上限,所以没有内嵌全文(按块摘要见下)。`)
223
+ lines.push('')
224
+ lines.push(`变更块(从 diff 的 @@ 头提取,共 ${headers.length} 处,最多列出 ${AI_REVIEW_MAX_HUNKS} 处):`)
225
+ } else {
226
+ lines.push(`Diff size: ${diffByteLength(input.diff)} bytes; above the ${AI_REVIEW_MAX_BYTES}-byte inline limit, so the body is not included (per-hunk summary below).`)
227
+ lines.push('')
228
+ lines.push(`Changed hunks (taken from the diff's @@ headers; ${headers.length} in total, at most ${AI_REVIEW_MAX_HUNKS} listed):`)
229
+ }
230
+ if (listed.length === 0) {
231
+ lines.push(input.lang === 'zh' ? '(没有解析到 @@ 头:这份 diff 可能不是标准 unified 输出)' : '(no @@ header found: the diff may not be standard unified output)')
232
+ }
233
+ lines.push(...listed)
234
+ if (omitted > 0) {
235
+ lines.push(input.lang === 'zh' ? `(另有 ${omitted} 处变更块未列出)` : `(${omitted} more hunks not listed)`)
236
+ }
237
+ lines.push('')
238
+ if (input.lang === 'zh') {
239
+ lines.push(`获取完整内容:请读取 ${input.fullPath},或在该主机(${input.alias})的仓库根 ${input.root} 上自行执行 git diff / git show 取回完整差异,再用上面的 @@ 头定位。`)
240
+ } else {
241
+ lines.push(`Get the full text: read ${input.fullPath}, or run git diff / git show yourself in the repository root ${input.root} on host ${input.alias}, then use the @@ headers above as anchors.`)
242
+ }
243
+ return lines
244
+ }
245
+
246
+ /**
247
+ * The no-text prompt: untracked and binary files have no diff to send, so the
248
+ * model is asked to read the file and obtain the diff itself — never an empty
249
+ * fenced block, which reads as "the change is empty".
250
+ */
251
+ function pathOnlyBlock(input: ReviewPromptInput): string[] {
252
+ if (input.lang === 'zh') {
253
+ return [
254
+ '没有可内嵌的 diff 文本(未跟踪文件或二进制文件没有文本差异)。',
255
+ `请在该主机上读取 ${input.fullPath} 并自行获取差异(git diff / git show),然后按下面的要求审查。`,
256
+ ]
257
+ }
258
+ return [
259
+ 'No diff text is available (an untracked or binary file has no textual diff).',
260
+ `Read ${input.fullPath} on that host and obtain the diff yourself (git diff / git show), then review it against the requirements below.`,
261
+ ]
262
+ }
263
+
264
+ /**
265
+ * The prompt that goes into the composer draft.
266
+ *
267
+ * `mode` is what the caller decided (see {@link pickReviewMode}), but an empty
268
+ * diff is normalized to `pathOnly` here as well: an empty file is not an empty
269
+ * CHANGE, and an empty fenced block would answer the wrong question.
270
+ */
271
+ export function buildReviewPrompt(input: ReviewPromptInput): string {
272
+ const mode: ReviewMode = input.diff === '' ? 'pathOnly' : input.mode
273
+ const lines: string[] = []
274
+ // The cap warning is the FIRST line on purpose: it is the one fact that must
275
+ // not be buried (a review of a prefix presented as a review of the change is
276
+ // the failure mode this whole module guards).
277
+ if (input.capped) lines.push(cappedWarning(input.lang))
278
+ lines.push(input.lang === 'zh' ? '请审查下面这个文件的改动。' : 'Please review the change to the file below.')
279
+ lines.push('')
280
+ lines.push(...contextLines(input))
281
+ lines.push('')
282
+ let body: string[]
283
+ if (mode === 'full') body = fullBlock(input)
284
+ else if (mode === 'summary') body = summaryBlock(input)
285
+ else body = pathOnlyBlock(input)
286
+ lines.push(...body)
287
+ lines.push('')
288
+ lines.push(input.lang === 'zh' ? '审查要求:' : 'Review requirements:')
289
+ lines.push(...reviewRules(input.lang))
290
+ return lines.join('\n')
291
+ }
292
+
293
+ // ------------------------------------------------------- whole-commit review
294
+
295
+ /** How many changed files a commit prompt enumerates before it stops. */
296
+ export const AI_REVIEW_MAX_FILES = 100
297
+
298
+ /** One `git show --name-status` row, as the prompt needs it. */
299
+ export interface CommitFileLike {
300
+ /** Single letter (`R`/`C` for renames/copies). */
301
+ status: string
302
+ path: string
303
+ /** Rename/copy source. */
304
+ origPath?: string
305
+ }
306
+
307
+ /** Everything a whole-commit prompt needs — all of it already on the history pane. */
308
+ export interface CommitReviewInput {
309
+ /** SSH host alias the commit was read from (named, no secrets). */
310
+ alias: string
311
+ /** Repository root on that host (absolute POSIX path). */
312
+ root: string
313
+ hash: string
314
+ subject: string
315
+ /** Message body below the subject ('' when there is none). */
316
+ body: string
317
+ /** Files the commit touched (`git show --name-status`); empty when unread. */
318
+ files: readonly CommitFileLike[]
319
+ /** Raw `git show --patch` text ('' when the commit has no textual diff). */
320
+ patch: string
321
+ mode: ReviewMode
322
+ /** The patch is a `GIT_CAP`-capped PREFIX (`loadCommitPatch.truncated`). */
323
+ capped: boolean
324
+ lang: ReviewLang
325
+ }
326
+
327
+ /** `A\tsrc/a.ts`, or `R\tsrc/a.ts → src/b.ts` for a rename. */
328
+ function commitFileLine(file: CommitFileLike): string {
329
+ if (file.origPath === undefined || file.origPath === file.path) return `${file.status}\t${file.path}`
330
+ return `${file.status}\t${file.origPath} → ${file.path}`
331
+ }
332
+
333
+ /** The commit's identity and files, in both languages. */
334
+ function commitFacts(input: CommitReviewInput): string[] {
335
+ const lines: string[] = []
336
+ if (input.lang === 'zh') {
337
+ lines.push(`提交:${input.hash}`, `标题:${input.subject}`)
338
+ if (input.body.trim() !== '') lines.push(`提交说明:\n${input.body.trim()}`)
339
+ lines.push(`主机:${input.alias}`, `仓库根:${input.root}`)
340
+ } else {
341
+ lines.push(`Commit: ${input.hash}`, `Subject: ${input.subject}`)
342
+ if (input.body.trim() !== '') lines.push(`Commit message:\n${input.body.trim()}`)
343
+ lines.push(`Host: ${input.alias}`, `Repository root: ${input.root}`)
344
+ }
345
+ if (input.files.length === 0) return lines
346
+ const listed = input.files.slice(0, AI_REVIEW_MAX_FILES)
347
+ const omitted = input.files.length - listed.length
348
+ lines.push('')
349
+ lines.push(input.lang === 'zh'
350
+ ? `改动文件(${input.files.length} 个,最多列出 ${AI_REVIEW_MAX_FILES} 个):`
351
+ : `Changed files (${input.files.length} total, at most ${AI_REVIEW_MAX_FILES} listed):`)
352
+ lines.push(...listed.map(commitFileLine))
353
+ if (omitted > 0) lines.push(input.lang === 'zh' ? `(另有 ${omitted} 个文件未列出)` : `(${omitted} more files not listed)`)
354
+ return lines
355
+ }
356
+
357
+ /** The fenced, verbatim `git show --patch` body. */
358
+ function commitFullBlock(input: CommitReviewInput): string[] {
359
+ const intro = input.lang === 'zh' ? '完整 patch:' : 'Complete patch:'
360
+ const body = input.patch.endsWith('\n') ? input.patch.slice(0, -1) : input.patch
361
+ const fence = diffFence(input.patch)
362
+ return [intro, `${fence}diff`, body, fence]
363
+ }
364
+
365
+ /**
366
+ * The size-reduced commit prompt: the file list above is the map, and the model
367
+ * is told how to fetch the patch instead of being handed a truncated prefix.
368
+ */
369
+ function commitSummaryBlock(input: CommitReviewInput): string[] {
370
+ const hunks = hunkHeaders(input.patch).length
371
+ const bytes = diffByteLength(input.patch)
372
+ if (input.lang === 'zh') {
373
+ return [
374
+ `patch 大小:${bytes} 字节,共 ${hunks} 处变更块${input.capped ? '(已被截断)' : `(超过 ${AI_REVIEW_MAX_BYTES} 字节的内嵌上限)`},所以没有内嵌全文。`,
375
+ `获取完整内容:请在该主机(${input.alias})的仓库根 ${input.root} 上执行 git show ${input.hash} 取回完整 patch,必要时再逐个读取上面列出的文件。`,
376
+ ]
377
+ }
378
+ return [
379
+ `Patch size: ${bytes} bytes, ${hunks} hunks${input.capped ? ' (truncated)' : ` (above the ${AI_REVIEW_MAX_BYTES}-byte inline limit)`}, so the body is not included.`,
380
+ `Get the full text: run git show ${input.hash} in the repository root ${input.root} on host ${input.alias}, then read the files listed above as needed.`,
381
+ ]
382
+ }
383
+
384
+ /** The no-text commit prompt (empty commit, binary-only change, merge). */
385
+ function commitPathOnlyBlock(input: CommitReviewInput): string[] {
386
+ if (input.lang === 'zh') {
387
+ return [
388
+ '该提交没有可内嵌的文本 diff(可能是空提交、仅二进制改动或合并提交)。',
389
+ `请在该主机(${input.alias})的仓库根 ${input.root} 上执行 git show ${input.hash} 查看完整改动,然后按下面的要求审查。`,
390
+ ]
391
+ }
392
+ return [
393
+ 'This commit has no inline textual diff (empty commit, binary-only change, or a merge).',
394
+ `Run git show ${input.hash} in the repository root ${input.root} on host ${input.alias}, then review it against the requirements below.`,
395
+ ]
396
+ }
397
+
398
+ /** One rule that only makes sense for a WHOLE commit (cross-file coherence). */
399
+ function commitRule(lang: ReviewLang): string {
400
+ if (lang === 'zh') return '5. 以整个提交为单位:核对提交信息与改动是否一致,以及多个文件之间的关联改动是否有遗漏或不一致。'
401
+ return '5. Review the commit as a whole: does the message match the change, and are the related edits across files consistent and complete?'
402
+ }
403
+
404
+ /**
405
+ * The prompt for reviewing a WHOLE commit from the history pane (F6 v2).
406
+ *
407
+ * Same byte discipline as the single-file prompt (a capped `git show --patch`
408
+ * must never be presented as the complete change), but the shape differs: a
409
+ * commit is a set of files, so the facts list the files and the model is told
410
+ * how to fetch the patch. `mode` is what the caller decided; an empty patch is
411
+ * normalized to `pathOnly` here as well.
412
+ */
413
+ export function buildCommitReviewPrompt(input: CommitReviewInput): string {
414
+ const mode: ReviewMode = input.patch === '' ? 'pathOnly' : input.mode
415
+ const lines: string[] = []
416
+ if (input.capped) lines.push(cappedWarning(input.lang))
417
+ lines.push(input.lang === 'zh' ? '请审查下面这个提交的改动。' : 'Please review the changes in the commit below.')
418
+ lines.push('')
419
+ lines.push(...commitFacts(input))
420
+ lines.push('')
421
+ if (mode === 'full') lines.push(...commitFullBlock(input))
422
+ else if (mode === 'summary') lines.push(...commitSummaryBlock(input))
423
+ else lines.push(...commitPathOnlyBlock(input))
424
+ lines.push('')
425
+ lines.push(input.lang === 'zh' ? '审查要求:' : 'Review requirements:')
426
+ lines.push(...reviewRules(input.lang), commitRule(input.lang))
427
+ return lines.join('\n')
428
+ }
@@ -273,6 +273,24 @@ function inputFor(
273
273
  }
274
274
  }
275
275
 
276
+ /**
277
+ * Whether this session has a usable draft-insert channel right now.
278
+ *
279
+ * A PREFLIGHT for surfaces that must not offer an action they cannot complete
280
+ * (the diff view's "review this diff with AI" button): the conversation service
281
+ * is a soft, version-dependent read (see {@link conversationOf}), so on a host
282
+ * that does not expose it the button has to say so up front instead of failing
283
+ * on click with a message about a busy composer — a wrong cause is worse than no
284
+ * button.
285
+ *
286
+ * Read-only and side-effect free on purpose: it never calls
287
+ * `input.for()` (resolving the facade could materialise a per-session input
288
+ * shell), so it can run on every render of the owning view.
289
+ */
290
+ export function canInsertDraft(ctx: Context, sessionId: string): boolean {
291
+ return sessionScope(ctx, sessionId) !== undefined && conversationOf(ctx) !== undefined
292
+ }
293
+
276
294
  /**
277
295
  * Mint one reference chip through the host's public `insertReference` facade —
278
296
  * the same method the native `@` picker's event listener calls, so the
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Spring-loaded directory expansion during a drag.
3
+ *
4
+ * A file manager opens a folder when a dragged item RESTS on it for a moment
5
+ * ("spring-loaded folder", macOS Finder / VS Code behaviour): without it the
6
+ * user has to remember the target path, drop, then find the file again inside
7
+ * the freshly opened tree. The editor's drop path already lands a drop on the
8
+ * row under the pointer (`RemoteExplorer` `dropDirFromEvent`), so opening the
9
+ * row mid-drag is what makes the gesture a single movement instead of two.
10
+ *
11
+ * Why this is a module of its own with an INJECTED scheduler
12
+ * ---------------------------------------------------------
13
+ * The rule that matters is timing, and timing is exactly what a jsdom/node gate
14
+ * cannot observe through `window.setTimeout` without waiting real seconds. The
15
+ * scheduler seam lets `scripts/check-drag-expand.mjs` drive a fake clock and
16
+ * pin every transition; the view passes `window`'s functions in. Nothing here
17
+ * touches the DOM, React or a browser global.
18
+ *
19
+ * Why ONE candidate
20
+ * -----------------
21
+ * There is one pointer and one drag. Keeping a set would let two directories
22
+ * open from a single path if `dragleave` were ever missed, and the second open
23
+ * would move the row the user is aiming at.
24
+ */
25
+
26
+ /**
27
+ * How long the pointer must rest on a closed directory before it opens, in ms.
28
+ *
29
+ * Long enough that a drag ACROSS the tree does not flash every folder open on
30
+ * the way; short enough that a deliberate pause feels like the folder was
31
+ * waiting. 650 ms is a common file-manager value (Finder uses ~0.5 s) and sits
32
+ * well above `PREFETCH_HOVER_MS` (150 ms), so the listing warm-up still starts
33
+ * first and the expand usually paints from the warmed cache.
34
+ */
35
+ export const DRAG_EXPAND_DELAY_MS = 650
36
+
37
+ /**
38
+ * The timer functions the expander needs.
39
+ *
40
+ * Injected rather than imported so the gate can run on a fake clock; the view
41
+ * passes `window.setTimeout` / `window.clearTimeout` (they return numbers in a
42
+ * browser, which is why the handle is a number).
43
+ */
44
+ export interface DragExpandScheduler {
45
+ set(callback: () => void, ms: number): number
46
+ clear(handle: number): void
47
+ }
48
+
49
+ /** The handle the view talks to (one per mounted tree). */
50
+ export interface DragExpander {
51
+ /**
52
+ * The pointer is resting on `dir`: open it after the delay.
53
+ *
54
+ * Idempotent for the same directory on purpose. `dragover` fires repeatedly
55
+ * (every few hundred ms at least) while a drag stays still, and restarting
56
+ * the countdown on every event would mean it never completes.
57
+ */
58
+ hover(dir: string): void
59
+ /**
60
+ * The pointer left `dir`.
61
+ *
62
+ * Cancels only when `dir` is the current candidate: React delivers a leave
63
+ * for rows the pointer merely passed through, and one late leave from a row
64
+ * the pointer already left must not cancel the timer armed on the row it now
65
+ * rests on.
66
+ */
67
+ leave(dir: string): void
68
+ /** Cancel any pending open (drop, dragend, binding change, unmount). */
69
+ reset(): void
70
+ /** The directory a countdown is running for, or undefined. Test seam. */
71
+ pending(): string | undefined
72
+ }
73
+
74
+ /**
75
+ * Build one expander.
76
+ *
77
+ * @param onExpand - called ONCE per rest, after the delay, with the directory
78
+ * that was still hovered when the timer fired.
79
+ * @param scheduler - timer implementation (see {@link DragExpandScheduler}).
80
+ * @param delayMs - rest time; defaults to {@link DRAG_EXPAND_DELAY_MS}.
81
+ */
82
+ export function createDragExpander(
83
+ onExpand: (dir: string) => void,
84
+ scheduler: DragExpandScheduler,
85
+ delayMs: number = DRAG_EXPAND_DELAY_MS,
86
+ ): DragExpander {
87
+ /** The directory a timer is running for; undefined = idle. */
88
+ let candidate: string | undefined
89
+ /** The pending timer handle, or undefined when idle. */
90
+ let timer: number | undefined
91
+
92
+ const clear = (): void => {
93
+ if (timer !== undefined) {
94
+ scheduler.clear(timer)
95
+ timer = undefined
96
+ }
97
+ }
98
+
99
+ return {
100
+ hover(dir: string): void {
101
+ // A second dragover for the row already counting down: keep the original
102
+ // deadline (see the interface docstring).
103
+ if (candidate === dir && timer !== undefined) return
104
+ clear()
105
+ candidate = dir
106
+ timer = scheduler.set(() => {
107
+ // A leave (or a different hover) may have replaced the candidate while
108
+ // the callback sat in the queue; only the CURRENT one may open.
109
+ if (candidate !== dir) return
110
+ candidate = undefined
111
+ timer = undefined
112
+ onExpand(dir)
113
+ }, delayMs)
114
+ },
115
+ leave(dir: string): void {
116
+ if (candidate !== dir) return
117
+ clear()
118
+ candidate = undefined
119
+ },
120
+ reset(): void {
121
+ clear()
122
+ candidate = undefined
123
+ },
124
+ pending(): string | undefined {
125
+ return candidate
126
+ },
127
+ }
128
+ }
@@ -463,6 +463,15 @@ const zh: Record<string, string> = {
463
463
  'scm.commitDiff': '提交差异',
464
464
  'scm.checkoutCommitTitle': '检出提交(分离头指针)',
465
465
  'scm.checkoutCommitText': '将把远端工作区切到 {hash},处于分离头指针状态。',
466
+ // -- AI 审查此 diff(只预填草稿,不自动发送)
467
+ 'scm.aiReview': '让 AI 审查此 diff(只追加到对话草稿,不会自动发送)',
468
+ 'scm.aiReviewNoSession': '当前会话与这个远端工作区没有绑定:绑定后才能把 diff 交给 AI 审查',
469
+ 'scm.aiReviewNoContext': '插件上下文尚未就绪,暂时无法写入对话草稿',
470
+ 'scm.aiReviewNoChannel': '当前宿主没有可用的对话输入通道,无法写入草稿(宿主版本可能不兼容)',
471
+ 'scm.aiReviewAdded': '已追加到对话草稿,请检查后发送',
472
+ 'scm.aiReviewAddedSummary': 'diff 较大(或已被截断),已按摘要方式追加到草稿,请检查后发送',
473
+ 'scm.aiReviewAddedRead': '该文件没有可内嵌的 diff 文本(新增或未跟踪),已让 AI 自行读取,请检查后发送',
474
+ 'scm.aiReviewFailed': '追加失败:当前会话的输入框不可用(可能正在发送或校验中),请稍后重试',
466
475
  'history.filter': '过滤提交(信息 / 作者 / 哈希)',
467
476
  'history.details': '提交详情',
468
477
  'history.content': '内容',
@@ -490,6 +499,9 @@ const zh: Record<string, string> = {
490
499
  'history.copyMessage': '复制提交信息',
491
500
  'history.copyFilePatch': '复制该文件补丁',
492
501
  'history.copyCommitPatch': '复制整个补丁',
502
+ // -- 按提交记录做 AI 审查(只预填草稿,不自动发送;v2)
503
+ 'history.aiReview': '让 AI 审查此提交(只追加到对话草稿,不会自动发送)',
504
+ 'history.aiReviewNoPatch': '该提交的 patch 尚未加载完成,或没有可内嵌的文本 diff',
493
505
  'history.copiedMessage': '已复制提交信息',
494
506
  'history.copiedHash': '已复制完整哈希',
495
507
  'history.copiedSubject': '已复制提交标题',
@@ -997,6 +1009,15 @@ const en: Record<string, string> = {
997
1009
  'scm.commitDiff': 'commit diff',
998
1010
  'scm.checkoutCommitTitle': 'Check out commit (detached HEAD)',
999
1011
  'scm.checkoutCommitText': 'The remote working tree switches to {hash} in detached HEAD state.',
1012
+ // -- AI review of this diff (draft only: nothing is sent automatically)
1013
+ 'scm.aiReview': 'Ask AI to review this diff (appends to the conversation draft; nothing is sent automatically)',
1014
+ 'scm.aiReviewNoSession': 'No session is bound to this remote workspace — binding one is what lets the diff be handed to AI',
1015
+ 'scm.aiReviewNoContext': 'The plugin context is not ready yet, so the draft cannot be written',
1016
+ 'scm.aiReviewNoChannel': 'This host exposes no conversation input channel, so the draft cannot be written (the host version may be incompatible)',
1017
+ 'scm.aiReviewAdded': 'Appended to the conversation draft — check it, then send',
1018
+ 'scm.aiReviewAddedSummary': 'Large (or truncated) diff: appended as a summary — check it, then send',
1019
+ 'scm.aiReviewAddedRead': 'This file has no inline diff (added or untracked), so AI was asked to read it — check the draft, then send',
1020
+ 'scm.aiReviewFailed': 'Append failed: this session’s composer is not writable right now (it may be sending) — try again later',
1000
1021
  'history.filter': 'Filter commits (message / author / hash)',
1001
1022
  'history.details': 'Commit details',
1002
1023
  'history.content': 'Contents',
@@ -1024,6 +1045,9 @@ const en: Record<string, string> = {
1024
1045
  'history.copyMessage': 'Copy commit message',
1025
1046
  'history.copyFilePatch': 'Copy file patch',
1026
1047
  'history.copyCommitPatch': 'Copy whole patch',
1048
+ // -- AI review of a WHOLE commit (draft only: nothing is sent automatically; v2)
1049
+ 'history.aiReview': 'Ask AI to review this commit (appends to the conversation draft; nothing is sent automatically)',
1050
+ 'history.aiReviewNoPatch': 'This commit’s patch is not loaded yet, or it has no inline textual diff',
1027
1051
  'history.copiedMessage': 'Commit message copied',
1028
1052
  'history.copiedHash': 'Full hash copied',
1029
1053
  'history.copiedSubject': 'Subject copied',