Files
apes-sidebar/src/wire.ts
T
Menghuan1918andrainmanhhh 6615f63602 feat(git): AI 生成提交信息(Ctrl+G、多行提交框、可固定生成模型)
移植 PR #642(refs/tmp/pr642 → 当前 dev 重写,不机械解冲突)。

复用(与 dev clean 或纯逻辑无冲突面):
- src/commit-message.ts 纯逻辑模块原样取用:prompt 契约、provider/model 路由
  词法、reasoning effort 取最低档、宽容的 provider/model 目录读取、建议文本清理。
- host 半边(git.suggest-message / git.commit-model / git.models 三条路由 +
  pinned / 会话 / agent-default-model 三级路由解析)按 dev 现状重贴:ctx.llm、
  agentDefaultModel、git.status/diff、sessionId 参数名逐条对照本机 0.2.0-rc.1 核实。
- 设置缝复用 dev 已有的 SidebarSettingsRenderProps + settings.render(PR 侧写在
  同一接口上,零适配)。
- 三个新 spec 原样取用,只有 git-suggest 的 harness 改了「visible 默认 true」——
  dev 的共享 git-status store 只在可见时订阅,不可见时 snapshot 恒 null,
  commit bar 根本不渲染(PR 作者当年跑绿的是本机未提交状态)。

丢弃 / 按 dev 重写:
- PR 的 GitLens 客户端半边基于 #471 重写前的 GitLens:提交栏在 dev 已是
  primitives Input + commitBar/commitRow/commitInput,且 Ctrl/Cmd+Enter 提交
  已存在(重复实现)。现按 dev 的 .commitRow 结构重做多行 textarea + 自动增高,
  保留既有快捷键,并追加 Ctrl/Cmd+G。
- 六个 Icon*16 具名导入在 0.2.0-rc.1 一个不剩(§3.1 第 2 条:缺导出 = render 期
  Element type is invalid),改用 IconSparkleRegular size={14}。
- CSS 类名跟随 dev 的 commit* 前缀(PR 的 gitCommit*/gitSuggest*/gitError 在 dev
  已不存在;错误行改走 dev 的 Notice,不新增自绘错误样式)。
- 消息 source kind 用生产者自有值 plugin:dsh-better-sidebar:0.1.7 起
  kind:'plugin' 会被 format v4 硬拒。
- locales:dev 已删 commitError 锚点,且 19 份词典与 locales.ts 必须键集相等,
  故按各文件在 commit 行后逐份插入,不整份取 PR 侧。

验收:pnpm typecheck 0;pnpm exec vitest run --maxWorkers=3 全绿(163 files /
1836 tests);新增 spec 单独跑绿;真机挂载冒烟未跑(见报告)。

Refs #642

Co-authored-by: rainmanhhh <13862623+rainmanhhh@users.noreply.github.com>
2026-10-05 02:19:58 +08:00

123 lines
4.3 KiB
TypeScript

/**
* Wire helpers for the /sidebar JSON API: bounded body reading, response
* writing, and the shared error envelope. Every API method returns
* `{ok: true, value}` on success and `{ok: false, error: {code, message}}`
* (HTTP 4xx/5xx matching the code) on failure.
*/
import type { SidebarHttpRequest, SidebarHttpResponse } from './context-types.ts'
// Value import for the error-class branch in writeError. git.ts imports only
// node builtins, so this introduces no cycle; wire.ts is host-half only and is
// never reachable from the browser bundle.
import { GitCommandError } from './git.ts'
/** Machine-readable error codes of the sidebar API. */
export type SidebarErrorCode =
| 'bad-request'
| 'not-found'
| 'forbidden'
| 'method-error'
| 'too-large'
| 'fs-error'
| 'fs-conflict'
| 'git-error'
| 'git-suggest-empty'
| 'git-suggest-error'
| 'job-error'
| 'team-error'
| 'team-conflict'
| 'sidechat-error'
| 'subagents-unavailable'
| 'settings-rejected'
| 'settings-conflict'
| 'internal'
/** One API failure with its wire code and HTTP status. */
export class SidebarError extends Error {
constructor(
readonly code: SidebarErrorCode,
message: string,
readonly status = 400,
/** Optional structured context carried alongside the code. */
readonly meta?: Record<string, string>,
) {
super(message)
}
}
/** Body size bound of one JSON request (defense against unbounded reads). */
const MAX_BODY_BYTES = 1 << 20
/** Success envelope of one API method. */
export interface SidebarOk<T> { ok: true; value: T }
/** Failure envelope of one API method. */
export interface SidebarErr { ok: false; error: { code: SidebarErrorCode; message: string } }
/** Read and parse the JSON request body (bounded; malformed → bad-request). */
export async function readJsonBody(req: SidebarHttpRequest): Promise<unknown> {
const chunks: Buffer[] = []
let total = 0
for await (const chunk of req) {
// The structural request yields string | Uint8Array; Buffer.from accepts
// both (and the real runtime chunks are node Buffers anyway).
const buffer = Buffer.from(chunk)
total += buffer.length
if (total > MAX_BODY_BYTES) {
throw new SidebarError('bad-request', 'request body too large')
}
chunks.push(buffer)
}
const text = Buffer.concat(chunks).toString('utf8')
if (text.trim() === '') return {}
try {
return JSON.parse(text) as unknown
} catch {
throw new SidebarError('bad-request', 'request body is not valid JSON')
}
}
/** Write a JSON response with the given status. */
export function writeJson(res: SidebarHttpResponse, status: number, body: unknown): void {
const payload = JSON.stringify(body)
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
res.end(payload)
}
/** Write the success envelope. */
export function writeOk(res: SidebarHttpResponse, value: unknown): void {
writeJson(res, 200, { ok: true, value })
}
/** Write the failure envelope for any thrown value (unknown → internal 500). */
export function writeError(res: SidebarHttpResponse, error: unknown): void {
if (error instanceof SidebarError) {
writeJson(res, error.status, { ok: false, error: { code: error.code, message: error.message } })
return
}
// A git failure is a state/input problem the user caused (unknown ref, path
// outside the repository, not a repository), not a plugin fault. Reporting it
// as 500 "internal" reads as a crash and hides the localized not-a-repository
// copy the client already knows how to render; `not-repo` carries its own
// code (409) so that path is reachable at all.
if (error instanceof GitCommandError) {
const notRepo = error.code === 'not-repo'
writeJson(res, notRepo ? 409 : 400, {
ok: false,
error: { code: notRepo ? 'not-repo' : 'git-error', message: error.message },
})
return
}
const message = error instanceof Error ? error.message : String(error)
writeJson(res, 500, { ok: false, error: { code: 'internal', message } })
}
/** Narrow an unknown payload value to a string, else throw bad-request. */
export function requireString(payload: unknown, key: string): string {
const record = payload as Record<string, unknown> | null
const value = record?.[key]
if (typeof value !== 'string' || value === '') {
throw new SidebarError('bad-request', `missing or invalid "${key}"`)
}
return value
}