@each1024/pi-mini-mode 2.0.19 → 2.0.20

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.
@@ -93,7 +93,7 @@ export default function (pi: ExtensionAPI) {
93
93
  let saveChain: Promise<void> = Promise.resolve();
94
94
  const configPath = settingsPath();
95
95
  let updateBannerChecked = false;
96
- let activeUpdateBanner: { sessionKey: string; version: string; collapsed: boolean } | undefined;
96
+ let activeUpdateBanner: { sessionKey: string; version: string; previousVersion?: string; collapsed: boolean } | undefined;
97
97
  const getSessionKey = (ctx: ExtensionContext) =>
98
98
  ctx.sessionManager.getSessionFile?.() ?? (ctx.sessionManager as { getSessionId?(): string | undefined }).getSessionId?.() ?? "";
99
99
 
@@ -187,6 +187,7 @@ export default function (pi: ExtensionAPI) {
187
187
  updateBanner: () => activeUpdateBanner && activeUpdateBanner.sessionKey === sessionKey
188
188
  ? {
189
189
  version: activeUpdateBanner.version,
190
+ previousVersion: activeUpdateBanner.previousVersion,
190
191
  collapsed: activeUpdateBanner.collapsed,
191
192
  toggle: () => {
192
193
  if (!activeUpdateBanner) return;
@@ -204,12 +205,13 @@ export default function (pi: ExtensionAPI) {
204
205
  const hideStartupLine = (line: string) => line.replace(/\x1b\[[0-9;]*m/g, "").includes("No models match pattern");
205
206
  // Transcript hover wrappers must surround the compact widget handlers;
206
207
  // unmount in reverse order so neither adapter resurrects stale handlers.
207
- restoreAgentWidgets = attachAgentWidgets(tui, theme, () => subAgentsExpanded, undefined, true);
208
+ restoreAgentWidgets = attachAgentWidgets(tui, theme, () => subAgentsExpanded, undefined, true, () => uiLanguage(settings));
208
209
  restoreTranscript = attachTranscript(tui, view, {
209
210
  turnCount: () => minimalTurns.length,
210
211
  supervisor: {
211
212
  theme,
212
213
  expanded: () => processExpanded,
214
+ language: () => uiLanguage(settings),
213
215
  handledRunIds: () => handledRunIds,
214
216
  onNotices: groups => {
215
217
  let changed = false;
@@ -453,7 +455,7 @@ export default function (pi: ExtensionAPI) {
453
455
  settings = loaded.settings;
454
456
  messageCwd = ctx.cwd;
455
457
  // 输入增强只在会话中生效,会话开始时再加载;传 getter 让开关变更即时生效,重复调用是幂等的。
456
- cleanupInputEnhancements = installInputEnhancements(pi, ctx, () => settings["pi-mini-mode-input-enhancements"], () => settings["pi-mini-mode-image-preview"]);
458
+ cleanupInputEnhancements = installInputEnhancements(pi, ctx, () => settings["pi-mini-mode-input-enhancements"], () => settings["pi-mini-mode-image-preview"], () => uiLanguage(settings));
457
459
  thinkingStream.stop(activeMinimalTurn, "aborted");
458
460
  thinkingStream.reset();
459
461
  minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
@@ -479,7 +481,7 @@ export default function (pi: ExtensionAPI) {
479
481
  await saveSettings(settings, configPath).catch(() => {});
480
482
  }
481
483
  if (loaded.exists && versionChanged && ctx.mode === "tui" && ctx.hasUI && minimalTurns.length === 0) {
482
- activeUpdateBanner = { sessionKey: currentSessionKey, version: PACKAGE_VERSION, collapsed: false };
484
+ activeUpdateBanner = { sessionKey: currentSessionKey, version: PACKAGE_VERSION, previousVersion: prevVersion, collapsed: false };
483
485
  }
484
486
  }
485
487
  mountMinimalOutput(ctx);
@@ -497,7 +499,7 @@ export default function (pi: ExtensionAPI) {
497
499
  refreshFooter = () => tui.requestRender();
498
500
  speedHover?.dispose();
499
501
  speedHover = attachSpeedHover(tui, theme, () => ({
500
- metrics: settings["pi-mini-mode-speed-show"] ? speeds.metrics() : [],
502
+ metrics: settings["pi-mini-mode-speed-show"] ? speeds.metrics(uiLanguage(settings)) : [],
501
503
  hit: speedHitBox,
502
504
  }));
503
505
  const onBranchChange = footerData?.onBranchChange?.(() => tui.requestRender());
@@ -375,11 +375,11 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
375
375
  const item = msg && typeof msg === "object" ? msg as Record<string, unknown> : undefined;
376
376
  const details = item?.details && typeof item.details === "object" ? item.details as Record<string, unknown> : undefined;
377
377
  if (item?.customType === "subagent_supervisor_request" && details?.reason === "progress_update") {
378
- const progress = extractNoticeBody(msg);
378
+ const progress = extractNoticeBody(msg, lang);
379
379
  if (progress) latestProgress = progress;
380
380
  continue;
381
381
  }
382
- const b = supervisorNoticeBody(msg);
382
+ const b = supervisorNoticeBody(msg, lang);
383
383
  if (b && !bodies.includes(b)) bodies.push(b);
384
384
  }
385
385
  if (!bodies.length && latestProgress) bodies.push(latestProgress);
@@ -501,11 +501,11 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
501
501
  const item = msg && typeof msg === "object" ? msg as Record<string, unknown> : undefined;
502
502
  const details = item?.details && typeof item.details === "object" ? item.details as Record<string, unknown> : undefined;
503
503
  if (item?.customType === "subagent_supervisor_request" && details?.reason === "progress_update") {
504
- const progress = extractNoticeBody(msg);
504
+ const progress = extractNoticeBody(msg, lang);
505
505
  if (progress) latestProgress = progress;
506
506
  continue;
507
507
  }
508
- const b = supervisorNoticeBody(msg);
508
+ const b = supervisorNoticeBody(msg, lang);
509
509
  if (b && !bodies.includes(b)) bodies.push(b);
510
510
  }
511
511
  if (!bodies.length && latestProgress) bodies.push(latestProgress);
@@ -187,14 +187,16 @@ export function retainAgentStatuses(previous: Record<string, unknown>[], current
187
187
  const retained = new Map(previous.map(status => [String(status.runId), status]));
188
188
  for (const status of new Map([...previous, ...current].map(status => [String(status.runId), status])).values()) {
189
189
  const saved = retained.get(String(status.runId));
190
- const children = agentChildren([status]).map(child => {
191
- const previous = saved && agentChildren([saved]).find(item => item.displayId === child.displayId);
190
+ const children = agentChildren([status]);
191
+ const previousChildren = saved && saved !== status ? agentChildren([saved]) : saved ? children : undefined;
192
+ const merged = children.map(child => {
193
+ const previous = previousChildren?.find(item => item.displayId === child.displayId);
192
194
  const sameAttempt = previous?.sessionFile === child.sessionFile && previous?.startedAt === child.startedAt;
193
195
  const finalOutput = childSessionData(child.sessionFile)?.finalOutput ?? child.finalOutput ?? (sameAttempt ? previous?.finalOutput : undefined);
194
196
  return { ...child, finalOutput, notice: child.notice ?? previous?.notice, noticeMessages: child.noticeMessages ?? previous?.noticeMessages };
195
197
  });
196
- retained.set(String(status.runId), children.length
197
- ? { ...status, steps: children, workflowChildren: undefined, children: undefined } : status);
198
+ retained.set(String(status.runId), merged.length
199
+ ? { ...status, steps: merged, workflowChildren: undefined, children: undefined } : status);
198
200
  }
199
201
  return [...retained.values()];
200
202
  }
@@ -218,38 +220,173 @@ export function readAgentStatuses(sessionId: string, root = process.env.PI_SUBAG
218
220
  } catch { return previous.filter(status => status.sessionId === sessionId); }
219
221
  }
220
222
 
221
- export function currentAgentStatuses(statuses: Record<string, unknown>[], callsOrIds: unknown[]): Record<string, unknown>[] {
223
+ // Frames re-read every call output unless the source values are unchanged. Object calls
224
+ // keep their extracted run ids in a WeakMap (collected with the call); short string ids use
225
+ // a bounded LRU. Any edited source rescans that call. An append can create or destroy a
226
+ // UUID word boundary, so a tail increment is not reused.
227
+ const RUN_ID_PATTERN = /\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/gi;
228
+ const STRING_RUN_CACHE_LIMIT = 256;
229
+ const STRING_RUN_CACHE_MAX_LENGTH = 128;
230
+ const stringRunCache = new Map<string, string | null>();
231
+ type SourceSnap = { ref: unknown; text?: string };
232
+ type CallSnap = { id: SourceSnap; output: SourceSnap; task: SourceSnap; action: SourceSnap; callId?: string; runIds: string[] };
233
+ const callSnaps = new WeakMap<object, CallSnap>();
234
+
235
+ function sourceSnap(value: unknown): SourceSnap {
236
+ if (typeof value === "string" || value == null) return { ref: value };
237
+ return { ref: value, text: String(value) };
238
+ }
239
+ function sourceText(snap: SourceSnap): string {
240
+ if (typeof snap.ref === "string") return snap.ref;
241
+ if (snap.ref == null) return "";
242
+ return snap.text ?? "";
243
+ }
244
+ function sameSource(value: unknown, snap: SourceSnap): boolean {
245
+ if (typeof value === "string" || value == null) return value === snap.ref;
246
+ return String(value) === snap.text;
247
+ }
248
+ function collectRunIds(text: string, seen: Set<string>, into: string[]) {
249
+ if (text.length < 36) return;
250
+ RUN_ID_PATTERN.lastIndex = 0;
251
+ let match: RegExpExecArray | null;
252
+ while ((match = RUN_ID_PATTERN.exec(text))) {
253
+ if (seen.has(match[1])) continue;
254
+ seen.add(match[1]);
255
+ into.push(match[1]);
256
+ }
257
+ RUN_ID_PATTERN.lastIndex = 0;
258
+ }
259
+ function firstRunId(text: string): string | null {
260
+ if (text.length < 36) return null;
261
+ RUN_ID_PATTERN.lastIndex = 0;
262
+ const match = RUN_ID_PATTERN.exec(text);
263
+ RUN_ID_PATTERN.lastIndex = 0;
264
+ return match?.[1] ?? null;
265
+ }
266
+ function cachedStringRunId(item: string): string | null {
267
+ if (item.length > STRING_RUN_CACHE_MAX_LENGTH) return firstRunId(item);
268
+ const cached = stringRunCache.get(item);
269
+ if (cached !== undefined) {
270
+ stringRunCache.delete(item);
271
+ stringRunCache.set(item, cached);
272
+ return cached;
273
+ }
274
+ const found = firstRunId(item);
275
+ stringRunCache.set(item, found);
276
+ if (stringRunCache.size > STRING_RUN_CACHE_LIMIT) {
277
+ const oldest = stringRunCache.keys().next().value;
278
+ if (oldest !== undefined) stringRunCache.delete(oldest);
279
+ }
280
+ return found;
281
+ }
282
+ function callSnap(item: object): CallSnap {
283
+ const call = item as Record<string, unknown>;
284
+ const cached = callSnaps.get(item);
285
+ if (cached && sameSource(call.id, cached.id) && sameSource(call.output, cached.output)
286
+ && sameSource(call.task, cached.task) && sameSource(call.action, cached.action)) return cached;
287
+ const output = sourceSnap(call.output);
288
+ const task = sourceSnap(call.task);
289
+ const action = sourceSnap(call.action);
290
+ const runIds: string[] = [];
291
+ const seen = new Set<string>();
292
+ collectRunIds(sourceText(output), seen, runIds);
293
+ collectRunIds(sourceText(task), seen, runIds);
294
+ collectRunIds(sourceText(action), seen, runIds);
295
+ const next: CallSnap = {
296
+ id: sourceSnap(call.id), output, task, action,
297
+ callId: typeof call.id === "string" ? call.id : undefined, runIds,
298
+ };
299
+ callSnaps.set(item, next);
300
+ return next;
301
+ }
302
+ type CallKeys = { callIds: Set<string>; runIds: Set<string> };
303
+ function collectCallKeys(items: unknown[]): CallKeys {
222
304
  const callIds = new Set<string>();
223
305
  const runIds = new Set<string>();
224
- for (const item of callsOrIds) {
306
+ for (const item of items) {
225
307
  if (typeof item === "string") {
226
308
  callIds.add(item);
227
- const match = item.match(/\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/i);
228
- if (match) runIds.add(match[1]);
309
+ const runId = cachedStringRunId(item);
310
+ if (runId) runIds.add(runId);
229
311
  } else if (item && typeof item === "object") {
230
- const call = item as Record<string, unknown>;
231
- if (typeof call.id === "string") callIds.add(call.id);
232
- const text = `${call.output ?? ""} ${call.task ?? ""} ${call.action ?? ""}`;
233
- const matches = text.matchAll(/\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/gi);
234
- for (const m of matches) runIds.add(m[1]);
312
+ const snap = callSnap(item);
313
+ if (snap.callId) callIds.add(snap.callId);
314
+ for (const runId of snap.runIds) runIds.add(runId);
235
315
  }
236
316
  }
237
- const selected = new Set<string>();
238
- for (const status of statuses) {
239
- const runId = String(status.runId ?? "");
317
+ return { callIds, runIds };
318
+ }
319
+
320
+ type StatusHit = { status: Record<string, unknown>; index: number };
321
+ type StatusIndex = { byRun: Map<string, StatusHit[]>; byTool: Map<string, string[]>; children: Map<string, string[]> };
322
+ function indexStatuses(statuses: Record<string, unknown>[]): StatusIndex {
323
+ const byRun = new Map<string, StatusHit[]>();
324
+ const byTool = new Map<string, string[]>();
325
+ const children = new Map<string, string[]>();
326
+ for (let index = 0; index < statuses.length; index++) {
327
+ const status = statuses[index];
328
+ const selectKey = String(status.runId);
329
+ const bucket = byRun.get(selectKey);
330
+ if (bucket) bucket.push({ status, index });
331
+ else byRun.set(selectKey, [{ status, index }]);
332
+ const directKey = String(status.runId ?? "");
240
333
  const toolCallId = String(status.toolCallId ?? "");
241
- if ((toolCallId && callIds.has(toolCallId)) || (runId && runIds.has(runId))) {
242
- if (runId) selected.add(runId);
334
+ if (toolCallId && directKey) {
335
+ const tools = byTool.get(toolCallId);
336
+ if (tools) tools.push(directKey);
337
+ else byTool.set(toolCallId, [directKey]);
338
+ }
339
+ const parentId = String(status.parentWorkflowRunId ?? "");
340
+ if (parentId) {
341
+ const kids = children.get(parentId);
342
+ if (kids) kids.push(selectKey);
343
+ else children.set(parentId, [selectKey]);
243
344
  }
244
345
  }
245
- for (let size = -1; size !== selected.size;) {
246
- size = selected.size;
247
- for (const status of statuses) {
248
- const parentId = String(status.parentWorkflowRunId ?? "");
249
- if (parentId && selected.has(parentId)) selected.add(String(status.runId));
346
+ return { byRun, byTool, children };
347
+ }
348
+ function selectRunIds(index: StatusIndex, keys: CallKeys): Set<string> {
349
+ const selected = new Set<string>();
350
+ for (const id of keys.callIds) {
351
+ const runs = index.byTool.get(id);
352
+ if (runs) for (const runId of runs) selected.add(runId);
353
+ }
354
+ for (const runId of keys.runIds) if (index.byRun.has(runId)) selected.add(runId);
355
+ if (selected.size === 0) return selected;
356
+ const queue = [...selected];
357
+ for (let i = 0; i < queue.length; i++) {
358
+ const kids = index.children.get(queue[i]);
359
+ if (!kids) continue;
360
+ for (const runId of kids) if (!selected.has(runId)) {
361
+ selected.add(runId);
362
+ queue.push(runId);
250
363
  }
251
364
  }
252
- return statuses.filter(status => selected.has(String(status.runId)));
365
+ return selected;
366
+ }
367
+ function takeStatuses(index: StatusIndex, selected: Set<string>, claimed?: Set<string>): Record<string, unknown>[] {
368
+ const hits: StatusHit[] = [];
369
+ for (const runId of selected) {
370
+ const bucket = index.byRun.get(runId);
371
+ if (!bucket) continue;
372
+ for (const hit of bucket) {
373
+ const key = String(hit.status.runId ?? "");
374
+ if (claimed && key && claimed.has(key)) continue;
375
+ hits.push(hit);
376
+ }
377
+ }
378
+ if (hits.length > 1) hits.sort((a, b) => a.index - b.index);
379
+ if (claimed) for (const hit of hits) {
380
+ const key = String(hit.status.runId ?? "");
381
+ if (key) claimed.add(key);
382
+ }
383
+ return hits.map(hit => hit.status);
384
+ }
385
+
386
+ export function currentAgentStatuses(statuses: Record<string, unknown>[], callsOrIds: unknown[]): Record<string, unknown>[] {
387
+ if (statuses.length === 0 || callsOrIds.length === 0) return [];
388
+ const index = indexStatuses(statuses);
389
+ return takeStatuses(index, selectRunIds(index, collectCallKeys(callsOrIds)));
253
390
  }
254
391
 
255
392
  /** Associate each status only with the user turn that dispatched its tool call.
@@ -257,22 +394,21 @@ export function currentAgentStatuses(statuses: Record<string, unknown>[], callsO
257
394
  */
258
395
  export function agentStatusesByTurn(statuses: Record<string, unknown>[], turns: Array<{ agentCalls?: unknown[] }>): Map<number, Record<string, unknown>[]> {
259
396
  const assigned = new Map<number, Record<string, unknown>[]>();
397
+ if (statuses.length === 0) {
398
+ for (let index = 0; index < turns.length; index++) assigned.set(index, []);
399
+ return assigned;
400
+ }
401
+ const indexed = indexStatuses(statuses);
260
402
  const claimed = new Set<string>();
261
- for (const [index, turn] of turns.entries()) {
262
- const matched = currentAgentStatuses(statuses, turn.agentCalls ?? []).filter(status => {
263
- const runId = String(status.runId ?? "");
264
- return !runId || !claimed.has(runId);
265
- });
266
- assigned.set(index, matched);
267
- for (const status of matched) {
268
- const runId = String(status.runId ?? "");
269
- if (runId) claimed.add(runId);
270
- }
403
+ for (let index = 0; index < turns.length; index++) {
404
+ const calls = turns[index]?.agentCalls ?? [];
405
+ assigned.set(index, calls.length === 0 ? [] : takeStatuses(indexed, selectRunIds(indexed, collectCallKeys(calls)), claimed));
271
406
  }
272
407
  return assigned;
273
408
  }
274
409
 
275
410
  export function agentChildren(statuses: Record<string, unknown>[]): Record<string, unknown>[] {
411
+ if (statuses.length === 0) return [];
276
412
  const children = new Map<string, Record<string, unknown>>();
277
413
  const visit = (value: unknown, key: string) => {
278
414
  if (!value || typeof value !== "object") return;
@@ -1,6 +1,7 @@
1
1
  import { diagramMarkdown, renderMinimalMarkdown } from "./minimal-markdown.ts";
2
2
  import { plain } from "./agent-state.ts";
3
3
  import { agentSummary, liveAgentRows, runningGlyph, type AgentDeadlines } from "./agent-render.ts";
4
+ import type { UiLanguage } from "./settings.ts";
4
5
  import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
5
6
  import { truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
6
7
 
@@ -64,7 +65,7 @@ const isAgentFleetSummary = (lines: string[]) => {
64
65
  };
65
66
 
66
67
  /** Pi 0.85 widget containers: preserve unrelated widgets and their lifecycle. */
67
- export function attachAgentWidgets(tui: unknown, theme: Theme, expanded: () => boolean, statuses?: () => Record<string, unknown>[], inline = false): () => void {
68
+ export function attachAgentWidgets(tui: unknown, theme: Theme, expanded: () => boolean, statuses?: () => Record<string, unknown>[], inline = false, language: () => UiLanguage = () => "zh"): () => void {
68
69
  const host = tui as { children?: Array<Component & { children?: Component[] }> };
69
70
  if (host.children?.length !== 7) return () => {};
70
71
  const restores: Array<() => void> = [];
@@ -75,7 +76,8 @@ export function attachAgentWidgets(tui: unknown, theme: Theme, expanded: () => b
75
76
  const descriptor = Object.getOwnPropertyDescriptor(container, "render");
76
77
  const mouseDescriptor = Object.getOwnPropertyDescriptor(container, "handleMouse");
77
78
  const render = (width: number) => {
78
- const live = !inline && statuses ? liveAgentRows(statuses(), theme, width, expanded(), deadlines) : [];
79
+ const lang = language();
80
+ const live = !inline && statuses ? liveAgentRows(statuses(), theme, width, expanded(), deadlines, lang) : [];
79
81
  let inserted = false;
80
82
  const rows = container.children!.flatMap(child => {
81
83
  const original = child.render(width);
@@ -96,7 +98,8 @@ export function attachAgentWidgets(tui: unknown, theme: Theme, expanded: () => b
96
98
  const mouse: NonNullable<Component["handleMouse"]> = (event) => {
97
99
  let y = 0;
98
100
  let inserted = false;
99
- const live = !inline && statuses ? liveAgentRows(statuses(), theme, event.width, expanded(), deadlines) : [];
101
+ const lang = language();
102
+ const live = !inline && statuses ? liveAgentRows(statuses(), theme, event.width, expanded(), deadlines, lang) : [];
100
103
 
101
104
  for (const child of container.children!) {
102
105
  const original = child.render(event.width);
@@ -73,7 +73,7 @@ export function imagePlaceholders(source: string, cwd: string): string {
73
73
  const spans = assistantImageSpans(source, cwd, true);
74
74
  for (let index = spans.length - 1; index >= 0; index--) {
75
75
  const span = spans[index];
76
- out = out.slice(0, span.start) + fileLink(` 图片 ${index + 1}`, span.path, false) + out.slice(span.end);
76
+ out = out.slice(0, span.start) + fileLink(` #${index + 1}`, span.path, false) + out.slice(span.end);
77
77
  }
78
78
  if (placeholdersCache.size >= IMAGE_CACHE_MAX) {
79
79
  const first = placeholdersCache.keys().next().value;
@@ -2,6 +2,7 @@ import type { spawn } from "node:child_process";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import type { EditorComponent, OverlayHandle, OverlayOptions, renderImage, TUI } from "@earendil-works/pi-tui";
4
4
  import type { Preview } from "./input-image-paths.ts";
5
+ import type { UiLanguage } from "./settings.ts";
5
6
 
6
7
  export interface PreviewState {
7
8
  path?: string;
@@ -38,6 +39,7 @@ export interface Enhancements {
38
39
  hoverLink?: { row: number; start: number; end: number; path: string };
39
40
  previewOptions?: OverlayOptions;
40
41
  previewMode: () => "hover" | "inline";
42
+ language?: () => UiLanguage;
41
43
  inlineImages: Map<string, Preview | undefined>;
42
44
  inlinePending: Map<string, Promise<Preview | undefined>>;
43
45
  inlineGraphics: Map<string, { layout: string } & NonNullable<ReturnType<typeof renderImage>>>;
@@ -18,6 +18,7 @@ import { installEditor, liveUI } from "./input-editor.ts";
18
18
  import { handleTerminalInput, requestPreview, setPointer } from "./input-hover-preview.ts";
19
19
  import { clearInlineGraphics, syncInlineImages } from "./input-inline-images.ts";
20
20
  import { createSkillAutocompleteProvider, handleInput, readSkillCommands } from "./input-skill-completion.ts";
21
+ import type { UiLanguage } from "./settings.ts";
21
22
 
22
23
  export { MAX_PREVIEW_BYTES, imagePathsInLine, imagePathAtCursor, imageDirectoryUrl, readPreview } from "./input-image-paths.ts";
23
24
  export type { ImagePathMatch, PreviewImage, PreviewNote, Preview } from "./input-image-paths.ts";
@@ -31,12 +32,13 @@ export const INPUT_ENHANCEMENTS_SETTING = "pi-mini-mode-input-enhancements";
31
32
 
32
33
  let installed: Enhancements | undefined;
33
34
 
34
- export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean), previewMode: () => "hover" | "inline" = () => "hover"): InputEnhancementsCleanup {
35
+ export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean), previewMode: () => "hover" | "inline" = () => "hover", language: () => UiLanguage = () => "zh"): InputEnhancementsCleanup {
35
36
  const enabled = typeof isEnabled === "function" ? isEnabled : () => isEnabled;
36
37
  if (installed && installed.pi !== pi) installed.cleanup();
37
38
  const state = installed?.pi === pi ? installed : (installed = createEnhancements(pi));
38
39
  state.enabled = enabled;
39
40
  state.previewMode = previewMode;
41
+ state.language = language;
40
42
  state.ctx = ctx;
41
43
  state.cwd = ctx.cwd;
42
44
  state.theme = ctx.hasUI ? ctx.ui.theme : undefined;
@@ -85,10 +85,11 @@ export async function requestPreview(state: Enhancements, path: string | undefin
85
85
  return;
86
86
  }
87
87
  const cells = getCellDimensions();
88
+ const lang = state.language?.() ?? "zh";
88
89
  const preview = await readPreview(path, state.cwd ?? process.cwd(), {
89
90
  widthPx: Math.max(1, (state.tui?.terminal.columns ?? 80) - 2) * cells.widthPx,
90
91
  heightPx: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2) * cells.heightPx,
91
- });
92
+ }, lang);
92
93
  if (token !== state.previewToken || !state.enabled()) return;
93
94
  setPreview(state, preview);
94
95
  }
@@ -107,9 +108,10 @@ function setPreview(state: Enhancements, preview: Preview | undefined): void {
107
108
  maxHeightCells: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2),
108
109
  imageId: allocateImageId(), moveCursor: false,
109
110
  }) ?? undefined : undefined;
111
+ const lang = state.language?.() ?? "zh";
110
112
  state.preview = {
111
113
  path: preview?.path, graphic,
112
- note: preview?.kind === "note" ? preview.note : graphic ? undefined : "终端未能生成图片预览",
114
+ note: preview?.kind === "note" ? preview.note : graphic ? undefined : (lang === "en" ? "Terminal cannot render image preview" : "终端未能生成图片预览"),
113
115
  };
114
116
  if (state.preview.path && !state.overlayReady) showOverlay(state);
115
117
  positionPreview(state);
@@ -123,7 +125,7 @@ function showOverlay(state: Enhancements): void {
123
125
  state.previewHandle = state.tui.showOverlay({
124
126
  render: width => {
125
127
  if (state.previewLayout !== imageLayoutKey()) setPreview(state, state.previewSource);
126
- return previewLines(state.preview, state.theme!, width);
128
+ return previewLines(state.preview, state.theme!, width, state.language?.() ?? "zh");
127
129
  },
128
130
  invalidate: () => {},
129
131
  }, state.previewOptions);
@@ -133,7 +135,7 @@ export function positionPreview(state: Enhancements): void {
133
135
  if (!state.previewOptions || !state.tui || !state.theme) return;
134
136
  const { rows, columns } = state.tui.terminal;
135
137
  const width = Math.max(3, Math.min((state.preview.graphic?.columns ?? 26) + 2, columns || 80));
136
- const height = Math.min(rows, previewLines(state.preview, state.theme, width).length);
138
+ const height = Math.min(rows, previewLines(state.preview, state.theme, width, state.language?.() ?? "zh").length);
137
139
  const { x, y } = state.previewAnchor ?? { x: 0, y: rows - 2 };
138
140
  const previewRow = y + 1 + height <= rows ? y + 1 : Math.max(0, y - height);
139
141
  // Keep hover previews out of the draft attachment band. If there is no safe
@@ -1,6 +1,7 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { getCapabilities, getCellDimensions, truncateToWidth } from "@earendil-works/pi-tui";
3
3
  import type { PreviewState } from "./input-enhancements-types.ts";
4
+ import type { UiLanguage } from "./settings.ts";
4
5
 
5
6
  export function positionedGraphic(sequence: string, up: number, right: number): string {
6
7
  // Pi <=0.87's ANSI slicer needs an SGR terminator after relative motion.
@@ -19,7 +20,7 @@ export function imageLayoutKey(): string {
19
20
  }
20
21
 
21
22
  /** A tightly sized image frame. Draw after clearing its interior, never a path-only tooltip. */
22
- export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
23
+ export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"]["theme"], width: number, lang: UiLanguage = "zh"): string[] {
23
24
  if (!preview.path) return [];
24
25
  const graphic = preview.graphic;
25
26
  const innerWidth = Math.max(1, Math.min(width - 2, graphic?.columns ?? 26));
@@ -27,7 +28,7 @@ export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"
27
28
  const lines = [border(`╭${"─".repeat(innerWidth)}╮`)];
28
29
  if (graphic) {
29
30
  for (let row = 0; row < graphic.rows; row++) lines.push(border("│") + " ".repeat(innerWidth) + border("│"));
30
- } else lines.push(border("│") + truncateToWidth(preview.note ?? "无法预览图片", innerWidth, "", true) + border("│"));
31
+ } else lines.push(border("│") + truncateToWidth(preview.note ?? (lang === "en" ? "Cannot preview image" : "无法预览图片"), innerWidth, "", true) + border("│"));
31
32
  const draw = graphic ? positionedGraphic(graphic.sequence, graphic.rows, 1) : "";
32
33
  lines.push(draw + border(`╰${"─".repeat(innerWidth)}╯`));
33
34
  return lines;
@@ -1,6 +1,7 @@
1
1
  import { resizeImage } from "@earendil-works/pi-coding-agent";
2
2
  import { getImageDimensions, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
3
3
  import { filePaths } from "./file-links.ts";
4
+ import type { UiLanguage } from "./settings.ts";
4
5
  import { open } from "node:fs/promises";
5
6
  import { existsSync } from "node:fs";
6
7
  import { homedir } from "node:os";
@@ -48,7 +49,7 @@ export function imagePathsInLine(line: string): ImagePathMatch[] {
48
49
  if (!IMAGE_MIME[extname(path).toLowerCase()]) continue;
49
50
  matches.push({ path, start, end, startCol: visibleWidth(plain.slice(0, start)), endCol: visibleWidth(plain.slice(0, end)) });
50
51
  }
51
- return matches;
52
+ return matches.sort((a, b) => a.start - b.start);
52
53
  }
53
54
 
54
55
  /** Image path token the cursor sits in, if any. */
@@ -78,11 +79,38 @@ export interface PreviewNote {
78
79
  }
79
80
  export type Preview = PreviewImage | PreviewNote;
80
81
 
82
+ const PREVIEW_NOTES: Record<UiLanguage, {
83
+ overLimit: (mb: number) => string;
84
+ badDimensions: string;
85
+ resizeFailed: string;
86
+ convertFailed: string;
87
+ tooLarge: string;
88
+ readFailed: string;
89
+ }> = {
90
+ zh: {
91
+ overLimit: mb => `超过 ${mb}MB`,
92
+ badDimensions: "无法解析图片尺寸",
93
+ resizeFailed: "无法缩小图片预览",
94
+ convertFailed: "无法转换图片预览",
95
+ tooLarge: "图片预览过大",
96
+ readFailed: "读取失败",
97
+ },
98
+ en: {
99
+ overLimit: mb => `Over ${mb}MB`,
100
+ badDimensions: "Cannot read image dimensions",
101
+ resizeFailed: "Cannot resize image preview",
102
+ convertFailed: "Cannot convert image preview",
103
+ tooLarge: "Image preview too large",
104
+ readFailed: "Read failed",
105
+ },
106
+ };
107
+
81
108
  /**
82
109
  * Read a preview for an image path. Returns undefined when there is nothing to show
83
110
  * (unknown extension, missing file, directory) so typing never raises a hint.
84
111
  */
85
- export async function readPreview(path: string, cwd: string, bounds = { widthPx: MAX_PREVIEW_WIDTH_PX, heightPx: MAX_PREVIEW_HEIGHT_PX }): Promise<Preview | undefined> {
112
+ export async function readPreview(path: string, cwd: string, bounds = { widthPx: MAX_PREVIEW_WIDTH_PX, heightPx: MAX_PREVIEW_HEIGHT_PX }, lang: UiLanguage = "zh"): Promise<Preview | undefined> {
113
+ const copy = PREVIEW_NOTES[lang] ?? PREVIEW_NOTES.zh;
86
114
  const absolute = absolutePath(path, cwd);
87
115
  const mimeType = IMAGE_MIME[extname(absolute).toLowerCase()];
88
116
  if (!mimeType) return undefined;
@@ -91,7 +119,7 @@ export async function readPreview(path: string, cwd: string, bounds = { widthPx:
91
119
  try {
92
120
  const info = await file.stat();
93
121
  if (!info.isFile()) return undefined;
94
- if (info.size > MAX_PREVIEW_BYTES) return { kind: "note", path, note: `超过 ${MAX_PREVIEW_BYTES / 1024 / 1024}MB` };
122
+ if (info.size > MAX_PREVIEW_BYTES) return { kind: "note", path, note: copy.overLimit(MAX_PREVIEW_BYTES / 1024 / 1024) };
95
123
  const bytes = Buffer.alloc(info.size);
96
124
  let offset = 0;
97
125
  while (offset < bytes.length) {
@@ -102,19 +130,19 @@ export async function readPreview(path: string, cwd: string, bounds = { widthPx:
102
130
  const data = bytes.subarray(0, offset);
103
131
  const base64 = data.toString("base64");
104
132
  const dimensions = getImageDimensions(base64, mimeType);
105
- if (!dimensions) return { kind: "note", path, note: "无法解析图片尺寸" };
133
+ if (!dimensions) return { kind: "note", path, note: copy.badDimensions };
106
134
  const maxWidth = Math.max(1, Math.min(MAX_PREVIEW_WIDTH_PX, Math.floor(bounds.widthPx)));
107
135
  const maxHeight = Math.max(1, Math.min(MAX_PREVIEW_HEIGHT_PX, Math.floor(bounds.heightPx)));
108
136
  // renderImage controls cell placement, not pixels; its Kitty f=100 payload must be PNG.
109
137
  const resized = dimensions.widthPx <= maxWidth && dimensions.heightPx <= maxHeight && base64.length < MAX_PREVIEW_ENCODED_BYTES
110
138
  ? { data: base64, mimeType } : await resizeImage(data, mimeType, { maxWidth, maxHeight, maxBytes: MAX_PREVIEW_ENCODED_BYTES });
111
- if (!resized) return { kind: "note", path, note: "无法缩小图片预览" };
139
+ if (!resized) return { kind: "note", path, note: copy.resizeFailed };
112
140
  const png = resized.mimeType === "image/png" ? resized
113
141
  : await (await import("@earendil-works/pi-coding-agent")).convertToPng(resized.data, resized.mimeType);
114
- if (!png) return { kind: "note", path, note: "无法转换图片预览" };
115
- if (png.data.length > MAX_PREVIEW_ENCODED_BYTES) return { kind: "note", path, note: "图片预览过大" };
142
+ if (!png) return { kind: "note", path, note: copy.convertFailed };
143
+ if (png.data.length > MAX_PREVIEW_ENCODED_BYTES) return { kind: "note", path, note: copy.tooLarge };
116
144
  return { kind: "image", path, mimeType: png.mimeType, base64: png.data, widthPx: dimensions.widthPx, heightPx: dimensions.heightPx };
117
145
  } catch {
118
- return { kind: "note", path, note: "读取失败" };
146
+ return { kind: "note", path, note: copy.readFailed };
119
147
  } finally { await file.close(); }
120
148
  }
@@ -4,6 +4,12 @@ import type { Enhancements } from "./input-enhancements-types.ts";
4
4
  import { editorImagePaths } from "./input-editor-paths.ts";
5
5
  import { imageLayoutKey, positionedGraphic } from "./input-image-graphics.ts";
6
6
  import { readPreview } from "./input-image-paths.ts";
7
+ import type { UiLanguage } from "./settings.ts";
8
+
9
+ const INLINE_COPY: Record<UiLanguage, { loading: string; cannotPreview: string }> = {
10
+ zh: { loading: "加载中", cannotPreview: "无法预览" },
11
+ en: { loading: "Loading", cannotPreview: "No preview" },
12
+ };
7
13
 
8
14
  function draftImagePaths(editor: EditorComponent): string[] {
9
15
  const source = (editor as EditorComponent & { state?: { lines: string[] } }).state?.lines ?? editor.getText().split("\n");
@@ -27,8 +33,9 @@ export function syncInlineImages(state: Enhancements): void {
27
33
  for (const path of paths) {
28
34
  if (state.inlineImages.has(path) || state.inlinePending.has(path)) continue;
29
35
  const cwd = state.cwd ?? process.cwd();
36
+ const lang = state.language?.() ?? "zh";
30
37
  // Cell placement scales the image; keep a bounded copy independent of startup cell metrics.
31
- const pending = readPreview(path, cwd).catch(() => undefined);
38
+ const pending = readPreview(path, cwd, undefined, lang).catch(() => undefined);
32
39
  state.inlinePending.set(path, pending);
33
40
  void pending.then(preview => {
34
41
  if (state.inlinePending.get(path) !== pending) return;
@@ -40,9 +47,10 @@ export function syncInlineImages(state: Enhancements): void {
40
47
  }
41
48
  }
42
49
 
43
- export function inlinePreviewLines(state: Pick<Enhancements, "editor" | "enabled" | "previewMode" | "inlineImages" | "inlinePending" | "inlineGraphics" | "tui">, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
50
+ export function inlinePreviewLines(state: Pick<Enhancements, "editor" | "enabled" | "previewMode" | "inlineImages" | "inlinePending" | "inlineGraphics" | "tui" | "language">, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
44
51
  const paths = state.editor && state.enabled() && state.previewMode() === "inline" && width >= 12 ? draftImagePaths(state.editor) : [];
45
52
  if (!paths.length) { clearInlineGraphics(state); return []; }
53
+ const copy = INLINE_COPY[state.language?.() ?? "zh"] ?? INLINE_COPY.zh;
46
54
  const cardWidth = Math.min(14, width);
47
55
  // ponytail: cards are capped at one row; beyond viewport width show compact numbered tags, upgrade to a gallery when scrolling is supported.
48
56
  const count = Math.max(1, Math.floor((width + 2) / (cardWidth + 2)));
@@ -77,14 +85,14 @@ export function inlinePreviewLines(state: Pick<Enhancements, "editor" | "enabled
77
85
  return frame(`${top ? "╭" : "╰"}${"─".repeat(Math.floor(fill / 2))} ${caption} ${"─".repeat(Math.ceil(fill / 2))}${top ? "╮" : "╯"}`);
78
86
  };
79
87
  const top = rim(` #${index + 1}`, true);
80
- const size = preview?.kind === "image" ? `${preview.widthPx}x${preview.heightPx}` : state.inlinePending.has(path) ? "加载中" : "无法预览";
88
+ const size = preview?.kind === "image" ? `${preview.widthPx}x${preview.heightPx}` : state.inlinePending.has(path) ? copy.loading : copy.cannotPreview;
81
89
  return { graphic, preview, top, size, rim, frame };
82
90
  });
83
91
  // OMP's 12x4 inner grid; never grow a tall empty box for a wide image.
84
92
  const bodyHeight = 4;
85
93
  rows.push(cards.map(card => card.top).join(" "));
86
94
  for (let row = 0; row < bodyHeight; row++) rows.push(cards.map(card => {
87
- const content = row === 0 && !card.graphic ? truncateToWidth(card.preview?.kind === "note" ? card.preview.note : card.size === "加载中" ? "加载中" : "无法预览", cardWidth - 4, "…") : "";
95
+ const content = row === 0 && !card.graphic ? truncateToWidth(card.preview?.kind === "note" ? card.preview.note : card.size === copy.loading ? copy.loading : copy.cannotPreview, cardWidth - 4, "…") : "";
88
96
  const left = card.graphic ? Math.floor((cardWidth - 2 - card.graphic.columns) / 2) : 0;
89
97
  return card.frame("│") + " ".repeat(left) + " ".repeat(cardWidth - 2 - left - visibleWidth(content)) + content + card.frame("│");
90
98
  }).join(" "));