@each1024/pi-mini-mode 1.0.3 → 1.0.4
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.
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/extensions/footer-status.ts +12 -3
- package/lib/file-links.ts +11 -17
- package/lib/input-enhancements.ts +319 -47
- package/lib/settings.html +12 -2
- package/lib/terminal-capabilities.ts +45 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -93,7 +93,7 @@ This earlier screenshot and recording show footer configuration, not the newer i
|
|
|
93
93
|
|
|
94
94
|
## Compatibility
|
|
95
95
|
|
|
96
|
-
- **Images:** previews require a terminal image protocol; unsupported terminals show a hint. Image reads are limited to **20 MB**, and deleted files cannot be reopened. Link gestures depend on the terminal: usually `Cmd+click` on macOS or `Ctrl+click` on Windows/Linux; Ghostty fullscreen may require `Shift+Cmd` / `Shift+Ctrl`. Pi fullscreen also supports direct link clicks. See [Pi terminal setup](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/terminal-setup.md).
|
|
96
|
+
- **Images:** previews require a terminal image protocol; unsupported terminals show a hint. Large images are resized for the terminal preview only (up to 1200 × 800 pixels and 1 MB encoded); the original file and submitted path are unchanged. Image reads are limited to **20 MB**, and deleted files cannot be reopened. Link gestures depend on the terminal: usually `Cmd+click` on macOS or `Ctrl+click` on Windows/Linux; Ghostty fullscreen may require `Shift+Cmd` / `Shift+Ctrl`. Pi fullscreen also supports direct link clicks. See [Pi terminal setup](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/terminal-setup.md).
|
|
97
97
|
- **Minimal output:** uses a private Pi 0.85.x layout adapter without patching Pi’s installation. Unknown layouts refuse activation and keep native output. Recheck after Pi upgrades; other transcript-replacing extensions can conflict.
|
|
98
98
|
- **Subagents:** the pi-subagents widget adapter runs only in minimal mode, restores on disable, and passes unknown formats through. Available details depend on the integration’s status/output data; this is not a complete subagent transcript viewer.
|
|
99
99
|
- **History:** `/reload` remounts the transcript, including history created in native mode. Empty progress events do not erase existing content; tools without output show elapsed waiting time. Legacy per-item minimal controls no longer filter content.
|
package/README.zh-CN.md
CHANGED
|
@@ -93,7 +93,7 @@ pi install git:github.com/eachann1024/pi-mini-mode
|
|
|
93
93
|
|
|
94
94
|
## 兼容性
|
|
95
95
|
|
|
96
|
-
- **图片:**
|
|
96
|
+
- **图片:** 预览依赖终端图片协议,不支持时显示提示。大图仅对终端预览副本缩放(不超过 1200 × 800 像素、编码后 1 MB);原文件和提交路径不变。读取上限 **20 MB**,文件被清理后无法重新打开。点击手势由终端决定:macOS 通常使用 `Cmd+点击`,Windows/Linux 通常使用 `Ctrl+点击`;Ghostty 全屏可能需要 `Shift+Cmd` / `Shift+Ctrl`。Pi 全屏也支持直接点击链接。参见 [Pi 终端设置](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/terminal-setup.md)。
|
|
97
97
|
- **极简输出:** 使用私有 Pi 0.85.x 布局适配器,不修改 Pi 安装目录。未知布局会拒绝启用并保留原生输出;升级 Pi 后需重新检查,其他替换 transcript 的扩展可能冲突。
|
|
98
98
|
- **子代理:** pi-subagents 小组件适配仅在极简模式启用,关闭后恢复原状,未知格式原样交给原生处理。可用详情取决于集成提供的状态/输出数据,不是完整子代理会话查看器。
|
|
99
99
|
- **历史:** `/reload` 会重新挂载 transcript,包含原生模式中产生的历史。空进度事件不覆盖已有内容;无输出的工具显示等待时间。旧的极简输出细项不再单独过滤内容。
|
|
@@ -6,6 +6,7 @@ import { minimalSurface, paintExpandedHeading } from "../lib/minimal-theme.ts";
|
|
|
6
6
|
import { Markdown, matchesKey, isKeyRelease, isKeyRepeat, sliceByColumn, type SettingItem, Text, type TuiMouseEvent, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
7
7
|
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
8
8
|
import { installInputEnhancements, type InputEnhancementsCleanup } from "../lib/input-enhancements.ts";
|
|
9
|
+
import { installTerminalCapabilities } from "../lib/terminal-capabilities.ts";
|
|
9
10
|
import { linkMessageFiles } from "../lib/file-links.ts";
|
|
10
11
|
import { homedir } from "node:os";
|
|
11
12
|
import { stripVTControlCharacters } from "node:util";
|
|
@@ -33,6 +34,7 @@ export interface MiniLensSettings {
|
|
|
33
34
|
"pi-mini-mode-speed-unit-show": boolean;
|
|
34
35
|
"pi-mini-mode-minimal-show": boolean;
|
|
35
36
|
"pi-mini-mode-input-enhancements": boolean;
|
|
37
|
+
"pi-mini-mode-image-preview": "hover" | "inline";
|
|
36
38
|
"pi-mini-mode-minimal-thinking-show": boolean;
|
|
37
39
|
"pi-mini-mode-minimal-tools-show": boolean;
|
|
38
40
|
"pi-mini-mode-minimal-output-show": boolean;
|
|
@@ -61,6 +63,7 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
|
|
|
61
63
|
"pi-mini-mode-speed-unit-show": true,
|
|
62
64
|
"pi-mini-mode-minimal-show": true,
|
|
63
65
|
"pi-mini-mode-input-enhancements": true,
|
|
66
|
+
"pi-mini-mode-image-preview": "inline",
|
|
64
67
|
"pi-mini-mode-minimal-thinking-show": true,
|
|
65
68
|
"pi-mini-mode-minimal-tools-show": true,
|
|
66
69
|
"pi-mini-mode-minimal-output-show": true,
|
|
@@ -98,7 +101,9 @@ export function parseSettings(value: unknown): MiniLensSettings {
|
|
|
98
101
|
const candidate = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
|
99
102
|
const settings = { ...DEFAULT_SETTINGS };
|
|
100
103
|
for (const id of SETTING_IDS) {
|
|
101
|
-
if (
|
|
104
|
+
if (id === "pi-mini-mode-image-preview") {
|
|
105
|
+
if (candidate[id] === "hover" || candidate[id] === "inline") settings[id] = candidate[id];
|
|
106
|
+
} else if (isBoolean(candidate[id])) settings[id] = candidate[id];
|
|
102
107
|
}
|
|
103
108
|
if (Array.isArray(candidate.footerOrder)) {
|
|
104
109
|
settings.footerOrder = [...new Set(candidate.footerOrder.filter((id): id is typeof FOOTER_FIELDS[number] =>
|
|
@@ -487,7 +492,7 @@ export function isCollapsedReplyChildSetting(id: string): boolean {
|
|
|
487
492
|
|
|
488
493
|
export function settingsItems(settings: MiniLensSettings): SettingItem[] {
|
|
489
494
|
const values = ["on", "off"];
|
|
490
|
-
const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "footerOrder">, string> = {
|
|
495
|
+
const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "footerOrder" | "pi-mini-mode-image-preview">, string> = {
|
|
491
496
|
"pi-mini-mode-project-branch-show": "显示项目名称和分支(互斥)",
|
|
492
497
|
"pi-mini-mode-branch-show": "仅显示分支(思考等级后,互斥)",
|
|
493
498
|
"pi-mini-mode-model-show": COPY.model, "pi-mini-mode-thinking-show": COPY.thinking, "pi-mini-mode-session-tokens-show": COPY.total, "pi-mini-mode-cache-tokens-show": COPY.cached, "pi-mini-mode-cache-miss-show": COPY.miss, "pi-mini-mode-ch-show": COPY.cacheHit, "pi-mini-mode-cost-show": COPY.price, "pi-mini-mode-mcp-show": COPY.mcp, "pi-mini-mode-context-show": COPY.context, "pi-mini-mode-context-dots-show": COPY.dots, "pi-mini-mode-context-percent-show": COPY.percent, "pi-mini-mode-speed-show": COPY.speed, "pi-mini-mode-speed-unit-show": COPY.speedUnit, "pi-mini-mode-minimal-show": COPY.minimal, "pi-mini-mode-input-enhancements": COPY.inputEnhancements, "pi-mini-mode-minimal-thinking-show": COPY.showThinking, "pi-mini-mode-minimal-tools-show": COPY.tools, "pi-mini-mode-minimal-output-show": COPY.output, "pi-mini-mode-minimal-skills-show": COPY.skills, "pi-mini-mode-agent-usage-show": COPY.agentUsage, "pi-mini-mode-agent-shortcut-show": COPY.shortcut,
|
|
@@ -1005,6 +1010,8 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
1005
1010
|
}
|
|
1006
1011
|
|
|
1007
1012
|
export default function (pi: ExtensionAPI) {
|
|
1013
|
+
const restoreTerminalCapabilities = installTerminalCapabilities();
|
|
1014
|
+
pi.on("session_shutdown", restoreTerminalCapabilities);
|
|
1008
1015
|
attachFooterTidy(pi);
|
|
1009
1016
|
attachTitlePlain(pi);
|
|
1010
1017
|
let refreshFooter: (() => void) | undefined;
|
|
@@ -1292,6 +1299,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1292
1299
|
if (key === "footerOrder") {
|
|
1293
1300
|
if (!Array.isArray(entry) || new Set(entry).size !== entry.length
|
|
1294
1301
|
|| entry.some(id => typeof id !== "string" || !(FOOTER_FIELDS as readonly string[]).includes(id))) throw new TypeError("Invalid order");
|
|
1302
|
+
} else if (key === "pi-mini-mode-image-preview") {
|
|
1303
|
+
if (entry !== "hover" && entry !== "inline") throw new TypeError("Invalid preview mode");
|
|
1295
1304
|
} else if (!SETTING_IDS.includes(key as typeof SETTING_IDS[number]) || typeof entry !== "boolean") throw new TypeError("Invalid setting");
|
|
1296
1305
|
}
|
|
1297
1306
|
const next = parseSettings({ ...settings, ...input, onboardingCompleted: true });
|
|
@@ -1367,7 +1376,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1367
1376
|
if (loaded.exists && loaded.backfilled) await persistSettings(ctx);
|
|
1368
1377
|
messageCwd = ctx.cwd;
|
|
1369
1378
|
// 输入增强只在会话中生效,会话开始时再加载;传 getter 让开关变更即时生效,重复调用是幂等的。
|
|
1370
|
-
cleanupInputEnhancements = installInputEnhancements(pi, ctx, () => settings["pi-mini-mode-input-enhancements"]);
|
|
1379
|
+
cleanupInputEnhancements = installInputEnhancements(pi, ctx, () => settings["pi-mini-mode-input-enhancements"], () => settings["pi-mini-mode-image-preview"]);
|
|
1371
1380
|
minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
|
|
1372
1381
|
activeMinimalTurn = undefined;
|
|
1373
1382
|
pendingMinimalFinal = "";
|
package/lib/file-links.ts
CHANGED
|
@@ -16,17 +16,8 @@ export function webPaths(text: string) {
|
|
|
16
16
|
});
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
/** Pi
|
|
20
|
-
export
|
|
21
|
-
const caps = getCapabilities();
|
|
22
|
-
if (env.TMUX || /^(screen|tmux)/.test(env.TERM ?? "")) return caps;
|
|
23
|
-
// Herdr panes advertise xterm-256color; the user's Kitty-capable fork renders images.
|
|
24
|
-
if (env.HERDR_PANE_ID) return { ...caps, hyperlinks: env.PI_HYPERLINKS !== "0",
|
|
25
|
-
images: env.PI_IMAGE_PROTOCOL === "0" || env.PI_IMAGE_PROTOCOL === "none" ? null : caps.images ?? "kitty" as const };
|
|
26
|
-
if (env.TERM_PROGRAM?.toLowerCase() !== "otty") return caps;
|
|
27
|
-
return { ...caps, hyperlinks: env.PI_HYPERLINKS === "0" ? false : true,
|
|
28
|
-
images: env.PI_IMAGE_PROTOCOL === "0" || env.PI_IMAGE_PROTOCOL === "none" ? null : caps.images ?? "kitty" as const };
|
|
29
|
-
}
|
|
19
|
+
/** Use Pi's effective capabilities, including user overrides and renderer restrictions. */
|
|
20
|
+
export const inputCapabilities = getCapabilities;
|
|
30
21
|
|
|
31
22
|
export function localPath(path: string, cwd: string): string {
|
|
32
23
|
return path.startsWith("~/") ? resolve(homedir(), path.slice(2)) : isAbsolute(path) ? path : resolve(cwd, path);
|
|
@@ -52,17 +43,19 @@ function fenceRanges(text: string): Array<[number, number]> {
|
|
|
52
43
|
return ranges;
|
|
53
44
|
}
|
|
54
45
|
|
|
55
|
-
/** Quoted paths may contain spaces;
|
|
46
|
+
/** Quoted or shell-escaped paths may contain spaces; spans refer to the original text. */
|
|
56
47
|
export function filePaths(text: string) {
|
|
57
48
|
const matches: Array<{ path: string; start: number; end: number }> = [];
|
|
58
49
|
const fences = fenceRanges(text);
|
|
59
|
-
const pattern = /(["'`])([^\r\n]*?)\1|[^\s"'`<>()[\]{},。;!?]+/g;
|
|
50
|
+
const pattern = /(["'`])([^\r\n]*?)\1|(?:\\[^\r\n]|[^\s"'`<>()[\]{},。;!?])+/g;
|
|
60
51
|
for (const match of text.matchAll(pattern)) {
|
|
61
|
-
const
|
|
52
|
+
const raw = (match[2] ?? match[0]).replace(/[.,;:!?]+$/, "");
|
|
53
|
+
const path = !match[1] && /^(?:\/|~\/|\.\.?\/)/.test(raw)
|
|
54
|
+
? raw.replace(/\\([ \t"'`()\[\]{}!#$&;<>?|*\\])/g, "$1") : raw;
|
|
62
55
|
if (!path || /^[\\/]+$/.test(path) || /[\x00-\x1f\x7f]/.test(path) || /^[a-z][\w+.-]*:\/\//i.test(path)) continue;
|
|
63
56
|
if (!/^(?:\/|~\/|\.{1,2}\/|[a-z]:[\\/])|[\\/]|\.[a-z\d]{1,12}$/i.test(path)) continue;
|
|
64
57
|
const start = match.index + (match[1] ? 1 : 0);
|
|
65
|
-
const end = start +
|
|
58
|
+
const end = start + raw.length;
|
|
66
59
|
if (fences.some(([from, to]) => start < to && end > from)) continue;
|
|
67
60
|
matches.push({ path, start, end });
|
|
68
61
|
}
|
|
@@ -85,11 +78,12 @@ export function linkMessageFiles(text: string, cwd: string): string {
|
|
|
85
78
|
return existsSync(path) ? `${prefix}<${pathToFileURL(path).href}>${suffix}` : original;
|
|
86
79
|
});
|
|
87
80
|
}
|
|
88
|
-
const matches = filePaths(part).map(match => ({ ...match,
|
|
81
|
+
const matches = filePaths(part).map(match => ({ ...match, image: /\.(png|jpe?g|gif|webp)$/i.test(match.path) && existsSync(localPath(match.path, cwd)), number: 0 }));
|
|
82
|
+
for (const match of matches) if (match.image) match.number = ++imageNumber;
|
|
89
83
|
for (const match of matches.reverse()) {
|
|
90
84
|
const path = localPath(match.path, cwd);
|
|
91
85
|
if (!existsSync(path)) continue;
|
|
92
|
-
part = part.slice(0, match.start) + fileLink(match.
|
|
86
|
+
part = part.slice(0, match.start) + fileLink(match.image ? ` #${match.number}` : match.path, path, !match.image) + part.slice(match.end);
|
|
93
87
|
}
|
|
94
88
|
return part;
|
|
95
89
|
}).join("");
|
|
@@ -11,19 +11,23 @@
|
|
|
11
11
|
* and call cleanup.refresh() when the setting changes; call cleanup from
|
|
12
12
|
* `session_shutdown`.
|
|
13
13
|
*/
|
|
14
|
-
import { CustomEditor, stripFrontmatter, type ExtensionAPI, type ExtensionContext, type InputEvent, type InputEventResult } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import { CustomEditor, resizeImage, stripFrontmatter, type ExtensionAPI, type ExtensionContext, type InputEvent, type InputEventResult } from "@earendil-works/pi-coding-agent";
|
|
15
15
|
import {
|
|
16
|
-
allocateImageId, getCellDimensions, getImageDimensions, renderImage, getCapabilities,
|
|
16
|
+
CURSOR_MARKER, allocateImageId, deleteKittyImage, encodeKitty, getCellDimensions, getImageDimensions, renderImage, getCapabilities, getOsc8LinkAtColumn, matchesKey, sliceByColumn, stripTerminalSequences, truncateToWidth, visibleWidth,
|
|
17
17
|
type AutocompleteItem, type AutocompleteProvider, type EditorComponent, type TuiMouseEvent, type TUI, type OverlayHandle, type OverlayOptions,
|
|
18
18
|
} from "@earendil-works/pi-tui";
|
|
19
19
|
import { filePaths, inputCapabilities, linkRenderedPath, localPath, webPaths } from "./file-links.ts";
|
|
20
20
|
import { open, readFile } from "node:fs/promises";
|
|
21
|
+
import { existsSync } from "node:fs";
|
|
21
22
|
import { homedir } from "node:os";
|
|
22
23
|
import { dirname, extname, isAbsolute, join, resolve } from "node:path";
|
|
23
24
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
24
25
|
|
|
25
26
|
export const INPUT_ENHANCEMENTS_SETTING = "pi-mini-mode-input-enhancements";
|
|
26
27
|
export const MAX_PREVIEW_BYTES = 20 * 1024 * 1024;
|
|
28
|
+
const MAX_PREVIEW_ENCODED_BYTES = 1024 * 1024;
|
|
29
|
+
const MAX_PREVIEW_WIDTH_PX = 1200;
|
|
30
|
+
const MAX_PREVIEW_HEIGHT_PX = 800;
|
|
27
31
|
|
|
28
32
|
const IMAGE_MIME: Record<string, string> = {
|
|
29
33
|
".png": "image/png",
|
|
@@ -55,9 +59,13 @@ function absolutePath(path: string, cwd: string): string {
|
|
|
55
59
|
export function imagePathsInLine(line: string): ImagePathMatch[] {
|
|
56
60
|
const plain = stripTerminalSequences(line);
|
|
57
61
|
const matches: ImagePathMatch[] = [];
|
|
58
|
-
|
|
62
|
+
// ponytail: accept existing absolute clipboard paths with spaces; extend to cwd-aware relative paths if needed.
|
|
63
|
+
const spaced = [...plain.matchAll(/(?:^|[\s"'`])((?:\/|~\/|\.\.?\/)[^\n"'`<>()[\]{},。;!?]+?\.(?:png|jpe?g|gif|webp))(?=$|[\s"'`<>()[\]{},。;!?])/gi)]
|
|
64
|
+
.map(match => ({ path: match[1], start: match.index + match[0].length - match[1].length, end: match.index + match[0].length }))
|
|
65
|
+
.filter(match => isAbsolute(match.path) && match.path.includes(" ") && existsSync(match.path));
|
|
66
|
+
for (const { path, start, end } of [...spaced, ...filePaths(plain).filter(match => !spaced.some(full => match.start >= full.start && match.start < full.end))]) {
|
|
59
67
|
if (!IMAGE_MIME[extname(path).toLowerCase()]) continue;
|
|
60
|
-
matches.push({ path, start, end
|
|
68
|
+
matches.push({ path, start, end, startCol: visibleWidth(plain.slice(0, start)), endCol: visibleWidth(plain.slice(0, end)) });
|
|
61
69
|
}
|
|
62
70
|
return matches;
|
|
63
71
|
}
|
|
@@ -79,6 +87,8 @@ export interface PreviewImage {
|
|
|
79
87
|
path: string;
|
|
80
88
|
mimeType: string;
|
|
81
89
|
base64: string;
|
|
90
|
+
widthPx: number;
|
|
91
|
+
heightPx: number;
|
|
82
92
|
}
|
|
83
93
|
export interface PreviewNote {
|
|
84
94
|
kind: "note";
|
|
@@ -91,7 +101,7 @@ export type Preview = PreviewImage | PreviewNote;
|
|
|
91
101
|
* Read a preview for an image path. Returns undefined when there is nothing to show
|
|
92
102
|
* (unknown extension, missing file, directory) so typing never raises a hint.
|
|
93
103
|
*/
|
|
94
|
-
export async function readPreview(path: string, cwd: string): Promise<Preview | undefined> {
|
|
104
|
+
export async function readPreview(path: string, cwd: string, bounds = { widthPx: MAX_PREVIEW_WIDTH_PX, heightPx: MAX_PREVIEW_HEIGHT_PX }): Promise<Preview | undefined> {
|
|
95
105
|
const absolute = absolutePath(path, cwd);
|
|
96
106
|
const mimeType = IMAGE_MIME[extname(absolute).toLowerCase()];
|
|
97
107
|
if (!mimeType) return undefined;
|
|
@@ -108,7 +118,21 @@ export async function readPreview(path: string, cwd: string): Promise<Preview |
|
|
|
108
118
|
if (!bytesRead) break;
|
|
109
119
|
offset += bytesRead;
|
|
110
120
|
}
|
|
111
|
-
|
|
121
|
+
const data = bytes.subarray(0, offset);
|
|
122
|
+
const base64 = data.toString("base64");
|
|
123
|
+
const dimensions = getImageDimensions(base64, mimeType);
|
|
124
|
+
if (!dimensions) return { kind: "note", path, note: "无法解析图片尺寸" };
|
|
125
|
+
const maxWidth = Math.max(1, Math.min(MAX_PREVIEW_WIDTH_PX, Math.floor(bounds.widthPx)));
|
|
126
|
+
const maxHeight = Math.max(1, Math.min(MAX_PREVIEW_HEIGHT_PX, Math.floor(bounds.heightPx)));
|
|
127
|
+
// renderImage controls cell placement, not pixels; its Kitty f=100 payload must be PNG.
|
|
128
|
+
const resized = dimensions.widthPx <= maxWidth && dimensions.heightPx <= maxHeight && base64.length < MAX_PREVIEW_ENCODED_BYTES
|
|
129
|
+
? { data: base64, mimeType } : await resizeImage(data, mimeType, { maxWidth, maxHeight, maxBytes: MAX_PREVIEW_ENCODED_BYTES });
|
|
130
|
+
if (!resized) return { kind: "note", path, note: "无法缩小图片预览" };
|
|
131
|
+
const png = resized.mimeType === "image/png" ? resized
|
|
132
|
+
: await (await import("@earendil-works/pi-coding-agent")).convertToPng(resized.data, resized.mimeType);
|
|
133
|
+
if (!png) return { kind: "note", path, note: "无法转换图片预览" };
|
|
134
|
+
if (png.data.length > MAX_PREVIEW_ENCODED_BYTES) return { kind: "note", path, note: "图片预览过大" };
|
|
135
|
+
return { kind: "image", path, mimeType: png.mimeType, base64: png.data, widthPx: dimensions.widthPx, heightPx: dimensions.heightPx };
|
|
112
136
|
} catch {
|
|
113
137
|
return { kind: "note", path, note: "读取失败" };
|
|
114
138
|
} finally { await file.close(); }
|
|
@@ -232,8 +256,24 @@ export interface PreviewState {
|
|
|
232
256
|
graphic?: NonNullable<ReturnType<typeof renderImage>>;
|
|
233
257
|
}
|
|
234
258
|
|
|
259
|
+
function positionedGraphic(sequence: string, up: number, right: number): string {
|
|
260
|
+
// Pi <=0.87's ANSI slicer needs an SGR terminator after relative motion.
|
|
261
|
+
// Otty places Kitty graphics against the last committed cursor while DEC 2026
|
|
262
|
+
// buffers text/cursor updates. Commit the target before the APC, then resume
|
|
263
|
+
// Pi's synchronized frame. Other terminals retain their atomic rendering.
|
|
264
|
+
const flush = process.env.TERM_PROGRAM?.toLowerCase() === "otty"
|
|
265
|
+
&& !process.env.TMUX && !process.env.STY && !/^(tmux|screen)/i.test(process.env.TERM ?? "")
|
|
266
|
+
&& sequence.startsWith("\x1b_G");
|
|
267
|
+
return `\x1b[s\x1b[${up}A\x1b[${right}C\x1b[0m${flush ? "\x1b[?2026l\x1b[0m" : ""}${sequence}\x1b[u${flush ? "\x1b[?2026h" : ""}\x1b[0m`;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function imageLayoutKey(): string {
|
|
271
|
+
const cells = getCellDimensions();
|
|
272
|
+
return `${getCapabilities().images}:${cells.widthPx}:${cells.heightPx}`;
|
|
273
|
+
}
|
|
274
|
+
|
|
235
275
|
/** A tightly sized image frame. Draw after clearing its interior, never a path-only tooltip. */
|
|
236
|
-
export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"]["theme"], width: number
|
|
276
|
+
export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
|
|
237
277
|
if (!preview.path) return [];
|
|
238
278
|
const graphic = preview.graphic;
|
|
239
279
|
const innerWidth = Math.max(1, Math.min(width - 2, graphic?.columns ?? 26));
|
|
@@ -242,8 +282,7 @@ export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"
|
|
|
242
282
|
if (graphic) {
|
|
243
283
|
for (let row = 0; row < graphic.rows; row++) lines.push(border("│") + " ".repeat(innerWidth) + border("│"));
|
|
244
284
|
} else lines.push(border("│") + truncateToWidth(preview.note ?? "无法预览图片", innerWidth, "", true) + border("│"));
|
|
245
|
-
|
|
246
|
-
const draw = graphic ? `\x1b[${origin.row + 2};${origin.col + 2}H${graphic.sequence}\x1b[${origin.row + graphic.rows + 2};${origin.col + 1}H` : "";
|
|
285
|
+
const draw = graphic ? positionedGraphic(graphic.sequence, graphic.rows, 1) : "";
|
|
247
286
|
lines.push(draw + border(`╰${"─".repeat(innerWidth)}╯`));
|
|
248
287
|
return lines;
|
|
249
288
|
}
|
|
@@ -264,6 +303,8 @@ interface Enhancements {
|
|
|
264
303
|
theme?: ExtensionContext["ui"]["theme"];
|
|
265
304
|
generation?: unknown;
|
|
266
305
|
preview: PreviewState;
|
|
306
|
+
previewSource?: Preview;
|
|
307
|
+
previewLayout?: string;
|
|
267
308
|
previewToken: number;
|
|
268
309
|
overlayReady: boolean;
|
|
269
310
|
previewTui?: { requestRender(): void };
|
|
@@ -272,7 +313,12 @@ interface Enhancements {
|
|
|
272
313
|
requestedPath?: string;
|
|
273
314
|
pointer?: boolean;
|
|
274
315
|
previewAnchor?: { x: number; y: number };
|
|
316
|
+
hoverLink?: { row: number; start: number; end: number; path: string };
|
|
275
317
|
previewOptions?: OverlayOptions;
|
|
318
|
+
previewMode: () => "hover" | "inline";
|
|
319
|
+
inlineImages: Map<string, Preview | undefined>;
|
|
320
|
+
inlinePending: Map<string, Promise<Preview | undefined>>;
|
|
321
|
+
inlineGraphics: Map<string, { layout: string } & NonNullable<ReturnType<typeof renderImage>>>;
|
|
276
322
|
baseFactory?: EditorFactoryFunction;
|
|
277
323
|
editor?: EditorComponent;
|
|
278
324
|
editorFactory?: EditorFactoryFunction;
|
|
@@ -322,32 +368,44 @@ function liveUI(ctx?: ExtensionContext): ExtensionContext["ui"] | undefined {
|
|
|
322
368
|
}
|
|
323
369
|
|
|
324
370
|
/** Compact image attachments without losing their paths on submit, reload, or external editing. */
|
|
325
|
-
function wrapEditor(inner: EditorComponent, cwd: string, isEnabled: () => boolean, onCursor: () => void, onHoverEditor: (editor: EditorComponent, event: TuiMouseEvent) => void): EditorComponent {
|
|
371
|
+
function wrapEditor(inner: EditorComponent, cwd: string, isEnabled: () => boolean, isInline: () => boolean, theme: ExtensionContext["ui"]["theme"], inlineState: Enhancements, onCursor: () => void, onHoverEditor: (editor: EditorComponent, event: TuiMouseEvent) => void, onEditorRender: () => void = () => {}): EditorComponent {
|
|
326
372
|
const attachments = new Map<string, string>();
|
|
327
|
-
const
|
|
373
|
+
const sources = new Map<string, string>();
|
|
374
|
+
const expand = (text: string) => text.replace(/\[img\d+\]/g, (label, index) => {
|
|
375
|
+
const path = sources.get(label) ?? attachments.get(label);
|
|
376
|
+
const next = /^\[img\d+\]/.exec(text.slice(index + label.length));
|
|
377
|
+
return path === undefined ? label : path + (next && attachments.has(next[0]) ? " " : "");
|
|
378
|
+
});
|
|
328
379
|
const compact = (text: string) => {
|
|
329
380
|
if (!isEnabled()) return text;
|
|
330
381
|
const replacements = imagePathsInLine(text).map(match => {
|
|
331
|
-
|
|
332
|
-
|
|
382
|
+
const source = text.slice(match.start, match.end);
|
|
383
|
+
let label = [...attachments].find(([label, path]) => path === match.path && (sources.get(label) ?? path) === source)?.[0];
|
|
384
|
+
if (!label) {
|
|
385
|
+
label = `[img${attachments.size + 1}]`;
|
|
386
|
+
attachments.set(label, match.path);
|
|
387
|
+
sources.set(label, source);
|
|
388
|
+
}
|
|
333
389
|
return { ...match, label };
|
|
334
390
|
});
|
|
335
391
|
for (const match of replacements.reverse()) text = text.slice(0, match.start) + match.label + text.slice(match.end);
|
|
336
392
|
return text;
|
|
337
393
|
};
|
|
338
394
|
// ponytail: Pi 0.87 image paste calls the private inserter, bypassing the public proxy; replace with a public attachment API when available.
|
|
339
|
-
const core = inner as EditorComponent & { expandPasteMarkers?(text: string): string; insertTextAtCursorInternal?(text: string): void; segment?(text: string, mode?: string): Array<{ segment: string; index: number; input: string }>; imageAttachments?: Map<string, string>; state?: { lines: string[] } };
|
|
395
|
+
const core = inner as EditorComponent & { expandPasteMarkers?(text: string): string; insertTextAtCursorInternal?(text: string): void; setTextInternal?(text: string, placement?: "start" | "end"): void; segment?(text: string, mode?: string): Array<{ segment: string; index: number; input: string }>; imageAttachments?: Map<string, string>; state?: { lines: string[] } };
|
|
340
396
|
core.imageAttachments = attachments;
|
|
341
397
|
// Rendering reads the stored lines directly, so the submit expansion must not put the temp path back on screen.
|
|
342
398
|
if (core.state) core.state.lines = compact(core.state.lines.join("\n")).split("\n");
|
|
343
399
|
if (core.expandPasteMarkers) { const original = core.expandPasteMarkers.bind(core); core.expandPasteMarkers = text => expand(original(text)); }
|
|
344
400
|
if (core.insertTextAtCursorInternal) { const insert = core.insertTextAtCursorInternal.bind(core); core.insertTextAtCursorInternal = text => insert(compact(text)); }
|
|
401
|
+
// Native history navigation bypasses setText; compact the restored draft before its onChange/render.
|
|
402
|
+
if (core.setTextInternal) { const restore = core.setTextInternal.bind(core); core.setTextInternal = (text, placement) => restore(compact(text), placement); }
|
|
345
403
|
const pasteEditor = inner as EditorComponent & { handlePaste?(text: string): void };
|
|
346
404
|
if (pasteEditor.handlePaste) { const paste = pasteEditor.handlePaste.bind(inner); pasteEditor.handlePaste = text => paste(compact(text)); }
|
|
347
405
|
if (core.segment) {
|
|
348
406
|
const original = core.segment.bind(core);
|
|
349
407
|
core.segment = (text, mode) => {
|
|
350
|
-
const spans = [...text.matchAll(/\[
|
|
408
|
+
const spans = [...text.matchAll(/\[img\d+\]/g)].filter(match => attachments.has(match[0]));
|
|
351
409
|
return [...original(text, mode)].flatMap(segment => {
|
|
352
410
|
const span = spans.find(match => segment.index >= match.index && segment.index < match.index + match[0].length);
|
|
353
411
|
return !span ? [segment] : segment.index === span.index ? [{ segment: span[0], index: span.index, input: text }] : [];
|
|
@@ -358,18 +416,28 @@ function wrapEditor(inner: EditorComponent, cwd: string, isEnabled: () => boolea
|
|
|
358
416
|
return new Proxy(inner, {
|
|
359
417
|
get(target, property, receiver) {
|
|
360
418
|
if (property === "getText") return () => expand(target.getText());
|
|
361
|
-
if (property === "setText" || property === "insertTextAtCursor" || property === "insertTextAtCursorInternal") return (text: string) => { const insert = (target as EditorComponent & { insertTextAtCursorInternal?(value: string): void })[property] as ((value: string) => void) | undefined; insert?.call(target, compact(text)); };
|
|
419
|
+
if (property === "setText" || property === "insertTextAtCursor" || property === "insertTextAtCursorInternal") return (text: string) => { const insert = (target as EditorComponent & { insertTextAtCursorInternal?(value: string): void })[property] as ((value: string) => void) | undefined; insert?.call(target, compact(text)); onEditorRender(); };
|
|
362
420
|
if (property === "render") {
|
|
363
421
|
return (width: number) => {
|
|
364
422
|
const lines = target.render(width);
|
|
365
|
-
|
|
423
|
+
onEditorRender();
|
|
424
|
+
const linked = isEnabled() ? linkImagePaths(lines, target, cwd, width) : lines;
|
|
425
|
+
if (!isInline()) return linked;
|
|
426
|
+
const cards = inlinePreviewLines(inlineState, theme, width);
|
|
427
|
+
if (!cards.length) return linked;
|
|
428
|
+
// ponytail: Pi's editor has no rich image nodes; keep its cursor/text layout and mask owned tokens only in render. Replace with native attachment nodes when available.
|
|
429
|
+
const labels = new Set(attachments.keys());
|
|
430
|
+
const body = linked.map((line, row) => row > 0 && row <= ((target as EditorComponent & { renderedVisibleLineCount?: number }).renderedVisibleLineCount ?? 0) ? hideImageLabels(line, labels, theme, lines[row]) : line);
|
|
431
|
+
return [...cards, ...body];
|
|
366
432
|
};
|
|
367
433
|
}
|
|
368
434
|
if (property === "handleMouse") {
|
|
369
435
|
return (event: TuiMouseEvent) => {
|
|
370
|
-
const
|
|
371
|
-
|
|
372
|
-
|
|
436
|
+
const offset = isInline() ? inlinePreviewLines(inlineState, theme, event.width).length : 0;
|
|
437
|
+
const adjusted = offset ? { ...event, y: event.y - offset } : event;
|
|
438
|
+
const result = !offset || event.y >= offset ? target.handleMouse?.(adjusted) : undefined;
|
|
439
|
+
if (event.type === "move") onHoverEditor(target, adjusted);
|
|
440
|
+
else if (event.type === "click") void requestPreview(inlineState, undefined);
|
|
373
441
|
return result;
|
|
374
442
|
};
|
|
375
443
|
}
|
|
@@ -392,6 +460,7 @@ function wrapEditor(inner: EditorComponent, cwd: string, isEnabled: () => boolea
|
|
|
392
460
|
onChange = value as ((text: string) => void) | undefined;
|
|
393
461
|
return Reflect.set(target, property, (text: string) => {
|
|
394
462
|
onChange?.(expand(text));
|
|
463
|
+
onEditorRender();
|
|
395
464
|
onCursor();
|
|
396
465
|
});
|
|
397
466
|
}
|
|
@@ -404,14 +473,14 @@ function wrapEditor(inner: EditorComponent, cwd: string, isEnabled: () => boolea
|
|
|
404
473
|
function editorImagePaths(editor: EditorComponent, text: string): ImagePathMatch[] {
|
|
405
474
|
const attachments = (editor as EditorComponent & { imageAttachments?: Map<string, string> }).imageAttachments;
|
|
406
475
|
const paths = imagePathsInLine(text);
|
|
407
|
-
for (const match of text.matchAll(/\[
|
|
476
|
+
for (const match of text.matchAll(/\[img\d+\]/g)) {
|
|
408
477
|
const path = attachments?.get(match[0]);
|
|
409
478
|
if (path) paths.push({ path, start: match.index, end: match.index + match[0].length, startCol: visibleWidth(text.slice(0, match.index)), endCol: visibleWidth(text.slice(0, match.index + match[0].length)) });
|
|
410
479
|
}
|
|
411
480
|
return paths.sort((a, b) => a.start - b.start);
|
|
412
481
|
}
|
|
413
482
|
|
|
414
|
-
function editorPaths(editor: EditorComponent, row: number, width: number, includeWeb = false) {
|
|
483
|
+
function editorPaths(editor: EditorComponent, row: number, width: number, includeWeb = false, compactImages = false) {
|
|
415
484
|
const core = editor as EditorComponent & { lastWidth?: number; scrollOffset?: number; renderedVisibleLineCount?: number; getPaddingX?(): number; buildVisualLineMap?(width: number): Array<{ logicalLine: number; startCol: number; length: number }> };
|
|
416
485
|
if (!core.buildVisualLineMap || !core.lastWidth) return imagePathsInLine(editor.render(width)[row] ?? "");
|
|
417
486
|
if (row < 1 || row > (core.renderedVisibleLineCount ?? 0)) return [];
|
|
@@ -421,11 +490,50 @@ function editorPaths(editor: EditorComponent, row: number, width: number, includ
|
|
|
421
490
|
const padding = Math.min(core.getPaddingX?.() ?? 0, Math.max(0, Math.floor((width - 1) / 2)));
|
|
422
491
|
return [...editorImagePaths(editor, source), ...(includeWeb ? webPaths(source) : [])].filter(match => match.end > chunk.startCol && match.start < chunk.startCol + chunk.length).map(match => ({
|
|
423
492
|
...match,
|
|
424
|
-
startCol: padding + visibleWidth(source.slice(chunk.startCol, Math.max(chunk.startCol, match.start)))
|
|
425
|
-
|
|
493
|
+
startCol: padding + visibleWidth(source.slice(chunk.startCol, Math.max(chunk.startCol, match.start)))
|
|
494
|
+
+ (compactImages && /^\[img\d+\]$/.test(source.slice(match.start, match.end)) ? 1 : 0),
|
|
495
|
+
endCol: padding + visibleWidth(source.slice(chunk.startCol, Math.min(chunk.startCol + chunk.length, compactImages && /^\[img\d+\]$/.test(source.slice(match.start, match.end))
|
|
496
|
+
? match.start + 1 + visibleWidth(` #${source.slice(match.start + 4, match.end - 1)}`) : match.end))),
|
|
426
497
|
}));
|
|
427
498
|
}
|
|
428
499
|
|
|
500
|
+
function hideImageLabels(line: string, labels: Set<string>, theme: ExtensionContext["ui"]["theme"], original: string): string {
|
|
501
|
+
const markerIndex = original.indexOf(CURSOR_MARKER);
|
|
502
|
+
const cursorCol = markerIndex < 0 ? -1 : visibleWidth(original.slice(0, markerIndex));
|
|
503
|
+
const plain = stripTerminalSequences(line);
|
|
504
|
+
const clean = line.replaceAll(CURSOR_MARKER, "").replaceAll("\x1b[7m", "");
|
|
505
|
+
const reset = "\x1b]8;;\x07\x1b[0m";
|
|
506
|
+
const caret = (cell: string) => reset + CURSOR_MARKER + `\x1b[7m${cell}\x1b[27m`;
|
|
507
|
+
const textSlice = (start: number, length: number) => {
|
|
508
|
+
const part = sliceByColumn(clean, start, length, true);
|
|
509
|
+
if (getOsc8LinkAtColumn(clean, start)) return part;
|
|
510
|
+
return part.replace(/^(?:\x1b\[[0-?]*[ -/]*[@-~]|\x1b[\]_][^\x07\x1b]*(?:\x07|\x1b\\))*/,
|
|
511
|
+
leading => leading.replace(/\x1b\]8;[^\x07\x1b]*(?:\x07|\x1b\\)/g, ""));
|
|
512
|
+
};
|
|
513
|
+
const textSpan = (start: number, end: number) => {
|
|
514
|
+
if (cursorCol < start || cursorCol >= end) return textSlice(start, end - start);
|
|
515
|
+
const cell = stripTerminalSequences(sliceByColumn(clean, cursorCol, 1));
|
|
516
|
+
return textSlice(start, cursorCol - start) + caret(cell)
|
|
517
|
+
+ textSlice(cursorCol + visibleWidth(cell), end - cursorCol - visibleWidth(cell));
|
|
518
|
+
};
|
|
519
|
+
const parts: string[] = [];
|
|
520
|
+
let previous = 0;
|
|
521
|
+
for (const match of plain.matchAll(/\[img\d+\]/g)) {
|
|
522
|
+
if (!labels.has(match[0])) continue;
|
|
523
|
+
const start = visibleWidth(plain.slice(0, match.index));
|
|
524
|
+
const end = start + visibleWidth(match[0]);
|
|
525
|
+
const icon = theme.fg("accent", ` #${match[0].slice(4, -1)}`);
|
|
526
|
+
const url = getOsc8LinkAtColumn(line, start);
|
|
527
|
+
const chip = url ? `\x1b]8;;${url}\x07${icon}\x1b]8;;\x07` : icon;
|
|
528
|
+
// [imgN] fits exactly one insertion cell plus the visible chip; no hidden padding.
|
|
529
|
+
// Emit the caret before styling the chip: slicing styled output replays stale ANSI resets.
|
|
530
|
+
parts.push(textSpan(previous, start), reset, cursorCol === start ? caret(" ") : " ", chip);
|
|
531
|
+
previous = end;
|
|
532
|
+
}
|
|
533
|
+
parts.push(textSpan(previous, visibleWidth(plain)), reset);
|
|
534
|
+
return parts.join("");
|
|
535
|
+
}
|
|
536
|
+
|
|
429
537
|
function linkImagePaths(lines: string[], editor: EditorComponent, cwd: string, width: number): string[] {
|
|
430
538
|
if (!inputCapabilities().hyperlinks) return lines;
|
|
431
539
|
return lines.map((line, row) => {
|
|
@@ -436,12 +544,12 @@ function linkImagePaths(lines: string[], editor: EditorComponent, cwd: string, w
|
|
|
436
544
|
});
|
|
437
545
|
}
|
|
438
546
|
|
|
439
|
-
export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean)): InputEnhancementsCleanup {
|
|
440
|
-
if (process.env.TERM_PROGRAM?.toLowerCase() === "otty" || process.env.HERDR_PANE_ID) setCapabilities(inputCapabilities());
|
|
547
|
+
export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean), previewMode: () => "hover" | "inline" = () => "hover"): InputEnhancementsCleanup {
|
|
441
548
|
const enabled = typeof isEnabled === "function" ? isEnabled : () => isEnabled;
|
|
442
549
|
if (installed && installed.pi !== pi) installed.cleanup();
|
|
443
550
|
const state = installed?.pi === pi ? installed : (installed = createEnhancements(pi));
|
|
444
551
|
state.enabled = enabled;
|
|
552
|
+
state.previewMode = previewMode;
|
|
445
553
|
state.ctx = ctx;
|
|
446
554
|
state.cwd = ctx.cwd;
|
|
447
555
|
state.theme = ctx.hasUI ? ctx.ui.theme : undefined;
|
|
@@ -449,6 +557,10 @@ export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext
|
|
|
449
557
|
const generation = ctx.sessionManager;
|
|
450
558
|
if (state.generation !== generation) {
|
|
451
559
|
state.generation = generation;
|
|
560
|
+
void requestPreview(state, undefined);
|
|
561
|
+
state.inlinePending.clear();
|
|
562
|
+
state.inlineImages.clear();
|
|
563
|
+
clearInlineGraphics(state);
|
|
452
564
|
state.unsubscribeInput?.();
|
|
453
565
|
state.unsubscribeInput = ctx.ui.onTerminalInput?.((data) => handleTerminalInput(state, data)) ?? undefined;
|
|
454
566
|
ctx.ui.addAutocompleteProvider((current) => createSkillAutocompleteProvider(current, () => readSkillCommands(pi), () => state.enabled()));
|
|
@@ -456,7 +568,6 @@ export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext
|
|
|
456
568
|
// /reload clears the editor before session_start, so the saved factory can still be current while the live editor is unwrapped.
|
|
457
569
|
const active = ctx.ui.getEditorComponent();
|
|
458
570
|
if (active !== state.editorFactory || !state.editor) installEditor(ctx, state, active === state.editorFactory ? state.baseFactory : active);
|
|
459
|
-
if (getCapabilities().images) state.tui?.terminal.write("\x1b[16t");
|
|
460
571
|
}
|
|
461
572
|
return state.cleanup;
|
|
462
573
|
}
|
|
@@ -467,6 +578,10 @@ function createEnhancements(pi: ExtensionAPI): Enhancements {
|
|
|
467
578
|
enabled: () => true,
|
|
468
579
|
preview: {},
|
|
469
580
|
previewToken: 0,
|
|
581
|
+
previewMode: () => "hover",
|
|
582
|
+
inlineImages: new Map(),
|
|
583
|
+
inlinePending: new Map(),
|
|
584
|
+
inlineGraphics: new Map(),
|
|
470
585
|
overlayReady: false,
|
|
471
586
|
cleanup: (() => {}) as InputEnhancementsCleanup,
|
|
472
587
|
};
|
|
@@ -478,7 +593,14 @@ function createEnhancements(pi: ExtensionAPI): Enhancements {
|
|
|
478
593
|
state.restoreViewportInput = undefined;
|
|
479
594
|
state.requestedPath = undefined;
|
|
480
595
|
state.previewToken++;
|
|
596
|
+
if (state.preview.graphic?.imageId) state.tui?.terminal.write(deleteKittyImage(state.preview.graphic.imageId));
|
|
481
597
|
state.preview = {};
|
|
598
|
+
state.previewSource = undefined;
|
|
599
|
+
state.previewLayout = undefined;
|
|
600
|
+
state.hoverLink = undefined;
|
|
601
|
+
state.inlineImages.clear();
|
|
602
|
+
state.inlinePending.clear();
|
|
603
|
+
clearInlineGraphics(state);
|
|
482
604
|
setPointer(state, false);
|
|
483
605
|
state.previewHandle?.hide();
|
|
484
606
|
state.previewHandle = undefined;
|
|
@@ -494,6 +616,8 @@ function createEnhancements(pi: ExtensionAPI): Enhancements {
|
|
|
494
616
|
},
|
|
495
617
|
{
|
|
496
618
|
refresh: () => {
|
|
619
|
+
syncInlineImages(state);
|
|
620
|
+
if (state.previewMode() === "inline") { void requestPreview(state, undefined); setPointer(state, false); }
|
|
497
621
|
if (!state.enabled()) {
|
|
498
622
|
void requestPreview(state, undefined);
|
|
499
623
|
setPointer(state, false);
|
|
@@ -526,23 +650,26 @@ function installEditor(ctx: ExtensionContext, state: Enhancements, base?: Editor
|
|
|
526
650
|
const factory: EditorFactoryFunction = (tui, theme, keybindings) => {
|
|
527
651
|
state.tui = tui;
|
|
528
652
|
state.previewTui = tui;
|
|
529
|
-
// Otty is detected after fullscreen startup; synchronize its cached protocol for placement cleanup.
|
|
530
|
-
const renderer = tui as TUI & { imageProtocol?: string | null };
|
|
531
|
-
if (renderer.imageProtocol === null && getCapabilities().images === "kitty") renderer.imageProtocol = "kitty";
|
|
532
653
|
// ponytail: fullscreen's first input listener consumes mouse events before extension listeners.
|
|
533
654
|
// Observe its entry point until Pi exposes a pre-dispatch mouse subscription.
|
|
534
655
|
state.restoreViewportInput = hookViewportInput(tui, (data) => handleTerminalInput(state, data));
|
|
535
656
|
const inner: CursorEditor = create(tui, theme, keybindings);
|
|
536
|
-
const editor = wrapEditor(inner, state.cwd ?? process.cwd(), () => state.enabled(), () => {
|
|
657
|
+
const editor = wrapEditor(inner, state.cwd ?? process.cwd(), () => state.enabled(), () => state.enabled() && state.previewMode() === "inline", state.theme!, state, () => {
|
|
537
658
|
const cursor = inner.getCursor?.();
|
|
538
659
|
const path = cursor ? editorImagePaths(inner, inner.getText().split("\n")[cursor.line] ?? "").find(match => cursor.col >= match.start && cursor.col <= match.end)?.path : undefined;
|
|
539
|
-
void requestPreview(state, state.enabled() ? path : undefined);
|
|
660
|
+
if (state.previewMode() === "hover") void requestPreview(state, state.enabled() ? path : undefined);
|
|
540
661
|
}, (target, event) => {
|
|
541
|
-
const match = state.enabled() ? editorPaths(target, event.y, event.width).find(path => event.x >= path.startCol && event.x < path.endCol) : undefined;
|
|
542
|
-
|
|
662
|
+
const match = state.enabled() && event.y >= 1 ? editorPaths(target, event.y, event.width, false, state.previewMode() === "inline").find(path => event.x >= path.startCol && event.x < path.endCol) : undefined;
|
|
663
|
+
const screenStart = match ? event.screenX - event.x + match.startCol : 0;
|
|
664
|
+
const screenEnd = match ? event.screenX - event.x + match.endCol : 0;
|
|
665
|
+
if (match && (match.path !== state.requestedPath || state.previewAnchor?.y !== event.screenY
|
|
666
|
+
|| state.previewAnchor.x < screenStart || state.previewAnchor.x >= screenEnd)) {
|
|
667
|
+
state.previewAnchor = { x: event.screenX, y: event.screenY };
|
|
668
|
+
if (match.path === state.requestedPath && state.preview.path) { positionPreview(state); state.previewTui?.requestRender(); }
|
|
669
|
+
}
|
|
543
670
|
setPointer(state, !!match);
|
|
544
671
|
void requestPreview(state, match?.path);
|
|
545
|
-
});
|
|
672
|
+
}, () => syncInlineImages(state));
|
|
546
673
|
state.editor = editor;
|
|
547
674
|
return editor;
|
|
548
675
|
};
|
|
@@ -551,6 +678,114 @@ function installEditor(ctx: ExtensionContext, state: Enhancements, base?: Editor
|
|
|
551
678
|
ctx.ui.setEditorComponent(factory);
|
|
552
679
|
}
|
|
553
680
|
|
|
681
|
+
function draftImagePaths(editor: EditorComponent): string[] {
|
|
682
|
+
const source = (editor as EditorComponent & { state?: { lines: string[] } }).state?.lines ?? editor.getText().split("\n");
|
|
683
|
+
return source.flatMap(line => editorImagePaths(editor, line).map(match => match.path));
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function clearInlineGraphics(state: Pick<Enhancements, "inlineGraphics" | "tui">): void {
|
|
687
|
+
for (const graphic of state.inlineGraphics.values()) {
|
|
688
|
+
if (graphic.imageId) state.tui?.terminal.write(deleteKittyImage(graphic.imageId));
|
|
689
|
+
}
|
|
690
|
+
state.inlineGraphics.clear();
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/** Only the editing draft is shown here; history hover remains the separate mode. */
|
|
694
|
+
function syncInlineImages(state: Enhancements): void {
|
|
695
|
+
const paths = state.editor && state.enabled() && state.previewMode() === "inline"
|
|
696
|
+
? [...new Set(draftImagePaths(state.editor))].slice(0, 15) : [];
|
|
697
|
+
if (!paths.length) clearInlineGraphics(state);
|
|
698
|
+
for (const path of state.inlineImages.keys()) if (!paths.includes(path)) { state.inlineImages.delete(path); clearInlineGraphics(state); }
|
|
699
|
+
for (const path of state.inlinePending.keys()) if (!paths.includes(path)) state.inlinePending.delete(path);
|
|
700
|
+
for (const path of paths) {
|
|
701
|
+
if (state.inlineImages.has(path) || state.inlinePending.has(path)) continue;
|
|
702
|
+
const cwd = state.cwd ?? process.cwd();
|
|
703
|
+
// Cell placement scales the image; keep a bounded copy independent of startup cell metrics.
|
|
704
|
+
const pending = readPreview(path, cwd).catch(() => undefined);
|
|
705
|
+
state.inlinePending.set(path, pending);
|
|
706
|
+
void pending.then(preview => {
|
|
707
|
+
if (state.inlinePending.get(path) !== pending) return;
|
|
708
|
+
state.inlinePending.delete(path);
|
|
709
|
+
if (!state.editor || !state.enabled() || state.previewMode() !== "inline" || !draftImagePaths(state.editor).includes(path)) return;
|
|
710
|
+
state.inlineImages.set(path, preview);
|
|
711
|
+
state.tui?.requestRender();
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
export function inlinePreviewLines(state: Pick<Enhancements, "editor" | "enabled" | "previewMode" | "inlineImages" | "inlinePending" | "inlineGraphics" | "tui">, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
|
|
717
|
+
const paths = state.editor && state.enabled() && state.previewMode() === "inline" && width >= 12 ? draftImagePaths(state.editor) : [];
|
|
718
|
+
if (!paths.length) { clearInlineGraphics(state); return []; }
|
|
719
|
+
const cardWidth = Math.min(14, width);
|
|
720
|
+
// ponytail: cards are capped at one row; beyond viewport width show compact numbered tags, upgrade to a gallery when scrolling is supported.
|
|
721
|
+
const count = Math.max(1, Math.floor((width + 2) / (cardWidth + 2)));
|
|
722
|
+
const protocol = getCapabilities().images;
|
|
723
|
+
const layout = `${cardWidth}:${imageLayoutKey()}`;
|
|
724
|
+
const keys = paths.slice(0, count).map((path, index) => `${index}:${path}`);
|
|
725
|
+
if ([...state.inlineGraphics].some(([key, graphic]) => graphic.layout !== layout || !keys.includes(key))) clearInlineGraphics(state);
|
|
726
|
+
const rows: string[] = [];
|
|
727
|
+
const color = (index: number, text: string) => theme.fg((["warning", "accent", "success", "error"] as const)[index % 4], text);
|
|
728
|
+
{
|
|
729
|
+
const cards = paths.slice(0, count).map((path, index) => {
|
|
730
|
+
const key = `${index}:${path}`;
|
|
731
|
+
const preview = state.inlineImages.get(path);
|
|
732
|
+
const dimensions = preview?.kind === "image" ? getImageDimensions(preview.base64, preview.mimeType) : undefined;
|
|
733
|
+
let graphic = state.inlineGraphics.get(key);
|
|
734
|
+
if (preview?.kind === "image" && dimensions && protocol && !graphic) {
|
|
735
|
+
const cells = getCellDimensions();
|
|
736
|
+
const scale = Math.min((cardWidth - 2) * cells.widthPx / dimensions.widthPx, 4 * cells.heightPx / dimensions.heightPx);
|
|
737
|
+
const columns = Math.min(cardWidth - 2, Math.ceil(dimensions.widthPx * scale / cells.widthPx));
|
|
738
|
+
const rows = Math.min(4, Math.ceil(dimensions.heightPx * scale / cells.heightPx));
|
|
739
|
+
const imageId = protocol === "kitty" ? allocateImageId() : undefined;
|
|
740
|
+
// ponytail: bottom-row placement must not register top-row crop metadata; use Pi's encoder until its layout API supports positioned graphics.
|
|
741
|
+
const rendered = protocol === "kitty"
|
|
742
|
+
? { sequence: encodeKitty(preview.base64, { imageId, columns, rows, moveCursor: false }), imageId, rows, columns }
|
|
743
|
+
: renderImage(preview.base64, dimensions, { maxWidthCells: cardWidth - 2, maxHeightCells: 4, moveCursor: false });
|
|
744
|
+
if (rendered) { graphic = { layout, ...rendered }; state.inlineGraphics.set(key, graphic); }
|
|
745
|
+
}
|
|
746
|
+
const frame = (text: string) => color(index, text);
|
|
747
|
+
const rim = (text: string, top: boolean) => {
|
|
748
|
+
const caption = truncateToWidth(text, cardWidth - 4, "…");
|
|
749
|
+
const fill = cardWidth - 4 - visibleWidth(caption);
|
|
750
|
+
return frame(`${top ? "╭" : "╰"}${"─".repeat(Math.floor(fill / 2))} ${caption} ${"─".repeat(Math.ceil(fill / 2))}${top ? "╮" : "╯"}`);
|
|
751
|
+
};
|
|
752
|
+
const top = rim(` #${index + 1}`, true);
|
|
753
|
+
const size = preview?.kind === "image" ? `${preview.widthPx}x${preview.heightPx}` : state.inlinePending.has(path) ? "加载中" : "无法预览";
|
|
754
|
+
return { graphic, preview, top, size, rim, frame };
|
|
755
|
+
});
|
|
756
|
+
// OMP's 12x4 inner grid; never grow a tall empty box for a wide image.
|
|
757
|
+
const bodyHeight = 4;
|
|
758
|
+
rows.push(cards.map(card => card.top).join(" "));
|
|
759
|
+
for (let row = 0; row < bodyHeight; row++) rows.push(cards.map(card => {
|
|
760
|
+
const content = row === 0 && !card.graphic ? truncateToWidth(card.preview?.kind === "note" ? card.preview.note : card.size === "加载中" ? "加载中" : "无法预览", cardWidth - 4, "…") : "";
|
|
761
|
+
const left = card.graphic ? Math.floor((cardWidth - 2 - card.graphic.columns) / 2) : 0;
|
|
762
|
+
return card.frame("│") + " ".repeat(left) + " ".repeat(cardWidth - 2 - left - visibleWidth(content)) + content + card.frame("│");
|
|
763
|
+
}).join(" "));
|
|
764
|
+
const bottom = cards.map(card => card.rim(card.size, false)).join(" ");
|
|
765
|
+
// Draw the cleared card first, then place images over its interior from the final row.
|
|
766
|
+
const drawings = cards.map((card, index) => {
|
|
767
|
+
if (!card.graphic) return "";
|
|
768
|
+
const topPad = Math.floor((bodyHeight - card.graphic.rows) / 2);
|
|
769
|
+
const leftPad = Math.floor((cardWidth - 2 - card.graphic.columns) / 2);
|
|
770
|
+
const up = bodyHeight - topPad;
|
|
771
|
+
const right = index * (cardWidth + 2) + leftPad + 1;
|
|
772
|
+
return positionedGraphic(card.graphic.sequence, up, right);
|
|
773
|
+
}).join("");
|
|
774
|
+
rows.push(drawings + bottom);
|
|
775
|
+
}
|
|
776
|
+
if (paths.length > count) {
|
|
777
|
+
rows.push("");
|
|
778
|
+
let line = "";
|
|
779
|
+
for (let index = count; index < paths.length; index++) {
|
|
780
|
+
const tag = color(index, ` #${index + 1}`);
|
|
781
|
+
if (visibleWidth(line) + visibleWidth(tag) + 2 > width) { rows.push(line); line = ""; }
|
|
782
|
+
line += (line ? " " : "") + tag;
|
|
783
|
+
}
|
|
784
|
+
if (line) rows.push(line);
|
|
785
|
+
}
|
|
786
|
+
return rows;
|
|
787
|
+
}
|
|
788
|
+
|
|
554
789
|
function setPointer(state: Enhancements, pointer: boolean): void {
|
|
555
790
|
if (state.pointer === pointer) return;
|
|
556
791
|
if (pointer || state.pointer) state.tui?.terminal.write(`\x1b]22;${pointer ? "pointer" : "default"}\x07`);
|
|
@@ -558,20 +793,32 @@ function setPointer(state: Enhancements, pointer: boolean): void {
|
|
|
558
793
|
}
|
|
559
794
|
|
|
560
795
|
function handleTerminalInput(state: Enhancements, data: string): { consume?: boolean } | undefined {
|
|
561
|
-
|
|
562
|
-
const cells = /^\x1b\[6;(\d+);(\d+)t$/.exec(data);
|
|
563
|
-
if (cells && +cells[1] > 0 && +cells[2] > 0) setCellDimensions({ widthPx: +cells[2], heightPx: +cells[1] });
|
|
796
|
+
if (data === "\x1b[O") { setPointer(state, false); void requestPreview(state, undefined); }
|
|
564
797
|
const mouse = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);
|
|
565
798
|
if (mouse) {
|
|
566
799
|
const x = Number(mouse[2]) - 1, y = Number(mouse[3]) - 1;
|
|
567
800
|
// ponytail: Pi 0.85 has no public screen hit-test API; inspect its last rendered OSC 8 cells.
|
|
568
801
|
const screen = (state.tui as TUI & { previousScreen?: string[] } | undefined)?.previousScreen;
|
|
569
|
-
const
|
|
802
|
+
const moving = !!(Number(mouse[1]) & 32) && mouse[4] === "M";
|
|
803
|
+
if (!moving) { setPointer(state, false); void requestPreview(state, undefined); return undefined; }
|
|
804
|
+
const cached = state.hoverLink;
|
|
805
|
+
const sameTarget = cached?.row === y && x >= cached.start && x < cached.end;
|
|
806
|
+
const url = state.enabled()
|
|
807
|
+
? sameTarget ? pathToFileURL(cached.path).href : getOsc8LinkAtColumn(screen?.[y] ?? "", x)
|
|
808
|
+
: undefined;
|
|
570
809
|
let path: string | undefined;
|
|
571
810
|
if (url?.startsWith("file:")) {
|
|
572
811
|
try { const file = fileURLToPath(url); if (IMAGE_MIME[extname(file).toLowerCase()]) path = file; } catch { /* Reject malformed or remote file URLs. */ }
|
|
573
812
|
}
|
|
574
|
-
if (path
|
|
813
|
+
if (path && (path !== state.requestedPath || !sameTarget)) {
|
|
814
|
+
state.previewAnchor = { x, y };
|
|
815
|
+
if (path === state.requestedPath && state.preview.path) { positionPreview(state); state.previewTui?.requestRender(); }
|
|
816
|
+
let start = x, end = x + 1;
|
|
817
|
+
const line = screen?.[y] ?? "";
|
|
818
|
+
while (start > 0 && getOsc8LinkAtColumn(line, start - 1) === url) start--;
|
|
819
|
+
while (end < visibleWidth(line) && getOsc8LinkAtColumn(line, end) === url) end++;
|
|
820
|
+
state.hoverLink = { row: y, start, end, path };
|
|
821
|
+
} else if (!path) state.hoverLink = undefined;
|
|
575
822
|
setPointer(state, !!path);
|
|
576
823
|
void requestPreview(state, path);
|
|
577
824
|
}
|
|
@@ -581,22 +828,35 @@ function handleTerminalInput(state: Enhancements, data: string): { consume?: boo
|
|
|
581
828
|
}
|
|
582
829
|
|
|
583
830
|
async function requestPreview(state: Enhancements, path: string | undefined): Promise<void> {
|
|
584
|
-
if (path && state.enabled() && path === state.requestedPath)
|
|
831
|
+
if (path && state.enabled() && path === state.requestedPath) return;
|
|
832
|
+
if (!path || !state.enabled()) state.hoverLink = undefined;
|
|
833
|
+
if (!path && !state.requestedPath && !state.preview.path) return;
|
|
585
834
|
state.requestedPath = state.enabled() ? path : undefined;
|
|
586
835
|
const token = ++state.previewToken;
|
|
587
836
|
if (!path || !state.enabled()) {
|
|
588
837
|
setPreview(state, undefined);
|
|
589
838
|
return;
|
|
590
839
|
}
|
|
591
|
-
const
|
|
840
|
+
const cells = getCellDimensions();
|
|
841
|
+
const preview = await readPreview(path, state.cwd ?? process.cwd(), {
|
|
842
|
+
widthPx: Math.max(1, (state.tui?.terminal.columns ?? 80) - 2) * cells.widthPx,
|
|
843
|
+
heightPx: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2) * cells.heightPx,
|
|
844
|
+
});
|
|
592
845
|
if (token !== state.previewToken || !state.enabled()) return;
|
|
593
846
|
setPreview(state, preview);
|
|
594
847
|
}
|
|
595
848
|
|
|
596
849
|
function setPreview(state: Enhancements, preview: Preview | undefined): void {
|
|
850
|
+
// Overlay visibility only erases text; explicitly free the image owned by this preview.
|
|
851
|
+
if (state.preview.graphic?.imageId) state.tui?.terminal.write(deleteKittyImage(state.preview.graphic.imageId));
|
|
852
|
+
state.previewSource = preview;
|
|
853
|
+
state.previewLayout = imageLayoutKey();
|
|
597
854
|
const dimensions = preview?.kind === "image" ? getImageDimensions(preview.base64, preview.mimeType) : undefined;
|
|
855
|
+
const bandWidth = state.previewMode() === "inline" && state.editor && state.theme
|
|
856
|
+
? visibleWidth(inlinePreviewLines(state, state.theme, state.tui?.terminal.columns ?? 80)[0] ?? "") : 0;
|
|
857
|
+
const available = (state.tui?.terminal.columns ?? 80) - (bandWidth ? bandWidth + 4 : 2);
|
|
598
858
|
const graphic = preview?.kind === "image" && dimensions ? renderImage(preview.base64, dimensions, {
|
|
599
|
-
maxWidthCells: Math.max(1, Math.min(Math.floor(dimensions.widthPx / getCellDimensions().widthPx),
|
|
859
|
+
maxWidthCells: Math.max(1, Math.min(Math.floor(dimensions.widthPx / getCellDimensions().widthPx), available)),
|
|
600
860
|
maxHeightCells: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2),
|
|
601
861
|
imageId: allocateImageId(), moveCursor: false,
|
|
602
862
|
}) ?? undefined : undefined;
|
|
@@ -614,7 +874,10 @@ function showOverlay(state: Enhancements): void {
|
|
|
614
874
|
state.overlayReady = true;
|
|
615
875
|
state.previewOptions = { width: 60, maxHeight: "100%", nonCapturing: true, visible: () => state.enabled() && state.preview.path !== undefined };
|
|
616
876
|
state.previewHandle = state.tui.showOverlay({
|
|
617
|
-
render: width =>
|
|
877
|
+
render: width => {
|
|
878
|
+
if (state.previewLayout !== imageLayoutKey()) setPreview(state, state.previewSource);
|
|
879
|
+
return previewLines(state.preview, state.theme!, width);
|
|
880
|
+
},
|
|
618
881
|
invalidate: () => {},
|
|
619
882
|
}, state.previewOptions);
|
|
620
883
|
}
|
|
@@ -623,8 +886,17 @@ function positionPreview(state: Enhancements): void {
|
|
|
623
886
|
if (!state.previewOptions || !state.tui || !state.theme) return;
|
|
624
887
|
const { rows, columns } = state.tui.terminal;
|
|
625
888
|
const width = Math.max(3, Math.min((state.preview.graphic?.columns ?? 26) + 2, columns || 80));
|
|
626
|
-
const height = Math.min(rows, previewLines(state.preview, state.theme, width
|
|
889
|
+
const height = Math.min(rows, previewLines(state.preview, state.theme, width).length);
|
|
627
890
|
const { x, y } = state.previewAnchor ?? { x: 0, y: rows - 2 };
|
|
628
|
-
|
|
629
|
-
|
|
891
|
+
const previewRow = y + 1 + height <= rows ? y + 1 : Math.max(0, y - height);
|
|
892
|
+
// Keep hover previews out of the draft attachment band. If there is no safe
|
|
893
|
+
// vertical gap, move to the side rather than painting over the thumbnail.
|
|
894
|
+
const band = state.previewMode() === "inline" && state.editor && state.theme
|
|
895
|
+
? inlinePreviewLines(state, state.theme, columns).length : 0;
|
|
896
|
+
const overlapsBand = band > 0 && previewRow < y && previewRow + height > y - band - 1;
|
|
897
|
+
const bandWidth = band && state.theme && state.editor ? visibleWidth(inlinePreviewLines(state, state.theme, columns)[0] ?? "") : 0;
|
|
898
|
+
const side = Math.min(columns - width, bandWidth + 2);
|
|
899
|
+
const beside = overlapsBand && side >= bandWidth + 2;
|
|
900
|
+
Object.assign(state.previewOptions, { width, col: beside ? side : Math.max(0, Math.min(x, columns - width)),
|
|
901
|
+
row: beside ? Math.max(0, Math.min(y + 1, rows - height)) : previewRow });
|
|
630
902
|
}
|
package/lib/settings.html
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
<title>Pi Mini Mode 设置</title>
|
|
5
5
|
<style>
|
|
6
6
|
:root{color-scheme:light dark;--background:light-dark(#f4f3ef,#141614);--foreground:light-dark(#1f241f,#eceee8);--surface:light-dark(#fffcf7,#1d211d);--muted:light-dark(#667066,#a8b0a4);--border:light-dark(#e2ddd4,#3a4038);--accent:light-dark(#2f5a3e,#b7d4b0);--destructive:light-dark(#a52c26,#ffafa5);--ring:var(--accent);--preview-bg:light-dark(#f7f7f8,#131217);--preview-text:light-dark(#242127,#f5f5f5);--preview-muted:light-dark(#625f68,#a1a1aa);--preview-accent:light-dark(#2563eb,#5e9cff);--preview-warning:light-dark(#a16207,#facc15);--preview-success:light-dark(#15803d,#4ade80);--preview-error:light-dark(#dc2626,#fb7185);--text-sm:.875rem;--text-base:1rem;--text-lg:2.75rem;--radius:8px}
|
|
7
|
-
*{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font:var(--text-base)/1.5 ui-sans-serif,system-ui,sans-serif}main{max-width:1080px;margin:auto;padding:40px 24px 72px}header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}h1{font:italic 400 var(--text-lg)/1.05 "Didot","Bodoni 72","Iowan Old Style","Songti SC","STSong",serif;letter-spacing:.04em;margin:0}h2{font-size:var(--text-sm);font-weight:600;margin:0 0 12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}nav{display:flex;gap:8px;align-items:center}.hint{margin:12px 0 0;color:var(--accent);font-weight:600}section{margin:28px 0}button{font:inherit;color:inherit;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:8px 12px;cursor:pointer}button:disabled{opacity:.4;cursor:default}:focus-visible{outline:2px solid var(--ring);outline-offset:3px}#preview{position:relative;padding:16px 20px;background:var(--preview-bg);color:var(--preview-text);border:1px dashed var(--border);border-radius:var(--radius);font:var(--text-sm)/1.8 ui-monospace,monospace;display:flex;flex-wrap:wrap;align-items:center;gap:4px 12px;height:112px;overflow:auto}#preview button{flex:none;font:inherit;padding:4px 2px;border-color:transparent;background:transparent;color:var(--preview-muted);cursor:grab;white-space:nowrap}#preview button:focus-visible{border-color:var(--accent)}#preview button.over{border-left:2px solid var(--accent)}#preview button.preview-exit{opacity:0;pointer-events:none;transition:opacity 280ms ease-in;position:absolute}#preview .tone-accent{color:var(--preview-accent);font-weight:650}#preview .tone-text{color:var(--preview-text)}#preview .tone-warning{color:var(--preview-warning);font-weight:650}#preview .tone-success{color:var(--preview-success);font-weight:650}#preview .tone-error{color:var(--preview-error);font-weight:650}#preview .tone-muted{color:var(--preview-muted)}#preview #preview-context{flex:1 1 180px;display:flex;align-items:center;gap:8px;min-width:180px}.progress{flex:1;overflow:hidden;text-align:left;color:var(--preview-accent);min-width:0}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:2px 6px}label{display:flex;align-items:center;gap:10px;padding:10px 0;cursor:pointer;-webkit-user-select:none;user-select:none}.grid label{border:1px solid transparent;border-radius:var(--radius);padding:10px}input{accent-color:var(--accent);width:18px;height:18px;flex-shrink:0}.dragging{opacity:.45}#statusbar{position:fixed;top:12px;right:12px;z-index:2;display:flex;align-items:center;gap:10px;max-width:min(520px,calc(100vw - 24px));padding:8px 12px;background:var(--surface);border:1px solid var(--accent);border-radius:var(--radius);box-shadow:0 6px 20px rgb(0 0 0/.12);color:var(--accent);font-size:var(--text-sm);opacity:0;transform:translateY(-6px);transition:opacity 150ms ease-out,transform 150ms ease-out;pointer-events:none}#statusbar.on{opacity:1;transform:none}#statusbar.error{border-color:var(--destructive);color:var(--destructive)}#statusbar #retry{pointer-events:auto}[hidden]{display:none!important}nav button[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.features{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:12px}.feature{display:flex;flex-direction:column;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px}.feature-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.feature-head h3{margin:0;font-size:var(--text-base);font-weight:600}.feature-body{margin:10px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.65}.feature-points{margin:10px 0 0;padding-left:1.15em;font-size:var(--text-sm);line-height:1.7}.feature-points li{margin:2px 0}.feature-points li::marker{color:var(--accent)}.feature-hint{margin:auto 0 0;padding-top:12px;color:var(--muted);font:var(--text-sm)/1.6 ui-monospace,monospace;overflow-wrap:anywhere}.feature-hint::before{content:'› ';color:var(--accent)}.switch{display:flex;align-items:center;gap:8px;padding:0;font-size:var(--text-sm);color:var(--muted)}.notice{display:flex;gap:16px;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;margin:20px 0 0;padding:14px 16px;background:var(--surface);border:1px solid var(--accent);border-left-width:4px;border-radius:var(--radius)}.notice strong{font-size:var(--text-sm)}.notice p{margin:6px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.6;max-width:640px}.notice code{display:block;margin:0 0 8px;padding:8px 10px;background:var(--background);border:1px solid var(--border);border-radius:var(--radius);font:var(--text-sm)/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;max-width:520px;color:var(--foreground)}#preview{margin-top:12px;margin-bottom:20px}@media(max-width:450px){h1{font-size:2rem}main{padding:24px 16px}#statusbar{top:8px;right:8px;max-width:calc(100vw - 16px)}}@media(prefers-reduced-motion:reduce){#preview button.preview-exit{transition-duration:80ms}}@media(prefers-reduced-motion:reduce){#statusbar{transform:none;transition:opacity 80ms ease-out}}
|
|
7
|
+
*{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font:var(--text-base)/1.5 ui-sans-serif,system-ui,sans-serif}main{max-width:1080px;margin:auto;padding:40px 24px 72px}header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}h1{font:italic 400 var(--text-lg)/1.05 "Didot","Bodoni 72","Iowan Old Style","Songti SC","STSong",serif;letter-spacing:.04em;margin:0}h2{font-size:var(--text-sm);font-weight:600;margin:0 0 12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}nav{display:flex;gap:8px;align-items:center}.hint{margin:12px 0 0;color:var(--accent);font-weight:600}section{margin:28px 0}button{font:inherit;color:inherit;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:8px 12px;cursor:pointer}button:disabled{opacity:.4;cursor:default}:focus-visible{outline:2px solid var(--ring);outline-offset:3px}#preview{position:relative;padding:16px 20px;background:var(--preview-bg);color:var(--preview-text);border:1px dashed var(--border);border-radius:var(--radius);font:var(--text-sm)/1.8 ui-monospace,monospace;display:flex;flex-wrap:wrap;align-items:center;gap:4px 12px;height:112px;overflow:auto}#preview button{flex:none;font:inherit;padding:4px 2px;border-color:transparent;background:transparent;color:var(--preview-muted);cursor:grab;white-space:nowrap}#preview button:focus-visible{border-color:var(--accent)}#preview button.over{border-left:2px solid var(--accent)}#preview button.preview-exit{opacity:0;pointer-events:none;transition:opacity 280ms ease-in;position:absolute}#preview .tone-accent{color:var(--preview-accent);font-weight:650}#preview .tone-text{color:var(--preview-text)}#preview .tone-warning{color:var(--preview-warning);font-weight:650}#preview .tone-success{color:var(--preview-success);font-weight:650}#preview .tone-error{color:var(--preview-error);font-weight:650}#preview .tone-muted{color:var(--preview-muted)}#preview #preview-context{flex:1 1 180px;display:flex;align-items:center;gap:8px;min-width:180px}.progress{flex:1;overflow:hidden;text-align:left;color:var(--preview-accent);min-width:0}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:2px 6px}label{display:flex;align-items:center;gap:10px;padding:10px 0;cursor:pointer;-webkit-user-select:none;user-select:none}.grid label{border:1px solid transparent;border-radius:var(--radius);padding:10px}input{accent-color:var(--accent);width:18px;height:18px;flex-shrink:0}.dragging{opacity:.45}#statusbar{position:fixed;top:12px;right:12px;z-index:2;display:flex;align-items:center;gap:10px;max-width:min(520px,calc(100vw - 24px));padding:8px 12px;background:var(--surface);border:1px solid var(--accent);border-radius:var(--radius);box-shadow:0 6px 20px rgb(0 0 0/.12);color:var(--accent);font-size:var(--text-sm);opacity:0;transform:translateY(-6px);transition:opacity 150ms ease-out,transform 150ms ease-out;pointer-events:none}#statusbar.on{opacity:1;transform:none}#statusbar.error{border-color:var(--destructive);color:var(--destructive)}#statusbar #retry{pointer-events:auto}[hidden]{display:none!important}nav button[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.features{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:12px}.feature{display:flex;flex-direction:column;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px}.feature-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.feature-head h3{margin:0;font-size:var(--text-base);font-weight:600}.feature-body{margin:10px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.65}.feature-points{margin:10px 0 0;padding-left:1.15em;font-size:var(--text-sm);line-height:1.7}.feature-points li{margin:2px 0}.feature-points li::marker{color:var(--accent)}.feature-hint{margin:auto 0 0;padding-top:12px;color:var(--muted);font:var(--text-sm)/1.6 ui-monospace,monospace;overflow-wrap:anywhere}.feature-hint::before{content:'› ';color:var(--accent)}.preview-mode{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:14px 0 0;font-size:var(--text-sm)}.preview-mode select{font:inherit;color:var(--foreground);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:8px;min-height:44px}.preview-mode select:disabled{opacity:.5}.switch{display:flex;align-items:center;gap:8px;padding:0;font-size:var(--text-sm);color:var(--muted)}.notice{display:flex;gap:16px;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;margin:20px 0 0;padding:14px 16px;background:var(--surface);border:1px solid var(--accent);border-left-width:4px;border-radius:var(--radius)}.notice strong{font-size:var(--text-sm)}.notice p{margin:6px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.6;max-width:640px}.notice code{display:block;margin:0 0 8px;padding:8px 10px;background:var(--background);border:1px solid var(--border);border-radius:var(--radius);font:var(--text-sm)/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;max-width:520px;color:var(--foreground)}#preview{margin-top:12px;margin-bottom:20px}@media(max-width:450px){h1{font-size:2rem}main{padding:24px 16px}#statusbar{top:8px;right:8px;max-width:calc(100vw - 16px)}}@media(prefers-reduced-motion:reduce){#preview button.preview-exit{transition-duration:80ms}}@media(prefers-reduced-motion:reduce){#statusbar{transform:none;transition:opacity 80ms ease-out}}
|
|
8
8
|
@media(hover:hover) and (pointer:fine){#preview button:hover,.grid label:hover,.feature:hover{border-color:var(--accent)}}
|
|
9
9
|
#preview button.preview-highlight{border-color:var(--accent)}#preview button.preview-placeholder{border-style:dashed;opacity:1}
|
|
10
10
|
|
|
@@ -40,7 +40,7 @@ const I18N={
|
|
|
40
40
|
featuresHeading:{zh:'功能说明',en:'Features'},
|
|
41
41
|
fieldsHeading:{zh:'状态栏字段与预览',en:'Status bar items & preview'},
|
|
42
42
|
optionsHeading:{zh:'状态栏样式',en:'Status bar style'},
|
|
43
|
-
on:{zh:'开启',en:'On'},off:{zh:'关闭',en:'Off'},
|
|
43
|
+
on:{zh:'开启',en:'On'},off:{zh:'关闭',en:'Off'},previewModeLabel:{zh:'图片预览方式',en:'Image preview mode'},previewHover:{zh:'光标浮窗',en:'Cursor popup'},previewInline:{zh:'内联卡片(多图排列)',en:'Inline cards (multiple images)'},previewModeHint:{zh:'卡片显示在输入框上方;终端不支持图片时显示占位。',en:'Cards appear above the editor; unsupported terminals show placeholders.'},
|
|
44
44
|
featureList:{
|
|
45
45
|
zh:[
|
|
46
46
|
{id:'minimal',setting:'pi-mini-mode-minimal-show',title:'极简输出',body:'把对话收成结论:思考、工具与技能汇成一棵按时间排序的可折叠过程树。',points:['长用户消息默认保留前四行,点击展开全文','子代理行可展开活动记录与输出','Ctrl+O 展开或收起过程树,新问题默认收起','最终 Markdown 流畅呈现,失败与中断明确标记']},
|
|
@@ -204,6 +204,16 @@ function feature(item){
|
|
|
204
204
|
const points=document.createElement('ul');points.className='feature-points';
|
|
205
205
|
points.append(...item.points.map(point=>{const li=document.createElement('li');li.textContent=point;return li}));
|
|
206
206
|
card.append(head,body,points);
|
|
207
|
+
if(item.id==='input-enhancements'){
|
|
208
|
+
const label=document.createElement('label');label.className='preview-mode';label.htmlFor='pi-mini-mode-image-preview';
|
|
209
|
+
const text=document.createElement('span');text.textContent=t('previewModeLabel');
|
|
210
|
+
const select=document.createElement('select');select.id=label.htmlFor;select.disabled=!state[item.setting];
|
|
211
|
+
for(const [value,key] of [['hover','previewHover'],['inline','previewInline']]){const option=document.createElement('option');option.value=value;option.textContent=t(key);select.append(option)}
|
|
212
|
+
select.value=state[select.id]||'inline';select.onchange=()=>{state[select.id]=select.value;change()};
|
|
213
|
+
label.append(text,select);card.append(label);
|
|
214
|
+
const hint=document.createElement('p');hint.className='feature-hint';hint.textContent=t('previewModeHint');card.append(hint);
|
|
215
|
+
head.querySelector('input').addEventListener('change',()=>{select.disabled=!state[item.setting]});
|
|
216
|
+
}
|
|
207
217
|
if(item.hint){const hint=document.createElement('p');hint.className='feature-hint';hint.textContent=item.hint;card.append(hint)}
|
|
208
218
|
return card;
|
|
209
219
|
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
type CapabilityGetter = SettingsManager["getTerminalCapabilityOverrides"];
|
|
4
|
+
type CapabilityOverrides = ReturnType<CapabilityGetter>;
|
|
5
|
+
type CapabilityBridge = { original: CapabilityGetter; getter: CapabilityGetter; owners: Set<symbol> };
|
|
6
|
+
const BRIDGE = Symbol.for("@each1024/pi-mini-mode/terminal-capabilities");
|
|
7
|
+
|
|
8
|
+
function terminalDefaults(overrides: CapabilityOverrides): CapabilityOverrides {
|
|
9
|
+
const term = process.env.TERM?.toLowerCase() ?? "";
|
|
10
|
+
if (process.env.TERM_PROGRAM?.toLowerCase() !== "otty" || process.env.TMUX || process.env.STY || /^(tmux|screen)/.test(term)) return overrides;
|
|
11
|
+
const defaults: CapabilityOverrides = {};
|
|
12
|
+
const protocol = process.env.PI_IMAGE_PROTOCOL?.toLowerCase();
|
|
13
|
+
if (overrides.images === undefined && !["kitty", "iterm2", "none", "0"].includes(protocol ?? "")) defaults.images = "kitty";
|
|
14
|
+
if (overrides.hyperlinks === undefined && !["0", "1"].includes(process.env.PI_HYPERLINKS ?? "")) defaults.hyperlinks = true;
|
|
15
|
+
return Object.keys(defaults).length ? { ...overrides, ...defaults } : overrides;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Temporary bridge: Pi exposes settings overrides but no extension hook for detection defaults.
|
|
19
|
+
* Install in the extension factory, before the host applies settings and starts its renderer.
|
|
20
|
+
* Never infer why getCapabilities().images is null or override the renderer's restrictions.
|
|
21
|
+
*/
|
|
22
|
+
export function installTerminalCapabilities(): () => void {
|
|
23
|
+
const prototype = SettingsManager.prototype as SettingsManager & { [BRIDGE]?: CapabilityBridge };
|
|
24
|
+
if (typeof prototype?.getTerminalCapabilityOverrides !== "function") return () => {};
|
|
25
|
+
let bridge = prototype[BRIDGE];
|
|
26
|
+
if (!bridge) {
|
|
27
|
+
const original = prototype.getTerminalCapabilityOverrides;
|
|
28
|
+
const owners = new Set<symbol>();
|
|
29
|
+
const getter: CapabilityGetter = function (this: SettingsManager, ...args: Parameters<CapabilityGetter>) {
|
|
30
|
+
const overrides = original.apply(this, args);
|
|
31
|
+
return owners.size ? terminalDefaults(overrides) : overrides;
|
|
32
|
+
};
|
|
33
|
+
bridge = { original, getter, owners };
|
|
34
|
+
prototype[BRIDGE] = bridge;
|
|
35
|
+
prototype.getTerminalCapabilityOverrides = getter;
|
|
36
|
+
}
|
|
37
|
+
const owner = Symbol();
|
|
38
|
+
bridge.owners.add(owner);
|
|
39
|
+
return () => {
|
|
40
|
+
if (!bridge.owners.delete(owner) || bridge.owners.size) return;
|
|
41
|
+
// A later third-party wrapper may retain ours; leave it installed and ours inactive.
|
|
42
|
+
if (prototype.getTerminalCapabilityOverrides === bridge.getter) prototype.getTerminalCapabilityOverrides = bridge.original;
|
|
43
|
+
if (prototype[BRIDGE] === bridge) delete prototype[BRIDGE];
|
|
44
|
+
};
|
|
45
|
+
}
|
package/package.json
CHANGED