Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
--- a/apps/desktop/native/region-screenshot/macos-snapshot.swift
+++ b/apps/desktop/native/region-screenshot/macos-snapshot.swift
@@ -257,6 +257,10 @@
}
}
+// AppKit's window hit-testing needs an application connection even in this
+// stdin-driven helper; without it windowNumber(at:) returns 0 for real windows.
+// Stay a background-only process: no Dock entry, activation or app event loop.
+NSApplication.shared.setActivationPolicy(.prohibited)
setvbuf(stdout, nil, _IOLBF, 0)
while let line = readLine() {
guard let data = line.data(using: .utf8),
--- a/apps/desktop/src/renderer/features/region-screenshot/LiveCapturePanel.tsx
+++ b/apps/desktop/src/renderer/features/region-screenshot/LiveCapturePanel.tsx
@@ -92,7 +92,8 @@
state.startedAt = performance.now(); state.elapsed = 0;
state.recorder = new CaptureRecorder(state.canvas!, begin.mode === 'gif' ? 'gif' : 'webm', () => { setStatus('limit'); void finish(); });
}
- state.recorder.add(currentTime());
+ await state.recorder.add(currentTime());
+ if (!state.active || state.phase !== 'capturing') return;
setElapsed(Math.floor(currentTime() / 1000) * 1000);
if (currentTime() >= MAX_RECORDING_MS) { setStatus('limit'); queueMicrotask(() => void finish()); }
}
--- a/apps/desktop/src/renderer/features/region-screenshot/Magnifier.tsx
+++ b/apps/desktop/src/renderer/features/region-screenshot/Magnifier.tsx
@@ -55,8 +55,11 @@
const canvas = canvasRef.current;
if (!canvas || !frame) return;
const dpr = window.devicePixelRatio || 1;
- canvas.width = Math.round(VIEW * dpr);
- canvas.height = Math.round(VIEW * dpr);
+ const pixels = Math.round(VIEW * dpr);
+ // Assigning even an unchanged size resets the backing store and context.
+ // Pointer movement only needs a repaint; resize when the density changes.
+ if (canvas.width !== pixels) canvas.width = pixels;
+ if (canvas.height !== pixels) canvas.height = pixels;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
--- a/apps/desktop/src/renderer/features/region-screenshot/captureRecorder.test.ts
+++ b/apps/desktop/src/renderer/features/region-screenshot/captureRecorder.test.ts
@@ -1,6 +1,7 @@
import { afterEach, expect, it, vi } from 'vitest';
import { CaptureRecorder } from './captureRecorder';
import { finalizeWebmDuration } from './webmDuration';
+import { GifEncoding, type GifRequest } from './gifEncoding';
// Real playback reported Infinity and could not show a timeline. Existing tests
// only decoded pixels. Minimal streaming WebM Info without Duration; tier: unit.
@@ -17,7 +18,7 @@
// Unit regression: the UI matrix produced an empty short WebM that was reported
// as saved. Exercise the encoder's real finish boundary with an empty browser
// stop event; geometry and browser playback tests do not cover this outcome.
-afterEach(() => vi.unstubAllGlobals());
+afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); });
it('rejects a recording when the browser stops without encoded frames', async () => {
class EmptyRecorder {
@@ -31,7 +32,7 @@
const track = { stop: vi.fn(), requestFrame: vi.fn() };
const canvas = { captureStream: () => ({ getTracks: () => [track], getVideoTracks: () => [track] }) } as unknown as HTMLCanvasElement;
const recorder = new CaptureRecorder(canvas, 'webm', () => {});
- recorder.add(0);
+ await recorder.add(0);
await expect(recorder.finish(1)).rejects.toThrow('No video frames were encoded');
expect(track.stop).toHaveBeenCalled();
});
@@ -67,17 +68,84 @@
const canvas = { width: 2, height: 1, getContext: () => ({
getImageData: () => ({ data: pixels.slice() }),
}) } as unknown as HTMLCanvasElement;
- const recorder = new CaptureRecorder(canvas, 'gif', () => {});
- recorder.add(0);
- recorder.add(100);
- recorder.add(200);
+ const recorder = new CaptureRecorder(canvas, 'gif', () => {}, () => new TestGifWorker() as unknown as Worker);
+ await recorder.add(0);
+ await recorder.add(100);
+ await recorder.add(200);
pixels.set([0, 0, 255, 255], 4);
- recorder.add(300);
+ await recorder.add(300);
recorder.pause(400);
recorder.resume();
- recorder.add(400);
- recorder.add(500);
+ await recorder.add(400);
+ await recorder.add(500);
const bytes = await recorder.finish(600);
expect(frameDelays(bytes)).toEqual([300, 100, 200]);
recorder.dispose();
});
+
+// The unit transport delivers the actual encoder's results; the Electron benchmark
+// exercises the real Worker separately. Structured clone models buffer ownership.
+class TestGifWorker {
+ onmessage: Worker['onmessage'] = null;
+ onerror: Worker['onerror'] = null;
+ onmessageerror: Worker['onmessageerror'] = null;
+ terminated = false;
+ messages: GifRequest[] = [];
+ private encoder: GifEncoding | null = null;
+ constructor(private readonly automatic = true) {}
+ postMessage(message: GifRequest, transfer: Transferable[] = []) {
+ this.messages.push(structuredClone(message, { transfer }));
+ if (this.automatic) queueMicrotask(() => this.deliver());
+ }
+ deliver() {
+ if (this.terminated) return;
+ for (const data of this.messages.splice(0)) {
+ if (data.kind === 'init') this.encoder = new GifEncoding(data.width, data.height);
+ else if (data.kind === 'pause') this.encoder!.pause(data.at);
+ else {
+ const response = data.kind === 'add'
+ ? { kind: 'added', id: data.id, limit: this.encoder!.add(data.pixels, data.at) }
+ : { kind: 'finished', id: data.id, bytes: this.encoder!.finish(data.at) };
+ this.onmessage?.call(this as unknown as Worker, { data: response } as MessageEvent);
+ }
+ }
+ }
+ terminate() { this.terminated = true; }
+}
+
+const gifCanvas = () => ({ width: 2, height: 1, getContext: () => ({
+ getImageData: () => ({ data: new Uint8ClampedArray([255, 0, 0, 255, 0, 0, 255, 255]) }),
+}) }) as unknown as HTMLCanvasElement;
+
+// Worker migration creates new timing boundaries. Existing synchronous GIF tests
+// cannot cover pause/finish during encoding, cancellation or worker failure. Unit:
+// one accepted 2x1 frame must settle before finish, without buffering a second frame.
+it('orders pause and finish behind an in-flight GIF frame and bounds the queue', async () => {
+ const worker = new TestGifWorker(false);
+ const recorder = new CaptureRecorder(gifCanvas(), 'gif', () => {}, () => worker as unknown as Worker);
+ const adding = recorder.add(0);
+ await expect(recorder.add(100)).rejects.toThrow('still in flight');
+ recorder.pause(200);
+ const finishing = recorder.finish(300);
+ worker.deliver();
+ await adding;
+ worker.deliver();
+ expect(frameDelays(await finishing)).toEqual([200]);
+ expect(worker.terminated).toBe(true);
+ await expect(recorder.finish(400)).rejects.toThrow('already stopped');
+});
+
+it.each(['cancel', 'error', 'messageerror', 'timeout'] as const)('settles a pending GIF frame on %s and releases its worker', async (cause) => {
+ vi.useFakeTimers();
+ const worker = new TestGifWorker(false);
+ const recorder = new CaptureRecorder(gifCanvas(), 'gif', () => {}, () => worker as unknown as Worker);
+ const rejected = expect(recorder.add(0)).rejects.toThrow(/disposed|failed|timed out/);
+ if (cause === 'cancel') recorder.dispose();
+ else if (cause === 'error') worker.onerror?.call(worker as unknown as Worker, {} as ErrorEvent);
+ else if (cause === 'messageerror') worker.onmessageerror?.call(worker as unknown as Worker, {} as MessageEvent);
+ else await vi.advanceTimersByTimeAsync(15_000);
+ await rejected;
+ expect(worker.terminated).toBe(true);
+ expect(vi.getTimerCount()).toBe(0);
+ recorder.dispose();
+});
--- a/apps/desktop/src/renderer/features/region-screenshot/captureRecorder.ts
+++ b/apps/desktop/src/renderer/features/region-screenshot/captureRecorder.ts
@@ -1,20 +1,20 @@
-import { GIFEncoder, applyPalette, quantize } from 'gifenc';
+import { GifWorker } from './gifWorker';
import { MAX_RECORDING_BYTES } from '../../../shared/regionCapture';
import { finalizeWebmDuration } from './webmDuration';
/** Bounded, local-only encoding. Source pixels are supplied by the host's selected region. */
export class CaptureRecorder {
- private readonly gif;
+ private readonly gif: GifWorker | null;
+ private inFlight: Promise<void> | null = null;
private readonly recorder: MediaRecorder | null;
private readonly stream: MediaStream | null;
private readonly chunks: Blob[] = [];
private bytes = 0;
- private previous: { pixels: Uint8ClampedArray; index: Uint8Array; palette: number[][]; at: number } | null = null;
private stopped = false;
private failure: Error | null = null;
- constructor(private readonly canvas: HTMLCanvasElement, readonly format: 'webm' | 'gif', private readonly onLimit: () => void) {
- this.gif = format === 'gif' ? GIFEncoder() : null;
+ constructor(private readonly canvas: HTMLCanvasElement, readonly format: 'webm' | 'gif', private readonly onLimit: () => void, createGifWorker?: () => Worker) {
+ this.gif = format === 'gif' ? new GifWorker(canvas.width, canvas.height, createGifWorker) : null;
this.stream = format === 'webm' ? canvas.captureStream(0) : null;
if (this.stream) {
const mimeType = ['video/webm;codecs=vp9', 'video/webm;codecs=vp8', 'video/webm'].find((type) => MediaRecorder.isTypeSupported(type));
@@ -36,33 +36,23 @@
} else this.recorder = null;
}
- add(at: number): void {
- if (this.stopped) return;
+ add(at: number): Promise<void> {
+ if (this.stopped) return Promise.resolve();
+ if (this.inFlight) return Promise.reject(new Error('Recording frame still in flight'));
if (this.recorder) {
(this.stream!.getVideoTracks()[0] as CanvasCaptureMediaStreamTrack).requestFrame();
- } else if (this.gif) {
- const pixels = this.canvas.getContext('2d', { willReadFrequently: true })!.getImageData(0, 0, this.canvas.width, this.canvas.height);
- // Hold identical frames until the next change, pause or finish. Exact RGBA
- // comparison preserves small cursor/text changes and the full hold duration.
- if (this.previous && samePixels(this.previous.pixels, pixels.data)) return;
- this.flushGif(at);
- const palette = quantize(pixels.data, 256, { format: 'rgb444' });
- this.previous = { pixels: pixels.data, palette, index: applyPalette(pixels.data, palette, 'rgb444'), at };
- if (this.gif.bytesView().length > MAX_RECORDING_BYTES - 4 * 1024 * 1024) this.onLimit();
+ return Promise.resolve();
}
- }
-
- private flushGif(at: number): void {
- if (!this.previous || !this.gif) return;
- this.gif.writeFrame(this.previous.index, this.canvas.width, this.canvas.height, {
- palette: this.previous.palette, delay: Math.max(20, at - this.previous.at), repeat: 0,
- });
- this.previous = null;
+ const pixels = this.canvas.getContext('2d', { willReadFrequently: true })!.getImageData(0, 0, this.canvas.width, this.canvas.height);
+ this.inFlight = this.gif!.add(pixels.data, at).then((limit) => {
+ if (limit && !this.stopped) this.onLimit();
+ }).finally(() => { this.inFlight = null; });
+ return this.inFlight;
}
pause(at: number): void {
if (this.recorder?.state === 'recording') this.recorder.pause();
- this.flushGif(at);
+ this.gif?.pause(at);
}
resume(): void { if (this.recorder?.state === 'paused') this.recorder.resume(); }
@@ -82,11 +72,8 @@
if (bytes.length > MAX_RECORDING_BYTES) throw new Error('Recording size limit');
return bytes;
}
- this.flushGif(at);
- this.gif!.finish();
- const bytes = this.gif!.bytes();
- if (bytes.length > MAX_RECORDING_BYTES) throw new Error('Recording size limit');
- return bytes;
+ await this.inFlight;
+ return this.gif!.finish(at);
}
dispose(): void {
@@ -94,14 +81,6 @@
if (this.recorder && this.recorder.state !== 'inactive') this.recorder.stop();
this.stream?.getTracks().forEach((track) => track.stop());
this.chunks.length = 0;
- this.previous = null;
+ this.gif?.dispose();
}
}
-
-function samePixels(a: Uint8ClampedArray, b: Uint8ClampedArray): boolean {
- if (a.length !== b.length) return false;
- const left = new Uint32Array(a.buffer, a.byteOffset, a.length / 4);
- const right = new Uint32Array(b.buffer, b.byteOffset, b.length / 4);
- for (let i = 0; i < left.length; i++) if (left[i] !== right[i]) return false;
- return true;
-}
--- /dev/null
+++ b/apps/desktop/src/renderer/features/region-screenshot/gifEncoding.ts
@@ -0,0 +1,53 @@
+import { GIFEncoder, applyPalette, quantize } from 'gifenc';
+import { MAX_RECORDING_BYTES } from '../../../shared/regionCapture';
+
+/** The original GIF algorithm, isolated from Canvas and scheduling. One instance
+ * owns one recording; no shared palettes, frame dropping or quality changes. */
+export class GifEncoding {
+ private readonly gif = GIFEncoder();
+ private previous: { pixels: Uint8ClampedArray; index: Uint8Array; palette: number[][]; at: number } | null = null;
+
+ constructor(private readonly width: number, private readonly height: number) {}
+
+ add(pixels: Uint8ClampedArray, at: number): boolean {
+ if (this.previous && samePixels(this.previous.pixels, pixels)) return false;
+ this.pause(at);
+ const palette = quantize(pixels, 256, { format: 'rgb444' });
+ this.previous = { pixels, palette, index: applyPalette(pixels, palette, 'rgb444'), at };
+ return this.gif.bytesView().length > MAX_RECORDING_BYTES - 4 * 1024 * 1024;
+ }
+
+ pause(at: number): void {
+ if (!this.previous) return;
+ this.gif.writeFrame(this.previous.index, this.width, this.height, {
+ palette: this.previous.palette, delay: Math.max(20, at - this.previous.at), repeat: 0,
+ });
+ this.previous = null;
+ }
+
+ finish(at: number): Uint8Array<ArrayBuffer> {
+ this.pause(at);
+ this.gif.finish();
+ const bytes = this.gif.bytes();
+ if (bytes.length > MAX_RECORDING_BYTES) throw new Error('Recording size limit');
+ return bytes;
+ }
+}
+
+function samePixels(a: Uint8ClampedArray, b: Uint8ClampedArray): boolean {
+ if (a.length !== b.length) return false;
+ const left = new Uint32Array(a.buffer, a.byteOffset, a.length / 4);
+ const right = new Uint32Array(b.buffer, b.byteOffset, b.length / 4);
+ for (let i = 0; i < left.length; i++) if (left[i] !== right[i]) return false;
+ return true;
+}
+
+export type GifRequest =
+ | { kind: 'init'; width: number; height: number }
+ | { kind: 'add'; id: number; pixels: Uint8ClampedArray<ArrayBuffer>; at: number }
+ | { kind: 'pause'; at: number }
+ | { kind: 'finish'; id: number; at: number };
+export type GifResponse =
+ | { kind: 'added'; id: number; limit: boolean }
+ | { kind: 'finished'; id: number; bytes: Uint8Array<ArrayBuffer> }
+ | { kind: 'error'; message: string };
--- /dev/null
+++ b/apps/desktop/src/renderer/features/region-screenshot/gifEncoding.worker.ts
@@ -0,0 +1,23 @@
+import { GifEncoding, type GifRequest, type GifResponse } from './gifEncoding';
+
+let encoder: GifEncoding | null = null;
+const send = (response: GifResponse, transfer: Transferable[] = []) => (self as unknown as Worker).postMessage(response, transfer);
+
+// A worker processes these messages in order. Pause cannot overtake an accepted
+// frame, and finish cannot overtake pause, even while encoding blocks this thread.
+self.onmessage = ({ data }: MessageEvent<GifRequest>) => {
+ try {
+ if (data.kind === 'init') encoder = new GifEncoding(data.width, data.height);
+ else if (!encoder) throw new Error('GIF encoder unavailable');
+ else if (data.kind === 'add') send({ kind: 'added', id: data.id, limit: encoder.add(data.pixels, data.at) });
+ else if (data.kind === 'pause') encoder.pause(data.at);
+ else {
+ const bytes = encoder.finish(data.at);
+ send({ kind: 'finished', id: data.id, bytes }, [bytes.buffer]);
+ encoder = null;
+ }
+ } catch (error) {
+ encoder = null;
+ send({ kind: 'error', message: error instanceof Error ? error.message : 'GIF encoding failed' });
+ }
+};
--- /dev/null
+++ b/apps/desktop/src/renderer/features/region-screenshot/gifWorker.ts
@@ -0,0 +1,71 @@
+import EncodingWorker from './gifEncoding.worker?worker';
+import type { GifRequest, GifResponse } from './gifEncoding';
+
+/** At most one frame is in flight. Pixels and final bytes are transferred, not
+ * cloned. Cancelling terminates work immediately and settles the awaiting sample. */
+export class GifWorker {
+ private readonly worker: Worker;
+ private sequence = 0;
+ private failure: Error | null = null;
+ private pending: { id: number; resolve: (response: GifResponse) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> } | null = null;
+
+ constructor(width: number, height: number, createWorker = () => new EncodingWorker()) {
+ this.worker = createWorker();
+ this.worker.onmessage = ({ data }: MessageEvent<GifResponse>) => {
+ if (data.kind === 'error') { this.fail(new Error(data.message)); return; }
+ if (this.pending?.id !== data.id) return;
+ const pending = this.pending;
+ this.pending = null;
+ clearTimeout(pending.timer);
+ pending.resolve(data);
+ };
+ this.worker.onerror = () => this.fail(new Error('GIF worker failed'));
+ this.worker.onmessageerror = () => this.fail(new Error('GIF worker response failed'));
+ try { this.worker.postMessage({ kind: 'init', width, height } satisfies GifRequest); }
+ catch (error) { this.worker.terminate(); throw error; }
+ }
+
+ private request(message: GifRequest & { id: number }, transfer: Transferable[] = []): Promise<GifResponse> {
+ if (this.failure) return Promise.reject(this.failure);
+ if (this.pending) return Promise.reject(new Error('GIF frame still in flight'));
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => this.fail(new Error('GIF encoding timed out')), 15_000);
+ this.pending = { id: message.id, resolve, reject, timer };
+ try { this.worker.postMessage(message, transfer); }
+ catch (error) { this.fail(error instanceof Error ? error : new Error('GIF worker unavailable')); }
+ });
+ }
+
+ async add(pixels: Uint8ClampedArray<ArrayBuffer>, at: number): Promise<boolean> {
+ const result = await this.request({ kind: 'add', id: ++this.sequence, pixels, at }, [pixels.buffer]);
+ if (result.kind !== 'added') throw new Error('Invalid GIF frame response');
+ return result.limit;
+ }
+
+ pause(at: number): void {
+ if (this.failure) return;
+ try { this.worker.postMessage({ kind: 'pause', at } satisfies GifRequest); }
+ catch (error) { this.fail(error instanceof Error ? error : new Error('GIF worker unavailable')); }
+ }
+
+ async finish(at: number): Promise<Uint8Array<ArrayBuffer>> {
+ try {
+ const result = await this.request({ kind: 'finish', id: ++this.sequence, at });
+ if (result.kind !== 'finished') throw new Error('Invalid GIF finish response');
+ return result.bytes;
+ } finally { this.dispose(); }
+ }
+
+ private fail(error: Error): void {
+ this.failure ??= error;
+ this.worker.terminate();
+ if (this.pending) {
+ const pending = this.pending;
+ this.pending = null;
+ clearTimeout(pending.timer);
+ pending.reject(this.failure);
+ }
+ }
+
+ dispose(): void { this.fail(new Error('GIF recording disposed')); }
+}
--- a/apps/desktop/src/shared/scrollCapture.ts
+++ b/apps/desktop/src/shared/scrollCapture.ts
@@ -82,6 +82,7 @@
}
const rowErrors = Array.from({ length: height }, (_, y) => errorAt(previous, next, y, y, columns));
if (rowErrors.every((error) => error < 2)) return { kind: 'same' };
+ const mostlyStationary = rowErrors.filter((error) => error < 2).length / height >= 0.9;
let header = 0;
let footer = 0;
const fixedLimit = Math.floor(height / 3);
@@ -102,10 +103,15 @@
for (let sample = 0; sample < rows; sample++) {
const y = start + Math.floor((sample / rows) * overlap);
sum += errorAt(previous, next, y + offset, y, columns);
- // Errors are nonnegative. Once a reliable candidate exists, an offset
- // already outside its ambiguity margin can neither win nor invalidate it.
- // Keep searching all offsets, but stop reading rows for this loser.
- if (bestScore <= 3 && sum / rows > bestScore + Math.max(0.15, bestScore * 0.5)) break;
+ // Errors are nonnegative: this partial mean is a lower bound. An accepted
+ // score is <= 3 and its largest ambiguity margin is 1.5, so a candidate
+ // already above 4.5 cannot win or invalidate any accepted match. Prune it
+ // even before finding a winner (especially valuable for unrelated frames).
+ // Keep full scores for mostly-stationary frames: their zero-motion winner
+ // may intentionally be accepted above 3, so its ordering still matters.
+ const cutoff = bestScore <= 3 ? bestScore + Math.max(0.15, bestScore * 0.5)
+ : mostlyStationary ? Infinity : 4.5;
+ if (sum / rows > cutoff) break;
}
const score = sum / rows;
candidates.push({ offset, score });
@@ -117,7 +123,7 @@
const reverse = matchSampledFrames(next, previous, false);
return reverse.kind === 'append' ? { ...reverse, kind: 'prepend', offset: -reverse.offset } : { kind: 'unmatched' };
}
- if (best?.offset === 0 && (best.score <= 3 || rowErrors.filter((error) => error < 2).length / height >= 0.9)) return { kind: 'same' };
+ if (best?.offset === 0 && (best.score <= 3 || mostlyStationary)) return { kind: 'same' };
if (!best || best.offset <= 0 || best.score > 3) return { kind: 'unmatched' };
const rival = candidates.find((candidate) => Math.abs(candidate.offset - best.offset) > 2);
// White space dilutes the mean error on text pages. Compare relative confidence: