dsh-remote-vs 0.26.0 → 0.27.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.
Files changed (46) hide show
  1. package/README.en.md +4 -11
  2. package/README.md +4 -8
  3. package/THIRD-PARTY-NOTICES.md +7 -2
  4. package/lib/client.js +6622 -5821
  5. package/lib/index.js +275 -1
  6. package/lib/types/client/CodeEditor.d.ts +14 -0
  7. package/lib/types/client/OutlinePanel.d.ts +22 -0
  8. package/lib/types/client/ProcessesSection.d.ts +19 -0
  9. package/lib/types/client/api.d.ts +5 -1
  10. package/lib/types/client/blame-model.d.ts +77 -0
  11. package/lib/types/client/i18n.d.ts +1 -1
  12. package/lib/types/client/outline-model.d.ts +59 -0
  13. package/lib/types/client/scm/actions.d.ts +12 -1
  14. package/lib/types/client/store.d.ts +18 -0
  15. package/lib/types/client/vsc/blame.d.ts +19 -0
  16. package/lib/types/client/vsc/kit.d.ts +0 -2
  17. package/lib/types/client/vsc/preview-document.d.ts +46 -0
  18. package/lib/types/client/vsc/preview-model.d.ts +31 -0
  19. package/lib/types/client/vsc/preview-services.d.ts +24 -0
  20. package/lib/types/git-ops.d.ts +18 -0
  21. package/lib/types/processes.d.ts +43 -0
  22. package/lib/types/protocol.d.ts +34 -0
  23. package/package.json +2 -1
  24. package/src/client/CodeEditor.tsx +43 -1
  25. package/src/client/EditorPane.tsx +520 -37
  26. package/src/client/MonitorView.tsx +16 -5
  27. package/src/client/OutlinePanel.tsx +287 -0
  28. package/src/client/ProcessesSection.tsx +292 -0
  29. package/src/client/api.ts +8 -0
  30. package/src/client/blame-model.ts +242 -0
  31. package/src/client/i18n.ts +194 -0
  32. package/src/client/index.tsx +4 -0
  33. package/src/client/outline-model.ts +775 -0
  34. package/src/client/scm/HistoryPanel.tsx +38 -1
  35. package/src/client/scm/actions.ts +55 -2
  36. package/src/client/store.tsx +54 -5
  37. package/src/client/vsc/blame.ts +147 -0
  38. package/src/client/vsc/kit.tsx +3 -11
  39. package/src/client/vsc/preview-document.tsx +323 -0
  40. package/src/client/vsc/preview-model.ts +216 -0
  41. package/src/client/vsc/preview-services.ts +118 -0
  42. package/src/client/vsc/vsc.css +6509 -5716
  43. package/src/git-ops.ts +34 -0
  44. package/src/processes.ts +177 -0
  45. package/src/protocol.ts +37 -0
  46. package/src/routes.ts +118 -0
package/lib/index.js CHANGED
@@ -417,7 +417,9 @@ const REMOTE_API = {
417
417
  /** Remote listening TCP sockets for the port panel (one bounded probe). */
418
418
  listenPorts: "/api/dsh-remote/listen-ports",
419
419
  /** Live system metrics for the monitor panel (one bounded probe per host). */
420
- metrics: "/api/dsh-remote/metrics"
420
+ metrics: "/api/dsh-remote/metrics",
421
+ /** One bounded process table for the monitor page, plus TERM/KILL actions. */
422
+ processes: "/api/dsh-remote/processes"
421
423
  };
422
424
  /** Suggested/attachment file name for one multi-selection archive. */
423
425
  function selectionDownloadName(count) {
@@ -3809,6 +3811,153 @@ var HostMonitor = class {
3809
3811
  }
3810
3812
  };
3811
3813
  //#endregion
3814
+ //#region src/processes.ts
3815
+ /** Marker proving which probe branch actually ran. */
3816
+ const PROCESSES_MARK = "@@RVS-PROCS";
3817
+ /** Budget for the whole probe; a stuck process table must not pin a channel. */
3818
+ const PROCESSES_TIMEOUT_MS = 15e3;
3819
+ /**
3820
+ * One bounded probe.
3821
+ *
3822
+ * GNU first (`--sort` + `etimes`), then the portable `ps aux` table for BSD /
3823
+ * old systems (`ppid` and elapsed time are unknown there). The marker
3824
+ * line is printed BEFORE the table so an interrupted probe is distinguishable
3825
+ * from a genuinely empty one; the final marker lets the parser reject a
3826
+ * truncated run.
3827
+ */
3828
+ function processesCommand(max = 500) {
3829
+ const cap = Math.max(1, Math.min(500, Math.floor(max)));
3830
+ const gnu = `ps -eo pid=,ppid=,user:20=,pcpu=,pmem=,etimes=,args= --sort=-pcpu 2>/dev/null`;
3831
+ return [
3832
+ "export LC_ALL=C",
3833
+ `if ${gnu} >/dev/null 2>&1; then`,
3834
+ ` echo "${PROCESSES_MARK} gnu"`,
3835
+ ` ${gnu} | head -n ${cap + 1}`,
3836
+ "elif ps aux >/dev/null 2>&1; then",
3837
+ ` echo "${PROCESSES_MARK} bsd"`,
3838
+ ` ps aux | tail -n +2 | sort -k3 -rn | head -n ${cap + 1}`,
3839
+ "else",
3840
+ ` echo "${PROCESSES_MARK} none"`,
3841
+ "fi",
3842
+ `echo "${PROCESSES_MARK} end"`
3843
+ ].join("\n");
3844
+ }
3845
+ function isKillSignal(value) {
3846
+ return value === "TERM" || value === "KILL";
3847
+ }
3848
+ /** Assert a PID a process snapshot may contain (1 is the remote init). */
3849
+ function assertProcessPid(value) {
3850
+ const pid = typeof value === "number" ? value : Number(value);
3851
+ if (!Number.isInteger(pid) || pid <= 1 || pid > 2147483647) throw new Error("invalid process id");
3852
+ return pid;
3853
+ }
3854
+ /**
3855
+ * Build the one kill command. The PID has already passed the snapshot check;
3856
+ * single-quoting it keeps the command shape uniform with every other builder.
3857
+ */
3858
+ function killCommand(pid, signal) {
3859
+ return `kill -s ${signal} ${shQuote(String(assertProcessPid(pid)))}`;
3860
+ }
3861
+ function numberOr(value) {
3862
+ if (!/^[0-9]+(?:\.[0-9]+)?$/.test(value)) return null;
3863
+ const number = Number(value);
3864
+ return Number.isFinite(number) ? number : null;
3865
+ }
3866
+ /** Bound one argv line before it is serialized into the JSON response. */
3867
+ function trimCommand(command) {
3868
+ return command.length <= 300 ? command : `${command.slice(0, 299)}…`;
3869
+ }
3870
+ /** GNU row: pid ppid user pcpu pmem etimes args. */
3871
+ function parseGnuRow(line) {
3872
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+([0-9.]+)\s+([0-9.]+)\s+(\d+)\s+(.*)$/.exec(line);
3873
+ if (match === null) return void 0;
3874
+ const pid = match[1];
3875
+ const ppid = match[2];
3876
+ const user = match[3];
3877
+ const cpu = match[4];
3878
+ const mem = match[5];
3879
+ const elapsed = match[6];
3880
+ const command = match[7];
3881
+ return {
3882
+ pid: Number(pid),
3883
+ ppid: Number(ppid),
3884
+ user,
3885
+ cpuPercent: numberOr(cpu) ?? 0,
3886
+ memPercent: numberOr(mem) ?? 0,
3887
+ elapsedSeconds: numberOr(elapsed) ?? null,
3888
+ command: trimCommand(command.trim())
3889
+ };
3890
+ }
3891
+ /** BSD `ps aux` row: user pid %cpu %mem vsz rss tt stat started time command. */
3892
+ function parseBsdRow(line) {
3893
+ const match = /^\s*(\S+)\s+(\d+)\s+([0-9.]+)\s+([0-9.]+)\s+\S+\s+\S+\s+\S+\s+\S+\s+(\S+)\s+\S+\s+(.*)$/.exec(line);
3894
+ if (match === null) return void 0;
3895
+ const user = match[1];
3896
+ const pid = match[2];
3897
+ const cpu = match[3];
3898
+ const mem = match[4];
3899
+ const command = match[6];
3900
+ return {
3901
+ pid: Number(pid),
3902
+ ppid: 0,
3903
+ user,
3904
+ cpuPercent: numberOr(cpu) ?? 0,
3905
+ memPercent: numberOr(mem) ?? 0,
3906
+ elapsedSeconds: null,
3907
+ command: trimCommand(command.trim())
3908
+ };
3909
+ }
3910
+ /**
3911
+ * Parse one probe. `exitCode === null` (channel died) or a missing end marker
3912
+ * means `unknown`, never an empty process table.
3913
+ */
3914
+ function parseProcesses(stdout, exitCode) {
3915
+ const lines = stdout.split("\n").map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
3916
+ const markerAt = lines.findIndex((line) => line.trim() === `@@RVS-PROCS gnu` || line.trim() === `@@RVS-PROCS bsd` || line.trim() === `@@RVS-PROCS none`);
3917
+ if (exitCode === null || markerAt < 0) return {
3918
+ tool: "unknown",
3919
+ processes: [],
3920
+ truncated: false,
3921
+ error: "the remote process probe ended without a complete answer"
3922
+ };
3923
+ const marker = lines[markerAt]?.trim() ?? "";
3924
+ let endAt = -1;
3925
+ for (let index = lines.length - 1; index > markerAt; index -= 1) if (lines[index].trim() === `@@RVS-PROCS end`) {
3926
+ endAt = index;
3927
+ break;
3928
+ }
3929
+ if (endAt < 0) return {
3930
+ tool: "unknown",
3931
+ processes: [],
3932
+ truncated: false,
3933
+ error: "the remote process probe was interrupted"
3934
+ };
3935
+ if (marker.endsWith("none")) return {
3936
+ tool: "none",
3937
+ processes: [],
3938
+ truncated: false
3939
+ };
3940
+ const gnu = marker.endsWith("gnu");
3941
+ const parsedProcesses = [];
3942
+ for (const line of lines.slice(markerAt + 1, endAt)) {
3943
+ if (line.trim() === "") continue;
3944
+ const row = gnu ? parseGnuRow(line) : parseBsdRow(line);
3945
+ if (row !== void 0 && !row.command.includes("@@RVS-PROCS")) parsedProcesses.push(row);
3946
+ }
3947
+ if (parsedProcesses.length === 0) return {
3948
+ tool: "unknown",
3949
+ processes: [],
3950
+ truncated: false,
3951
+ error: "the remote ps output could not be parsed"
3952
+ };
3953
+ const truncated = parsedProcesses.length > 500;
3954
+ return {
3955
+ tool: gnu ? "gnu" : "bsd",
3956
+ processes: parsedProcesses.slice(0, 500),
3957
+ truncated
3958
+ };
3959
+ }
3960
+ //#endregion
3812
3961
  //#region src/routes.ts
3813
3962
  function queryParam(url, name) {
3814
3963
  const value = url.searchParams.get(name);
@@ -4001,6 +4150,60 @@ function makeRoutes(deps) {
4001
4150
  const files = new RemoteFiles(pool);
4002
4151
  const terminalSessions = new TerminalSessionRegistry(pool);
4003
4152
  const monitor = new HostMonitor(pool);
4153
+ /**
4154
+ * Last process snapshot per alias. The kill route validates against this
4155
+ * table, so a browser cannot construct a `kill` for an arbitrary PID; a stale
4156
+ * entry is refreshed before validation rather than trusted indefinitely.
4157
+ */
4158
+ const processSnapshots = /* @__PURE__ */ new Map();
4159
+ /** One probe per alias at a time; a second reader joins the in-flight one. */
4160
+ const processInflight = /* @__PURE__ */ new Map();
4161
+ const forgetProcesses = (alias) => {
4162
+ processSnapshots.delete(alias);
4163
+ processInflight.delete(alias);
4164
+ };
4165
+ const readProcesses = async (alias, maxAgeMs) => {
4166
+ const cached = processSnapshots.get(alias);
4167
+ if (maxAgeMs > 0 && cached !== void 0 && Date.now() - cached.at < maxAgeMs) return cached.result;
4168
+ const joined = processInflight.get(alias);
4169
+ if (joined !== void 0) return joined;
4170
+ const task = (async () => {
4171
+ const result = await pool.exec(alias, processesCommand(), { timeoutMs: PROCESSES_TIMEOUT_MS });
4172
+ let parsed;
4173
+ if (result.error !== void 0) parsed = {
4174
+ tool: "unknown",
4175
+ processes: [],
4176
+ truncated: false,
4177
+ error: result.error
4178
+ };
4179
+ else if (result.timedOut) parsed = {
4180
+ tool: "unknown",
4181
+ processes: [],
4182
+ truncated: false,
4183
+ error: `the process probe did not finish within ${PROCESSES_TIMEOUT_MS / 1e3}s`
4184
+ };
4185
+ else if (result.exitCode === null) parsed = {
4186
+ tool: "unknown",
4187
+ processes: [],
4188
+ truncated: false,
4189
+ error: "the process probe ended without an exit status"
4190
+ };
4191
+ else parsed = parseProcesses(result.stdout, result.exitCode);
4192
+ if (parsed.tool === "gnu" || parsed.tool === "bsd") processSnapshots.set(alias, {
4193
+ at: Date.now(),
4194
+ result: parsed
4195
+ });
4196
+ else processSnapshots.delete(alias);
4197
+ return parsed;
4198
+ })();
4199
+ processInflight.set(alias, task);
4200
+ task.then(() => {
4201
+ if (processInflight.get(alias) === task) processInflight.delete(alias);
4202
+ }, () => {
4203
+ if (processInflight.get(alias) === task) processInflight.delete(alias);
4204
+ });
4205
+ return task;
4206
+ };
4004
4207
  const forwards = deps.forwards;
4005
4208
  const viewSettings = deps.viewSettings ?? new RemoteViewSettingsStore();
4006
4209
  /**
@@ -4193,6 +4396,7 @@ function makeRoutes(deps) {
4193
4396
  forwards?.stopAlias(alias);
4194
4397
  pool.forget(alias);
4195
4398
  monitor.forget(alias);
4399
+ forgetProcesses(alias);
4196
4400
  worlds.dropHost(alias).catch(() => void 0);
4197
4401
  if (!store.remove(alias)) {
4198
4402
  writeJson(res, 404, { error: `unknown host alias: ${alias}` });
@@ -4212,6 +4416,7 @@ function makeRoutes(deps) {
4212
4416
  try {
4213
4417
  pool.forget(alias);
4214
4418
  monitor.forget(alias);
4419
+ forgetProcesses(alias);
4215
4420
  worlds.dropHost(alias).catch(() => void 0);
4216
4421
  const entry = store.update(alias, body);
4217
4422
  writeJson(res, 200, { host: store.summarize(entry) });
@@ -5163,6 +5368,75 @@ function makeRoutes(deps) {
5163
5368
  }
5164
5369
  }
5165
5370
  },
5371
+ {
5372
+ kind: "exact",
5373
+ path: REMOTE_API.processes,
5374
+ handler: async (req, res) => {
5375
+ if (!isLoopbackRequest(req)) {
5376
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
5377
+ return;
5378
+ }
5379
+ const method = req.method ?? "GET";
5380
+ if (method !== "GET" && method !== "POST") {
5381
+ writeJson(res, 405, { error: `method not allowed: ${method}` });
5382
+ return;
5383
+ }
5384
+ try {
5385
+ if (method === "GET") {
5386
+ const url = new URL(req.url ?? "/", "http://localhost");
5387
+ const alias = queryParam(url, "alias");
5388
+ if (alias === void 0 || alias === "") {
5389
+ writeJson(res, 400, { error: "alias query parameter is required" });
5390
+ return;
5391
+ }
5392
+ if (store.get(alias) === void 0) {
5393
+ writeJson(res, 404, { error: `unknown host alias: ${alias}` });
5394
+ return;
5395
+ }
5396
+ writeJson(res, 200, await readProcesses(alias, queryParam(url, "refresh") === "1" ? 0 : 3e3));
5397
+ return;
5398
+ }
5399
+ const read = await readBodyOrError(req, res, { objectOnly: true });
5400
+ if (!read.ok) return;
5401
+ const body = read.body ?? {};
5402
+ const alias = typeof body.alias === "string" ? body.alias : "";
5403
+ if (alias === "") {
5404
+ writeJson(res, 400, { error: "alias is required" });
5405
+ return;
5406
+ }
5407
+ let pid;
5408
+ try {
5409
+ pid = assertProcessPid(body.pid);
5410
+ } catch (error) {
5411
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
5412
+ return;
5413
+ }
5414
+ if (!isKillSignal(body.signal)) {
5415
+ writeJson(res, 400, { error: "signal must be TERM or KILL" });
5416
+ return;
5417
+ }
5418
+ if ((await readProcesses(alias, 0)).processes.find((process) => process.pid === pid) === void 0) {
5419
+ writeJson(res, 400, { error: `process ${pid} is not in the current remote snapshot` });
5420
+ return;
5421
+ }
5422
+ const result = await pool.exec(alias, killCommand(pid, body.signal), { timeoutMs: 1e4 });
5423
+ if (result.error !== void 0 || result.exitCode !== 0) {
5424
+ const message = result.error ?? result.stderr.trim() ?? "";
5425
+ writeJson(res, 502, { error: message === "" ? `kill failed [exit code: ${result.exitCode ?? "?"}]` : message });
5426
+ return;
5427
+ }
5428
+ processSnapshots.delete(alias);
5429
+ writeJson(res, 200, {
5430
+ ok: true,
5431
+ pid,
5432
+ signal: body.signal
5433
+ });
5434
+ } catch (error) {
5435
+ if (isStoreError(error)) writeStoreError(res, error);
5436
+ else writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
5437
+ }
5438
+ }
5439
+ },
5166
5440
  {
5167
5441
  kind: "exact",
5168
5442
  path: REMOTE_API.metrics,
@@ -52,6 +52,7 @@ export interface CodeEditorHandle {
52
52
  getChangeStale: () => boolean;
53
53
  }
54
54
  import { type ChangeMark, type ChangeSet } from './vsc/change-marks.ts';
55
+ import type { BlameLine } from './blame-model.ts';
55
56
  /**
56
57
  * The editor surface is OPAQUE and scrolls in the editor's own palette
57
58
  * (`vsc/editor-theme.ts`): a code editor is not a translucent DSH panel, and
@@ -102,6 +103,19 @@ export declare const CodeEditor: import("react").ForwardRefExoticComponent<{
102
103
  * 加入本功能之前完全一致。
103
104
  */
104
105
  changeSet?: ChangeSet | null;
106
+ /**
107
+ * Line→commit map for the inline blame gutter. `undefined`/empty removes the
108
+ * gutter entirely, so diff panes and files without blame data keep their old
109
+ * layout.
110
+ */
111
+ blame?: ReadonlyMap<number, BlameLine> | null;
112
+ /** Clicking a blame cell asks the pane to reveal that commit. */
113
+ onOpenBlame?: (entry: BlameLine) => void;
114
+ /**
115
+ * Reports the visible 1-based line range. The pane uses it to fetch blame one
116
+ * window at a time; CodeMirror is the only code that knows the viewport.
117
+ */
118
+ onViewport?: (first: number, last: number) => void;
105
119
  /**
106
120
  * 用户在某一处改动上按下「撤销这处改动」时回调。
107
121
  *
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 符号大纲浮层:可筛选的符号列表 + ↑↓/Enter/点击跳转。
3
+ *
4
+ * 只在打开时挂载(父组件用 `undefined` 表示关闭),所以「关闭」就是卸载 —— 不会
5
+ * 留下第二个 `isOpen` 状态要同步,也不会在关闭后留一个偷键盘的监听器。条目由
6
+ * `outline-model.ts` 的纯函数产出;这里只负责像素、焦点和按键。
7
+ *
8
+ * PORTAL 到 `<body>`:编辑器有三种座位(侧栏 / 中间 / 浮窗),浮层若留在原 DOM
9
+ * 里会被祖先的 `overflow: hidden` 裁掉。`.rvs-portal` 负责声明 `--rvs-*` token
10
+ * 子集 —— portal 之后已经不在 `.rvs-root` 作用域内,缺了它颜色/边框全是空值。
11
+ */
12
+ import { type ReactNode } from 'react';
13
+ import { type OutlineEntry } from './outline-model.ts';
14
+ export declare function OutlinePanel(props: {
15
+ t: (key: string) => string;
16
+ /** 远端绝对路径(判断语言 + 标题)。 */
17
+ path: string;
18
+ /** 实时缓冲区全文:dirty 时必须来自编辑器,不是 `tab.text`。 */
19
+ text: string;
20
+ onPick: (entry: OutlineEntry) => void;
21
+ onClose: () => void;
22
+ }): ReactNode;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Remote process table shown on the monitor page.
3
+ *
4
+ * One bounded snapshot per selected host, polled only while the monitor page and
5
+ * the browser tab are both visible. Killing is always confirmed and always goes
6
+ * through the Host route (which validates the PID against its own snapshot), so
7
+ * the browser never builds a shell command from a process row.
8
+ */
9
+ import { type ReactNode } from 'react';
10
+ import type { RemoteHostSummary } from '../protocol.ts';
11
+ export declare const PROCESS_POLL_MS = 5000;
12
+ export declare function ProcessesSection(props: {
13
+ t: (key: string) => string;
14
+ hosts: RemoteHostSummary[];
15
+ aliases: string[];
16
+ visible: boolean;
17
+ paused: boolean;
18
+ intervalMs: number;
19
+ }): ReactNode;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Typed fetch wrapper over the /api/dsh-remote JSON API (full P0 surface).
3
3
  */
4
- import { type GitBranch, type GitCommit, type GitShow, type GitStatus, type HelperAvailability, type ImportReport, type RemoteChangesDiff, type RemoteChangesSummary, type RemoteConnectionStatus, type RemoteDeployState, type RemoteExecResult, type RemoteFileEntry, type RemoteForwardRequest, type RemoteForwardState, type RemoteHostSummary, type RemoteListenPortsResult, type RemotePluginMeta, type RemoteProbe, type RemoteRead, type RemoteRoutingStatus, type RemoteTimeouts, type RemoteViewSettings, type RemoteWorkspaceBinding, type RemoteWriteConflict, type RemoteWriteResult } from '../protocol.ts';
4
+ import { type GitBranch, type GitCommit, type GitShow, type GitStatus, type HelperAvailability, type ImportReport, type RemoteChangesDiff, type RemoteChangesSummary, type RemoteConnectionStatus, type RemoteDeployState, type RemoteExecResult, type RemoteFileEntry, type RemoteForwardRequest, type RemoteForwardState, type RemoteHostSummary, type RemoteListenPortsResult, type RemoteProcessKillResult, type RemoteProcessesResult, type RemotePluginMeta, type RemoteProbe, type RemoteRead, type RemoteRoutingStatus, type RemoteTimeouts, type RemoteViewSettings, type RemoteWorkspaceBinding, type RemoteWriteConflict, type RemoteWriteResult } from '../protocol.ts';
5
5
  export declare class RemoteApiError extends Error {
6
6
  readonly status: number;
7
7
  /**
@@ -295,6 +295,10 @@ export declare const api: {
295
295
  * found" (see `RemoteListenPortsResult`).
296
296
  */
297
297
  listenPorts: (alias: string) => Promise<RemoteListenPortsResult>;
298
+ /** One bounded remote process table (per-host cache on the Host side). */
299
+ processes: (alias: string, refresh?: boolean) => Promise<RemoteProcessesResult>;
300
+ /** Signal one PID from the latest snapshot; the route rejects unknown PIDs. */
301
+ killProcess: (alias: string, pid: number, signal: "TERM" | "KILL") => Promise<RemoteProcessKillResult>;
298
302
  /**
299
303
  * One host's live metrics sample.
300
304
  *
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Pure parsing/formatting for `git blame` (and the shared vocabulary the
3
+ * editor UI uses for a line's provenance). No CodeMirror and no DOM here, so
4
+ * the gate can feed it real porcelain output.
5
+ */
6
+ import type { GitCommit } from '../protocol.ts';
7
+ /** One blamed line: 1-based final line number plus the commit that owns it. */
8
+ export interface BlameLine {
9
+ line: number;
10
+ hash: string;
11
+ author: string;
12
+ email: string;
13
+ /** Author timestamp, seconds since the epoch (git's `author-time`). */
14
+ time: number;
15
+ summary: string;
16
+ }
17
+ /** A run of consecutive lines owned by the same commit. */
18
+ export interface BlameRun {
19
+ from: number;
20
+ to: number;
21
+ hash: string;
22
+ }
23
+ /** One `--follow` file-history row, plus the name the file had in that commit. */
24
+ export interface FileHistoryCommit extends GitCommit {
25
+ /** Path to show/diff for THIS commit (old name before a rename). */
26
+ path: string;
27
+ /** Rename source when this commit renamed the file. */
28
+ origPath?: string;
29
+ }
30
+ /**
31
+ * Parse `git blame --line-porcelain`.
32
+ *
33
+ * `--line-porcelain` repeats the commit header and metadata for every line (no
34
+ * previous-commit grouping), which keeps this parser stateless: a header starts
35
+ * a record, the metadata lines fill it, and the tab-prefixed content line ends
36
+ * it. Lines that do not match the shape are ignored rather than aborting the
37
+ * whole read — a partially understood blame is still useful.
38
+ */
39
+ export declare function parseBlamePorcelain(stdout: string): BlameLine[];
40
+ /** Group consecutive lines of one commit; non-adjacent runs stay separate. */
41
+ export declare function blameRuns(rows: readonly BlameLine[]): BlameRun[];
42
+ /** Short author name for the narrow blame gutter. */
43
+ export declare function shortAuthor(author: string): string;
44
+ /**
45
+ * Relative age labels, deliberately compact (`now`, `5m`, `3h`, `2d`, `4w`,
46
+ * `3mo`, `2y`) because this text lives in a gutter.
47
+ */
48
+ export declare function relativeBlameTime(timeSeconds: number, nowSeconds?: number): string;
49
+ /** One-line gutter label: author initials/name plus relative age. */
50
+ export declare function blameLabel(row: BlameLine, nowSeconds?: number): string;
51
+ /**
52
+ * Hover text: full attribution. The browser renders `title` as plain text, so
53
+ * no markup is needed (and no translator dependency leaks into the model).
54
+ */
55
+ export declare function blameTitle(row: BlameLine): string;
56
+ /** False for git's all-zero "not committed yet" pseudo-commit. */
57
+ export declare function isCommittedBlame(hash: string): boolean;
58
+ /**
59
+ * The next `-L` window to request, or undefined when the viewport is covered.
60
+ *
61
+ * Pure and exported so the gate can prove the "3000-line file only asks for
62
+ * the visible window" requirement without a browser. `overscan` keeps a small
63
+ * buffer above/below so a normal scroll does not immediately need a new call.
64
+ */
65
+ export declare function planBlameWindow(first: number, last: number, total: number, covered: ReadonlySet<number>, overscan?: number): {
66
+ from: number;
67
+ to: number;
68
+ } | undefined;
69
+ /**
70
+ * Parse `git log --follow --name-status -M` output into per-commit rows.
71
+ *
72
+ * `--follow` reports the file under its name AT THAT COMMIT. Starting from the
73
+ * current name and walking newest→oldest, each rename row supplies the next
74
+ * (older) name, so a click on an old history row opens the right path instead
75
+ * of an empty diff for the current name.
76
+ */
77
+ export declare function parseFileHistory(stdout: string, currentPath: string): FileHistoryCommit[];
@@ -11,7 +11,7 @@
11
11
  * them here keeps the check meaningful in both directions: every entry must
12
12
  * exist in both dictionaries, and nothing else may be unreferenced.
13
13
  */
14
- export declare const DYNAMIC_KEYS: readonly ["common.loading", "editor.saving", "editor.unsaved", "editor.saved", "scm.hunkStaged", "scm.hunkUnstaged", "scm.hunkReverted", "history.details", "history.content", "history.diff", "downloads.running", "downloads.indeterminate", "downloads.sizeUnknown", "downloads.handedOff", "term.disconnected", "term.closed", "term.copy", "term.paste", "term.selectAll", "connection.ok", "connection.error", "connection.idle", "connection.actionFailed", "doctor.state.ok", "doctor.state.missing", "doctor.state.unknown", "doctor.item.os", "doctor.item.libc", "doctor.item.git", "doctor.item.rg", "doctor.item.tar", "doctor.item.setsid", "doctor.item.disk", "doctor.item.nproc", "doctor.item.memory", "doctor.item.helpers", "doctor.item.sshd", "editor.crumbRoot", "editor.crumbLabel", "editor.crumbUp", "editor.crumbEmpty", "editor.imageHint", "editor.imageFitHint", "editor.imageFailedHint", "editor.imageTooLargeTitle", "editor.imageTooLargeHint"];
14
+ export declare const DYNAMIC_KEYS: readonly ["common.loading", "editor.saving", "editor.unsaved", "editor.saved", "scm.hunkStaged", "scm.hunkUnstaged", "scm.hunkReverted", "history.details", "history.content", "history.diff", "downloads.running", "downloads.indeterminate", "downloads.sizeUnknown", "downloads.handedOff", "term.disconnected", "term.closed", "term.copy", "term.paste", "term.selectAll", "connection.ok", "connection.error", "connection.idle", "connection.actionFailed", "doctor.state.ok", "doctor.state.missing", "doctor.state.unknown", "doctor.item.os", "doctor.item.libc", "doctor.item.git", "doctor.item.rg", "doctor.item.tar", "doctor.item.setsid", "doctor.item.disk", "doctor.item.nproc", "doctor.item.memory", "doctor.item.helpers", "doctor.item.sshd", "editor.crumbRoot", "editor.crumbLabel", "editor.crumbUp", "editor.crumbEmpty", "outline.kind.class", "outline.kind.interface", "outline.kind.struct", "outline.kind.enum", "outline.kind.trait", "outline.kind.impl", "outline.kind.namespace", "outline.kind.module", "outline.kind.function", "outline.kind.method", "outline.kind.constructor", "outline.kind.field", "outline.kind.variable", "outline.kind.type", "outline.kind.macro", "preview.officeUnavailableTitle", "preview.unavailableTitle", "preview.officeUnavailableHint", "preview.unavailableHint", "editor.imageHint", "editor.imageFitHint", "editor.imageFailedHint", "editor.imageTooLargeTitle", "editor.imageTooLargeHint"];
15
15
  export type Lang = 'zh' | 'en';
16
16
  export declare function detectLang(): Lang;
17
17
  export declare function makeT(lang: Lang): (key: string) => string;
@@ -0,0 +1,59 @@
1
+ export type OutlineLanguage = 'java' | 'c' | 'cpp' | 'go' | 'rust' | 'python' | 'javascript' | 'typescript' | 'unknown';
2
+ export type OutlineKind = 'class' | 'interface' | 'struct' | 'enum' | 'trait' | 'impl' | 'namespace' | 'module' | 'function' | 'method' | 'constructor' | 'field' | 'variable' | 'type' | 'macro';
3
+ export interface OutlineEntry {
4
+ name: string;
5
+ kind: OutlineKind;
6
+ /** 1-based 行号(与 `revealRange` 同一套语义)。 */
7
+ line: number;
8
+ /** 嵌套层数,0 = 顶层。用缩进表达嵌套,不暴露大括号深度。 */
9
+ depth: number;
10
+ /** 直接外层类型/命名空间的名字(没有就是顶层)。 */
11
+ container?: string;
12
+ }
13
+ export interface OutlineResult {
14
+ language: OutlineLanguage;
15
+ entries: OutlineEntry[];
16
+ /** 扫描到的符号总数;可能大于 `entries.length`(被上限截断)。 */
17
+ total: number;
18
+ truncated: boolean;
19
+ /** 语言未识别:条目是按缩进 + 关键字猜的,UI 必须标注。 */
20
+ guessed: boolean;
21
+ }
22
+ /**
23
+ * 单个文件最多列出的条目数。
24
+ *
25
+ * 20k 行的 Java 文件大约几百个符号,5000 已经远超真实代码;设上限是为了让病态
26
+ * 输入(生成代码、压缩成一行的 JSON 式脚本)不会把 DOM 拖垮,同时 `total` 仍然
27
+ * 报出真实数量,截断不撒谎。
28
+ */
29
+ export declare const OUTLINE_MAX_ENTRIES = 5000;
30
+ /** 面板一次渲染的候选上限(过滤后)。 */
31
+ export declare const OUTLINE_RESULT_LIMIT = 300;
32
+ /** 由远端路径判断语言;不认识就返回 `unknown`(走降级大纲)。 */
33
+ export declare function outlineLanguageOf(path: string): OutlineLanguage;
34
+ /**
35
+ * 把注释与字符串逐字符替换成空格(换行保留),返回按行切好的副本。
36
+ *
37
+ * 「长度不变」很重要:任何后续的行内偏移都还对得上原文件,行号也直接来自下标。
38
+ * 状态机是近似的(C++ 原始字符串、Java 文本块、JS 正则字面量不特殊处理),目标
39
+ * 是让「注释/字符串里的伪符号」不出现,不是做词法分析。
40
+ */
41
+ export declare function maskSource(text: string, language: OutlineLanguage): string[];
42
+ /**
43
+ * 从源文本生成大纲。
44
+ *
45
+ * `text` 必须是**实时缓冲区**(dirty 时不是 `tab.text`);行号 1-based 直接对应
46
+ * `CodeEditorHandle.revealRange`。
47
+ */
48
+ export declare function buildOutline(text: string, path: string): OutlineResult;
49
+ /**
50
+ * 按查询过滤并排序符号。
51
+ *
52
+ * 空查询 = 源码顺序(大纲的默认视图);有查询时复用 quick open 的 `fuzzyScore`
53
+ * 打分,同分按行号升序 —— 排序必须确定,否则两次相同的输入会闪出两种顺序。
54
+ * 名字不匹配但 `容器.名字` 匹配(用户常敲 `Foo.bar`)时也算命中。
55
+ */
56
+ export declare function rankOutline(query: string, entries: readonly OutlineEntry[], limit: number): {
57
+ hits: OutlineEntry[];
58
+ truncated: boolean;
59
+ };
@@ -8,7 +8,8 @@
8
8
  * messages a user can act on (missing identity, no upstream, conflicts, ...).
9
9
  */
10
10
  import { REMOTE_API } from '../../protocol.ts';
11
- import type { GitBranch, GitCommitFile, GitRemote, GitStash, GitStatusDetail, RemoteExecResult, RemoteRead } from '../../protocol.ts';
11
+ import type { GitBranch, GitCommit, GitCommitFile, GitRemote, GitStash, GitStatusDetail, RemoteExecResult, RemoteRead } from '../../protocol.ts';
12
+ import { type BlameLine, type FileHistoryCommit } from '../blame-model.ts';
12
13
  import { type PushTarget } from '../exec-output.ts';
13
14
  /** Error carrying a message already fit for the UI. */
14
15
  export declare class GitOpError extends Error {
@@ -156,6 +157,16 @@ export declare function loadCommitPatch(alias: string, root: string, hash: strin
156
157
  text: string;
157
158
  truncated: boolean;
158
159
  }>;
160
+ /** One viewport window of `git blame` for a repo-relative path. */
161
+ export declare function loadBlame(alias: string, root: string, path: string, from: number, to: number, options?: RunOptions): Promise<BlameLine[]>;
162
+ /**
163
+ * Commits that touched one path. `--follow` makes renames visible as history
164
+ * of the CURRENT name, which is exactly what the editor's file-history menu
165
+ * promises; the rows use the same shape as the repository log.
166
+ */
167
+ export declare function loadFileHistory(alias: string, root: string, path: string, max?: number): Promise<FileHistoryCommit[]>;
168
+ /** One commit header when the hash is older than the loaded log window. */
169
+ export declare function loadCommit(alias: string, root: string, hash: string): Promise<GitCommit | undefined>;
159
170
  /** Local + remote-tracking branches. */
160
171
  export declare function loadBranches(alias: string, root: string, current: string): Promise<GitBranch[]>;
161
172
  /** Configured remotes. */
@@ -152,6 +152,12 @@ export interface TerminalRequest {
152
152
  /** Absolute remote directory the fresh shell should `cd` into. */
153
153
  dir: string;
154
154
  }
155
+ /** One "show this commit in the history rail" request. */
156
+ export interface CommitFocusRequest {
157
+ /** Monotonic id so selecting the same commit twice still re-triggers. */
158
+ id: number;
159
+ hash: string;
160
+ }
155
161
  /** Stored repository sub-directory for one binding ('' = the workspace root). */
156
162
  export declare function readRepoSubdir(workspaceId: string): string;
157
163
  /** Everything a view can read, plus the actions. */
@@ -202,6 +208,8 @@ export interface ExplorerValue {
202
208
  revealRequest: RevealRequest | undefined;
203
209
  /** Pending "open a terminal here" request (consumed by the terminal panel). */
204
210
  terminalRequest: TerminalRequest | undefined;
211
+ /** Pending "select this commit in the history rail" request. */
212
+ commitFocus: CommitFocusRequest | undefined;
205
213
  setView: (view: RailView) => void;
206
214
  /** Switch to the search panel (optionally scoped to a folder) — the tree's
207
215
  "find in folder" entry point. */
@@ -221,6 +229,8 @@ export interface ExplorerValue {
221
229
  * search results' "open in terminal" entry.
222
230
  */
223
231
  openTerminalAt: (dir: string) => void;
232
+ /** Open the history rail with this commit selected (blame / file history). */
233
+ focusCommit: (hash: string) => void;
224
234
  /**
225
235
  * The USER's pick — the workspace dropdowns and the wizard's "open files".
226
236
  *
@@ -460,6 +470,14 @@ export declare function jumpToTerminalPath(alias: string, token: string, hints?:
460
470
  * @param dir - absolute remote directory.
461
471
  */
462
472
  export declare function openTerminalAt(dir: string): void;
473
+ /**
474
+ * Open the history rail and select one commit.
475
+ *
476
+ * Blame cells and the file-history menu only know a hash; the history panel owns
477
+ * the list and the detail pane, so the selection travels as a request (the same
478
+ * pattern as `revealInExplorer` / `openTerminalAt`).
479
+ */
480
+ export declare function focusCommit(hash: string): void;
463
481
  /**
464
482
  * Select the binding every view works against — the USER's choice.
465
483
  *
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Inline blame gutter for the CodeMirror editor.
3
+ *
4
+ * The data is fetched by the editor pane (one `-L` window at a time) and handed
5
+ * in as a line→commit map; this module only paints it. Keeping the fetch out of
6
+ * here is deliberate: the same model is used by the gate without CodeMirror,
7
+ * and a scroll must not be able to start a request from inside a gutter
8
+ * callback.
9
+ */
10
+ import { type Extension } from '@codemirror/state';
11
+ import { type BlameLine } from '../blame-model.ts';
12
+ /**
13
+ * Build the gutter extension. Rebuilt by the editor's compartment whenever a
14
+ * blame window lands; `nowSeconds` is pinned so every cell in one render has
15
+ * the same clock.
16
+ */
17
+ export declare function blameExtension(entries: ReadonlyMap<number, BlameLine>, onOpen?: (entry: BlameLine) => void): Extension;
18
+ /** Internal export for the editor to forward viewport changes. */
19
+ export declare function blameViewportReporter(report: (first: number, last: number) => void): Extension;
@@ -124,8 +124,6 @@ export declare function ExplorerFolderIcon(props: {
124
124
  className?: string;
125
125
  }): ReactNode;
126
126
  export declare function isImageFile(path: string): boolean;
127
- export declare function isMarkdownFile(path: string): boolean;
128
- export declare function isHtmlFile(path: string): boolean;
129
127
  export declare function mimeFor(path: string): string;
130
128
  /** True for a file that always opens as a preview, never as a diff. */
131
129
  export declare function isPreviewOnlyFile(path: string): boolean;