Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions docs/ai-chat-turbo-engine.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

面向长对话与重度使用的跨平台 AI 聊天增强用户脚本。在受支持的 AI 对话页面上叠加一层轻量增强,解决四类实际痛点:长会话渲染变卡、超长代码块挤占阅读空间、大段文本撑爆输入框、上下文难以迁移到新会话。

当前版本:**0.23.13**
当前版本:**0.23.14**
许可证:**MIT**
运行方式:单文件用户脚本,无外部依赖,无网络请求,不申请任何 GM 权限。

Expand Down Expand Up @@ -167,7 +167,7 @@ ChatGPT 的代码卡片结构较特殊,脚本会向上最多追溯 10 层祖

托盘头部提供「文本转文件」:把输入框里的长文本收进一个 `composer_text_{KB}kb.txt` 并清空输入框;每个文件条目提供「转文本」:把正文放回输入框(已有其他文字时空一行追加)并移除该文件。正文始终原样保留,两个方向可以反复往返,不会因为转换丢失换行或截断内容。

转换方向决定托盘的去留:把文本收进文件后托盘继续显示文件条目;把最后一个文件转回文本、或发送后清空附件时,托盘整块移除,不在输入框上留下只剩「文本转文件」的空壳。纯提示态另有关闭按钮,关掉后同一段文本不再重复提示;抑制记录按文本内容匹配,改字或删到阈值以下即恢复判断。
转换方向决定托盘的去留:把文本收进文件后托盘继续显示文件条目;把最后一个文件转回文本、或发送后清空附件时,托盘整块移除,不在输入框上留下只剩「文本转文件」的空壳。纯提示态同样随发送退场:点站点的发送按钮时立即收起,输入框被站点清空后由追踪循环兜底移除,即使宿主不派发 `input` 事件也不会留下空壳。纯提示态另有关闭按钮,关掉后同一段文本不再重复提示;抑制记录按文本内容匹配,改字或删到阈值以下即恢复判断。

每个虚拟文件条目提供:

Expand Down Expand Up @@ -198,7 +198,8 @@ ChatGPT 的代码卡片结构较特殊,脚本会向上最多追溯 10 层祖
- 不含输入类子节点的单独 `button` / `[role="button"]`
- 顶部已滚出视口上方(`rect.top < 8`)的节点,命中后立即终止向上扩展
- 高度超过 `max(baseRect.height * 3, 320px)` 的巨型容器(通常代表整段对话容器)
- **rAF 持续追踪循环**:以 90ms 间隔调用位置更新,捕捉 `ResizeObserver` 无法感知的纯平移。循环仅在存在虚拟文件时运行。
- **rAF 持续追踪循环**:以 90ms 间隔调用位置更新,捕捉 `ResizeObserver` 无法感知的纯平移。循环在托盘存在期间运行(含纯提示态)。
- **纯提示态复查**:无虚拟文件时,循环用 `value` / `textContent` 做一次廉价长度预检,只有疑似低于阈值才读取 `innerText` 复核;复核为短文本即移除托盘,覆盖「站点发送后静默清空输入框」的路径,且不会为长文本反复强制排版。
- **位置签名去重**:每帧计算 `left|bottom|width|maxHeight` 组合签名,未变化时不写样式,避免打断 CSS 过渡。
- **输入框引用缓存**:仅在失效时才走完整 `getChatInput()`,避免每帧全量查询。
- **`ResizeObserver` 扩展**:同时观察输入框、anchor、以及向上 5 层的祖先及其父节点,覆盖"祖先 wrapper 被附件撑高"的场景。
Expand Down Expand Up @@ -518,6 +519,15 @@ pointerdown → mousedown → pointerup → mouseup → click

## 版本记录

### 0.23.14

**修好消息发出后纯提示态托盘仍挂在输入框上方的问题。**

- **问题。** 输入框里的长文本会让托盘显示「文本转文件」提示;消息发出后站点把输入框清空,但两条清理路径都失效:纯提示态托盘只在 `input` 事件里复查,而多数站点清空输入框时不派发该事件;点击发送按钮的拦截在「无待发送虚拟文件」时直接返回,根本没看到这次点击。结果是空输入框上方一直留着只剩转换按钮的空壳。
- **发送点击即退场。** 发送拦截器在没有虚拟文件、但托盘处于纯提示态时,仍会识别发送控件;命中后收起提示并放行点击,站点的发送行为完全不变。识别的成本只在托盘可见时发生,平时点击不受影响。
- **追踪循环兜底。** 无虚拟文件时,90ms 的托盘追踪循环用 `value` / `textContent` 做廉价长度预检,疑似低于阈值才读 `innerText` 复核;确认为短文本就移除托盘。键盘发送、快捷键发送等不经过点击的路径也会在一个轮询周期内清理干净,同时不会为长文本反复强制排版。
- **测试覆盖。** 新增发送点击收起提示且不拦截、无关点击不动提示、站点静默清空输入框后提示消失、长文本仍在时提示保留四项用例。

### 0.23.13

**修好元宝上 `Enter` 仍然换行的问题:输入法提交后的 `229` 键和发送按钮查找各有一处误判。**
Expand Down
2 changes: 1 addition & 1 deletion scripts/ai-chat-turbo-engine/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { PLATFORM_MATCH_PATTERNS } from "./src/config";
const meta = {
name: "AI Chat Turbo Engine",
namespace: "https://cyojkoy.github.io/Payment/",
version: "0.23.13",
version: "0.23.14",
description: "跨平台 AI 对话加速:常驻统计 + 完整消息提取 + YAML 交接 + 多平台适配 + 长代码折叠 + 自适应脱水 + 推理强度记忆 + 元宝原子工具记忆 + 新对话快捷键覆盖",
author: "Yoko",
updateURL: "https://cdn.jsdelivr.net/gh/CYoJkoY/Yoko-ScriptCat-Scripts@release/ai-chat-turbo-engine.user.js",
Expand Down
17 changes: 16 additions & 1 deletion scripts/ai-chat-turbo-engine/src/core/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export interface SendInterceptDeps {
fuseAndSubmit: (inputElement: HTMLElement) => boolean;
resumeObservers: () => void;
hasActiveFiles: () => boolean;
hasConversionOffer: () => boolean;
dismissConversionOffer: () => void;
isSubmitting: () => boolean;
setSubmitting: (value: boolean) => void;
}
Expand Down Expand Up @@ -57,6 +59,8 @@ export function createSendInterceptUtils(
fuseAndSubmit,
resumeObservers,
hasActiveFiles,
hasConversionOffer,
dismissConversionOffer,
isSubmitting,
setSubmitting,
} = deps;
Expand Down Expand Up @@ -315,7 +319,13 @@ export function createSendInterceptUtils(
}

if (event.type === "click") {
if (!state.virtualFileEnabled || !hasActiveFiles()) return;
if (!state.virtualFileEnabled) return;

const hasFiles = hasActiveFiles();
// A prompt-only tray is just an offer to convert the composer text. A
// send click retires it here: the host clears the composer afterwards
// and often fires no input event, so nothing else would remove it.
if (!hasFiles && !hasConversionOffer()) return;

const eventTarget = event.target;
if (!(eventTarget instanceof Element)) return;
Expand Down Expand Up @@ -350,6 +360,11 @@ export function createSendInterceptUtils(

if (!sendControl) return;

if (!hasFiles) {
dismissConversionOffer();
return;
}

const input = composer.getChatInput();
if (!input) return;

Expand Down
2 changes: 2 additions & 0 deletions scripts/ai-chat-turbo-engine/src/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,8 @@ export function initializeEngine(): void {
codeBlocks.observeCodeLayout();
},
hasActiveFiles: () => virtualFiles.activeFileCount() > 0,
hasConversionOffer: () => virtualFiles.hasConversionOffer(),
dismissConversionOffer: () => virtualFiles.dismissConversionOffer(),
isSubmitting: () => isSubmitting,
setSubmitting: (value) => {
isSubmitting = value;
Expand Down
67 changes: 61 additions & 6 deletions scripts/ai-chat-turbo-engine/src/ui/virtual-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ export interface VirtualFileUtils {
clearFiles(): void;
activeFileCount(): number;
isTrayDirty(): boolean;
/** True while the tray holds only the long-text conversion offer. */
hasConversionOffer(): boolean;
/** Retire the conversion offer because the message is being sent. */
dismissConversionOffer(): void;
handlePasteIntercept(event: ClipboardEvent): void;
fuseAndSubmit(inputElement: HTMLElement): boolean;
}
Expand Down Expand Up @@ -127,13 +131,27 @@ export function createVirtualFileUtils(
* then dropped unless the new composer still asks for a conversion,
* so a detached editor cannot leave the tray behind.
*/
if (activeVirtualFiles.length === 0 && !trayInputIsUsable()) {
const input = composer.getChatInput();
if (input === null || !refreshConversionOffer(input)) {
removeVirtualFileTray();
return;
if (activeVirtualFiles.length === 0) {
const cached = virtualFileTrayCachedInput;
if (!trayInputIsUsable()) {
const input = composer.getChatInput();
if (input === null || !refreshConversionOffer(input)) {
removeVirtualFileTray();
return;
}
virtualFileTrayCachedInput = input;
} else if (cached && composerMayBeBelowThreshold(cached)) {
/*
* Sending clears the composer on the host side, and several hosts
* never dispatch an input event for that change. Without a
* re-check the conversion offer would keep hanging above an empty
* box, so sweep the prompt-only tray while it is on screen.
*/
if (!refreshConversionOffer(cached)) {
removeVirtualFileTray();
return;
}
}
virtualFileTrayCachedInput = input;
}

positionVirtualFileTray();
Expand Down Expand Up @@ -383,6 +401,41 @@ export function createVirtualFileUtils(
return text !== conversionDismissedText;
}

/**
* Cheap pre-check for the periodic sweep: a textarea value or raw
* `textContent` needs no layout, so only a composer that looks short pays
* for the `innerText` read inside `refreshConversionOffer`.
*/
function composerMayBeBelowThreshold(input: HTMLElement): boolean {
const raw =
input instanceof HTMLTextAreaElement || input instanceof HTMLInputElement
? input.value
: (input.textContent ?? "");
// Trimming only shortens the text, so a raw string below the threshold
// answers without copying a long composer on every tick.
if (raw.length < VIRTUAL_FILE_THRESHOLD) return true;
return raw.trim().length < VIRTUAL_FILE_THRESHOLD;
}

function hasConversionOffer(): boolean {
if (activeVirtualFiles.length > 0) return false;
const tray = document.getElementById("ai-turbo-vf-tray");
return tray !== null && tray.isConnected;
}

/**
* The user just sent the message the offer pointed at, so the tray must not
* survive the send. The text is remembered as dismissed in case the host
* echoes the old content back with an input event.
*/
function dismissConversionOffer(): void {
if (!hasConversionOffer()) return;
conversionDismissedText = readComposerText(
composer.getChatInput(),
).trim();
removeVirtualFileTray();
}

/** Drop the tray and its layout tracking; nothing is left on the page. */
function removeVirtualFileTray(): void {
const current = document.getElementById("ai-turbo-vf-tray");
Expand Down Expand Up @@ -863,6 +916,8 @@ export function createVirtualFileUtils(
clearFiles,
activeFileCount,
isTrayDirty,
hasConversionOffer,
dismissConversionOffer,
handlePasteIntercept,
handleComposerInput,
fuseAndSubmit,
Expand Down
59 changes: 59 additions & 0 deletions tests/ai-chat-turbo-send.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ interface FixtureOptions {
platform?: PlatformDefinition;
input?: HTMLElement;
hasFiles?: boolean;
hasConversionOffer?: boolean;
virtualFileEnabled?: boolean;
}

Expand All @@ -30,6 +31,8 @@ interface SendFixture {
utils: SendInterceptUtils;
fuseAndSubmit: ReturnType<typeof vi.fn<(input: HTMLElement) => boolean>>;
resumeObservers: ReturnType<typeof vi.fn<() => void>>;
dismissConversionOffer: ReturnType<typeof vi.fn<() => void>>;
clickSendButton(): MouseEvent;
isSubmitting: () => boolean;
press(init?: KeyInit, target?: EventTarget): KeyboardEvent;
type(init: InputEventInit, target?: EventTarget): InputEvent;
Expand Down Expand Up @@ -89,6 +92,7 @@ function createFixture(options: FixtureOptions = {}): SendFixture {
let submitting = false;
const fuseAndSubmit = vi.fn<(input: HTMLElement) => boolean>(() => true);
const resumeObservers = vi.fn<() => void>();
const dismissConversionOffer = vi.fn<() => void>();

const utils = createSendInterceptUtils({
currentPlatform: platform,
Expand All @@ -98,13 +102,29 @@ function createFixture(options: FixtureOptions = {}): SendFixture {
fuseAndSubmit,
resumeObservers,
hasActiveFiles: () => options.hasFiles === true,
hasConversionOffer: () => options.hasConversionOffer === true,
dismissConversionOffer,
isSubmitting: () => submitting,
setSubmitting: (value: boolean) => {
submitting = value;
},
});
utils.bindCompositionTracking(window);

function clickSendButton(): MouseEvent {
const event = new MouseEvent("click", {
bubbles: true,
cancelable: true,
});
const handler = (received: Event): void => {
utils.handleSendIntercept(received as MouseEvent);
};
sendButton.addEventListener("click", handler);
sendButton.dispatchEvent(event);
sendButton.removeEventListener("click", handler);
return event;
}

function press(init: KeyInit = {}, target: EventTarget = input): KeyboardEvent {
const event = new KeyboardEvent("keydown", {
key: "Enter",
Expand Down Expand Up @@ -153,6 +173,8 @@ function createFixture(options: FixtureOptions = {}): SendFixture {
utils,
fuseAndSubmit,
resumeObservers,
dismissConversionOffer,
clickSendButton,
isSubmitting: () => submitting,
press,
type,
Expand Down Expand Up @@ -441,4 +463,41 @@ describe("send intercept", () => {
window.removeEventListener("keydown", onSoft);
expect(softSeen).toBe(true);
});

it("retires a prompt-only conversion offer on a send click", () => {
const fixture = createFixture({
platform: PLATFORMS.chatgpt,
hasConversionOffer: true,
});

const event = fixture.clickSendButton();

expect(fixture.dismissConversionOffer).toHaveBeenCalledTimes(1);
// The click must reach the site: the offer never owned the send.
expect(event.defaultPrevented).toBe(false);
expect(fixture.fuseAndSubmit).not.toHaveBeenCalled();
expect(fixture.composer.triggerSendButton).not.toHaveBeenCalled();
expect(fixture.isSubmitting()).toBe(false);
});

it("leaves unrelated clicks alone when only the offer is showing", () => {
const fixture = createFixture({
platform: PLATFORMS.chatgpt,
hasConversionOffer: true,
});
// Not a send-like control, so the offer must stay put.
const elsewhere = document.createElement("div");
document.body.append(elsewhere);

const event = new MouseEvent("click", { bubbles: true, cancelable: true });
const handler = (received: Event): void => {
fixture.utils.handleSendIntercept(received as MouseEvent);
};
elsewhere.addEventListener("click", handler);
elsewhere.dispatchEvent(event);
elsewhere.removeEventListener("click", handler);

expect(fixture.dismissConversionOffer).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(false);
});
});
32 changes: 32 additions & 0 deletions tests/ai-chat-turbo-virtual-files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,38 @@ describe("virtual file tray conversion", () => {
expect(tray()).toBeNull();
});

it("drops a prompt-only tray when a send clears the composer silently", async () => {
// A painted composer keeps the cached node usable, which is exactly the
// path a send takes: the host empties the box without any input event.
fixture.textarea.getBoundingClientRect = () =>
({ top: 500, left: 40, width: 720, height: 120 }) as DOMRect;
fixture.textarea.getClientRects = () =>
[fixture.textarea.getBoundingClientRect()] as unknown as DOMRectList;

fixture.textarea.value = LONG_TEXT;
fixture.files.handleComposerInput(fixture.textarea);
expect(tray()).not.toBeNull();

fixture.textarea.value = "";
await new Promise((resolve) => setTimeout(resolve, 160));

expect(tray()).toBeNull();
expect(fixture.files.isTrayDirty()).toBe(false);
});

it("keeps the conversion offer while the long text stays put", async () => {
fixture.textarea.getBoundingClientRect = () =>
({ top: 500, left: 40, width: 720, height: 120 }) as DOMRect;
fixture.textarea.getClientRects = () =>
[fixture.textarea.getBoundingClientRect()] as unknown as DOMRectList;

fixture.textarea.value = LONG_TEXT;
fixture.files.handleComposerInput(fixture.textarea);
await new Promise((resolve) => setTimeout(resolve, 160));

expect(tray()).not.toBeNull();
});

it("drops the tray when the host swaps in a fresh empty composer", async () => {
fixture.textarea.value = LONG_TEXT;
fixture.files.handleComposerInput(fixture.textarea);
Expand Down
Loading