@autopilot-agent/cli 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -6
- package/dist/activity-animation.d.ts +5 -0
- package/dist/activity-animation.js +13 -17
- package/dist/browser-client.d.ts +14 -0
- package/dist/browser-client.js +156 -0
- package/dist/composition-root.d.ts +41 -1
- package/dist/composition-root.js +141 -14
- package/dist/context-report.d.ts +9 -4
- package/dist/context-report.js +15 -3
- package/dist/controller.d.ts +81 -4
- package/dist/controller.js +468 -98
- package/dist/design-tokens.d.ts +7 -2
- package/dist/design-tokens.js +11 -3
- package/dist/desktop-status.d.ts +35 -0
- package/dist/desktop-status.js +304 -0
- package/dist/error-diagnostics.d.ts +2 -0
- package/dist/error-diagnostics.js +3 -1
- package/dist/event-projector.d.ts +16 -2
- package/dist/event-projector.js +74 -5
- package/dist/file-mention-budget.d.ts +16 -0
- package/dist/file-mention-budget.js +82 -0
- package/dist/file-mention-context.d.ts +26 -1
- package/dist/file-mention-context.js +70 -22
- package/dist/index.d.ts +1 -1
- package/dist/main.d.ts +3 -0
- package/dist/main.js +213 -12
- package/dist/managed-attach.d.ts +3 -0
- package/dist/managed-attach.js +132 -0
- package/dist/managed-controller.d.ts +49 -0
- package/dist/managed-controller.js +171 -0
- package/dist/orchestration-templates.d.ts +27 -0
- package/dist/orchestration-templates.js +20 -0
- package/dist/parser.d.ts +1 -1
- package/dist/parser.js +510 -2
- package/dist/renderer.js +3 -1
- package/dist/session-summary.d.ts +7 -0
- package/dist/session-summary.js +25 -0
- package/dist/session-title.d.ts +5 -0
- package/dist/session-title.js +10 -0
- package/dist/thread-commands.d.ts +37 -0
- package/dist/thread-commands.js +233 -0
- package/dist/thread-host.d.ts +36 -0
- package/dist/thread-host.js +79 -0
- package/dist/timeline-lines.js +36 -28
- package/dist/tui/app.d.ts +22 -0
- package/dist/tui/app.js +179 -43
- package/dist/tui/approval.d.ts +4 -0
- package/dist/tui/approval.js +13 -4
- package/dist/tui/brand/brand-header.d.ts +1 -3
- package/dist/tui/brand/brand-header.js +6 -8
- package/dist/tui/brand/logo.d.ts +3 -0
- package/dist/tui/brand/logo.js +89 -0
- package/dist/tui/brand/startup.d.ts +18 -0
- package/dist/tui/brand/startup.js +136 -0
- package/dist/tui/constants.d.ts +1 -1
- package/dist/tui/constants.js +1 -1
- package/dist/tui/context.js +1 -3
- package/dist/tui/desktop-resize.d.ts +9 -0
- package/dist/tui/desktop-resize.js +95 -0
- package/dist/tui/format.d.ts +1 -1
- package/dist/tui/format.js +19 -9
- package/dist/tui/hooks/use-file-mention-index.js +9 -4
- package/dist/tui/hooks/use-prompt-input.d.ts +54 -1
- package/dist/tui/hooks/use-prompt-input.js +159 -26
- package/dist/tui/hooks/use-status-view.d.ts +2 -2
- package/dist/tui/hooks/use-status-view.js +38 -11
- package/dist/tui/hooks/use-viewport.d.ts +2 -1
- package/dist/tui/hooks/use-viewport.js +15 -8
- package/dist/tui/inline-output.d.ts +17 -0
- package/dist/tui/inline-output.js +31 -0
- package/dist/tui/input/clipboard-image.d.ts +17 -0
- package/dist/tui/input/clipboard-image.js +117 -0
- package/dist/tui/input-area.d.ts +12 -1
- package/dist/tui/input-area.js +28 -8
- package/dist/tui/lifecycle.d.ts +1 -1
- package/dist/tui/lifecycle.js +84 -16
- package/dist/tui/markdown/diff.d.ts +1 -1
- package/dist/tui/markdown/diff.js +28 -1
- package/dist/tui/performance-diagnostics.js +2 -0
- package/dist/tui/pickers/permission.js +1 -1
- package/dist/tui/pickers/slash.d.ts +11 -2
- package/dist/tui/pickers/slash.js +21 -7
- package/dist/tui/prompt-input.d.ts +2 -0
- package/dist/tui/prompt-input.js +6 -4
- package/dist/tui/render-mode.d.ts +8 -4
- package/dist/tui/render-mode.js +17 -11
- package/dist/tui/run.js +53 -55
- package/dist/tui/session-manager.d.ts +116 -0
- package/dist/tui/session-manager.js +384 -0
- package/dist/tui/session-workspace.d.ts +9 -0
- package/dist/tui/session-workspace.js +383 -0
- package/dist/tui/status-line.d.ts +4 -0
- package/dist/tui/status-line.js +34 -13
- package/dist/tui/store.d.ts +3 -1
- package/dist/tui/store.js +60 -14
- package/dist/tui/timeline/live.js +2 -3
- package/dist/tui/timeline/progress.js +3 -2
- package/dist/tui/timeline/static-timeline.js +1 -2
- package/dist/tui/timeline/turn.js +3 -2
- package/dist/tui/transcript.d.ts +2 -1
- package/dist/tui/transcript.js +43 -5
- package/dist/tui/trust-dialog.d.ts +3 -0
- package/dist/tui/trust-dialog.js +23 -2
- package/dist/tui/types.d.ts +18 -1
- package/dist/tui/types.js +4 -1
- package/dist/tui/viewport/selection.d.ts +2 -2
- package/dist/tui/viewport/selection.js +13 -6
- package/dist/tui/viewport/sources.js +13 -14
- package/dist/types.d.ts +160 -3
- package/package.json +4 -4
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** prompt 输入状态与 handleInput:字符串/光标/历史维护与按键分发。 */
|
|
2
|
-
import {
|
|
2
|
+
import { useEffect, useState } from "react";
|
|
3
3
|
import { parseSlashAction } from "../../parser.js";
|
|
4
4
|
import { canNavigateTuiInputHistory, createTuiInputHistoryState, navigateTuiInputHistory, recordTuiInputHistory, updateTuiInputHistoryDraft, } from "../../tui-input-history.js";
|
|
5
5
|
import { createTuiApprovalOptions } from "../approval.js";
|
|
@@ -9,20 +9,93 @@ import { applyFileMentionSuggestion, extractFileMentionToken } from "../input/fi
|
|
|
9
9
|
import { hasTuiUnescapedContinuation, isTuiMultilineEnter, isTuiTerminalFocusSequence, isTuiViewportScrollKey, parseTuiControlAction, resolveTuiBracketedPasteBoundary, resolveTuiDeleteDirection, } from "../input/keys.js";
|
|
10
10
|
import { createTuiPromptLayout, resolveTuiPromptCursorIndex } from "../input/prompt-layout.js";
|
|
11
11
|
import { recordTuiPerformanceDiagnostic } from "../performance-diagnostics.js";
|
|
12
|
+
import { readMacClipboard, readWindowsClipboard } from "../input/clipboard-image.js";
|
|
13
|
+
/** 保存已打开会话的输入状态;视图卸载时不保留React子树或正文派生计算。 */
|
|
14
|
+
function createPromptDraft() {
|
|
15
|
+
return {
|
|
16
|
+
inputRef: { current: "" }, cursorIndexRef: { current: 0 },
|
|
17
|
+
verticalColumnRef: { current: undefined }, bracketedPasteRef: { current: false },
|
|
18
|
+
bracketedPasteHadContentRef: { current: false }, pasteCarriageReturnRef: { current: false },
|
|
19
|
+
inputHistoryRef: { current: createTuiInputHistoryState() },
|
|
20
|
+
imageDraftsRef: { current: new Map() }, historyImagesRef: { current: [] },
|
|
21
|
+
historyDraftImagesRef: { current: new Map() }, lastSubmittedImagesRef: { current: new Map() },
|
|
22
|
+
pasteQueueRef: { current: Promise.resolve() }, pastingCountRef: { current: 0 },
|
|
23
|
+
};
|
|
24
|
+
}
|
|
12
25
|
/** 管理 prompt 输入状态、历史与按键分发,并暴露 handleInput 供 Ink 的 useInput 使用。 */
|
|
13
26
|
export function usePromptInput(input) {
|
|
14
27
|
const { store, columns, busy, keepOpenAfterCancel, lastSubmittedPromptRef, rawInputSequenceRef, dispatchAction, onEof, onRequestInterrupt, onRequestCancel, isPickerActive, dispatchPickerInput, approvalPickerIndexRef, updateApprovalPickerIndex, slashCommandIndexRef, updateSlashCommandIndex, fileMentionIndexRef, updateFileMentionIndex, setFileMentionDismissedInput, derivedRef, } = input;
|
|
15
|
-
const [
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const cursorIndexRef =
|
|
19
|
-
const
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
28
|
+
const [draft] = useState(function initialDraft() { return input.draftRef?.current ?? createPromptDraft(); });
|
|
29
|
+
if (input.draftRef)
|
|
30
|
+
input.draftRef.current = draft;
|
|
31
|
+
const { inputRef, cursorIndexRef, verticalColumnRef, bracketedPasteRef, bracketedPasteHadContentRef, pasteCarriageReturnRef, inputHistoryRef, imageDraftsRef, historyImagesRef, historyDraftImagesRef, lastSubmittedImagesRef, pasteQueueRef, pastingCountRef } = draft;
|
|
32
|
+
const [inputValue, setInput] = useState(inputRef.current);
|
|
33
|
+
const [cursorIndex, setCursorIndex] = useState(cursorIndexRef.current);
|
|
34
|
+
/** 定位当前草稿中有附件身份的占位符,以 grapheme 位置保护原子编辑。 */
|
|
35
|
+
function imageSpans(value) {
|
|
36
|
+
const spans = [];
|
|
37
|
+
for (const match of value.matchAll(/\[Image (\d+)\]/g)) {
|
|
38
|
+
const id = Number(match[1]);
|
|
39
|
+
if (!imageDraftsRef.current.has(id))
|
|
40
|
+
continue;
|
|
41
|
+
const start = splitTuiInputGraphemes(value.slice(0, match.index)).length;
|
|
42
|
+
spans.push({ id, start, end: start + match[0].length });
|
|
43
|
+
}
|
|
44
|
+
return spans;
|
|
45
|
+
}
|
|
46
|
+
/** 把异步读取的剪贴板图片及文本按次序插入当前光标。 */
|
|
47
|
+
function pasteClipboard() {
|
|
48
|
+
pastingCountRef.current++;
|
|
49
|
+
const pending = (process.platform === "darwin" ? readMacClipboard() : readWindowsClipboard()).then(function read(value) { return { value }; }, function failed(error) { return { error }; });
|
|
50
|
+
pasteQueueRef.current = pasteQueueRef.current.then(async function insertPaste() {
|
|
51
|
+
try {
|
|
52
|
+
const outcome = await pending;
|
|
53
|
+
if ("error" in outcome)
|
|
54
|
+
throw outcome.error;
|
|
55
|
+
const result = outcome.value;
|
|
56
|
+
const currentCount = imageSpans(inputRef.current).length;
|
|
57
|
+
if (currentCount + result.images.length > 10)
|
|
58
|
+
throw new Error("一次最多发送 10 张图片");
|
|
59
|
+
const currentBytes = imageSpans(inputRef.current).reduce(function total(sum, span) { return sum + (imageDraftsRef.current.get(span.id)?.bytes.byteLength ?? 0); }, 0);
|
|
60
|
+
if (currentBytes + result.images.reduce(function total(sum, image) { return sum + image.bytes.byteLength; }, 0) > 20 * 1024 * 1024)
|
|
61
|
+
throw new Error("图片总大小超过 20 MiB");
|
|
62
|
+
if (result.images.some(function isGif(image) { return image.gifFirstFrame; }))
|
|
63
|
+
store.addNotice("GIF 图片仅发送静态首帧");
|
|
64
|
+
let inserted = result.text ?? "";
|
|
65
|
+
for (const image of result.images) {
|
|
66
|
+
const id = Math.max(0, ...imageDraftsRef.current.keys()) + 1;
|
|
67
|
+
imageDraftsRef.current.set(id, image);
|
|
68
|
+
inserted += `${inserted ? " " : ""}[Image ${id}]`;
|
|
69
|
+
}
|
|
70
|
+
if (!inserted)
|
|
71
|
+
return;
|
|
72
|
+
const chars = splitTuiInputGraphemes(inputRef.current);
|
|
73
|
+
const inside = imageSpans(inputRef.current).find(function contains(span) { return cursorIndexRef.current > span.start && cursorIndexRef.current < span.end; });
|
|
74
|
+
const cursor = inside?.end ?? cursorIndexRef.current;
|
|
75
|
+
const addition = splitTuiInputGraphemes(inserted);
|
|
76
|
+
chars.splice(cursor, 0, ...addition);
|
|
77
|
+
const next = chars.join("");
|
|
78
|
+
inputHistoryRef.current = updateTuiInputHistoryDraft(inputHistoryRef.current, next);
|
|
79
|
+
updateInput(next, cursor + addition.length);
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
const safeMessages = ["一次最多发送 10 张图片", "一次最多粘贴 10 张图片", "剪贴板包含不支持的文件", "图片超过 20 MiB 输入上限", "图片总大小超过 20 MiB"];
|
|
83
|
+
store.addNotice(error instanceof Error && safeMessages.includes(error.message) ? error.message : "剪贴板图片读取或处理失败");
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
pastingCountRef.current--;
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
}
|
|
23
90
|
/** 同步维护字符串与光标位置,避免只移动光标时 React 跳过重绘;输入变化即解除 @ 菜单的 Esc 关闭标记。 */
|
|
24
91
|
function updateInput(nextInput, nextCursorIndex) {
|
|
25
92
|
verticalColumnRef.current = undefined;
|
|
93
|
+
for (const id of imageDraftsRef.current.keys())
|
|
94
|
+
if (!nextInput.includes(`[Image ${id}]`))
|
|
95
|
+
imageDraftsRef.current.delete(id);
|
|
96
|
+
const inside = imageSpans(nextInput).find(function contains(span) { return nextCursorIndex > span.start && nextCursorIndex < span.end; });
|
|
97
|
+
if (inside)
|
|
98
|
+
nextCursorIndex = inside.end;
|
|
26
99
|
inputRef.current = nextInput;
|
|
27
100
|
cursorIndexRef.current = nextCursorIndex;
|
|
28
101
|
setFileMentionDismissedInput(undefined);
|
|
@@ -31,6 +104,9 @@ export function usePromptInput(input) {
|
|
|
31
104
|
}
|
|
32
105
|
/** 只移动逻辑光标,不清除上下键要保持的目标视觉列。 */
|
|
33
106
|
function updateCursorIndex(nextCursorIndex) {
|
|
107
|
+
const inside = imageSpans(inputRef.current).find(function contains(span) { return nextCursorIndex > span.start && nextCursorIndex < span.end; });
|
|
108
|
+
if (inside)
|
|
109
|
+
nextCursorIndex = inside.end;
|
|
34
110
|
cursorIndexRef.current = nextCursorIndex;
|
|
35
111
|
setCursorIndex(nextCursorIndex);
|
|
36
112
|
}
|
|
@@ -45,10 +121,14 @@ export function usePromptInput(input) {
|
|
|
45
121
|
const prompt = lastSubmittedPromptRef.current;
|
|
46
122
|
if (!prompt || inputRef.current !== "" || current.pendingInputs.length > 0)
|
|
47
123
|
return;
|
|
124
|
+
imageDraftsRef.current = new Map(lastSubmittedImagesRef.current);
|
|
48
125
|
updateInput(prompt, splitTuiInputGraphemes(prompt).length);
|
|
49
126
|
}
|
|
127
|
+
/** 分发终端按键并保持图片占位符与草稿身份一致。 */
|
|
50
128
|
function handleInput(value, key) {
|
|
51
129
|
recordTuiPerformanceDiagnostic("input_key_arrived", value && !key.ctrl && !key.meta ? "text" : "control");
|
|
130
|
+
if (!bracketedPasteRef.current && (key.ctrl && (value.toLowerCase() === "c" || value === "\u0003") || /^(?:\u001b)?\[99;6u$/.test(value)) && derivedRef.current.handleTuiViewportKey(key, value))
|
|
131
|
+
return;
|
|
52
132
|
const controlAction = parseTuiControlAction(value, key);
|
|
53
133
|
if (controlAction === "eof") {
|
|
54
134
|
onEof();
|
|
@@ -66,18 +146,30 @@ export function usePromptInput(input) {
|
|
|
66
146
|
const pasteBoundary = resolveTuiBracketedPasteBoundary(value);
|
|
67
147
|
if (pasteBoundary === "start") {
|
|
68
148
|
bracketedPasteRef.current = true;
|
|
149
|
+
bracketedPasteHadContentRef.current = false;
|
|
69
150
|
pasteCarriageReturnRef.current = false;
|
|
70
151
|
return;
|
|
71
152
|
}
|
|
72
153
|
if (pasteBoundary === "end") {
|
|
73
154
|
bracketedPasteRef.current = false;
|
|
74
155
|
pasteCarriageReturnRef.current = false;
|
|
156
|
+
if (!bracketedPasteHadContentRef.current && (process.platform === "win32" || process.platform === "darwin"))
|
|
157
|
+
pasteClipboard();
|
|
75
158
|
return;
|
|
76
159
|
}
|
|
160
|
+
if (bracketedPasteRef.current && (value || key.return))
|
|
161
|
+
bracketedPasteHadContentRef.current = true;
|
|
77
162
|
if (isPickerActive) {
|
|
78
163
|
dispatchPickerInput(value, key, controlAction);
|
|
79
164
|
return;
|
|
80
165
|
}
|
|
166
|
+
if (current.status !== "waiting_approval" && !bracketedPasteRef.current && (process.platform === "win32" || process.platform === "darwin") && ((key.ctrl && value.toLowerCase() === "v") || (key.meta && value.toLowerCase() === "v") || value === "\u0016")) {
|
|
167
|
+
pasteClipboard();
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
// 审批详情是当前顶层交互,翻页/关闭不穿透到历史滚动或 Turn 取消。
|
|
171
|
+
if (current.status === "waiting_approval" && current.pendingApproval && derivedRef.current.handleApprovalKey?.(value, key))
|
|
172
|
+
return;
|
|
81
173
|
if (controlAction === "cancel") {
|
|
82
174
|
// D3:@ 菜单激活时 Esc 仅关闭菜单,prompt 保留;再次 Esc 时菜单已关,走正常取消路径。
|
|
83
175
|
if (derivedRef.current.fileMentionSuggestions.length > 0) {
|
|
@@ -97,12 +189,12 @@ export function usePromptInput(input) {
|
|
|
97
189
|
}
|
|
98
190
|
if (derivedRef.current.slashCommandSuggestions.length > 0) {
|
|
99
191
|
const slashCommandSuggestions = derivedRef.current.slashCommandSuggestions;
|
|
100
|
-
const
|
|
192
|
+
const commandCount = slashCommandSuggestions.length;
|
|
193
|
+
const selectedIndex = Math.max(0, Math.min(slashCommandIndexRef.current, commandCount - 1));
|
|
194
|
+
const selectedCommand = slashCommandSuggestions[selectedIndex];
|
|
101
195
|
if (selectedCommand && (key.upArrow || key.downArrow)) {
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
: Math.min(slashCommandSuggestions.length - 1, slashCommandIndexRef.current + 1);
|
|
105
|
-
updateSlashCommandIndex(nextIndex);
|
|
196
|
+
const step = key.upArrow ? -1 : 1;
|
|
197
|
+
updateSlashCommandIndex((selectedIndex + step + commandCount) % commandCount);
|
|
106
198
|
return;
|
|
107
199
|
}
|
|
108
200
|
if (selectedCommand && key.tab) {
|
|
@@ -162,7 +254,7 @@ export function usePromptInput(input) {
|
|
|
162
254
|
}
|
|
163
255
|
if (derivedRef.current.handleTuiViewportKey(key))
|
|
164
256
|
return;
|
|
165
|
-
if (busy.current && !isActiveTuiStatus(current.status))
|
|
257
|
+
if (current.compacting || busy.current && !isActiveTuiStatus(current.status) && !input.parseInput)
|
|
166
258
|
return;
|
|
167
259
|
const deleteDirection = resolveTuiDeleteDirection(value, key, rawInputSequenceRef.current);
|
|
168
260
|
if (deleteDirection) {
|
|
@@ -171,6 +263,15 @@ export function usePromptInput(input) {
|
|
|
171
263
|
const removeIndex = deleteDirection === "backspace" ? cursor - 1 : cursor;
|
|
172
264
|
if (removeIndex < 0 || removeIndex >= characters.length)
|
|
173
265
|
return;
|
|
266
|
+
const image = imageSpans(inputRef.current).find(function contains(span) { return removeIndex >= span.start && removeIndex < span.end; });
|
|
267
|
+
if (image) {
|
|
268
|
+
characters.splice(image.start, image.end - image.start);
|
|
269
|
+
imageDraftsRef.current.delete(image.id);
|
|
270
|
+
const next = characters.join("");
|
|
271
|
+
inputHistoryRef.current = updateTuiInputHistoryDraft(inputHistoryRef.current, next);
|
|
272
|
+
updateInput(next, image.start);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
174
275
|
characters.splice(removeIndex, 1);
|
|
175
276
|
const nextInput = characters.join("");
|
|
176
277
|
inputHistoryRef.current = updateTuiInputHistoryDraft(inputHistoryRef.current, nextInput);
|
|
@@ -178,11 +279,13 @@ export function usePromptInput(input) {
|
|
|
178
279
|
return;
|
|
179
280
|
}
|
|
180
281
|
if (key.leftArrow) {
|
|
181
|
-
|
|
282
|
+
const image = imageSpans(inputRef.current).find(function atEnd(span) { return cursorIndexRef.current > span.start && cursorIndexRef.current <= span.end; });
|
|
283
|
+
updateInput(inputRef.current, image?.start ?? Math.max(0, cursorIndexRef.current - 1));
|
|
182
284
|
return;
|
|
183
285
|
}
|
|
184
286
|
if (key.rightArrow) {
|
|
185
|
-
|
|
287
|
+
const image = imageSpans(inputRef.current).find(function atStart(span) { return cursorIndexRef.current >= span.start && cursorIndexRef.current < span.end; });
|
|
288
|
+
updateInput(inputRef.current, image?.end ?? Math.min(splitTuiInputGraphemes(inputRef.current).length, cursorIndexRef.current + 1));
|
|
186
289
|
return;
|
|
187
290
|
}
|
|
188
291
|
if (key.upArrow || key.downArrow) {
|
|
@@ -198,9 +301,13 @@ export function usePromptInput(input) {
|
|
|
198
301
|
}
|
|
199
302
|
const historyDirection = key.upArrow ? "up" : "down";
|
|
200
303
|
const canNavigateHistory = canNavigateTuiInputHistory(historyDirection, layout.cursorLine, layout.lines.length, inputHistoryRef.current.index !== undefined, false);
|
|
304
|
+
const previousIndex = inputHistoryRef.current.index;
|
|
305
|
+
if (canNavigateHistory && previousIndex === undefined)
|
|
306
|
+
historyDraftImagesRef.current = new Map(imageDraftsRef.current);
|
|
201
307
|
const navigation = navigateTuiInputHistory(inputHistoryRef.current, historyDirection, inputRef.current, canNavigateHistory);
|
|
202
|
-
if (navigation.changed) {
|
|
308
|
+
if (navigation.changed || navigation.state.index !== previousIndex) {
|
|
203
309
|
inputHistoryRef.current = navigation.state;
|
|
310
|
+
imageDraftsRef.current = new Map(navigation.state.index === undefined ? historyDraftImagesRef.current : historyImagesRef.current[navigation.state.index] ?? []);
|
|
204
311
|
updateInput(navigation.input, splitTuiInputGraphemes(navigation.input).length);
|
|
205
312
|
}
|
|
206
313
|
return;
|
|
@@ -227,26 +334,49 @@ export function usePromptInput(input) {
|
|
|
227
334
|
}
|
|
228
335
|
pasteCarriageReturnRef.current = false;
|
|
229
336
|
if (key.return) {
|
|
337
|
+
// 受管远端提交期间允许继续编辑草稿,但不丢弃尚未可提交的下一条消息。
|
|
338
|
+
if (busy.current && !isActiveTuiStatus(current.status))
|
|
339
|
+
return;
|
|
340
|
+
if (pastingCountRef.current > 0) {
|
|
341
|
+
store.addNotice("图片仍在处理,请稍候发送");
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
230
344
|
const content = inputRef.current.trim();
|
|
231
|
-
updateInput("", 0);
|
|
232
345
|
if (!content)
|
|
233
346
|
return;
|
|
347
|
+
const spans = imageSpans(content);
|
|
348
|
+
if (new Set(spans.map(function id(span) { return span.id; })).size !== spans.length) {
|
|
349
|
+
store.addNotice("图片占位符重复,请删除重复内容");
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
const images = spans.map(function image(span) { return imageDraftsRef.current.get(span.id); });
|
|
353
|
+
const parsed = input.parseInput?.(content) ?? parseSlashAction(content);
|
|
354
|
+
if (parsed.kind === "error") {
|
|
355
|
+
store.addNotice(parsed.message);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (images.length && parsed.action.type !== "submit_prompt") {
|
|
359
|
+
store.addNotice("图片不能附加到命令,请先发送或删除图片");
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
if (parsed.action.type === "submit_prompt") {
|
|
363
|
+
lastSubmittedImagesRef.current = new Map(imageDraftsRef.current);
|
|
364
|
+
historyImagesRef.current = [...historyImagesRef.current, new Map(imageDraftsRef.current)].slice(-100);
|
|
365
|
+
}
|
|
366
|
+
updateInput("", 0);
|
|
367
|
+
imageDraftsRef.current = new Map();
|
|
234
368
|
void (async function dispatchEnteredLine() {
|
|
235
|
-
const parsed = parseSlashAction(content);
|
|
236
|
-
if (parsed.kind === "error") {
|
|
237
|
-
store.addNotice(parsed.message);
|
|
238
|
-
return;
|
|
239
|
-
}
|
|
240
369
|
const prompt = parsed.action.type === "submit_prompt" ? parsed.action.content : undefined;
|
|
241
370
|
if (prompt)
|
|
242
371
|
inputHistoryRef.current = recordTuiInputHistory(inputHistoryRef.current, prompt);
|
|
243
|
-
await dispatchAction(parsed.action, prompt);
|
|
372
|
+
await dispatchAction(parsed.action.type === "submit_prompt" && images.length ? { ...parsed.action, images } : parsed.action, prompt);
|
|
244
373
|
})();
|
|
245
374
|
return;
|
|
246
375
|
}
|
|
247
376
|
if (value && !key.ctrl && !key.meta) {
|
|
248
377
|
const characters = splitTuiInputGraphemes(inputRef.current);
|
|
249
|
-
const
|
|
378
|
+
const inside = imageSpans(inputRef.current).find(function contains(span) { return cursorIndexRef.current > span.start && cursorIndexRef.current < span.end; });
|
|
379
|
+
const cursor = inside?.end ?? cursorIndexRef.current;
|
|
250
380
|
const inserted = splitTuiInputGraphemes(normalizeTuiInputLineEndings(value));
|
|
251
381
|
characters.splice(cursor, 0, ...inserted);
|
|
252
382
|
const nextInput = characters.join("");
|
|
@@ -254,5 +384,8 @@ export function usePromptInput(input) {
|
|
|
254
384
|
updateInput(nextInput, cursor + inserted.length);
|
|
255
385
|
}
|
|
256
386
|
}
|
|
387
|
+
const attachmentNames = [...imageDraftsRef.current.values()].map(function name(image) { return image.name; });
|
|
388
|
+
/** 附件区只投影当前草稿的既有图片名,不复制图片字节或触发采样。 */
|
|
389
|
+
useEffect(function publishAttachments() { input.onAttachmentsChange?.(attachmentNames); }, [attachmentNames.join("\0"), input.onAttachmentsChange]);
|
|
257
390
|
return { input: inputValue, cursorIndex, handleInput };
|
|
258
391
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
/** statusView
|
|
1
|
+
/** statusView异步刷新hook:合并同批/在途刷新,切换和卸载失效旧订阅。 */
|
|
2
2
|
import type { CliController } from "../../controller.js";
|
|
3
3
|
import type { CliStatusView } from "../../types.js";
|
|
4
|
-
/**
|
|
4
|
+
/** 每挂载持有独立取消身份;一次查询期间的新刷新最多合并成一次后续查询。 */
|
|
5
5
|
export declare function useStatusView(controller: CliController): {
|
|
6
6
|
statusView: CliStatusView | undefined;
|
|
7
7
|
refreshStatusView: () => Promise<void>;
|
|
@@ -1,13 +1,40 @@
|
|
|
1
|
-
/** statusView
|
|
2
|
-
import { useState } from "react";
|
|
3
|
-
/**
|
|
1
|
+
/** statusView异步刷新hook:合并同批/在途刷新,切换和卸载失效旧订阅。 */
|
|
2
|
+
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
3
|
+
/** 每挂载持有独立取消身份;一次查询期间的新刷新最多合并成一次后续查询。 */
|
|
4
4
|
export function useStatusView(controller) {
|
|
5
|
-
const [
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
5
|
+
const [state, setState] = useState();
|
|
6
|
+
const lifecycle = useMemo(function createLifecycle() {
|
|
7
|
+
return { active: true, abort: new AbortController(), requested: false, pending: undefined };
|
|
8
|
+
}, [controller]);
|
|
9
|
+
useEffect(function bindStatusLifecycle() {
|
|
10
|
+
lifecycle.active = true;
|
|
11
|
+
if (lifecycle.abort.signal.aborted)
|
|
12
|
+
lifecycle.abort = new AbortController();
|
|
13
|
+
return function cancelStatusLifecycle() {
|
|
14
|
+
lifecycle.active = false;
|
|
15
|
+
lifecycle.requested = false;
|
|
16
|
+
lifecycle.abort.abort();
|
|
17
|
+
};
|
|
18
|
+
}, [lifecycle]);
|
|
19
|
+
const refreshStatusView = useCallback(async function refreshStatusView() {
|
|
20
|
+
if (!lifecycle.active || !controller.getStatusView)
|
|
21
|
+
return;
|
|
22
|
+
lifecycle.requested = true;
|
|
23
|
+
if (!lifecycle.pending) {
|
|
24
|
+
// 微任务合并同次提交触发的刷新,不额外叠加时间节流。
|
|
25
|
+
lifecycle.pending = Promise.resolve().then(async function drainStatusRefreshes() {
|
|
26
|
+
while (lifecycle.active && lifecycle.requested) {
|
|
27
|
+
lifecycle.requested = false;
|
|
28
|
+
try {
|
|
29
|
+
const next = await controller.getStatusView?.({ signal: lifecycle.abort.signal });
|
|
30
|
+
if (next && lifecycle.active && !lifecycle.abort.signal.aborted)
|
|
31
|
+
setState({ controller, value: next });
|
|
32
|
+
}
|
|
33
|
+
catch { /* 查询失败或失效不写入其他Session,也不产生未处理拒绝。 */ }
|
|
34
|
+
}
|
|
35
|
+
}).finally(function releaseStatusRefresh() { lifecycle.pending = undefined; });
|
|
36
|
+
}
|
|
37
|
+
await lifecycle.pending;
|
|
38
|
+
}, [controller, lifecycle]);
|
|
39
|
+
return { statusView: state?.controller === controller ? state.value : undefined, refreshStatusView };
|
|
13
40
|
}
|
|
@@ -14,9 +14,10 @@ export declare function useViewport(input: {
|
|
|
14
14
|
write(chunk: string): void;
|
|
15
15
|
};
|
|
16
16
|
onCopyText?: (text: string) => void;
|
|
17
|
+
onCopyError: () => void;
|
|
17
18
|
}): {
|
|
18
19
|
viewportState: ScrollViewportState;
|
|
19
20
|
selection: TuiTextSelection;
|
|
20
21
|
handleTuiMouseEvent: (event: TuiSgrMouseEvent, wheelNotches: number) => void;
|
|
21
|
-
handleTuiViewportKey: (key: Key) => boolean;
|
|
22
|
+
handleTuiViewportKey: (key: Key, value?: string) => boolean;
|
|
22
23
|
};
|
|
@@ -4,7 +4,7 @@ import { createScrollViewportState, resizeScrollViewport, scrollViewportDown, sc
|
|
|
4
4
|
import { copyTuiSelectedText, getTuiSelectedText, resolveTuiVisualLineOffset, } from "../viewport/selection.js";
|
|
5
5
|
/** 管理备用屏视口的滚动、鼠标事件与文字划选状态。 */
|
|
6
6
|
export function useViewport(input) {
|
|
7
|
-
const { isViewportMode, columns, viewportLines, viewportHeight, stdout, onCopyText } = input;
|
|
7
|
+
const { isViewportMode, columns, viewportLines, viewportHeight, stdout, onCopyText, onCopyError } = input;
|
|
8
8
|
const [selection, setSelection] = useState({});
|
|
9
9
|
const selectionRef = useRef(selection);
|
|
10
10
|
const scrollbarDraggingRef = useRef(false);
|
|
@@ -23,6 +23,10 @@ export function useViewport(input) {
|
|
|
23
23
|
selectionRef.current = next;
|
|
24
24
|
setSelection(next);
|
|
25
25
|
}
|
|
26
|
+
/** 剪贴板失败进入既有通知,不让子进程错误静默丢失。 */
|
|
27
|
+
function copySelection(text) {
|
|
28
|
+
void Promise.resolve().then(function copy() { return onCopyText ? onCopyText(text) : copyTuiSelectedText(text, stdout); }).catch(onCopyError);
|
|
29
|
+
}
|
|
26
30
|
/** 将视口内鼠标坐标转换成时间线来源坐标;固定输入区和滚动条不参与划选。 */
|
|
27
31
|
function resolveTuiSelectionPoint(event) {
|
|
28
32
|
if (event.column >= columns || event.row < 1 || event.row > viewportStateRef.current.viewportHeight)
|
|
@@ -52,12 +56,8 @@ export function useViewport(input) {
|
|
|
52
56
|
updateTuiTextSelection({ ...selectionRef.current, focus: selectionPoint });
|
|
53
57
|
selectionDraggingRef.current = false;
|
|
54
58
|
const text = getTuiSelectedText(viewportLines, selectionPoint ? { ...selectionRef.current, focus: selectionPoint } : selectionRef.current);
|
|
55
|
-
if (text)
|
|
56
|
-
|
|
57
|
-
onCopyText(text);
|
|
58
|
-
else
|
|
59
|
-
copyTuiSelectedText(text, stdout);
|
|
60
|
-
}
|
|
59
|
+
if (text)
|
|
60
|
+
copySelection(text);
|
|
61
61
|
return;
|
|
62
62
|
}
|
|
63
63
|
if (event.released) {
|
|
@@ -85,9 +85,16 @@ export function useViewport(input) {
|
|
|
85
85
|
updateViewportState({ ...current, scrollTop, pinnedToBottom: scrollTop >= maximumTop });
|
|
86
86
|
}
|
|
87
87
|
/** 在真实备用屏中处理半视口与顶底跳转;picker 和审批由前置键位分支优先消费。 */
|
|
88
|
-
function handleTuiViewportKey(key) {
|
|
88
|
+
function handleTuiViewportKey(key, value = "") {
|
|
89
89
|
if (!isViewportMode)
|
|
90
90
|
return false;
|
|
91
|
+
const explicitCopy = value === "[99;6u" || value === "\u001b[99;6u" || Boolean(key.ctrl && key.shift && value.toLowerCase() === "c");
|
|
92
|
+
if (explicitCopy || key.ctrl && (value === "c" || value === "\u0003")) {
|
|
93
|
+
const text = getTuiSelectedText(viewportLines, selectionRef.current);
|
|
94
|
+
if (text)
|
|
95
|
+
copySelection(text);
|
|
96
|
+
return explicitCopy || Boolean(text);
|
|
97
|
+
}
|
|
91
98
|
const current = viewportStateRef.current;
|
|
92
99
|
const jump = Math.max(1, Math.floor(current.viewportHeight / 2));
|
|
93
100
|
if (key.pageUp) {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** 单窗口唯一追加输出所有者:跨会话与resize保持Static挂载,稳定键只输出一次。 */
|
|
2
|
+
import { type ReactNode } from "react";
|
|
3
|
+
interface InlineItem {
|
|
4
|
+
key: string;
|
|
5
|
+
node?: ReactNode;
|
|
6
|
+
sequence?: number;
|
|
7
|
+
render?(after?: number): ReactNode;
|
|
8
|
+
}
|
|
9
|
+
/** 在会话壳之外持有追加列表,避免子会话卸载导致历史重放。 */
|
|
10
|
+
export declare function TuiInlineOutputOwner(props: {
|
|
11
|
+
children: ReactNode;
|
|
12
|
+
}): ReactNode;
|
|
13
|
+
/** 只提交新稳定内容,父所有者存在时不创建第二个Static。 */
|
|
14
|
+
export declare function TuiInlineOutput(props: {
|
|
15
|
+
items: InlineItem[];
|
|
16
|
+
}): ReactNode;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
/** 单窗口唯一追加输出所有者:跨会话与resize保持Static挂载,稳定键只输出一次。 */
|
|
3
|
+
import { createContext, useCallback, useContext, useLayoutEffect, useRef, useState } from "react";
|
|
4
|
+
import { Box, Static } from "ink";
|
|
5
|
+
const InlineOutputContext = createContext(undefined);
|
|
6
|
+
/** 在会话壳之外持有追加列表,避免子会话卸载导致历史重放。 */
|
|
7
|
+
export function TuiInlineOutputOwner(props) {
|
|
8
|
+
const seen = useRef(new Map());
|
|
9
|
+
const [items, setItems] = useState([]);
|
|
10
|
+
const append = useCallback(function append(next) {
|
|
11
|
+
const fresh = [];
|
|
12
|
+
for (const item of next) {
|
|
13
|
+
const previous = seen.current.get(item.key);
|
|
14
|
+
if (seen.current.has(item.key) && (item.sequence === undefined || item.sequence <= (previous ?? -1)))
|
|
15
|
+
continue;
|
|
16
|
+
seen.current.set(item.key, item.sequence);
|
|
17
|
+
fresh.push({ key: `${item.key}:${item.sequence ?? "once"}`, node: item.render ? item.render(previous) : item.node });
|
|
18
|
+
}
|
|
19
|
+
if (fresh.length)
|
|
20
|
+
setItems(function add(current) { return [...current, ...fresh]; });
|
|
21
|
+
}, []);
|
|
22
|
+
return _jsxs(InlineOutputContext.Provider, { value: append, children: [_jsx(Static, { items: items, children: function render(item) { return _jsx(Box, { flexDirection: "column", children: item.node }, item.key); } }), props.children] });
|
|
23
|
+
}
|
|
24
|
+
/** 只提交新稳定内容,父所有者存在时不创建第二个Static。 */
|
|
25
|
+
export function TuiInlineOutput(props) {
|
|
26
|
+
const append = useContext(InlineOutputContext);
|
|
27
|
+
useLayoutEffect(function publish() { append?.(props.items); }, [append, props.items]);
|
|
28
|
+
if (append)
|
|
29
|
+
return null;
|
|
30
|
+
return _jsx(TuiInlineOutputOwner, { children: _jsx(TuiInlineOutput, { ...props }) });
|
|
31
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** 待发送的有界图片副本。 */
|
|
2
|
+
export interface CliDraftImage {
|
|
3
|
+
name: string;
|
|
4
|
+
mimeType: string;
|
|
5
|
+
bytes: Uint8Array;
|
|
6
|
+
gifFirstFrame?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** 使用 STA 剪贴板读取文件列表或截图;普通文本作为文本返回。 */
|
|
9
|
+
export declare function readWindowsClipboard(): Promise<{
|
|
10
|
+
images: CliDraftImage[];
|
|
11
|
+
text?: string;
|
|
12
|
+
}>;
|
|
13
|
+
/** 使用 macOS 自带的 JXA 和 AppKit 按需读取文件列表、位图或普通文本。 */
|
|
14
|
+
export declare function readMacClipboard(): Promise<{
|
|
15
|
+
images: CliDraftImage[];
|
|
16
|
+
text?: string;
|
|
17
|
+
}>;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/** Windows 与 macOS 剪贴板图片摄取:仅读取显式粘贴事件,不后台轮询。 */
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { readFile, stat } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { normalizeWorkImage } from "@autopilot-agent/core";
|
|
7
|
+
const runFile = promisify(execFile);
|
|
8
|
+
/** 使用 STA 剪贴板读取文件列表或截图;普通文本作为文本返回。 */
|
|
9
|
+
export async function readWindowsClipboard() {
|
|
10
|
+
if (process.platform !== "win32")
|
|
11
|
+
return { images: [] };
|
|
12
|
+
const script = `[Console]::OutputEncoding = [Text.Encoding]::UTF8
|
|
13
|
+
Add-Type -AssemblyName System.Windows.Forms
|
|
14
|
+
Add-Type -AssemblyName System.Drawing
|
|
15
|
+
if ([Windows.Forms.Clipboard]::ContainsFileDropList()) {
|
|
16
|
+
@{ kind = 'files'; value = @([Windows.Forms.Clipboard]::GetFileDropList() | ForEach-Object { $_ }) } | ConvertTo-Json -Compress
|
|
17
|
+
} elseif ([Windows.Forms.Clipboard]::ContainsImage()) {
|
|
18
|
+
$image = [Windows.Forms.Clipboard]::GetImage()
|
|
19
|
+
$stream = New-Object IO.MemoryStream
|
|
20
|
+
try { if (([long]$image.Width * [long]$image.Height) -gt 40000000) { throw 'IMAGE_TOO_LARGE' }; $image.Save($stream, [Drawing.Imaging.ImageFormat]::Png); if ($stream.Length -gt 20971520) { throw 'IMAGE_TOO_LARGE' }; @{ kind = 'image'; value = [Convert]::ToBase64String($stream.ToArray()) } | ConvertTo-Json -Compress } finally { $stream.Dispose(); $image.Dispose() }
|
|
21
|
+
} elseif ([Windows.Forms.Clipboard]::ContainsText()) {
|
|
22
|
+
@{ kind = 'text'; value = [Windows.Forms.Clipboard]::GetText() } | ConvertTo-Json -Compress
|
|
23
|
+
} else { @{ kind = 'empty'; value = '' } | ConvertTo-Json -Compress }`;
|
|
24
|
+
const { stdout } = await runFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-STA", "-Command", script], { windowsHide: true, maxBuffer: 29 * 1024 * 1024, timeout: 15_000 });
|
|
25
|
+
const payload = JSON.parse(stdout);
|
|
26
|
+
return normalizeClipboardPayload(payload);
|
|
27
|
+
}
|
|
28
|
+
/** 使用 macOS 自带的 JXA 和 AppKit 按需读取文件列表、位图或普通文本。 */
|
|
29
|
+
export async function readMacClipboard() {
|
|
30
|
+
if (process.platform !== "darwin")
|
|
31
|
+
return { images: [] };
|
|
32
|
+
const script = `ObjC.import('AppKit');
|
|
33
|
+
function exists(value) { var unwrapped = ObjC.unwrap(value); return unwrapped !== null && unwrapped !== undefined; }
|
|
34
|
+
function run() {
|
|
35
|
+
var board = $.NSPasteboard.generalPasteboard;
|
|
36
|
+
var urls = board.readObjectsForClassesOptions($.NSArray.arrayWithObject($.NSURL), $.NSDictionary.dictionaryWithObjectForKey($.NSNumber.numberWithBool(true), $.NSPasteboardURLReadingFileURLsOnlyKey));
|
|
37
|
+
if (exists(urls) && Number(urls.count) > 0) {
|
|
38
|
+
if (Number(urls.count) > 10) throw new Error('TOO_MANY_IMAGES');
|
|
39
|
+
var files = [];
|
|
40
|
+
for (var i = 0; i < Number(urls.count); i++) files.push(ObjC.unwrap(urls.objectAtIndex(i).path));
|
|
41
|
+
return JSON.stringify({kind: 'files', value: files});
|
|
42
|
+
}
|
|
43
|
+
var data = board.dataForType($.NSPasteboardTypePNG);
|
|
44
|
+
if (!exists(data)) data = board.dataForType($.NSPasteboardTypeTIFF);
|
|
45
|
+
if (exists(data)) {
|
|
46
|
+
if (Number(data.length) > 20971520) throw new Error('IMAGE_TOO_LARGE');
|
|
47
|
+
var rep = $.NSBitmapImageRep.imageRepWithData(data);
|
|
48
|
+
if (!exists(rep) || Number(rep.pixelsWide) * Number(rep.pixelsHigh) > 40000000) throw new Error('IMAGE_TOO_LARGE');
|
|
49
|
+
var png = rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $.NSDictionary.dictionary);
|
|
50
|
+
if (!exists(png) || Number(png.length) > 20971520) throw new Error('IMAGE_TOO_LARGE');
|
|
51
|
+
var text = board.stringForType($.NSPasteboardTypeString);
|
|
52
|
+
return JSON.stringify({kind: 'image', value: ObjC.unwrap(png.base64EncodedStringWithOptions(0)), text: exists(text) ? ObjC.unwrap(text) : undefined});
|
|
53
|
+
}
|
|
54
|
+
var text = board.stringForType($.NSPasteboardTypeString);
|
|
55
|
+
return JSON.stringify(exists(text) ? {kind: 'text', value: ObjC.unwrap(text)} : {kind: 'empty', value: ''});
|
|
56
|
+
}`;
|
|
57
|
+
let payload;
|
|
58
|
+
try {
|
|
59
|
+
const { stdout } = await runFile("/usr/bin/osascript", ["-l", "JavaScript", "-e", script], { maxBuffer: 29 * 1024 * 1024, timeout: 15_000 });
|
|
60
|
+
payload = JSON.parse(stdout);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
const stderr = error && typeof error === "object" && "stderr" in error && typeof error.stderr === "string" ? error.stderr : "";
|
|
64
|
+
if (stderr.includes("TOO_MANY_IMAGES"))
|
|
65
|
+
throw new Error("一次最多粘贴 10 张图片");
|
|
66
|
+
if (stderr.includes("IMAGE_TOO_LARGE"))
|
|
67
|
+
throw new Error("图片超过 20 MiB 输入上限");
|
|
68
|
+
throw new Error("剪贴板图片读取或处理失败");
|
|
69
|
+
}
|
|
70
|
+
if (!payload || typeof payload !== "object" || (payload.text !== undefined && typeof payload.text !== "string"))
|
|
71
|
+
throw new Error("剪贴板图片读取或处理失败");
|
|
72
|
+
if (payload.kind === "image" && (typeof payload.value !== "string" || !payload.value.length || payload.value.length > 27_962_028 || payload.value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(payload.value)))
|
|
73
|
+
throw new Error("剪贴板图片读取或处理失败");
|
|
74
|
+
if (payload.kind === "files" && (!Array.isArray(payload.value) || payload.value.some(function invalid(value) { return typeof value !== "string" || !value; })))
|
|
75
|
+
throw new Error("剪贴板图片读取或处理失败");
|
|
76
|
+
if ((payload.kind === "text" || payload.kind === "empty") && typeof payload.value !== "string")
|
|
77
|
+
throw new Error("剪贴板图片读取或处理失败");
|
|
78
|
+
if (!["image", "files", "text", "empty"].includes(String(payload.kind)))
|
|
79
|
+
throw new Error("剪贴板图片读取或处理失败");
|
|
80
|
+
return normalizeClipboardPayload(payload);
|
|
81
|
+
}
|
|
82
|
+
/** 复用同一有界文件读取和图片规范化,保持两平台的输入限制一致。 */
|
|
83
|
+
async function normalizeClipboardPayload(payload) {
|
|
84
|
+
if (payload.kind === "text")
|
|
85
|
+
return { images: [], text: typeof payload.value === "string" ? payload.value : "" };
|
|
86
|
+
const candidates = [];
|
|
87
|
+
if (payload.kind === "image" && typeof payload.value === "string")
|
|
88
|
+
candidates.push({ name: "clipboard.png", mimeType: "image/png", bytes: Buffer.from(payload.value, "base64") });
|
|
89
|
+
if (payload.kind === "files") {
|
|
90
|
+
const files = Array.isArray(payload.value) ? payload.value : [payload.value];
|
|
91
|
+
if (files.length > 10)
|
|
92
|
+
throw new Error("一次最多粘贴 10 张图片");
|
|
93
|
+
for (const file of files) {
|
|
94
|
+
const extension = path.extname(file).toLowerCase();
|
|
95
|
+
const mimeType = extension === ".png" ? "image/png" : extension === ".jpg" || extension === ".jpeg" ? "image/jpeg" : extension === ".webp" ? "image/webp" : extension === ".gif" ? "image/gif" : "";
|
|
96
|
+
if (!mimeType)
|
|
97
|
+
throw new Error("剪贴板包含不支持的文件");
|
|
98
|
+
const info = await stat(file);
|
|
99
|
+
if (!info.isFile() || info.size > 20 * 1024 * 1024)
|
|
100
|
+
throw new Error("图片超过 20 MiB 输入上限");
|
|
101
|
+
const bytes = await readFile(file);
|
|
102
|
+
if (bytes.length !== info.size)
|
|
103
|
+
throw new Error("图片读取失败");
|
|
104
|
+
candidates.push({ name: path.basename(file), mimeType, bytes });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const images = [];
|
|
108
|
+
let total = 0;
|
|
109
|
+
for (const candidate of candidates) {
|
|
110
|
+
const normalized = await normalizeWorkImage(candidate);
|
|
111
|
+
total += normalized.bytes.byteLength;
|
|
112
|
+
if (total > 20 * 1024 * 1024)
|
|
113
|
+
throw new Error("图片总大小超过 20 MiB");
|
|
114
|
+
images.push({ name: candidate.name, mimeType: normalized.mimeType, bytes: normalized.bytes, gifFirstFrame: normalized.gifFirstFrame });
|
|
115
|
+
}
|
|
116
|
+
return { images, ...(typeof payload.text === "string" ? { text: payload.text } : {}) };
|
|
117
|
+
}
|