From b6c2de9f9277c49370644eed37169dc65b3e6279 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:09:11 +0000 Subject: [PATCH 01/83] fix(codex): index a new account home before bridging history into it (#22971) * fix(codex): index a new account home before bridging history into it Codex indexes every rollout present when it first creates its state DB, and the TUI gives up after 30s, so large histories broke a new account's launch. Fixes #20669 * test(codex): keep the account migration test from starting the real Codex binary Selecting an account starts the history bridge, which spawned codex app-server on the fixture homes and raced the test's temp-dir cleanup. * fix(codex): index a new account's most recent bridged history first Indexing a large history takes minutes, and Codex's /resume hides unindexed threads once a directory has any indexed one, so recent conversations stayed missing until the heal reached them in directory-listing order. * test(codex): cover the history bridge's quit, no-history and failed-link guards Drop the stop check before creating the state DB: it ran in the same tick as the check at bridge start, so it could never observe a quit. * test(codex): make the account heal tests fail closed instead of reaching a real codex Fake invocations now point at a nonexistent binary and a throwaway CODEX_HOME, and cover per-home failure memory and a session that fails during quit. --------- Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> --- ...home-service-per-account-migration.test.ts | 14 + .../codex-account-session-bridge.test.ts | 306 ++++++++++++++++-- .../codex/codex-account-session-bridge.ts | 128 +++++++- .../codex-account-session-index-heal.test.ts | 306 ++++++++++++++++++ .../codex/codex-account-session-index-heal.ts | 122 +++++++ .../codex-index-heal-binary-contract.test.ts | 42 ++- .../codex/codex-session-index-heal-state.ts | 18 +- .../codex/codex-session-index-heal.test.ts | 33 ++ src/main/codex/codex-session-index-heal.ts | 204 +++++++----- src/main/codex/codex-state-db-test-fixture.ts | 14 + src/main/codex/codex-state-db.test.ts | 42 ++- src/main/codex/codex-state-db.ts | 37 ++- src/main/startup/main-process-quit.ts | 2 + 13 files changed, 1128 insertions(+), 140 deletions(-) create mode 100644 src/main/codex/codex-account-session-index-heal.test.ts create mode 100644 src/main/codex/codex-account-session-index-heal.ts create mode 100644 src/main/codex/codex-state-db-test-fixture.ts diff --git a/src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts b/src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts index 53736a11beb..4a7ad01e1b5 100644 --- a/src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts +++ b/src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts @@ -6,6 +6,7 @@ import type { GlobalSettings } from '../../shared/global-settings-types' import type { CodexManagedAccount } from '../../shared/managed-account-types' import type * as NodeOs from 'node:os' import { readHookTrustEntries } from '../codex/config-toml-trust' +import { writeCodexStateDbBackfillStatus } from '../codex/codex-state-db-test-fixture' const testState = { userData: '', home: '' } const previousEnv: Record = {} @@ -15,6 +16,17 @@ vi.mock('node:os', async () => { const actual = await vi.importActual('node:os') return { ...actual, homedir: () => testState.home } }) +// Why: selecting an account starts the history bridge, which would otherwise +// spawn the real `codex app-server` on these fixture homes. +vi.mock('../codex/codex-account-session-index-heal', () => ({ + createCodexAccountStateDb: async () => false, + healCodexAccountSessionIndex: async () => ({ + outcome: 'up-to-date', + healedThreads: 0, + missingThreads: 0, + failedThreads: 0 + }) +})) beforeEach(() => { vi.resetModules() @@ -212,6 +224,8 @@ describe('CodexRuntimeHomeService per-account takeover composition', () => { const siblingRollout = join('2026', '07', '21', 'rollout-2026-07-21T10-00-00-bbbb.jsonl') writeRollout(systemHome(), systemRollout, '{"session":"real-home"}\n') writeRollout(accountOne.managedHomePath, siblingRollout, '{"session":"account-one"}\n') + // Why: history is linked only once Codex has indexed the new home (#20669). + writeCodexStateDbBackfillStatus(accountTwo.managedHomePath, 'complete') const { settings, store } = createStore([accountOne, accountTwo], accountOne.id) const { CodexRuntimeHomeService } = await import('./runtime-home-service') const bridge = await import('../codex/codex-account-session-bridge') diff --git a/src/main/codex/codex-account-session-bridge.test.ts b/src/main/codex/codex-account-session-bridge.test.ts index 7cebd37c1f4..3befa013473 100644 --- a/src/main/codex/codex-account-session-bridge.test.ts +++ b/src/main/codex/codex-account-session-bridge.test.ts @@ -1,14 +1,31 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync +} from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { _internals, bridgeCodexSessionsIntoAccountHome, - startCodexAccountSessionBridgeInBackground + startCodexAccountSessionBridgeInBackground, + stopCodexAccountSessionBridges } from './codex-account-session-bridge' +import { writeCodexStateDbBackfillStatus } from './codex-state-db-test-fixture' +import SyncDatabase from '../sqlite/sync-database' let workspaceRoot: string +const healIndexStub = vi.fn(async () => ({ + outcome: 'up-to-date' as const, + healedThreads: 0, + missingThreads: 0, + failedThreads: 0 +})) function writeRollout(homePath: string, relativePath: string, contents: string): string { const filePath = join(homePath, 'sessions', relativePath) @@ -21,12 +38,25 @@ function rolloutPath(homePath: string, relativePath: string): string { return join(homePath, 'sessions', relativePath) } -const ROLLOUT_A = join('2026', '07', '20', 'rollout-2026-07-20T10-00-00-aaaa.jsonl') -const ROLLOUT_B = join('2026', '07', '21', 'rollout-2026-07-21T10-00-00-bbbb.jsonl') +const THREAD_A = '019a0000-0000-7000-8000-00000000000a' +const THREAD_B = '019a0000-0000-7000-8000-00000000000b' +const ROLLOUT_A = join( + '2026', + '07', + '20', + 'rollout-2026-07-20T10-00-00-019a0000-0000-7000-8000-00000000000a.jsonl' +) +const ROLLOUT_B = join( + '2026', + '07', + '21', + 'rollout-2026-07-21T10-00-00-019a0000-0000-7000-8000-00000000000b.jsonl' +) beforeEach(() => { workspaceRoot = mkdtempSync(join(tmpdir(), 'codex-account-session-bridge-')) _internals.resetBackgroundBridgeTasks() + healIndexStub.mockClear() }) afterEach(() => { @@ -47,7 +77,14 @@ describe('bridgeCodexSessionsIntoAccountHome', () => { options: { batchSize: 1, yieldMs: 0 } }) - expect(summary).toEqual({ scannedFiles: 2, linkedFiles: 2 }) + expect(summary).toEqual({ + scannedFiles: 2, + linkedFiles: 2, + bridgedThreads: new Map([ + [THREAD_A, '2026-07-20T10-00-00'], + [THREAD_B, '2026-07-21T10-00-00'] + ]) + }) expect(readFileSync(rolloutPath(targetHome, ROLLOUT_A), 'utf-8')).toBe('system session\n') expect(readFileSync(rolloutPath(targetHome, ROLLOUT_B), 'utf-8')).toBe('account a session\n') }) @@ -97,7 +134,11 @@ describe('bridgeCodexSessionsIntoAccountHome', () => { sourceCodexHomePaths: [systemHome] }) - expect(second).toEqual({ scannedFiles: 1, linkedFiles: 0 }) + expect(second).toEqual({ + scannedFiles: 1, + linkedFiles: 0, + bridgedThreads: new Map([[THREAD_A, '2026-07-20T10-00-00']]) + }) }) it('never links a home into itself or scans a duplicate source twice', async () => { @@ -109,7 +150,27 @@ describe('bridgeCodexSessionsIntoAccountHome', () => { sourceCodexHomePaths: [targetHome, targetHome] }) - expect(summary).toEqual({ scannedFiles: 0, linkedFiles: 0 }) + expect(summary).toEqual({ scannedFiles: 0, linkedFiles: 0, bridgedThreads: new Map() }) + }) + + it('does not hand a rollout it failed to link to the index heal', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + writeRollout(systemHome, ROLLOUT_A, 'session\n') + writeRollout(systemHome, ROLLOUT_B, 'session\n') + // A file where the target's day directory belongs makes that one link fail. + mkdirSync(join(targetHome, 'sessions', '2026', '07'), { recursive: true }) + writeFileSync(join(targetHome, 'sessions', '2026', '07', '20'), 'not a directory') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const summary = await bridgeCodexSessionsIntoAccountHome({ + targetCodexHomePath: targetHome, + sourceCodexHomePaths: [systemHome] + }) + + warn.mockRestore() + expect(summary.linkedFiles).toBe(1) + expect(summary.bridgedThreads).toEqual(new Map([[THREAD_B, '2026-07-21T10-00-00']])) }) it('skips a source home that has no sessions tree', async () => { @@ -119,24 +180,35 @@ describe('bridgeCodexSessionsIntoAccountHome', () => { sourceCodexHomePaths: [join(workspaceRoot, 'missing')] }) - expect(summary).toEqual({ scannedFiles: 0, linkedFiles: 0 }) + expect(summary).toEqual({ scannedFiles: 0, linkedFiles: 0, bridgedThreads: new Map() }) }) }) +type BridgeDependencies = NonNullable< + Parameters[1] +> + +// Why: the real steps spawn `codex app-server`; their behavior is covered separately. +function startBridge( + targetCodexHomePath: string, + sourceCodexHomePaths: string[], + dependencies: BridgeDependencies = {} +): Promise { + return startCodexAccountSessionBridgeInBackground( + { targetCodexHomePath, sourceCodexHomePaths }, + { createStateDb: async () => false, healIndex: healIndexStub, ...dependencies } + ) +} + describe('startCodexAccountSessionBridgeInBackground', () => { it('shares one in-flight task per target home', () => { const systemHome = join(workspaceRoot, 'system') const targetHome = join(workspaceRoot, 'account') writeRollout(systemHome, ROLLOUT_A, 'session\n') + writeCodexStateDbBackfillStatus(targetHome, 'complete') - const first = startCodexAccountSessionBridgeInBackground({ - targetCodexHomePath: targetHome, - sourceCodexHomePaths: [systemHome] - }) - const second = startCodexAccountSessionBridgeInBackground({ - targetCodexHomePath: targetHome, - sourceCodexHomePaths: [systemHome] - }) + const first = startBridge(targetHome, [systemHome]) + const second = startBridge(targetHome, [systemHome]) expect(second).toBe(first) return first @@ -147,19 +219,203 @@ describe('startCodexAccountSessionBridgeInBackground', () => { const firstTarget = join(workspaceRoot, 'account-a') const secondTarget = join(workspaceRoot, 'account-b') writeRollout(systemHome, ROLLOUT_A, 'session\n') + writeCodexStateDbBackfillStatus(firstTarget, 'complete') + writeCodexStateDbBackfillStatus(secondTarget, 'complete') await Promise.all([ - startCodexAccountSessionBridgeInBackground({ - targetCodexHomePath: firstTarget, - sourceCodexHomePaths: [systemHome] - }), - startCodexAccountSessionBridgeInBackground({ - targetCodexHomePath: secondTarget, - sourceCodexHomePaths: [systemHome] - }) + startBridge(firstTarget, [systemHome]), + startBridge(secondTarget, [systemHome]) ]) expect(readFileSync(rolloutPath(firstTarget, ROLLOUT_A), 'utf-8')).toBe('session\n') expect(readFileSync(rolloutPath(secondTarget, ROLLOUT_A), 'utf-8')).toBe('session\n') }) + + // #20669: rollouts present when Codex first creates its state DB force a + // blocking backfill that times out the first TUI launch. + it('lets Codex index a new home before linking history into it', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + writeRollout(systemHome, ROLLOUT_A, 'session\n') + const createStateDb = vi.fn(async (home: string) => { + expect(existsSync(rolloutPath(home, ROLLOUT_A))).toBe(false) + writeCodexStateDbBackfillStatus(home, 'complete') + return true + }) + + await startBridge(targetHome, [systemHome], { createStateDb }) + + expect(createStateDb).toHaveBeenCalledWith(targetHome) + expect(readFileSync(rolloutPath(targetHome, ROLLOUT_A), 'utf-8')).toBe('session\n') + }) + + // Why: an older Codex keeps no state DB, and `sqlite_home` keeps it outside + // the home; either way every launch must keep linking new history. + it('keeps linking new history on later launches when no state DB lives in the home', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + writeRollout(systemHome, ROLLOUT_A, 'first\n') + const createStateDb = vi.fn(async () => true) + + await startBridge(targetHome, [systemHome], { createStateDb }) + writeRollout(systemHome, ROLLOUT_B, 'second\n') + await startBridge(targetHome, [systemHome], { createStateDb }) + + expect(readFileSync(rolloutPath(targetHome, ROLLOUT_A), 'utf-8')).toBe('first\n') + expect(readFileSync(rolloutPath(targetHome, ROLLOUT_B), 'utf-8')).toBe('second\n') + // Only the empty home needed Codex to run first. + expect(createStateDb).toHaveBeenCalledTimes(1) + }) + + it('does not start Codex on an empty home when no source has history', async () => { + const createStateDb = vi.fn(async () => true) + + await startBridge(join(workspaceRoot, 'account'), [join(workspaceRoot, 'system')], { + createStateDb + }) + + expect(createStateDb).not.toHaveBeenCalled() + }) + + it('does not link history when Codex could not create the state DB', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + writeRollout(systemHome, ROLLOUT_A, 'session\n') + + await startBridge(targetHome, [systemHome], { createStateDb: async () => false }) + + expect(existsSync(rolloutPath(targetHome, ROLLOUT_A))).toBe(false) + expect(healIndexStub).not.toHaveBeenCalled() + }) + + it('bridges compressed-only history into a new home and indexes it', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + const compressed = `${ROLLOUT_A}.zst` + writeRollout(systemHome, compressed, 'compressed\n') + const createStateDb = vi.fn(async (home: string) => { + writeCodexStateDbBackfillStatus(home, 'complete') + return true + }) + + await startBridge(targetHome, [systemHome], { createStateDb }) + + expect(readFileSync(rolloutPath(targetHome, compressed), 'utf-8')).toBe('compressed\n') + expect(healIndexStub).toHaveBeenCalledWith( + targetHome, + new Map([[THREAD_A, '2026-07-20T10-00-00']]), + { + shouldStop: expect.any(Function) + } + ) + }) + + it('skips linking into a state DB that predates backfill tracking', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + writeRollout(systemHome, ROLLOUT_A, 'session\n') + mkdirSync(targetHome, { recursive: true }) + new SyncDatabase(join(targetHome, 'state_5.sqlite')).close() + + await startBridge(targetHome, [systemHome]) + + expect(existsSync(rolloutPath(targetHome, ROLLOUT_A))).toBe(false) + }) + + it('skips linking while Codex is still indexing the home', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + writeRollout(systemHome, ROLLOUT_A, 'session\n') + writeCodexStateDbBackfillStatus(targetHome, 'running') + + await startBridge(targetHome, [systemHome]) + + expect(existsSync(rolloutPath(targetHome, ROLLOUT_A))).toBe(false) + expect(healIndexStub).not.toHaveBeenCalled() + }) + + it('reports why it skips a home whose state DB cannot be read', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + writeRollout(systemHome, ROLLOUT_A, 'session\n') + mkdirSync(targetHome, { recursive: true }) + writeFileSync(join(targetHome, 'state_5.sqlite'), 'not a sqlite database') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await startBridge(targetHome, [systemHome]) + + expect(existsSync(rolloutPath(targetHome, ROLLOUT_A))).toBe(false) + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('Codex state DB is unreadable'), + expect.any(String) + ) + warn.mockRestore() + }) + + it('indexes the bridged threads once linking finishes', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + writeRollout(systemHome, ROLLOUT_A, 'session\n') + writeCodexStateDbBackfillStatus(targetHome, 'complete') + + await startBridge(targetHome, [systemHome]) + + expect(healIndexStub).toHaveBeenCalledWith( + targetHome, + new Map([[THREAD_A, '2026-07-20T10-00-00']]), + { + shouldStop: expect.any(Function) + } + ) + }) + + it('links nothing when the app quits while Codex creates the state DB', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + writeRollout(systemHome, ROLLOUT_A, 'session\n') + + await startBridge(targetHome, [systemHome], { + createStateDb: async (home) => { + writeCodexStateDbBackfillStatus(home, 'complete') + stopCodexAccountSessionBridges() + return true + } + }) + + expect(existsSync(rolloutPath(targetHome, ROLLOUT_A))).toBe(false) + expect(healIndexStub).not.toHaveBeenCalled() + }) + + it('does not start Codex on a new home after the app quits', async () => { + const systemHome = join(workspaceRoot, 'system') + writeRollout(systemHome, ROLLOUT_A, 'session\n') + const createStateDb = vi.fn(async () => true) + stopCodexAccountSessionBridges() + + await startBridge(join(workspaceRoot, 'account'), [systemHome], { createStateDb }) + + expect(createStateDb).not.toHaveBeenCalled() + }) + + it('stops indexing and starts no new bridge once the app quits', async () => { + const systemHome = join(workspaceRoot, 'system') + const targetHome = join(workspaceRoot, 'account') + const laterTarget = join(workspaceRoot, 'later-account') + writeRollout(systemHome, ROLLOUT_A, 'session\n') + writeCodexStateDbBackfillStatus(targetHome, 'complete') + writeCodexStateDbBackfillStatus(laterTarget, 'complete') + let shouldStop: (() => boolean) | undefined + + await startBridge(targetHome, [systemHome], { + healIndex: async (_home, _threads, options) => { + shouldStop = options?.shouldStop + stopCodexAccountSessionBridges() + return { outcome: 'stopped', healedThreads: 0, missingThreads: 0, failedThreads: 0 } + } + }) + await startBridge(laterTarget, [systemHome]) + + expect(shouldStop?.()).toBe(true) + expect(existsSync(rolloutPath(laterTarget, ROLLOUT_A))).toBe(false) + }) }) diff --git a/src/main/codex/codex-account-session-bridge.ts b/src/main/codex/codex-account-session-bridge.ts index 72096103aa1..bb6110a8651 100644 --- a/src/main/codex/codex-account-session-bridge.ts +++ b/src/main/codex/codex-account-session-bridge.ts @@ -3,7 +3,17 @@ import { dirname, join, relative } from 'node:path' import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' import { listCodexSessionRolloutFilesIncrementally } from './codex-session-file-listing' import type { CodexSessionBridgeIncrementalOptions } from './codex-session-file-listing' +import { + createCodexAccountStateDb, + healCodexAccountSessionIndex +} from './codex-account-session-index-heal' +import { parseCodexRolloutThreadId } from './codex-session-index-heal-state' import { linkCodexSessionFile } from './codex-session-link' +import { + countCodexSessionFilesUpTo, + findNewestCodexStateDbPath, + readCodexStateDbBackfillStatus +} from './codex-state-db' /** * Bridges Codex history between Orca-managed Codex homes. @@ -19,24 +29,99 @@ import { linkCodexSessionFile } from './codex-session-link' export type CodexAccountSessionBridgeSummary = { scannedFiles: number linkedFiles: number + /** Thread id -> rollout timestamp for every rollout present in the target home via this bridge. */ + bridgedThreads: Map } const backgroundBridgeTasksByTargetHome = new Map>() +let stopping = false + +type BackgroundBridgeDependencies = { + createStateDb: typeof createCodexAccountStateDb + healIndex: typeof healCodexAccountSessionIndex +} + +const defaultBackgroundBridgeDependencies: BackgroundBridgeDependencies = { + createStateDb: createCodexAccountStateDb, + healIndex: healCodexAccountSessionIndex +} + +/** + * Why: Codex indexes every rollout present when it first creates a home's state + * DB, and the TUI gives up waiting after 30s. Linking history into a fresh home + * first turns its first launch into a minutes-long backfill (#20669), so an + * empty home gets its state DB before any history; the heal indexes it afterwards. + */ +async function isReadyForBridgedHistory( + targetCodexHomePath: string, + sourceCodexHomePaths: readonly string[], + dependencies: BackgroundBridgeDependencies +): Promise { + if ( + !findNewestCodexStateDbPath(targetCodexHomePath) && + !hasSessionRollouts(targetCodexHomePath) + ) { + if ( + !sourceCodexHomePaths.some(hasSessionRollouts) || + !(await dependencies.createStateDb(targetCodexHomePath)) + ) { + return false + } + } + const status = readCodexStateDbBackfillStatus(targetCodexHomePath) + if (status.kind === 'unreadable') { + // Why: contention clears by the next launch; corruption would skip every launch, so surface it. + console.warn( + '[codex-account-session-bridge] Skipping history bridge; Codex state DB is unreadable:', + status.error + ) + return false + } + // Why: no DB in a home that has history means Codex keeps it elsewhere + // (`sqlite_home`) or keeps none, so linking cannot stall a launch here. + // `not-tracked` is a pre-backfill schema that Codex migrates to `pending`. + return status.kind === 'complete' || status.kind === 'missing' +} + +function hasSessionRollouts(codexHomePath: string): boolean { + return countCodexSessionFilesUpTo(join(codexHomePath, 'sessions'), 1) > 0 +} /** * Starts one background bridge per target home, sharing in-flight work. */ -export function startCodexAccountSessionBridgeInBackground(args: { - targetCodexHomePath: string - sourceCodexHomePaths: readonly string[] - options?: CodexSessionBridgeIncrementalOptions -}): Promise { +export function startCodexAccountSessionBridgeInBackground( + args: { + targetCodexHomePath: string + sourceCodexHomePaths: readonly string[] + options?: CodexSessionBridgeIncrementalOptions + }, + dependenciesOverride: Partial = {} +): Promise { + if (stopping) { + return Promise.resolve() + } const key = normalizeRuntimePathForComparison(args.targetCodexHomePath) const inFlight = backgroundBridgeTasksByTargetHome.get(key) if (inFlight) { return inFlight } - const task = bridgeCodexSessionsIntoAccountHome(args) + const dependencies = { ...defaultBackgroundBridgeDependencies, ...dependenciesOverride } + const task = isReadyForBridgedHistory( + args.targetCodexHomePath, + args.sourceCodexHomePaths, + dependencies + ) + .then(async (ready) => { + // Why: skip rather than feed a running backfill; the next launch retries. + if (!ready || stopping) { + return + } + const summary = await bridgeCodexSessionsIntoAccountHome(args) + await dependencies.healIndex(args.targetCodexHomePath, summary.bridgedThreads, { + shouldStop: () => stopping + }) + }) .catch((error: unknown) => { console.warn('[codex-account-session-bridge] Background session bridge failed:', error) }) @@ -50,6 +135,11 @@ export function startCodexAccountSessionBridgeInBackground(args: { return task } +/** Stops background bridges at quit; links and index reads made so far are kept. */ +export function stopCodexAccountSessionBridges(): void { + stopping = true +} + /** * Mirrors every source home's rollouts into the target home's sessions tree. */ @@ -58,7 +148,11 @@ export async function bridgeCodexSessionsIntoAccountHome(args: { sourceCodexHomePaths: readonly string[] options?: CodexSessionBridgeIncrementalOptions }): Promise { - const summary: CodexAccountSessionBridgeSummary = { scannedFiles: 0, linkedFiles: 0 } + const summary: CodexAccountSessionBridgeSummary = { + scannedFiles: 0, + linkedFiles: 0, + bridgedThreads: new Map() + } const targetSessionsRoot = join(args.targetCodexHomePath, 'sessions') for (const sourceHomePath of dedupeSourceHomes( args.sourceCodexHomePaths, @@ -73,9 +167,18 @@ export async function bridgeCodexSessionsIntoAccountHome(args: { args.options ?? {} )) { summary.scannedFiles += 1 - if (bridgeRolloutIntoAccountHome(sourceSessionsRoot, targetSessionsRoot, sourceFilePath)) { + const result = bridgeRolloutIntoAccountHome( + sourceSessionsRoot, + targetSessionsRoot, + sourceFilePath + ) + if (result === 'linked') { summary.linkedFiles += 1 } + const rollout = parseCodexRolloutThreadId(sourceFilePath) + if (result !== 'failed' && rollout) { + summary.bridgedThreads.set(rollout.threadId, rollout.rolloutStamp) + } } } return summary @@ -88,20 +191,20 @@ function bridgeRolloutIntoAccountHome( sourceSessionsRoot: string, targetSessionsRoot: string, sourceFilePath: string -): boolean { +): 'linked' | 'existing' | 'failed' { const targetFilePath = join(targetSessionsRoot, relative(sourceSessionsRoot, sourceFilePath)) // Why: rollout names carry the session UUID, so an existing target path is the // same conversation already bridged (often the same inode) — never a conflict. if (existsSync(targetFilePath)) { - return false + return 'existing' } try { mkdirSync(dirname(targetFilePath), { recursive: true }) } catch (error) { console.warn('[codex-account-session-bridge] Failed to create session directory:', error) - return false + return 'failed' } - return linkCodexSessionFile(sourceFilePath, targetFilePath) + return linkCodexSessionFile(sourceFilePath, targetFilePath) ? 'linked' : 'failed' } /** @@ -127,5 +230,6 @@ function dedupeSourceHomes( export const _internals = { resetBackgroundBridgeTasks: (): void => { backgroundBridgeTasksByTargetHome.clear() + stopping = false } } diff --git a/src/main/codex/codex-account-session-index-heal.test.ts b/src/main/codex/codex-account-session-index-heal.test.ts new file mode 100644 index 00000000000..fbb5fae404c --- /dev/null +++ b/src/main/codex/codex-account-session-index-heal.test.ts @@ -0,0 +1,306 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { + _internals, + createCodexAccountStateDb, + healCodexAccountSessionIndex +} from './codex-account-session-index-heal' +import { + CodexAppServerUnsupportedError, + type CodexAppServerInvocation, + type CodexAppServerRpc +} from './codex-app-server-session' + +const HOME = '/codex-accounts/account-1/home' + +// Why: fails closed if a regression bypasses the fake session — never the real codex or ~/.codex. +function buildInvocation(): CodexAppServerInvocation { + return { + command: '/nonexistent/orca-test-codex', + args: ['app-server'], + cliPath: null, + env: { CODEX_HOME: join(tmpdir(), 'orca-test-nonexistent-codex-home') }, + timeoutMs: 1_000 + } +} + +/** Runs the heal body against a fake app-server that answers thread/read. */ +function fakeAppServer(onRead: (threadId: string) => void = () => {}) { + const readThreadIds: string[] = [] + const runSession = vi.fn( + async ( + _invocation: CodexAppServerInvocation, + body: (rpc: CodexAppServerRpc) => Promise + ): Promise => { + await body({ + request: async (method, params) => { + expect(method).toBe('thread/read') + const threadId = String(params?.threadId) + readThreadIds.push(threadId) + onRead(threadId) + return {} + }, + notify: () => {} + }) + } + ) + return { runSession, readThreadIds } +} + +/** Bridged threads keyed by id, all from the same rollout timestamp. */ +function bridged(...threadIds: string[]): Map { + return new Map(threadIds.map((threadId) => [threadId, '2026-07-20T10-00-00'])) +} + +beforeEach(() => { + _internals.resetFailedThreads() +}) + +describe('healCodexAccountSessionIndex', () => { + it('reads only bridged threads missing from the Codex index', async () => { + const { runSession, readThreadIds } = fakeAppServer() + + const summary = await healCodexAccountSessionIndex(HOME, bridged('a', 'b', 'c'), { + readIndexedThreadIds: () => new Set(['b']), + buildInvocation, + runSession + }) + + expect(readThreadIds.sort()).toEqual(['a', 'c']) + expect(summary).toEqual({ + outcome: 'completed', + healedThreads: 2, + missingThreads: 0, + failedThreads: 0 + }) + }) + + it('reads the most recent bridged rollouts first', async () => { + const { runSession, readThreadIds } = fakeAppServer() + + await healCodexAccountSessionIndex( + HOME, + new Map([ + ['middle', '2026-08-01T09-00-00'], + ['oldest', '2025-12-31T23-59-59'], + ['newest', '2026-09-28T01-46-16'] + ]), + { readIndexedThreadIds: () => new Set(), buildInvocation, runSession, readConcurrency: 1 } + ) + + expect(readThreadIds).toEqual(['newest', 'middle', 'oldest']) + }) + + it('does not start Codex when every bridged thread is already indexed', async () => { + const { runSession } = fakeAppServer() + + const summary = await healCodexAccountSessionIndex(HOME, bridged('a'), { + readIndexedThreadIds: () => new Set(['a']), + buildInvocation, + runSession + }) + + expect(summary.outcome).toBe('up-to-date') + expect(runSession).not.toHaveBeenCalled() + }) + + it('does not start Codex when its index cannot be read', async () => { + const { runSession } = fakeAppServer() + + const summary = await healCodexAccountSessionIndex(HOME, bridged('a'), { + readIndexedThreadIds: () => null, + buildInvocation, + runSession + }) + + expect(summary.outcome).toBe('no-index') + expect(runSession).not.toHaveBeenCalled() + }) + + it('does not start Codex once the app is quitting', async () => { + const { runSession } = fakeAppServer() + + const summary = await healCodexAccountSessionIndex(HOME, bridged('a'), { + readIndexedThreadIds: () => new Set(), + buildInvocation, + runSession, + shouldStop: () => true + }) + + expect(summary.outcome).toBe('stopped') + expect(runSession).not.toHaveBeenCalled() + }) + + it('stops retrying a thread Codex refuses to index until Orca restarts', async () => { + const { runSession, readThreadIds } = fakeAppServer((threadId) => { + if (threadId === 'broken') { + throw new Error('codex app-server thread/read failed: invalid rollout') + } + }) + const dependencies = { + readIndexedThreadIds: () => new Set(), + buildInvocation, + runSession + } + + const first = await healCodexAccountSessionIndex(HOME, bridged('broken'), dependencies) + const second = await healCodexAccountSessionIndex(HOME, bridged('broken'), dependencies) + + expect(first).toEqual({ + outcome: 'completed', + healedThreads: 0, + missingThreads: 0, + failedThreads: 1 + }) + expect(second.outcome).toBe('up-to-date') + expect(readThreadIds).toEqual(['broken']) + }) + + it('remembers a refused thread only for the home that refused it', async () => { + const { runSession, readThreadIds } = fakeAppServer((threadId) => { + if (readThreadIds.length === 1) { + throw new Error(`codex app-server thread/read failed: invalid rollout ${threadId}`) + } + }) + const dependencies = { + readIndexedThreadIds: () => new Set(), + buildInvocation, + runSession + } + + await healCodexAccountSessionIndex(HOME, bridged('shared'), dependencies) + const other = await healCodexAccountSessionIndex( + '/codex-accounts/account-2/home', + bridged('shared'), + dependencies + ) + + expect(other.healedThreads).toBe(1) + expect(readThreadIds).toEqual(['shared', 'shared']) + }) + + it('counts a rollout Codex cannot find as missing and does not reread it', async () => { + const { runSession, readThreadIds } = fakeAppServer(() => { + throw new Error('codex app-server thread/read failed: no rollout found for thread id gone') + }) + const options = { readIndexedThreadIds: () => new Set(), buildInvocation, runSession } + + const first = await healCodexAccountSessionIndex(HOME, bridged('gone'), options) + const second = await healCodexAccountSessionIndex(HOME, bridged('gone'), options) + + expect(first).toEqual({ + outcome: 'completed', + healedThreads: 0, + missingThreads: 1, + failedThreads: 0 + }) + expect(second.outcome).toBe('up-to-date') + expect(readThreadIds).toEqual(['gone']) + }) + + it('retries a thread on the next pass when the app-server session fails', async () => { + const failing = vi.fn(async () => { + throw new Error('codex app-server exited before responding') + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const readIndexedThreadIds = (): Set => new Set() + + const first = await healCodexAccountSessionIndex(HOME, bridged('a'), { + readIndexedThreadIds, + buildInvocation, + runSession: failing + }) + const { runSession, readThreadIds } = fakeAppServer() + const second = await healCodexAccountSessionIndex(HOME, bridged('a'), { + readIndexedThreadIds, + buildInvocation, + runSession + }) + + expect(first.outcome).toBe('aborted') + expect(second.outcome).toBe('completed') + expect(readThreadIds).toEqual(['a']) + warn.mockRestore() + }) + + it('reports a session that fails during quit as stopped, not unsupported', async () => { + let stopping = false + const summary = await healCodexAccountSessionIndex(HOME, bridged('a'), { + readIndexedThreadIds: () => new Set(), + buildInvocation, + runSession: async () => { + stopping = true + throw new CodexAppServerUnsupportedError('app-server killed during quit') + }, + shouldStop: () => stopping + }) + + expect(summary.outcome).toBe('stopped') + }) + + it('aborts rather than writing off a thread while a live Codex holds the database', async () => { + const { runSession } = fakeAppServer(() => { + throw new Error('codex app-server thread/read failed: database is locked') + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const summary = await healCodexAccountSessionIndex(HOME, bridged('a'), { + readIndexedThreadIds: () => new Set(), + buildInvocation, + runSession + }) + + expect(summary).toEqual({ + outcome: 'aborted', + healedThreads: 0, + missingThreads: 0, + failedThreads: 0 + }) + warn.mockRestore() + }) +}) + +describe('createCodexAccountStateDb', () => { + it('starts Codex on the home without sending any request', async () => { + const { runSession, readThreadIds } = fakeAppServer() + const invocations: string[] = [] + + const created = await createCodexAccountStateDb(HOME, { + buildInvocation: (home, timeoutMs) => { + invocations.push(home) + return { ...buildInvocation(), timeoutMs } + }, + runSession + }) + + expect(created).toBe(true) + expect(invocations).toEqual([HOME]) + expect(readThreadIds).toEqual([]) + }) + + it('treats a Codex without app-server as having no state DB to stall', async () => { + const created = await createCodexAccountStateDb(HOME, { + buildInvocation, + runSession: async () => { + throw new CodexAppServerUnsupportedError('unknown subcommand app-server') + } + }) + + expect(created).toBe(true) + }) + + it('reports failure when Codex could not start', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const created = await createCodexAccountStateDb(HOME, { + buildInvocation, + runSession: async () => { + throw new Error('spawn codex ENOENT') + } + }) + + expect(created).toBe(false) + warn.mockRestore() + }) +}) diff --git a/src/main/codex/codex-account-session-index-heal.ts b/src/main/codex/codex-account-session-index-heal.ts new file mode 100644 index 00000000000..1af87e34407 --- /dev/null +++ b/src/main/codex/codex-account-session-index-heal.ts @@ -0,0 +1,122 @@ +import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' +import { + isCodexAppServerUnsupportedError, + runCodexAppServerSession +} from './codex-app-server-session' +import { + buildNativeHealInvocation, + readCodexThreadsForIndexHeal, + type CodexSessionIndexHealOptions, + type CodexThreadReadPassOutcome +} from './codex-session-index-heal' +import { readIndexedCodexThreadIds } from './codex-state-db' + +// Why: Codex indexes a home's rollouts only once, when it first creates the +// state DB, and the /resume picker's "All" view lists only indexed threads. +// History bridged in afterwards needs `thread/read`, Codex's lazy-indexing +// path, to become visible there (#20669). + +export type CodexAccountSessionIndexHealSummary = { + outcome: CodexThreadReadPassOutcome | 'up-to-date' | 'no-index' + healedThreads: number + missingThreads: number + failedThreads: number +} + +export type CodexAccountSessionIndexHealOptions = CodexSessionIndexHealOptions & { + readIndexedThreadIds?: (codexHomePath: string) => Set | null +} + +// Why: app-server finishes state DB startup before it answers `initialize`, +// which takes ~100ms on an empty home. +const STATE_DB_CREATE_TIMEOUT_MS = 15_000 + +// Why: a just-linked rollout Codex refuses or cannot find fails the same way on +// every read; skip it until Orca restarts instead of respawning app-server each launch. +const failedThreadIdsByHome = new Map>() + +/** + * Starts Codex once on an empty home so it creates and indexes its state DB + * before any history is bridged in. False when Codex could not start. + */ +export async function createCodexAccountStateDb( + codexHomePath: string, + options: Pick = {} +): Promise { + const buildInvocation = options.buildInvocation ?? buildNativeHealInvocation + const runSession = options.runSession ?? runCodexAppServerSession + try { + await runSession(buildInvocation(codexHomePath, STATE_DB_CREATE_TIMEOUT_MS), async () => {}) + return true + } catch (error) { + // Why: a Codex without app-server predates the state DB, so linking cannot stall it. + if (isCodexAppServerUnsupportedError(error)) { + return true + } + console.warn('[codex-account-session-index-heal] Failed to create Codex state DB:', error) + return false + } +} + +/** + * Indexes the bridged threads Codex has not indexed yet, newest rollout first. + * Diffing against the state DB on every pass makes an interrupted heal resume + * on the next launch. + */ +export async function healCodexAccountSessionIndex( + codexHomePath: string, + bridgedThreads: ReadonlyMap, + options: CodexAccountSessionIndexHealOptions = {} +): Promise { + const summary: CodexAccountSessionIndexHealSummary = { + outcome: 'up-to-date', + healedThreads: 0, + missingThreads: 0, + failedThreads: 0 + } + if (bridgedThreads.size === 0) { + return summary + } + // Why: with no DB in the home, Codex keeps none (older CLI) or uses a + // `sqlite_home` shared by every Orca home, which already indexes these threads. + const indexed = (options.readIndexedThreadIds ?? readIndexedCodexThreadIds)(codexHomePath) + if (!indexed) { + return { ...summary, outcome: 'no-index' } + } + const homeKey = normalizeRuntimePathForComparison(codexHomePath) + const failed = failedThreadIdsByHome.get(homeKey) ?? new Set() + failedThreadIdsByHome.set(homeKey, failed) + // Why: a large history takes minutes to index, and /resume hides unindexed + // threads once a directory has any indexed one, so recent work goes first. + const pending = [...bridgedThreads] + .filter(([threadId]) => !indexed.has(threadId) && !failed.has(threadId)) + .sort(([, left], [, right]) => (left < right ? 1 : left > right ? -1 : 0)) + .map(([threadId]) => ({ threadId })) + if (pending.length === 0) { + return summary + } + summary.outcome = await readCodexThreadsForIndexHeal( + codexHomePath, + pending, + ({ threadId }, outcome) => { + if (outcome === 'healed') { + summary.healedThreads += 1 + return + } + failed.add(threadId) + if (outcome === 'missing') { + summary.missingThreads += 1 + } else { + summary.failedThreads += 1 + } + }, + options + ) + return summary +} + +export const _internals = { + resetFailedThreads: (): void => { + failedThreadIdsByHome.clear() + } +} diff --git a/src/main/codex/codex-index-heal-binary-contract.test.ts b/src/main/codex/codex-index-heal-binary-contract.test.ts index 5580fc02d1d..8954f618a6a 100644 --- a/src/main/codex/codex-index-heal-binary-contract.test.ts +++ b/src/main/codex/codex-index-heal-binary-contract.test.ts @@ -3,10 +3,12 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' +import { zstdCompressSync } from 'node:zlib' import { afterEach, beforeAll, describe, expect, it } from 'vitest' +import { CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS } from '../codex-cli/codex-read-only-app-server-args' import SyncDatabase from '../sqlite/sync-database' import { runCodexAppServerSession, type CodexAppServerRpc } from './codex-app-server-session' -import { findNewestCodexStateDbPath } from './codex-state-db' +import { findNewestCodexStateDbPath, readCodexStateDbBackfillStatus } from './codex-state-db' // Why this file exists: every other index-heal test drives a stub app-server and // asserts "healed" as "the `thread/read` call did not error". That pins Orca's half @@ -17,7 +19,7 @@ import { findNewestCodexStateDbPath } from './codex-state-db' // real-binary backstop, built to the same shape as the Git binary compatibility // contract in src/shared/git-binary-compatibility.test.ts. // -// Keep it narrow. It pins the four arms that ablation established Orca relies on, +// Keep it narrow. It pins the arms that ablation established Orca relies on, // and deliberately asserts nothing else about the app-server, so an unrelated Codex // release does not redden it into being disabled. @@ -83,11 +85,18 @@ describeCodexContract( mkdirSync(join(home, 'sessions'), { recursive: true }) // An app-server session over an empty sessions tree is what stamps the backfill complete. await runAppServerSession(home, async () => undefined) + // Why: the account bridge links history only after this no-request session stamps it. + expect(readCodexStateDbBackfillStatus(home).kind).toBe('complete') expect(readThreadRows(home)).toEqual([]) return home } - function writeRollout(home: string, threadId: string, stamp: string): void { + function writeRollout( + home: string, + threadId: string, + stamp: string, + options: { compressed?: boolean } = {} + ): void { const dayDir = join(home, 'sessions', '2026', '08', '29') mkdirSync(dayDir, { recursive: true }) const meta = { @@ -112,10 +121,13 @@ describeCodexContract( type: 'event_msg', payload: { type: 'user_message', message: 'index-heal contract fixture' } } - writeFileSync( - join(dayDir, `rollout-${stamp}-${threadId}.jsonl`), - `${JSON.stringify(meta)}\n${JSON.stringify(userMessage)}\n` - ) + const contents = `${JSON.stringify(meta)}\n${JSON.stringify(userMessage)}\n` + const fileName = `rollout-${stamp}-${threadId}.jsonl` + if (options.compressed) { + writeFileSync(join(dayDir, `${fileName}.zst`), zstdCompressSync(contents)) + } else { + writeFileSync(join(dayDir, fileName), contents) + } } // Why reuse runCodexAppServerSession rather than a local JSON-RPC client: it is the @@ -128,7 +140,8 @@ describeCodexContract( return runCodexAppServerSession( { command: binary!, - args: ['app-server'], + // Why: the heal and account state-DB creation launch with these exact args. + args: [...CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS], cliPath: binary!, env: { CODEX_HOME: home }, timeoutMs: SESSION_TIMEOUT_MS @@ -171,6 +184,19 @@ describeCodexContract( expect(readThreadRows(home)).toEqual([{ id: threadId, archived: 0 }]) }) + // Why: the account bridge links `.jsonl.zst` history and heals it with the same read. + it('indexes a compressed-only rollout on read', async () => { + const home = await createBackfilledCodexHome() + const threadId = '01a04f62-715e-7830-9371-50db585caa74' + writeRollout(home, threadId, '2026-08-29T17-00-00', { compressed: true }) + + await runAppServerSession(home, async (rpc) => { + await rpc.request('thread/read', { threadId }) + }) + + expect(readThreadRows(home)).toEqual([{ id: threadId, archived: 0 }]) + }) + it('leaves an already-indexed thread as a single row', async () => { const home = await createBackfilledCodexHome() const threadId = '01a04f62-715e-7830-9371-50db585caa72' diff --git a/src/main/codex/codex-session-index-heal-state.ts b/src/main/codex/codex-session-index-heal-state.ts index 0a5fd0499c1..ab62b77669d 100644 --- a/src/main/codex/codex-session-index-heal-state.ts +++ b/src/main/codex/codex-session-index-heal-state.ts @@ -22,7 +22,7 @@ const HEAL_UNSUPPORTED_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 const HEAL_FAILED_THREAD_RETRY_INTERVAL_MS = 24 * 60 * 60 * 1000 const CODEX_ROLLOUT_THREAD_ID_PATTERN = - /^rollout-(.+)-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i + /^rollout-(.+)-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl(?:\.zst)?$/i export type CodexSessionIndexHealPaths = { auditLogPath: string @@ -70,11 +70,11 @@ export async function collectPendingHealThreads( if (!isPathInsideOrEqual(paths.systemSessionsRoot, line.target)) { continue } - const match = CODEX_ROLLOUT_THREAD_ID_PATTERN.exec(lastPathSegment(line.target)) - if (!match) { + const rollout = parseCodexRolloutThreadId(line.target) + if (!rollout) { continue } - const threadId = match[2].toLowerCase() + const { threadId } = rollout const auditRecordId = typeof line.recordId === 'string' ? line.recordId : null if ( auditRecordId @@ -88,13 +88,21 @@ export async function collectPendingHealThreads( pendingByThreadId.delete(threadId) continue } - pendingByThreadId.set(threadId, { threadId, rolloutStamp: match[1], auditRecordId }) + pendingByThreadId.set(threadId, { threadId, rolloutStamp: rollout.rolloutStamp, auditRecordId }) } return [...pendingByThreadId.values()].sort((left, right) => left.rolloutStamp < right.rolloutStamp ? 1 : left.rolloutStamp > right.rolloutStamp ? -1 : 0 ) } +/** Thread id (lower-cased) and timestamp segment encoded in a rollout file name. */ +export function parseCodexRolloutThreadId( + filePath: string +): { threadId: string; rolloutStamp: string } | null { + const match = CODEX_ROLLOUT_THREAD_ID_PATTERN.exec(lastPathSegment(filePath)) + return match ? { threadId: match[2].toLowerCase(), rolloutStamp: match[1] } : null +} + function lastPathSegment(filePath: string): string { return filePath.split(/[\\/]/).at(-1) ?? '' } diff --git a/src/main/codex/codex-session-index-heal.test.ts b/src/main/codex/codex-session-index-heal.test.ts index 20051fe1058..1be3d047207 100644 --- a/src/main/codex/codex-session-index-heal.test.ts +++ b/src/main/codex/codex-session-index-heal.test.ts @@ -10,10 +10,12 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' +import { CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS } from '../codex-cli/codex-read-only-app-server-args' import type { CodexAppServerInvocation } from './codex-app-server-session' import { createCodexSessionBackfillAuditWriter } from './codex-session-backfill-audit' import { CODEX_SESSION_INDEX_HEAL_VERSION } from './codex-session-index-heal-state' import { + buildNativeHealInvocation, runCodexSessionIndexHeal, type CodexSessionIndexHealPaths } from './codex-session-index-heal' @@ -340,6 +342,7 @@ describe('runCodexSessionIndexHeal', () => { const marker = JSON.parse(readFileSync(rig.paths.healMarkerPath, 'utf-8')) as { retryableFailureAt: number } + expect(marker.retryableFailureAt).toEqual(expect.any(Number)) marker.retryableFailureAt = 0 writeFileSync(rig.paths.healMarkerPath, `${JSON.stringify(marker)}\n`, 'utf-8') const retried = await runCodexSessionIndexHeal(rig.paths, { @@ -490,6 +493,25 @@ describe('runCodexSessionIndexHeal', () => { expect(resumed.healedThreads + summary.healedThreads).toBe(4) }) + it('writes no completion marker when stop flips inside the last batch', async () => { + const rig = createHealRig({ + auditedThreads: [ + { stamp: '2026-07-02T10-00-00', id: threadId('2') }, + { stamp: '2026-07-01T10-00-00', id: threadId('1') } + ] + }) + + const summary = await runCodexSessionIndexHeal(rig.paths, { + buildInvocation: rig.buildInvocation, + readConcurrency: 1, + interBatchDelayMs: 0, + shouldStop: () => rig.readLog().threadIds.length > 0 + }) + + expect(summary).toMatchObject({ outcome: 'stopped', healedThreads: 1 }) + expect(existsSync(rig.paths.healMarkerPath)).toBe(false) + }) + it('does not spawn another server when stop flips during the inter-batch delay', async () => { const rig = createHealRig({ auditedThreads: [ @@ -777,3 +799,14 @@ describe('runCodexSessionIndexHeal', () => { warnSpy.mockRestore() }) }) + +describe('buildNativeHealInvocation', () => { + it('starts a read-only, plugin-free app-server pinned to the given home', () => { + const invocation = buildNativeHealInvocation('/codex-home', 1_000) + + for (const arg of CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS) { + expect(invocation.args).toContain(arg) + } + expect(invocation.env).toEqual({ CODEX_HOME: '/codex-home' }) + }) +}) diff --git a/src/main/codex/codex-session-index-heal.ts b/src/main/codex/codex-session-index-heal.ts index 12747312646..364263f2f47 100644 --- a/src/main/codex/codex-session-index-heal.ts +++ b/src/main/codex/codex-session-index-heal.ts @@ -1,6 +1,7 @@ import { dirname, join } from 'node:path' import { resolveCodexCommand } from '../codex-cli/command' import { isTransientSqliteContention } from '../sqlite/sqlite-read-failure' +import { CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS } from '../codex-cli/codex-read-only-app-server-args' import { getSpawnArgsForWindows } from '../win32-utils' import { getCodexSessionBackfillStateDirPath } from './codex-home-paths' import { resolveCodexSessionBackfillPaths } from './codex-session-backfill' @@ -17,7 +18,8 @@ import { import { isCodexAppServerUnsupportedError, runCodexAppServerSession, - type CodexAppServerInvocation + type CodexAppServerInvocation, + type CodexAppServerRpc } from './codex-app-server-session' export type { CodexSessionIndexHealPaths } from './codex-session-index-heal-state' @@ -49,12 +51,20 @@ export type CodexSessionIndexHealSummary = { export type CodexSessionIndexHealOptions = { /** Polled between reads and batches; true stops promptly, progress is kept. */ shouldStop?: () => boolean - buildInvocation?: (systemCodexHomePath: string, timeoutMs: number) => CodexAppServerInvocation + buildInvocation?: (codexHomePath: string, timeoutMs: number) => CodexAppServerInvocation + runSession?: ( + invocation: CodexAppServerInvocation, + body: (rpc: CodexAppServerRpc) => Promise + ) => Promise readsPerServerSession?: number readConcurrency?: number interBatchDelayMs?: number } +export type CodexThreadReadOutcome = HealLedgerOutcome + +export type CodexThreadReadPassOutcome = 'completed' | 'stopped' | 'unsupported' | 'aborted' + let backgroundHealTask: Promise | null = null export function resolveCodexSessionIndexHealPaths( @@ -132,69 +142,30 @@ export async function runCodexSessionIndexHeal( return summary } - const systemCodexHomePath = dirname(paths.systemSessionsRoot) - const buildInvocation = options.buildInvocation ?? buildNativeHealInvocation - const readsPerServerSession = resolveHealWorkLimit( - options.readsPerServerSession, - HEAL_READS_PER_SERVER_SESSION - ) - const readConcurrency = resolveHealWorkLimit(options.readConcurrency, HEAL_READ_CONCURRENCY) - const interBatchDelayMs = options.interBatchDelayMs ?? HEAL_INTER_BATCH_DELAY_MS const shouldStop = options.shouldStop ?? ((): boolean => false) - - for (let offset = 0; offset < pending.length; offset += readsPerServerSession) { - if (shouldStop()) { - summary.outcome = 'stopped' - return summary - } - if (offset > 0 && interBatchDelayMs > 0) { - await new Promise((resolve) => setTimeout(resolve, interBatchDelayMs)) - if (shouldStop()) { - // Why: opt-out can happen during the throttle delay; do not spawn a - // real-home app-server after the lane has been disabled. - summary.outcome = 'stopped' - return summary + const outcome = await readCodexThreadsForIndexHeal( + dirname(paths.systemSessionsRoot), + pending, + (thread, readOutcome) => { + if (readOutcome === 'healed') { + summary.healedThreads += 1 + } else if (readOutcome === 'missing') { + // The backfilled rollout was deleted after the audit was written. + summary.missingThreads += 1 + } else { + summary.failedThreads += 1 } - } - const batch = pending.slice(offset, offset + readsPerServerSession) - const timeoutMs = HEAL_BATCH_TIMEOUT_BASE_MS + HEAL_BATCH_TIMEOUT_PER_READ_MS * batch.length - try { - await runCodexAppServerSession( - buildInvocation(systemCodexHomePath, timeoutMs), - async (rpc) => { - let nextIndex = 0 - const worker = async (): Promise => { - while (nextIndex < batch.length && !shouldStop()) { - const thread = batch[nextIndex] - nextIndex += 1 - await healOneThread(rpc, thread, paths, summary) - } - } - await Promise.all(Array.from({ length: readConcurrency }, () => worker())) - } - ) - } catch (error) { - if (isCodexAppServerUnsupportedError(error)) { - if (shouldStop()) { - summary.outcome = 'stopped' - return summary - } - // Why: no retry churn on old CLIs — remember unsupported and re-probe - // after the retry interval or a version bump; nothing is marked healed. - writeHealMarker(paths, auditBytes, summary, { unsupportedAt: Date.now() }) - summary.outcome = 'unsupported' - return summary - } - // Transport failure (timeout, early exit, spawn error): unprocessed ids - // were never appended to the ledger, so the next pass resumes them. - console.warn('[codex-session-index-heal] Heal batch aborted:', error) - summary.outcome = 'aborted' - return summary - } + recordHealOutcome(paths, thread, readOutcome) + }, + options + ) + if (outcome === 'unsupported') { + // Why: no retry churn on old CLIs — remember unsupported and re-probe + // after the retry interval or a version bump; nothing is marked healed. + writeHealMarker(paths, auditBytes, summary, { unsupportedAt: Date.now() }) } - - if (shouldStop()) { - summary.outcome = 'stopped' + if (outcome !== 'completed' || shouldStop()) { + summary.outcome = outcome === 'completed' ? 'stopped' : outcome return summary } writeHealMarker( @@ -206,16 +177,76 @@ export async function runCodexSessionIndexHeal( return summary } -async function healOneThread( - rpc: { request: (method: string, params?: Record) => Promise }, - thread: PendingHealThread, - paths: CodexSessionIndexHealPaths, - summary: CodexSessionIndexHealSummary -): Promise { +/** + * Drives `thread/read` over `threads` in bounded app-server batches, reporting + * each settled read. Transport failures and sqlite contention abort the pass + * without reporting, so the caller's next pass retries those threads. + */ +export async function readCodexThreadsForIndexHeal( + codexHomePath: string, + threads: readonly T[], + onOutcome: (thread: T, outcome: CodexThreadReadOutcome) => void, + options: CodexSessionIndexHealOptions = {} +): Promise { + const buildInvocation = options.buildInvocation ?? buildNativeHealInvocation + const runSession = options.runSession ?? runCodexAppServerSession + const readsPerServerSession = resolveHealWorkLimit( + options.readsPerServerSession, + HEAL_READS_PER_SERVER_SESSION + ) + const readConcurrency = resolveHealWorkLimit(options.readConcurrency, HEAL_READ_CONCURRENCY) + const interBatchDelayMs = options.interBatchDelayMs ?? HEAL_INTER_BATCH_DELAY_MS + const shouldStop = options.shouldStop ?? ((): boolean => false) + + for (let offset = 0; offset < threads.length; offset += readsPerServerSession) { + if (shouldStop()) { + return 'stopped' + } + if (offset > 0 && interBatchDelayMs > 0) { + await new Promise((resolve) => setTimeout(resolve, interBatchDelayMs)) + if (shouldStop()) { + // Why: opt-out can happen during the throttle delay; do not spawn an + // app-server after the lane has been disabled. + return 'stopped' + } + } + const batch = threads.slice(offset, offset + readsPerServerSession) + const timeoutMs = HEAL_BATCH_TIMEOUT_BASE_MS + HEAL_BATCH_TIMEOUT_PER_READ_MS * batch.length + try { + await runSession(buildInvocation(codexHomePath, timeoutMs), async (rpc) => { + let nextIndex = 0 + const worker = async (): Promise => { + while (nextIndex < batch.length && !shouldStop()) { + const thread = batch[nextIndex] + nextIndex += 1 + onOutcome(thread, await readOneThread(rpc, thread.threadId)) + } + } + await Promise.all(Array.from({ length: readConcurrency }, () => worker())) + }) + } catch (error) { + if (shouldStop()) { + return 'stopped' + } + if (isCodexAppServerUnsupportedError(error)) { + return 'unsupported' + } + // Transport failure (timeout, early exit, spawn error): unprocessed ids + // were never reported, so the next pass resumes them. + console.warn('[codex-session-index-heal] Heal batch aborted:', error) + return 'aborted' + } + } + return 'completed' +} + +async function readOneThread( + rpc: CodexAppServerRpc, + threadId: string +): Promise { try { - await rpc.request('thread/read', { threadId: thread.threadId }) - summary.healedThreads += 1 - recordHealOutcome(paths, thread, 'healed') + await rpc.request('thread/read', { threadId }) + return 'healed' } catch (error) { if (isCodexAppServerUnsupportedError(error)) { throw error @@ -223,22 +254,18 @@ async function healOneThread( const message = error instanceof Error ? error.message : String(error) if (!message.startsWith('codex app-server thread/read failed')) { // Not an RPC-level response: the server died or timed out. Abort the - // batch without recording, so the id is retried on the next pass. + // batch without reporting, so the id is retried on the next pass. throw error } if (/no rollout found/i.test(message)) { - // The backfilled rollout was deleted after the audit was written. - summary.missingThreads += 1 - recordHealOutcome(paths, thread, 'missing') - return + return 'missing' } if (isTransientSqliteContention(message)) { - // Why: an active Codex process can briefly own sqlite; leave the id off - // the ledger and abort this pass so a later startup resumes it. + // Why: an active Codex process can briefly own sqlite; leave the id + // unreported and abort this pass so a later startup resumes it. throw error } - summary.failedThreads += 1 - recordHealOutcome(paths, thread, 'failed') + return 'failed' } } @@ -259,20 +286,23 @@ function resolveHealWorkLimit(value: number | undefined, maximum: number): numbe return Math.min(Math.floor(value), maximum) } -function buildNativeHealInvocation( - systemCodexHomePath: string, +export function buildNativeHealInvocation( + codexHomePath: string, timeoutMs: number ): CodexAppServerInvocation { const command = resolveCodexCommand() - const { spawnCmd, spawnArgs } = getSpawnArgsForWindows(command, ['app-server']) + // Why: each session is torn down after one batch, so plugin startup could + // leave marketplace clones running; indexing needs neither plugins nor tools. + const { spawnCmd, spawnArgs } = getSpawnArgsForWindows(command, [ + ...CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS + ]) return { command: spawnCmd, args: spawnArgs, cliPath: command, - // Why: pin the real home explicitly — nested Orca launches can inherit a - // managed CODEX_HOME from the daemon environment, which would index the - // wrong sqlite DB. - env: { CODEX_HOME: systemCodexHomePath }, + // Why: pin the home explicitly — nested Orca launches can inherit a managed + // CODEX_HOME from the daemon environment, which would index the wrong sqlite DB. + env: { CODEX_HOME: codexHomePath }, timeoutMs } } diff --git a/src/main/codex/codex-state-db-test-fixture.ts b/src/main/codex/codex-state-db-test-fixture.ts new file mode 100644 index 00000000000..e84f0328c3b --- /dev/null +++ b/src/main/codex/codex-state-db-test-fixture.ts @@ -0,0 +1,14 @@ +import { mkdirSync } from 'node:fs' +import { join } from 'node:path' +import SyncDatabase from '../sqlite/sync-database' + +/** Writes a Codex state DB whose startup backfill reports `status`. */ +export function writeCodexStateDbBackfillStatus(codexHomePath: string, status: string): void { + mkdirSync(codexHomePath, { recursive: true }) + const db = new SyncDatabase(join(codexHomePath, 'state_5.sqlite')) + db.exec( + 'CREATE TABLE backfill_state (id INTEGER PRIMARY KEY, status TEXT NOT NULL); ' + + `INSERT INTO backfill_state (id, status) VALUES (1, '${status}')` + ) + db.close() +} diff --git a/src/main/codex/codex-state-db.test.ts b/src/main/codex/codex-state-db.test.ts index 7cf0ac88ac5..a89a556b807 100644 --- a/src/main/codex/codex-state-db.test.ts +++ b/src/main/codex/codex-state-db.test.ts @@ -1,12 +1,13 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import SyncDatabase from '../sqlite/sync-database' import { findNewestCodexStateDbPath, isCodexStateDbBackfillPending, - readCodexStateDbBackfillStatus + readCodexStateDbBackfillStatus, + readIndexedCodexThreadIds } from './codex-state-db' const temporaryHomes: string[] = [] @@ -67,6 +68,19 @@ describe('Codex state DB backfill status', () => { expect(isCodexStateDbBackfillPending(home)).toBe(true) }) + it('counts compressed rollouts, which Codex also backfills', async () => { + const home = await createHome() + const sessions = join(home, 'sessions', '2026', '08', '04') + await mkdir(sessions, { recursive: true }) + await Promise.all( + Array.from({ length: 100 }, (_, index) => + writeFile(join(sessions, `rollout-${index}.jsonl.zst`), '') + ) + ) + + expect(isCodexStateDbBackfillPending(home)).toBe(true) + }) + it('does not call a complete backfill pending', async () => { const home = await createHome() createBackfillDb(home, 5, 'complete') @@ -74,3 +88,27 @@ describe('Codex state DB backfill status', () => { expect(isCodexStateDbBackfillPending(home)).toBe(false) }) }) + +describe('readIndexedCodexThreadIds', () => { + it('returns lower-cased thread ids from the newest state DB', async () => { + const home = await createHome() + const path = createBackfillDb(home, 5, 'complete') + const db = new SyncDatabase(path) + db.exec( + "CREATE TABLE threads (id TEXT PRIMARY KEY); INSERT INTO threads (id) VALUES ('ABC'), ('def')" + ) + db.close() + + expect(readIndexedCodexThreadIds(home)).toEqual(new Set(['abc', 'def'])) + }) + + it('returns null when there is no state DB or no threads table', async () => { + const home = await createHome() + expect(readIndexedCodexThreadIds(home)).toBeNull() + + createBackfillDb(home, 5, 'complete') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + expect(readIndexedCodexThreadIds(home)).toBeNull() + warn.mockRestore() + }) +}) diff --git a/src/main/codex/codex-state-db.ts b/src/main/codex/codex-state-db.ts index e2b437aea3a..ae8ff3eb046 100644 --- a/src/main/codex/codex-state-db.ts +++ b/src/main/codex/codex-state-db.ts @@ -71,6 +71,37 @@ export function readCodexStateDbBackfillStatus(codexHomePath: string): CodexStat } } +/** + * Lower-cased thread ids already in Codex's state DB, or null when the DB is + * missing or unreadable. Read-only; never creates or mutates Codex's database. + */ +export function readIndexedCodexThreadIds(codexHomePath: string): Set | null { + const stateDbPath = findNewestCodexStateDbPath(codexHomePath) + if (!stateDbPath) { + return null + } + let db: SyncDatabase | null = null + try { + db = new SyncDatabase(stateDbPath, { readonly: true, fileMustExist: true }) + const ids = new Set() + for (const row of db.prepare('SELECT id FROM threads').all()) { + if (typeof row.id === 'string') { + ids.add(row.id.toLowerCase()) + } + } + return ids + } catch (error) { + console.warn('[codex-state-db] Failed to read indexed Codex threads:', error) + return null + } finally { + try { + db?.close() + } catch { + // A close failure cannot change the read-only result already collected. + } + } +} + export function countCodexSessionFilesUpTo(sessionsRoot: string, limit: number): number { let count = 0 const pendingDirectories = [sessionsRoot] @@ -85,7 +116,11 @@ export function countCodexSessionFilesUpTo(sessionsRoot: string, limit: number): for (const entry of entries) { if (entry.isDirectory()) { pendingDirectories.push(join(directory, entry.name)) - } else if (entry.isFile() && entry.name.endsWith('.jsonl')) { + } else if ( + entry.isFile() && + // Why: Codex's startup backfill parses compressed rollouts too. + (entry.name.endsWith('.jsonl') || entry.name.endsWith('.jsonl.zst')) + ) { count += 1 if (count >= limit) { break diff --git a/src/main/startup/main-process-quit.ts b/src/main/startup/main-process-quit.ts index ad4548db7bd..f104a3ec343 100644 --- a/src/main/startup/main-process-quit.ts +++ b/src/main/startup/main-process-quit.ts @@ -15,6 +15,7 @@ import { clearRuntimeMetadataIfOwned } from '../runtime/runtime-metadata' import { shutdownPairedRuntimeBrowserClientHosts } from '../browser/paired-runtime-browser-client-host-runtime' import { browserManager } from '../browser/browser-manager' import { stopCodexStateDbBackfillRecoveries } from '../codex/codex-state-db-backfill-recovery' +import { stopCodexAccountSessionBridges } from '../codex/codex-account-session-bridge' import { awaitPackedRefsLockRelease } from '../git/local-repo-ref-maintenance' import { settleTeardownWithinDeadline, settleWithinMs } from '../quit-teardown-deadline' import { quitTeardownStartGate } from '../quit-teardown-start-gate' @@ -134,6 +135,7 @@ function installWillQuitHandler(): void { state.pluginMarketplaceInstaller = null const pluginHostShutdown = state.pluginService?.dispose() ?? Promise.resolve() const codexBackfillRecoveryShutdown = stopCodexStateDbBackfillRecoveries() + stopCodexAccountSessionBridges() // Why before the stop: teardown stamps each working session's resume marker with why the app // went away, and an update install is a restart the user never chose. setStructuredAgentSessionTeardownTrigger(updateQuitInProgress ? 'update' : 'quit') From bb91e39eb961e2c63a839037f988d7c925ac5023 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:14:28 -0700 Subject: [PATCH 02/83] test(native-chat): main's Codex child tests expect a turn to end on its own turn/completed (#23783) * fix(native-chat): a Codex child's turn ends on its own turn/completed #22553 ended a child thread's turn on an `error` Codex will not retry, reading the verdict module #23682 deleted when it made turn/completed the only end of a Codex turn. The two landed minutes apart with no textual conflict, so main no longer typechecks. Codex runs every thread's events, spawned children included, through the same per-thread handler: a turn-ending error is recorded as the turn's last error and the turn then completes as failed. So a child's failed turn/completed is its end, as on the primary thread, and a closed thread stays the one child ending with no completion. * refactor(native-chat): a closed Codex child thread is its own frame With a child's turn now ending only on its own turn/completed, the turn-ended frame carried a fixed turnId (null) and state (unverifiable), and endTurn took parameters nothing passed. Name the one remaining case: a thread-closed frame, and closeThread ending the running turn as unverifiable. Drop a test step that no longer exercised anything. --- .../codex/codex-background-task-frames.ts | 32 ++++------ .../codex/codex-background-task-tracker.ts | 4 +- .../codex/codex-child-work-evidence.test.ts | 58 +++++++++---------- ...dex-structured-child-work-producer.test.ts | 7 ++- .../codex/codex-structured-thread-facts.ts | 8 --- src/main/codex/codex-subagent-executions.ts | 15 ++--- 6 files changed, 49 insertions(+), 75 deletions(-) diff --git a/src/main/codex/codex-background-task-frames.ts b/src/main/codex/codex-background-task-frames.ts index 029cc7b50c7..f01863956b6 100644 --- a/src/main/codex/codex-background-task-frames.ts +++ b/src/main/codex/codex-background-task-frames.ts @@ -7,7 +7,7 @@ import { import { codexChildTurnState } from './codex-subagent-executions' import { readRecord } from './codex-item-field-readers' import { readCodexThreadItem } from './codex-structured-item-translation' -import { readCodexErrorWillRetry, readCodexTurnId } from './codex-structured-thread-facts' +import { readCodexTurnId } from './codex-structured-thread-facts' export type CodexBackgroundTaskFrame = | { @@ -25,15 +25,11 @@ export type CodexBackgroundTaskFrame = state: NativeChatSubagentState } | { - /** A child turn that ended with no `turn/completed`. No `turnId`: the one it is running. */ - kind: 'turn-ended' + /** A child thread that closed: it ran its last turn, and Codex never said how it went. */ + kind: 'thread-closed' threadId: string - turnId: string | null - state: CodexChildTurnEnding } -type CodexChildTurnEnding = Extract - export type CodexBackgroundTaskEvent = { method: string threadId: string @@ -41,24 +37,16 @@ export type CodexBackgroundTaskEvent = { } /** - * The two ways Codex ends a child's turn without `turn/completed`. An `error` it will not retry is - * that turn's own end: for a child, `turn/completed` may never follow, and without this end the - * child's lifecycle row latches on `working` for the life of the session. A closed thread ran its - * last turn, and Codex never said how it went. - * - * #23682 dropped the equivalent reading from the primary journal path, where Codex's own failed - * `turn/completed` always follows within ~32 ms and carries the duration the error lacks. A child - * has no such guarantee, which is why this path still settles on the error. + * The one way Codex ends a child's turn without `turn/completed`: a closed thread ran its last + * turn and Codex never said how it went. A turn-ending `error` is not one — Codex follows it with + * a failed `turn/completed` for the same turn, which is that turn's end and carries the duration + * and receipt time the error does not. */ -function readCodexChildTurnEnding( +function readCodexChildThreadClosed( event: CodexBackgroundTaskEvent ): CodexBackgroundTaskFrame | null { - if (event.method === 'error' && !readCodexErrorWillRetry(event.params)) { - const turnId = readCodexTurnId(event.params) - return { kind: 'turn-ended', threadId: event.threadId, turnId, state: 'failed' } - } return event.method === 'thread/closed' - ? { kind: 'turn-ended', threadId: event.threadId, turnId: null, state: 'unverifiable' } + ? { kind: 'thread-closed', threadId: event.threadId } : null } @@ -67,7 +55,7 @@ export function readCodexBackgroundTaskFrame( primaryThreadId: string ): CodexBackgroundTaskFrame | null { // The session's own turn ends through the journal's turn boundaries, never here. - const ending = event.threadId === primaryThreadId ? null : readCodexChildTurnEnding(event) + const ending = event.threadId === primaryThreadId ? null : readCodexChildThreadClosed(event) if (ending) { return ending } diff --git a/src/main/codex/codex-background-task-tracker.ts b/src/main/codex/codex-background-task-tracker.ts index 351b35e6b84..6429a84d4fd 100644 --- a/src/main/codex/codex-background-task-tracker.ts +++ b/src/main/codex/codex-background-task-tracker.ts @@ -80,8 +80,8 @@ export class CodexBackgroundTaskTracker { frame.parentTurnId, frame.spawnerThreadId ) - } else if (frame?.kind === 'turn-ended') { - this.executions.endTurn(frame.threadId, frame.turnId, frame.state) + } else if (frame?.kind === 'thread-closed') { + this.executions.closeThread(frame.threadId) } else if (frame && frame.threadId !== this.primaryThreadId) { this.executions.observeTurn(frame.threadId, frame.turnId, frame.state) } diff --git a/src/main/codex/codex-child-work-evidence.test.ts b/src/main/codex/codex-child-work-evidence.test.ts index 9013b07a674..5b1b1bc29b4 100644 --- a/src/main/codex/codex-child-work-evidence.test.ts +++ b/src/main/codex/codex-child-work-evidence.test.ts @@ -159,18 +159,10 @@ describe('Codex child-work evidence', () => { expect(tracker.state).toBeNull() }) - const childError = ( - turnId: string | undefined, - willRetry: boolean - ): CodexBackgroundTaskEvent => ({ + const childError = (turnId: string, willRetry: boolean): CodexBackgroundTaskEvent => ({ method: 'error', threadId: CHILD, - params: { - threadId: CHILD, - ...(turnId ? { turnId } : {}), - willRetry, - error: { message: 'boom' } - } + params: { threadId: CHILD, turnId, willRetry, error: { message: 'boom' } } }) const childClosed: CodexBackgroundTaskEvent = { method: 'thread/closed', @@ -178,25 +170,30 @@ describe('Codex child-work evidence', () => { params: { threadId: CHILD } } - it.each([ - ['an error naming its turn that Codex will not retry', childError('c1', false), 'failed'], - ['an error naming no turn that Codex will not retry', childError(undefined, false), 'failed'], - ['its thread closing', childClosed, 'unknown'] - ])( - 'settles a working child whose turn ended with no turn/completed, by %s, in the strip and the record together', - (_label, ending, outcome) => { - const { send, tracker, records } = runningChild() - expect(tracker.state?.tasks).toHaveLength(1) - send(ending) - expect(records()).toEqual([ - expect.objectContaining({ membership: 'settled', state: 'done', outcome }) - ]) - expect(tracker.state).toBeNull() - // The first ending a turn gets stands. - send(turn('turn/completed', CHILD, 'c1', 'completed')) - expect(records()).toEqual([expect.objectContaining({ outcome })]) - } - ) + it('keeps a child working through an error Codex will not retry, and settles it on the failed turn/completed that follows', () => { + const { send, tracker, records } = runningChild() + send(childError('c1', false)) + expect(records()).toEqual([expect.objectContaining({ membership: 'live' })]) + expect(tracker.state?.tasks).toHaveLength(1) + send(turn('turn/completed', CHILD, 'c1', 'failed')) + expect(records()).toEqual([ + expect.objectContaining({ membership: 'settled', state: 'done', outcome: 'failed' }) + ]) + expect(tracker.state).toBeNull() + }) + + it('settles a working child whose thread closed with no turn/completed, in the strip and the record together', () => { + const { send, tracker, records } = runningChild() + expect(tracker.state?.tasks).toHaveLength(1) + send(childClosed) + expect(records()).toEqual([ + expect.objectContaining({ membership: 'settled', state: 'done', outcome: 'unknown' }) + ]) + expect(tracker.state).toBeNull() + // The first ending a turn gets stands. + send(turn('turn/completed', CHILD, 'c1', 'completed')) + expect(records()).toEqual([expect.objectContaining({ outcome: 'unknown' })]) + }) it('keeps a child working through a retried error and a systemError status: its turn runs on', () => { const { send, tracker, records } = runningChild() @@ -207,9 +204,6 @@ describe('Codex child-work evidence', () => { }) expect(records()).toEqual([expect.objectContaining({ membership: 'live', state: 'working' })]) expect(tracker.state?.tasks).toHaveLength(1) - // A fatal error naming a turn the child already finished ends nothing. - send(turn('turn/completed', CHILD, 'c1'), childError('c1', false)) - expect(records()).toEqual([expect.objectContaining({ outcome: 'succeeded' })]) }) it('never settles a child on its PARENT turn ending: children outlive the turn', () => { diff --git a/src/main/codex/codex-structured-child-work-producer.test.ts b/src/main/codex/codex-structured-child-work-producer.test.ts index fc011d48bb9..611b7f75b57 100644 --- a/src/main/codex/codex-structured-child-work-producer.test.ts +++ b/src/main/codex/codex-structured-child-work-producer.test.ts @@ -332,13 +332,18 @@ describe('Codex structured child-work producer', () => { { frame: turn('turn/started', TESTER, 't1'), lead: 'working' }, { frame: spawned(LINTER, 'lint', 'p2'), lead: 'working' }, { frame: turn('turn/started', LINTER, 'l1'), lead: 'working' }, - // Codex ends this child's turn with an error it will not retry, and no turn/completed. + // Codex ends this child's turn with an error it will not retry, then a failed completion. { frame: { method: 'error', params: { threadId: LINTER, turnId: 'l1', willRetry: false, error: { message: 'boom' } } }, lead: 'working', + check: () => expect(byDescription('lint')).toMatchObject({ membership: 'live' }) + }, + { + frame: turn('turn/completed', LINTER, 'l1', 'failed'), + lead: 'working', check: () => expect(byDescription('lint')).toMatchObject({ membership: 'settled', outcome: 'failed' }) }, diff --git a/src/main/codex/codex-structured-thread-facts.ts b/src/main/codex/codex-structured-thread-facts.ts index aaf65f93ec6..f2a42e6d3db 100644 --- a/src/main/codex/codex-structured-thread-facts.ts +++ b/src/main/codex/codex-structured-thread-facts.ts @@ -65,14 +65,6 @@ export function readCodexTurnDurationMs(payload: unknown): number | null { /** `thread/status/changed` carries a TAGGED status (`{status:{type}}`), never a * bare string. `idle` and `systemError` are the two arms that mean the thread * is not running; `active` and `notLoaded` are not. */ -/** - * Codex hardcodes `willRetry: false` on an `error` that affects turn status, and `true` on a - * stream error it is about to retry, which ends nothing. - */ -export function readCodexErrorWillRetry(payload: unknown): boolean { - return record(payload)?.willRetry === true -} - export function codexThreadStoppedRunning(payload: unknown): boolean { const type = record(record(payload)?.status)?.type return type === 'idle' || type === 'systemError' diff --git a/src/main/codex/codex-subagent-executions.ts b/src/main/codex/codex-subagent-executions.ts index 939d1b90331..87d9327c70c 100644 --- a/src/main/codex/codex-subagent-executions.ts +++ b/src/main/codex/codex-subagent-executions.ts @@ -94,17 +94,12 @@ export class CodexSubagentExecutions { return { child, execution } } - /** A child turn that ended with no `turn/completed`. With no turn named, the one the child is - * running ended; a child running none has nothing to end. The first ending a turn gets stands. */ - endTurn( - agentThreadId: string, - turnId: string | null, - state: Exclude - ): void { + /** The child's thread closed with no `turn/completed`: the turn it was running ended, and how + * it went is unknown. A child running none has nothing to end. */ + closeThread(agentThreadId: string): void { const current = this.children.get(agentThreadId)?.execution - const ended = turnId ?? (current?.state === 'working' ? current.turnId : null) - if (current && ended !== null) { - this.observeTurn(agentThreadId, ended, state) + if (current?.state === 'working') { + this.observeTurn(agentThreadId, current.turnId, 'unverifiable') } } From 36c473ea1ad30b68a7f09035bf7eeb74e8ff438d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:16:20 -0700 Subject: [PATCH 03/83] fix(runtime): wait out Codex 0.157's startup screen, and stop at Codex's startup dialogs, before typing a worker brief (#23745) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(runtime): wait for Codex's live chat before typing a worker brief Codex 0.157 draws a provisional startup screen (header reads model: loading) and discards typed input while it starts its shared daemon behind it; a fresh Codex home makes that window seconds long, so worker-start pasted briefs that were truncated or never submitted. Codex 0.158 dropped the header labels Orca matched, so worker-start stopped seeing Codex as ready at all. Readiness now requires Codex's live chat on both layouts: the provisional header vetoes a text match unless the live status row is already painted, and 0.158's greeting layout counts once that status row appears. Codex 0.158's model announcement dialog is reported as a blocked prompt instead of receiving the brief. * fix(runtime): recognise Codex's provisional screen from the text copy and the screen probe Live worker-start on a fresh Codex 0.157 home still typed during the daemon start: Codex leaves its alternate screen for that window, so the live screen showed no header and the screen-based veto never fired. The text copy keeps the provisional header until the live chat paints its status row, so the veto now reads it there. The tui-idle visible-screen probe used the bare text rule on the rendered screen; it now goes through the same body rule. * test(daemon): register the new Codex captures' known serializer divergences The serialize round-trip replay picks up every fixture under runtime/__fixtures__, and the three new Codex 0.157/0.158 captures showed 48/9/8 "new-fail" checkpoints against an expected 0, turning CI red. They are the existing live-pen colour leak on restored cells, the same class as the other Codex and DSH entries; this branch changes no serializer code. * fix(runtime): keep Qoder off the Codex screen probe change; drop an unbacked row filter - The tui-idle visible-screen probe now classified Qoder panes with isQoderComposerReady, which skips the working veto evaluateTuiIdle applies first. Qoder paints its composer mid-turn, so an adopted Qoder pane whose hooks said "working" settled the wait immediately. Only Codex and unknown panes take the body rule there; every other agent keeps its old verdict. - The live status-row check skipped rows containing "waiting for startup", a string Codex 0.157/0.158's TUI never prints. The line-folded text copy keeps a whole screen on one line, so the filter could only ever veto the real status row. It is now a bounded includes() with no split. - Lowercase the wait text once in isKnownReadyPromptBody. - Restore the per-frame "screen never takes a settled header away" check, guarded on the provisional veto, instead of checking the final frame only. * fix(runtime): stop reporting Codex 0.158's model announcement once it is answered The announcement's choices stay in the text copy after the user answers it, and the existing dismissal check needed the model:/directory: labels that 0.158's header lacks, so tui-idle waits and the agent-status query kept reporting codex-model-migration-prompt over a live chat. Codex repaints its whole screen, header included, when a startup dialog closes, so the header after the dialog now marks it answered. Also corrects the live-chat marker comments: the middle dot also comes from the daemon session's agents hint row and the warnings notice, not only the status row. * docs(runtime): note that Codex startup dialogs also draw the live-footer dot * fix(runtime): recognise Codex 0.157/0.158 startup dialogs by the rows they really print Codex 0.157 and 0.158 no longer print `Press enter to continue/confirm` on their startup dialogs; they print key rows instead (`enter continue · esc skip`, `enter confirm · esc skip`, `enter/esc continue · ctrl+c quit`). The update, hooks-review and model-migration matchers still required the old wording, so none of these dialogs was reported as blocked. On 0.157 the dialog's `·` also satisfied the live-footer check, so a tui-idle wait read the update dialog as ready and worker-start would type the brief into it, where Enter picks "Update now" (npm install -g, Codex exits). On 0.158 the wait timed out instead of reporting blocked. The matchers now accept the old wording or the new row, tolerating the spaces the line-folded text copy drops around `·`. Each one matches from the dialog's first `·` (for the update dialog that is its title row, `Update available · 0.157.0 → …`), so the dialog is blocked from the same character that would otherwise make the provisional header read as live. The retired-model notice without choices has a catalog-supplied heading (`GPT-5.4 is no longer available`), so it is matched by its own key row. No new blocked-reason value. The startup-dialog matchers move to startup-dialog-blocked-signals.ts to keep terminal-wait-detection.ts under the line limit. Backed by six real captures (update available, hooks review, retired model without choices, each on 0.157.0 and 0.158.0), replayed frame by frame and through a tui-idle wait; the serializer round-trip replay registers their existing live-pen colour divergences. * fix(runtime): keep reporting Codex's retired-model notice after a relaunch in the same pane The retired-model notice is matched by its key row alone, and the matcher took the first `enter/esc continue ·` in the live window while every other startup-dialog matcher takes the last. Quitting Codex from the notice and relaunching it in the same pane leaves the old copy ahead of the new launch's header, so the header read as having dismissed the new notice: 0.157 then read ready and a worker brief would be typed into the dialog. Take the last key row, and replay each captured dialog quit-and-relaunched to pin all six. * fix(runtime): match Codex startup dialogs by the rows the text copy keeps intact Codex 0.157+ paints each startup dialog over its startup screen by cell diff, so Orca's line-folded text copy can drop letters and spaces from a heading: #23765's 0.157.1 capture reads `Updat available`. The update matcher needed `update available`, so on that capture tier 1 read the dialog's own `·` as the live chat's footer and a tui-idle wait settled ready on the update dialog, whose Enter picks "Update now". Match each dialog from its first `·` by rows Codex prints as fixed literals: `available · ` and `enter continue · esc skip` (update), `enter confirm ·` (hooks review), `enter/esc continue|confirm ·` (model notices, which also covers 0.158's new-model announcement, so its choice-text matcher goes). Legacy `Press enter to …` wording still matches. Add the new rows to the blocked-signal prefilter, and replay #23765's 0.157.1 update capture in the dialog suite. * fix(runtime): don't name Codex's mid-session pickers a hooks review Codex's rate-limit reset popup (and its other pickers) end their key row with `enter confirm · esc back`, which the hooks-review row matched now that it no longer needs the heading. Exclude `esc back` instead of requiring `esc skip`, so a half-painted hooks-review row still blocks. --- .../serialize-grid-transcript-replay.test.ts | 11 + ...x-0157-fresh-home-daemon-install.meta.json | 9 + .../codex-0157-fresh-home-daemon-install.txt | 2 + .../codex-0157-hooks-review-dialog.meta.json | 9 + .../codex-0157-hooks-review-dialog.txt | 2 + .../codex-0157-model-retired-dialog.meta.json | 9 + .../codex-0157-model-retired-dialog.txt | 2 + ...dex-0157-update-available-dialog.meta.json | 9 + .../codex-0157-update-available-dialog.txt | 2 + .../codex-0158-fresh-home-greeting.meta.json | 9 + .../codex-0158-fresh-home-greeting.txt | 1 + .../codex-0158-hooks-review-dialog.meta.json | 9 + .../codex-0158-hooks-review-dialog.txt | 1 + ...x-0158-model-announcement-dialog.meta.json | 9 + .../codex-0158-model-announcement-dialog.txt | 1 + .../codex-0158-model-retired-dialog.meta.json | 9 + .../codex-0158-model-retired-dialog.txt | 1 + ...dex-0158-update-available-dialog.meta.json | 9 + .../codex-0158-update-available-dialog.txt | 1 + ...codex-header-readiness-transcripts.test.ts | 102 ++++++++- .../codex-startup-dialog-transcripts.test.ts | 198 ++++++++++++++++++ src/main/runtime/codex-terminal-readiness.ts | 21 ++ ...ntime-start-tui-idle-visible-read-probe.ts | 4 +- .../runtime/startup-dialog-blocked-signals.ts | 76 +++++++ src/main/runtime/terminal-wait-detection.ts | 45 ++-- 25 files changed, 521 insertions(+), 30 deletions(-) create mode 100644 src/main/runtime/__fixtures__/codex-0157-fresh-home-daemon-install.meta.json create mode 100644 src/main/runtime/__fixtures__/codex-0157-fresh-home-daemon-install.txt create mode 100644 src/main/runtime/__fixtures__/codex-0157-hooks-review-dialog.meta.json create mode 100644 src/main/runtime/__fixtures__/codex-0157-hooks-review-dialog.txt create mode 100644 src/main/runtime/__fixtures__/codex-0157-model-retired-dialog.meta.json create mode 100644 src/main/runtime/__fixtures__/codex-0157-model-retired-dialog.txt create mode 100644 src/main/runtime/__fixtures__/codex-0157-update-available-dialog.meta.json create mode 100644 src/main/runtime/__fixtures__/codex-0157-update-available-dialog.txt create mode 100644 src/main/runtime/__fixtures__/codex-0158-fresh-home-greeting.meta.json create mode 100644 src/main/runtime/__fixtures__/codex-0158-fresh-home-greeting.txt create mode 100644 src/main/runtime/__fixtures__/codex-0158-hooks-review-dialog.meta.json create mode 100644 src/main/runtime/__fixtures__/codex-0158-hooks-review-dialog.txt create mode 100644 src/main/runtime/__fixtures__/codex-0158-model-announcement-dialog.meta.json create mode 100644 src/main/runtime/__fixtures__/codex-0158-model-announcement-dialog.txt create mode 100644 src/main/runtime/__fixtures__/codex-0158-model-retired-dialog.meta.json create mode 100644 src/main/runtime/__fixtures__/codex-0158-model-retired-dialog.txt create mode 100644 src/main/runtime/__fixtures__/codex-0158-update-available-dialog.meta.json create mode 100644 src/main/runtime/__fixtures__/codex-0158-update-available-dialog.txt create mode 100644 src/main/runtime/codex-startup-dialog-transcripts.test.ts create mode 100644 src/main/runtime/startup-dialog-blocked-signals.ts diff --git a/src/main/daemon/serialize-grid-transcript-replay.test.ts b/src/main/daemon/serialize-grid-transcript-replay.test.ts index 298aaa681bf..cbe9b5db2c0 100644 --- a/src/main/daemon/serialize-grid-transcript-replay.test.ts +++ b/src/main/daemon/serialize-grid-transcript-replay.test.ts @@ -43,6 +43,17 @@ const KNOWN_PREEXISTING_I2_FAILURES: Record = { 'codex-0157-effort-override-embedded-warning': 4, 'codex-0157-no-daemon-effort-override': 16, 'codex-0157-plain-ready': 18, + // Fresh-home 0.157/0.158 captures: the live pen's true-colour fg/bg leaks onto restored cells. + 'codex-0157-fresh-home-daemon-install': 48, + 'codex-0158-fresh-home-greeting': 9, + 'codex-0158-model-announcement-dialog': 8, + // Codex 0.157/0.158 startup-dialog captures: the same live-pen true-colour leak onto restored cells. + 'codex-0157-update-available-dialog': 26, + 'codex-0158-update-available-dialog': 8, + 'codex-0157-hooks-review-dialog': 24, + 'codex-0158-hooks-review-dialog': 8, + 'codex-0157-model-retired-dialog': 22, + 'codex-0158-model-retired-dialog': 6, // Same extra dim bit on the 0.157/0.158 header row (STA-8834 fixtures). 'codex-0-157-1-update-dialog': 16, 'codex-0-158-0-approval': 12, diff --git a/src/main/runtime/__fixtures__/codex-0157-fresh-home-daemon-install.meta.json b/src/main/runtime/__fixtures__/codex-0157-fresh-home-daemon-install.meta.json new file mode 100644 index 00000000000..04203db4fbe --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0157-fresh-home-daemon-install.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-28T21:45:00.000Z", + "platform": "darwin", + "command": ["codex", "--dangerously-bypass-approvals-and-sandbox"], + "cols": 120, + "rows": 40, + "note": "codex-cli 0.157.0, plain launch (no -m/-c) on a fresh CODEX_HOME. The provisional screen reads `model: loading` while Codex installs and starts its shared daemon (`Installing daemon from CLI version 0.157.0`); 0.157 discards typed input during that start. The live header fills in at the end. Cut 6 s after spawn. Home-directory user name redacted by hand, same length.", + "exitCode": null +} diff --git a/src/main/runtime/__fixtures__/codex-0157-fresh-home-daemon-install.txt b/src/main/runtime/__fixtures__/codex-0157-fresh-home-daemon-install.txt new file mode 100644 index 00000000000..a6aa2c9af2c --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0157-fresh-home-daemon-install.txt @@ -0,0 +1,2 @@ +[?2004h[>4;0m[>7u[?1004h]10;?\]11;?\[?u[?2026h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l╭───────────────────────────────────────╮│ >_ OpenAI Codex (v0.157.0) ││ ││ model: loading /model to change ││ directory: loading │╰───────────────────────────────────────╯ › Ask Codex to do anything ? for shortcuts[0 q╭[?25h[?2026l[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l─────────────╮ │ │ loading /model to change │ /Users/user1/cr/rounds/x157fresh/repo ││ permissions: YOLO mode │╰────────────────────────────────────────────────────╯[?25h[?2026l[?2026h[?25h[?2026l[?1006l[?1015l[?1003l[?1002l[?1000l[<1u[?1007l[?1049l[<1u[>4;0m[?2004l[?1004l[0 q[?25hInstalling daemon from CLI version 0.157.0 into /Users/user1/cr/rounds/x157fresh/home/.codex/packages/app-server-daemon... +[?2004h[>4;0m[>7u[?1004h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l╭────────────────────────────────────────────────────╮│ >_ OpenAI Codex (v0.157.0) ││ ││ model: loading /model to change ││ directory: /Users/user1/cr/rounds/x157fresh/repo ││ permissions: YOLO mode │╰────────────────────────────────────────────────────╯ › Ask Codex to do anything ? for shortcuts[0 q╭[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l]0;repo[?2026h[?25h[?2026l[?2026h[?25lTip: Visit the ]8;;https://community.openai.com/c/codex/37Codex community forum]8;; (]8;;https://community.openai.com/c/codex/37https://community.openai.com/c/codex/37]8;;).GPT-6-Astra default · /Users/user1/cr/rounds/x157fresh/repo←agens · ? for shortcuts[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l]0;⠙ repo]0;repo[?2026h[?25lGPT-6-Astra /model to change⠈⢀⠁⠂⠄⠈⠁⠈⠁⠈⢀⠠⠄⠠⢀⠠⡀⠠⠁⢀⠁[?25h[?2026l[?2026h[?25l⠄[?25h[?2026l[?2026h[?25l⠄[?25h[?2026l[?2026h[?25l⠈⢀⠁⠐⠂⠄⠈⠁⠈⠁⠈⢀⠠⠄⠠⢀⠠⠄⡀⠈⠠⠁⢀⠁[?25h[?2026l[?2026h[?25l⠈⢀⠁⠐⠂⠄⠈⠁⠈⠁⠈⢀⠠⠄⠠⢀⠠⠄⡀⠈⠠⠁⢀[?25h[?2026l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/codex-0157-hooks-review-dialog.meta.json b/src/main/runtime/__fixtures__/codex-0157-hooks-review-dialog.meta.json new file mode 100644 index 00000000000..ebc2a471a20 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0157-hooks-review-dialog.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-29T03:30:27.000Z", + "platform": "darwin", + "command": ["codex", "--dangerously-bypass-approvals-and-sandbox"], + "cols": 120, + "rows": 40, + "note": "codex-cli 0.157.0, plain launch on a fresh CODEX_HOME with a hooks.json of 8 command hooks that were never trusted. Over the provisional screen Codex paints `Hooks need review`, `1. Review hooks` / `2. Trust all and continue` / `3. Continue without trusting (hooks won't run)` and the key row `enter confirm · esc skip`, where older builds wrote `Press enter to confirm`. No key was sent (only automatic terminal-query replies). Cut 6 s after spawn. Home-directory user name redacted by hand, same length.", + "exitCode": null +} diff --git a/src/main/runtime/__fixtures__/codex-0157-hooks-review-dialog.txt b/src/main/runtime/__fixtures__/codex-0157-hooks-review-dialog.txt new file mode 100644 index 00000000000..14b1ad743e1 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0157-hooks-review-dialog.txt @@ -0,0 +1,2 @@ +[?2004h[>4;0m[>7u[?1004h]10;?\]11;?\[?u[?2026h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l╭───────────────────────────────────────╮│ >_ OpenAI Codex (v0.157.0) ││ ││ model: loading /model to change ││ directory: loading │╰───────────────────────────────────────╯ › Ask Codex to do anything ? for shortcuts[0 q╭[?25h[?2026l[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l───────────╮ │ │ loading /model to change │ /Users/user1/cr/rounds/dlg-h57/repo ││ permissions: YOLO mode │╰──────────────────────────────────────────────────╯[?25h[?2026l[?1006l[?1015l[?1003l[?1002l[?1000l[<1u[?1007l[?1049l[<1u[>4;0m[?2004l[?1004l[0 q[?25hInstalling daemon from CLI version 0.157.0 into /Users/user1/cr/rounds/dlg-h57/home/.codex/packages/app-server-daemon... +[?2004h[>4;0m[>7u[?1004h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l╭──────────────────────────────────────────────────╮│ >_ OpenAI Codex (v0.157.0) ││ ││ model: loading /model to change ││ directory: /Users/user1/cr/rounds/dlg-h57/repo ││ permissions: YOLO mode │╰──────────────────────────────────────────────────╯ › Ask Codex to do anything ? for shortcuts[0 q╭[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l  Hooks need review 8 hooks are new or changed. Hooks can run outside the sandbox after you trust them.  › 1. Review hooks  2. Trust all and continue 3. Continue without trusting (hooks won't run) enter confirm · esc skip    [?2026l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/codex-0157-model-retired-dialog.meta.json b/src/main/runtime/__fixtures__/codex-0157-model-retired-dialog.meta.json new file mode 100644 index 00000000000..0e97bbe4715 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0157-model-retired-dialog.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-29T03:31:06.000Z", + "platform": "darwin", + "command": ["codex", "--dangerously-bypass-approvals-and-sandbox"], + "cols": 120, + "rows": 40, + "note": "codex-cli 0.157.0, plain launch on a fresh CODEX_HOME whose config.toml sets model = \"gpt-5.4-mini\", a model missing from 0.157's catalog, so Codex shows its retired-model notice without choices: `GPT-5.4 Mini is no longer available`, `Switch to GPT-6 Luna to continue.` and the key row `enter/esc continue · ctrl+c quit`. Enter or Esc switches the model; the heading comes from the model catalog, not the older `Codex just got an upgrade` wording. No key was sent (only automatic terminal-query replies). Cut 6 s after spawn. Home-directory user name redacted by hand, same length.", + "exitCode": null +} diff --git a/src/main/runtime/__fixtures__/codex-0157-model-retired-dialog.txt b/src/main/runtime/__fixtures__/codex-0157-model-retired-dialog.txt new file mode 100644 index 00000000000..776b261a2d6 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0157-model-retired-dialog.txt @@ -0,0 +1,2 @@ +[?2004h[>4;0m[>7u[?1004h]10;?\]11;?\[?u[?2026h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l╭───────────────────────────────────────╮│ >_ OpenAI Codex (v0.157.0) ││ ││ model: loading /model to change ││ directory: loading │╰───────────────────────────────────────╯ › Ask Codex to do anything ? for shortcuts[0 q╭[?25h[?2026l[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l───────────╮ │ │ loading /model to change │ /Users/user1/cr/rounds/dlg-m57/repo ││ permissions: YOLO mode │╰──────────────────────────────────────────────────╯[?25h[?2026l[?1006l[?1015l[?1003l[?1002l[?1000l[<1u[?1007l[?1049l[<1u[>4;0m[?2004l[?1004l[0 q[?25hInstalling daemon from CLI version 0.157.0 into /Users/user1/cr/rounds/dlg-m57/home/.codex/packages/app-server-daemon... +[?2004h[>4;0m[>7u[?1004h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l╭──────────────────────────────────────────────────╮│ >_ OpenAI Codex (v0.157.0) ││ ││ model: loading /model to change ││ directory: /Users/user1/cr/rounds/dlg-m57/repo ││ permissions: YOLO mode │╰──────────────────────────────────────────────────╯ › Ask Codex to do anything ? for shortcuts[0 q╭[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l  GPT-5.4 Mini is no longer available  Codex now uses GPT-6 Luna in place of GPT-5.4 Mini. Switch to GPT-6 Luna to continue. enter/esc continue · ctrl+c quit     [?2026l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/codex-0157-update-available-dialog.meta.json b/src/main/runtime/__fixtures__/codex-0157-update-available-dialog.meta.json new file mode 100644 index 00000000000..a81301d2215 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0157-update-available-dialog.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-29T03:29:52.000Z", + "platform": "darwin", + "command": ["codex", "--dangerously-bypass-approvals-and-sandbox"], + "cols": 120, + "rows": 40, + "note": "codex-cli 0.157.0, plain launch on a fresh CODEX_HOME whose config.toml sets check_for_update_on_startup = true, with a version.json cache naming 0.159.0 checked moments earlier (so no network check) and CODEX_MANAGED_BY_NPM=1 so Codex offers an update command. Over the provisional screen Codex paints `Update available · 0.157.0 → 0.159.0`, `1. Update now (runs `npm install -g @openai/codex`)` / `2. Skip` / `3. Skip until next version` and the key row `enter continue · esc skip`, where older builds wrote `Press enter to continue`. Enter picks Update now. No key was sent (only automatic terminal-query replies). Cut 6 s after spawn. Home-directory user name redacted by hand, same length.", + "exitCode": null +} diff --git a/src/main/runtime/__fixtures__/codex-0157-update-available-dialog.txt b/src/main/runtime/__fixtures__/codex-0157-update-available-dialog.txt new file mode 100644 index 00000000000..4701e63af24 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0157-update-available-dialog.txt @@ -0,0 +1,2 @@ +[?2004h[>4;0m[>7u[?1004h]10;?\]11;?\[?u[?2026h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l╭───────────────────────────────────────╮│ >_ OpenAI Codex (v0.157.0) ││ ││ model: loading /model to change ││ directory: loading │╰───────────────────────────────────────╯ › Ask Codex to do anything ? for shortcuts[0 q╭[?25h[?2026l[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l───────────╮ │ │ loading /model to change │ /Users/user1/cr/rounds/dlg-u57/repo ││ permissions: YOLO mode │╰──────────────────────────────────────────────────╯[?25h[?2026l[?2026h[?25h[?2026l[?1006l[?1015l[?1003l[?1002l[?1000l[<1u[?1007l[?1049l[<1u[>4;0m[?2004l[?1004l[0 q[?25hInstalling daemon from CLI version 0.157.0 into /Users/user1/cr/rounds/dlg-u57/home/.codex/packages/app-server-daemon... +[?2004h[>4;0m[>7u[?1004h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l╭──────────────────────────────────────────────────╮│ >_ OpenAI Codex (v0.157.0) ││ ││ model: loading /model to change ││ directory: /Users/user1/cr/rounds/dlg-u57/repo ││ permissions: YOLO mode │╰──────────────────────────────────────────────────╯ › Ask Codex to do anything ? for shortcuts[0 q╭[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l  Update available · 0.157.0 → 0.159.0 Release notes: ]8;;https://github.com/openai/codex/releases/latesthttps://github.com/openai/codex/releases/latest]8;; › 1. Update now (runs `npm install -g @openai/codex`)  2. Skip 3. Skip until next version  enter continue · esc skip    [?2026l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/codex-0158-fresh-home-greeting.meta.json b/src/main/runtime/__fixtures__/codex-0158-fresh-home-greeting.meta.json new file mode 100644 index 00000000000..ea7d9513a9f --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0158-fresh-home-greeting.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-28T21:44:00.000Z", + "platform": "darwin", + "command": ["codex", "--dangerously-bypass-approvals-and-sandbox"], + "cols": 120, + "rows": 40, + "note": "codex-cli 0.158.0, plain launch (no -m/-c) on a fresh CODEX_HOME. Greeting layout: an unboxed `>_ OpenAI Codex (v0.158.0)` header with no model:/directory: labels, starting from a provisional screen whose directory reads `loading`; the live status row under the composer appears last. Braille logo animation frames included. Cut 4.6 s after spawn. Home-directory user name redacted by hand, same length.", + "exitCode": null +} diff --git a/src/main/runtime/__fixtures__/codex-0158-fresh-home-greeting.txt b/src/main/runtime/__fixtures__/codex-0158-fresh-home-greeting.txt new file mode 100644 index 00000000000..72670b00f4b --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0158-fresh-home-greeting.txt @@ -0,0 +1 @@ +[?2004h[>4;0m[>7u[?1004h]10;?\]11;?\[?u[?2026h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l>_ OpenAI Codex (v0.158.0)loadingShall we see where this goes?⣀⣤⣤⣤⣀⣀⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⣦⣤⣤⣤⣤⣤⣤⡀⢀⣾⣿⣿⠿⠋⠉⠉⢉⣭⣿⣿⣿⣿⣿⠿⣿⣿⣿⣿⣷⣄⣀⣾⣿⣿⠃⣀⣴⣾⣿⣿⡿⠟⠋⣀⡀⠈⠙⢿⣿⣿⣧⣀⣶⣿⣿⣿⣿⡇⢸⣿⣿⡿⠛⠉⢀⣠⣴⣿⣿⣿⣷⣦⣀⠈⢻⣿⣿⡇⣰⣿⣿⡿⢿⣿⣿⡇⢸⣿⣿⢀⣤⣶⣿⣿⣿⠟⠛⠻⣿⣿⣿⣿⣮⣿⣿⡷⢰⣿⣿⡟⠁⢸⣿⣿⡇⢸⣿⣿⣿⣿⠿⠿⣿⣿⣿⣦⣄⡀⠈⠛⠿⣿⣿⣿⣧⡀⣾⣿⣿⠃⢸⣿⣿⡇⢸⣿⣿⠋⠁⠈⠙⢻⣿⣿⣿⣶⣤⡀⠹⢿⣿⣷⡄⢸⣿⣿⣇⠸⣿⣿⣷⣦⣼⣿⣿⢸⣿⣿⠻⢿⣿⣿⡇⠘⣿⣿⣿⠈⢿⣿⣿⣦⡀⠈⠛⠿⣿⣿⣿⣿⣄⡀⢀⣠⣼⣿⣿⣿⣿⡇⣿⣿⣿⠇⢻⣿⣿⣿⣷⣦⣀⠈⠙⠻⣿⣿⣿⣶⣶⣿⣿⣿⣿⣿⣿⣿⡇⣠⣿⣿⣿⢸⣿⣿⡿⢿⣿⣿⣿⣦⣠⣴⣿⣿⣿⡿⠟⠋⢸⣿⣿⣿⣿⣷⣴⣿⣿⣿⠃⠘⣿⣿⣷⠈⠛⢿⣿⣿⣿⠿⠋⠉⣠⣴⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠻⣿⣿⣿⣤⣀⠈⠉⢀⣤⣶⣿⣿⣿⠿⠟⠁⣰⣿⣿⡟⠋⠁⠈⠿⣿⣿⣿⣿⣶⣾⣿⣿⣿⣿⠟⠋⠁⣠⣼⣿⣿⡟⠙⠛⠛⠛⠻⠛⢿⣿⣿⣿⣿⣷⣾⣿⣿⣿⡿⠏⠈⠙⠛⠿⠿⠿⠿⠛⠉ › Ask Codex to do anything ? for shortcuts[0 q [?25h[?2026l[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l/Users/user1/cr/rounds/x158fresh/repo permissions: YOLO modeShall we see where this goes?[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l]0;repo[?2026h[?25h[?2026l[?2026h[?25lGPT-6-Astra default · /Users/user1/cr/rounds/x158fresh/repo←agens · ? for shortcuts[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l]0;⠋ repo[?2026h[?25h[?2026l[?2026h[?25h[?2026l]0;⠙ repo[?2026h[?25h[?2026l]0;repo[?2026h[?25l⠈⢀⠁⠂⠄⠈⠁⠈⠁⠈⢀⠠⠄⠠⢀⠠⡀⠠⠁⢀⠁[?25h[?2026l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/codex-0158-hooks-review-dialog.meta.json b/src/main/runtime/__fixtures__/codex-0158-hooks-review-dialog.meta.json new file mode 100644 index 00000000000..896d3474482 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0158-hooks-review-dialog.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-29T03:30:46.000Z", + "platform": "darwin", + "command": ["codex", "--dangerously-bypass-approvals-and-sandbox"], + "cols": 120, + "rows": 40, + "note": "codex-cli 0.158.0, plain launch on a fresh CODEX_HOME with a hooks.json of 8 command hooks that were never trusted. Over the provisional screen Codex paints `Hooks need review`, `1. Review hooks` / `2. Trust all and continue` / `3. Continue without trusting (hooks won't run)` and the key row `enter confirm · esc skip`, where older builds wrote `Press enter to confirm`. No key was sent (only automatic terminal-query replies). Cut 6 s after spawn. Home-directory user name redacted by hand, same length.", + "exitCode": null +} diff --git a/src/main/runtime/__fixtures__/codex-0158-hooks-review-dialog.txt b/src/main/runtime/__fixtures__/codex-0158-hooks-review-dialog.txt new file mode 100644 index 00000000000..ad25e6eda6e --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0158-hooks-review-dialog.txt @@ -0,0 +1 @@ +[?2004h[>4;0m[>7u[?1004h]10;?\]11;?\[?u[?2026h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l>_ OpenAI Codex (v0.158.0)loadingBring your unfinished thoughts.⣀⣤⣤⣤⣀⣀⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⣦⣤⣤⣤⣤⣤⣤⡀⢀⣾⣿⣿⠿⠋⠉⠉⢉⣭⣿⣿⣿⣿⣿⠿⣿⣿⣿⣿⣷⣄⣀⣾⣿⣿⠃⣀⣴⣾⣿⣿⡿⠟⠋⣀⡀⠈⠙⢿⣿⣿⣧⣀⣶⣿⣿⣿⣿⡇⢸⣿⣿⡿⠛⠉⢀⣠⣴⣿⣿⣿⣷⣦⣀⠈⢻⣿⣿⡇⣰⣿⣿⡿⢿⣿⣿⡇⢸⣿⣿⢀⣤⣶⣿⣿⣿⠟⠛⠻⣿⣿⣿⣿⣮⣿⣿⡷⢰⣿⣿⡟⠁⢸⣿⣿⡇⢸⣿⣿⣿⣿⠿⠿⣿⣿⣿⣦⣄⡀⠈⠛⠿⣿⣿⣿⣧⡀⣾⣿⣿⠃⢸⣿⣿⡇⢸⣿⣿⠋⠁⠈⠙⢻⣿⣿⣿⣶⣤⡀⠹⢿⣿⣷⡄⢸⣿⣿⣇⠸⣿⣿⣷⣦⣼⣿⣿⢸⣿⣿⠻⢿⣿⣿⡇⠘⣿⣿⣿⠈⢿⣿⣿⣦⡀⠈⠛⠿⣿⣿⣿⣿⣄⡀⢀⣠⣼⣿⣿⣿⣿⡇⣿⣿⣿⠇⢻⣿⣿⣿⣷⣦⣀⠈⠙⠻⣿⣿⣿⣶⣶⣿⣿⣿⣿⣿⣿⣿⡇⣠⣿⣿⣿⢸⣿⣿⡿⢿⣿⣿⣿⣦⣠⣴⣿⣿⣿⡿⠟⠋⢸⣿⣿⣿⣿⣷⣴⣿⣿⣿⠃⠘⣿⣿⣷⠈⠛⢿⣿⣿⣿⠿⠋⠉⣠⣴⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠻⣿⣿⣿⣤⣀⠈⠉⢀⣤⣶⣿⣿⣿⠿⠟⠁⣰⣿⣿⡟⠋⠁⠈⠿⣿⣿⣿⣿⣶⣾⣿⣿⣿⣿⠟⠋⠁⣠⣼⣿⣿⡟⠙⠛⠛⠛⠻⠛⢿⣿⣿⣿⣿⣷⣾⣿⣿⣿⡿⠏⠈⠙⠛⠿⠿⠿⠿⠛⠉ › Ask Codex to do anything ? for shortcuts[0 q [?25h[?2026l[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l/Users/user1/cr/rounds/dlg-h58/repo permissions: YOLO modeBring your unfinished thoughts.[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l  Hooks need review 8 hooks are new or changed. Hooks can run outside the sandbox after you trust them.  › 1. Review hooks  2. Trust all and continue 3. Continue without trusting (hooks won't run) enter confirm · esc skip    [?2026l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/codex-0158-model-announcement-dialog.meta.json b/src/main/runtime/__fixtures__/codex-0158-model-announcement-dialog.meta.json new file mode 100644 index 00000000000..05790b10e95 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0158-model-announcement-dialog.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-28T21:44:30.000Z", + "platform": "darwin", + "command": ["codex", "--dangerously-bypass-approvals-and-sandbox"], + "cols": 120, + "rows": 40, + "note": "codex-cli 0.158.0, plain launch on a fresh CODEX_HOME whose config.toml sets an older model with an available upgrade. After the provisional screen, Codex paints its model announcement (`Meet GPT-6 Sol`, `1. Try new model` / `2. Use existing model`, `enter/esc confirm`), which owns Enter. Cut 6 s after spawn. Home-directory user name redacted by hand, same length.", + "exitCode": null +} diff --git a/src/main/runtime/__fixtures__/codex-0158-model-announcement-dialog.txt b/src/main/runtime/__fixtures__/codex-0158-model-announcement-dialog.txt new file mode 100644 index 00000000000..a5c88157d74 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0158-model-announcement-dialog.txt @@ -0,0 +1 @@ +[?2004h[>4;0m[>7u[?1004h]10;?\]11;?\[?u[?2026h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l>_ OpenAI Codex (v0.158.0)loadingHere for a quick fix or the extended edition?⣀⣤⣤⣤⣀⣀⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⣦⣤⣤⣤⣤⣤⣤⡀⢀⣾⣿⣿⠿⠋⠉⠉⢉⣭⣿⣿⣿⣿⣿⠿⣿⣿⣿⣿⣷⣄⣀⣾⣿⣿⠃⣀⣴⣾⣿⣿⡿⠟⠋⣀⡀⠈⠙⢿⣿⣿⣧⣀⣶⣿⣿⣿⣿⡇⢸⣿⣿⡿⠛⠉⢀⣠⣴⣿⣿⣿⣷⣦⣀⠈⢻⣿⣿⡇⣰⣿⣿⡿⢿⣿⣿⡇⢸⣿⣿⢀⣤⣶⣿⣿⣿⠟⠛⠻⣿⣿⣿⣿⣮⣿⣿⡷⢰⣿⣿⡟⠁⢸⣿⣿⡇⢸⣿⣿⣿⣿⠿⠿⣿⣿⣿⣦⣄⡀⠈⠛⠿⣿⣿⣿⣧⡀⣾⣿⣿⠃⢸⣿⣿⡇⢸⣿⣿⠋⠁⠈⠙⢻⣿⣿⣿⣶⣤⡀⠹⢿⣿⣷⡄⢸⣿⣿⣇⠸⣿⣿⣷⣦⣼⣿⣿⢸⣿⣿⠻⢿⣿⣿⡇⠘⣿⣿⣿⠈⢿⣿⣿⣦⡀⠈⠛⠿⣿⣿⣿⣿⣄⡀⢀⣠⣼⣿⣿⣿⣿⡇⣿⣿⣿⠇⢻⣿⣿⣿⣷⣦⣀⠈⠙⠻⣿⣿⣿⣶⣶⣿⣿⣿⣿⣿⣿⣿⡇⣠⣿⣿⣿⢸⣿⣿⡿⢿⣿⣿⣿⣦⣠⣴⣿⣿⣿⡿⠟⠋⢸⣿⣿⣿⣿⣷⣴⣿⣿⣿⠃⠘⣿⣿⣷⠈⠛⢿⣿⣿⣿⠿⠋⠉⣠⣴⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠻⣿⣿⣿⣤⣀⠈⠉⢀⣤⣶⣿⣿⣿⠿⠟⠁⣰⣿⣿⡟⠋⠁⠈⠿⣿⣿⣿⣿⣶⣾⣿⣿⣿⣿⠟⠋⠁⣠⣼⣿⣿⡟⠙⠛⠛⠛⠻⠛⢿⣿⣿⣿⣿⣷⣾⣿⣿⣿⡿⠏⠈⠙⠛⠿⠿⠿⠿⠛⠉ › Ask Codex to do anything ? for shortcuts[0 q [?25h[?2026l[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l/Users/user1/cr/rounds/x158mig/repo permissions: YOLO modeHere for a quick fix or the extended edition?[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l  Meet GPT-6 Sol  Our latest Sol is more intelligent and more efficient so your usage limits go further. This model is a great daily driver for complex tasks, especially coding. › 1. Try new model  2. Use existing model  enter/esc confirm · ctrl+c quit    [?2026l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/codex-0158-model-retired-dialog.meta.json b/src/main/runtime/__fixtures__/codex-0158-model-retired-dialog.meta.json new file mode 100644 index 00000000000..92137927416 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0158-model-retired-dialog.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-29T03:31:56.000Z", + "platform": "darwin", + "command": ["codex", "--dangerously-bypass-approvals-and-sandbox"], + "cols": 120, + "rows": 40, + "note": "codex-cli 0.158.0, plain launch on a fresh CODEX_HOME whose config.toml sets model_provider = \"amazon-bedrock\" and model = \"openai.gpt-5.4\" (0.158 keeps the notice for a model missing from its catalog only on the OpenAI and Bedrock providers, and the OpenAI provider asks for a sign-in first, which the rig does not have). Codex shows the notice without choices: `GPT-5.4 on Amazon Bedrock is no longer offered in Codex`, `Switch to GPT-6 Sol on Amazon Bedrock to continue.` and the key row `enter/esc continue · ctrl+c quit`. Enter or Esc switches the model. No key was sent (only automatic terminal-query replies). Cut 6 s after spawn. Home-directory user name redacted by hand, same length.", + "exitCode": null +} diff --git a/src/main/runtime/__fixtures__/codex-0158-model-retired-dialog.txt b/src/main/runtime/__fixtures__/codex-0158-model-retired-dialog.txt new file mode 100644 index 00000000000..fd9fac82c43 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0158-model-retired-dialog.txt @@ -0,0 +1 @@ +[?2004h[>4;0m[>7u[?1004h]10;?\]11;?\[?u[?2026h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l>_ OpenAI Codex (v0.158.0)loadingBring a question. Bonus points if it’s a weird one.⣀⣤⣤⣤⣀⣀⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⣦⣤⣤⣤⣤⣤⣤⡀⢀⣾⣿⣿⠿⠋⠉⠉⢉⣭⣿⣿⣿⣿⣿⠿⣿⣿⣿⣿⣷⣄⣀⣾⣿⣿⠃⣀⣴⣾⣿⣿⡿⠟⠋⣀⡀⠈⠙⢿⣿⣿⣧⣀⣶⣿⣿⣿⣿⡇⢸⣿⣿⡿⠛⠉⢀⣠⣴⣿⣿⣿⣷⣦⣀⠈⢻⣿⣿⡇⣰⣿⣿⡿⢿⣿⣿⡇⢸⣿⣿⢀⣤⣶⣿⣿⣿⠟⠛⠻⣿⣿⣿⣿⣮⣿⣿⡷⢰⣿⣿⡟⠁⢸⣿⣿⡇⢸⣿⣿⣿⣿⠿⠿⣿⣿⣿⣦⣄⡀⠈⠛⠿⣿⣿⣿⣧⡀⣾⣿⣿⠃⢸⣿⣿⡇⢸⣿⣿⠋⠁⠈⠙⢻⣿⣿⣿⣶⣤⡀⠹⢿⣿⣷⡄⢸⣿⣿⣇⠸⣿⣿⣷⣦⣼⣿⣿⢸⣿⣿⠻⢿⣿⣿⡇⠘⣿⣿⣿⠈⢿⣿⣿⣦⡀⠈⠛⠿⣿⣿⣿⣿⣄⡀⢀⣠⣼⣿⣿⣿⣿⡇⣿⣿⣿⠇⢻⣿⣿⣿⣷⣦⣀⠈⠙⠻⣿⣿⣿⣶⣶⣿⣿⣿⣿⣿⣿⣿⡇⣠⣿⣿⣿⢸⣿⣿⡿⢿⣿⣿⣿⣦⣠⣴⣿⣿⣿⡿⠟⠋⢸⣿⣿⣿⣿⣷⣴⣿⣿⣿⠃⠘⣿⣿⣷⠈⠛⢿⣿⣿⣿⠿⠋⠉⣠⣴⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠻⣿⣿⣿⣤⣀⠈⠉⢀⣤⣶⣿⣿⣿⠿⠟⠁⣰⣿⣿⡟⠋⠁⠈⠿⣿⣿⣿⣿⣶⣾⣿⣿⣿⣿⠟⠋⠁⣠⣼⣿⣿⡟⠙⠛⠛⠛⠻⠛⢿⣿⣿⣿⣿⣷⣾⣿⣿⣿⡿⠏⠈⠙⠛⠿⠿⠿⠿⠛⠉ › Ask Codex to do anything ? for shortcuts[0 q [?25h[?2026l[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l/Users/user1/cr/rounds/dlg-m58b/repo permissions: YOLO modeBring a question. Bonus points if it’s a weird one.[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l  GPT-5.4 on Amazon Bedrock is no longer offered in Codex  Codex now uses GPT-6 Sol on Amazon Bedrock in place of GPT-5.4 on Amazon Bedrock. Switch to GPT-6 Sol on Amazon Bedrock to continue. enter/esc continue · ctrl+c quit    [?2026l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/codex-0158-update-available-dialog.meta.json b/src/main/runtime/__fixtures__/codex-0158-update-available-dialog.meta.json new file mode 100644 index 00000000000..db18029d308 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0158-update-available-dialog.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-29T03:30:10.000Z", + "platform": "darwin", + "command": ["codex", "--dangerously-bypass-approvals-and-sandbox"], + "cols": 120, + "rows": 40, + "note": "codex-cli 0.158.0, plain launch on a fresh CODEX_HOME whose config.toml sets check_for_update_on_startup = true, with a version.json cache naming 0.159.0 checked moments earlier (so no network check) and CODEX_MANAGED_BY_NPM=1 so Codex offers an update command. Over the provisional screen Codex paints `Update available · 0.158.0 → 0.159.0`, `1. Update now (runs `npm install -g @openai/codex`)` / `2. Skip` / `3. Skip until next version` and the key row `enter continue · esc skip`, where older builds wrote `Press enter to continue`. Enter picks Update now. No key was sent (only automatic terminal-query replies). Cut 6 s after spawn. Home-directory user name redacted by hand, same length.", + "exitCode": null +} diff --git a/src/main/runtime/__fixtures__/codex-0158-update-available-dialog.txt b/src/main/runtime/__fixtures__/codex-0158-update-available-dialog.txt new file mode 100644 index 00000000000..2c92e766ae2 --- /dev/null +++ b/src/main/runtime/__fixtures__/codex-0158-update-available-dialog.txt @@ -0,0 +1 @@ +[?2004h[>4;0m[>7u[?1004h]10;?\]11;?\[?u[?2026h[?25l[?1049h[>4;0m[>7u[?1007l[?1000h[?1002h[?1006h[?1003h[?25l[?2026h[?25l>_ OpenAI Codex (v0.158.0)loadingHere for a quick fix or the extended edition?⣀⣤⣤⣤⣀⣀⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⣦⣤⣤⣤⣤⣤⣤⡀⢀⣾⣿⣿⠿⠋⠉⠉⢉⣭⣿⣿⣿⣿⣿⠿⣿⣿⣿⣿⣷⣄⣀⣾⣿⣿⠃⣀⣴⣾⣿⣿⡿⠟⠋⣀⡀⠈⠙⢿⣿⣿⣧⣀⣶⣿⣿⣿⣿⡇⢸⣿⣿⡿⠛⠉⢀⣠⣴⣿⣿⣿⣷⣦⣀⠈⢻⣿⣿⡇⣰⣿⣿⡿⢿⣿⣿⡇⢸⣿⣿⢀⣤⣶⣿⣿⣿⠟⠛⠻⣿⣿⣿⣿⣮⣿⣿⡷⢰⣿⣿⡟⠁⢸⣿⣿⡇⢸⣿⣿⣿⣿⠿⠿⣿⣿⣿⣦⣄⡀⠈⠛⠿⣿⣿⣿⣧⡀⣾⣿⣿⠃⢸⣿⣿⡇⢸⣿⣿⠋⠁⠈⠙⢻⣿⣿⣿⣶⣤⡀⠹⢿⣿⣷⡄⢸⣿⣿⣇⠸⣿⣿⣷⣦⣼⣿⣿⢸⣿⣿⠻⢿⣿⣿⡇⠘⣿⣿⣿⠈⢿⣿⣿⣦⡀⠈⠛⠿⣿⣿⣿⣿⣄⡀⢀⣠⣼⣿⣿⣿⣿⡇⣿⣿⣿⠇⢻⣿⣿⣿⣷⣦⣀⠈⠙⠻⣿⣿⣿⣶⣶⣿⣿⣿⣿⣿⣿⣿⡇⣠⣿⣿⣿⢸⣿⣿⡿⢿⣿⣿⣿⣦⣠⣴⣿⣿⣿⡿⠟⠋⢸⣿⣿⣿⣿⣷⣴⣿⣿⣿⠃⠘⣿⣿⣷⠈⠛⢿⣿⣿⣿⠿⠋⠉⣠⣴⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠻⣿⣿⣿⣤⣀⠈⠉⢀⣤⣶⣿⣿⣿⠿⠟⠁⣰⣿⣿⡟⠋⠁⠈⠿⣿⣿⣿⣿⣶⣾⣿⣿⣿⣿⠟⠋⠁⣠⣼⣿⣿⡟⠙⠛⠛⠛⠻⠛⢿⣿⣿⣿⣿⣷⣾⣿⣿⣿⡿⠏⠈⠙⠛⠿⠿⠿⠿⠛⠉ › Ask Codex to do anything ? for shortcuts[0 q [?25h[?2026l[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l/Users/user1/cr/rounds/dlg-u58/repo permissions: YOLO modeHere for a quick fix or the extended edition?[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25h[?2026l[?2026h[?25l  Update available · 0.158.0 → 0.159.0 Release notes: ]8;;https://github.com/openai/codex/releases/latesthttps://github.com/openai/codex/releases/latest]8;; › 1. Update now (runs `npm install -g @openai/codex`)  2. Skip 3. Skip until next version  enter continue · esc skip    [?2026l \ No newline at end of file diff --git a/src/main/runtime/codex-header-readiness-transcripts.test.ts b/src/main/runtime/codex-header-readiness-transcripts.test.ts index 0cfcf548017..ea8dc03cef2 100644 --- a/src/main/runtime/codex-header-readiness-transcripts.test.ts +++ b/src/main/runtime/codex-header-readiness-transcripts.test.ts @@ -5,7 +5,11 @@ import { replayTranscript, type TranscriptReplayFrame } from './agent-transcript-replay-test-harness' -import { isKnownReadyPromptBody, isKnownReadyPromptPreview } from './terminal-wait-detection' +import { + isKnownReadyPromptBody, + isKnownReadyPromptPreview, + isKnownReadyPromptSettled +} from './terminal-wait-detection' vi.mock('electron', () => ({ BrowserWindow: { fromId: vi.fn(() => null) }, @@ -19,7 +23,9 @@ const PLAIN = 'codex-0157-plain-ready' const EFFORT_OVERRIDE = 'codex-0157-effort-override-embedded-warning' const CONFIG_OVERRIDE = 'codex-0157-config-override-embedded-warning' const NO_DAEMON = 'codex-0157-no-daemon-effort-override' -const ALL_FIXTURES = [PLAIN, EFFORT_OVERRIDE, CONFIG_OVERRIDE, NO_DAEMON] +// Fresh CODEX_HOME: the provisional header stays up while Codex installs and starts its daemon. +const FRESH_HOME = 'codex-0157-fresh-home-daemon-install' +const ALL_FIXTURES = [PLAIN, EFFORT_OVERRIDE, CONFIG_OVERRIDE, NO_DAEMON, FRESH_HOME] async function finalFrame( name: string, @@ -41,6 +47,16 @@ function screenShowsLoadingHeader(screenLines: string[]): boolean { return screen.includes('openai codex') && /(?:model|directory):\s+loading/.test(screen) } +// Codex's default status row opens with ` ·`; only the live chat paints it. +const LIVE_STATUS_ROW_RE = /\b(?:default|minimal|low|medium|high|xhigh) ·/ + +function screenShowsProvisionalStartup(screenLines: string[]): boolean { + return ( + screenShowsLoadingHeader(screenLines) && + !screenLines.some((line) => LIVE_STATUS_ROW_RE.test(line.toLowerCase())) + ) +} + describe('Codex 0.157 header readiness from captured bytes', () => { it.each([EFFORT_OVERRIDE, CONFIG_OVERRIDE])( '%s: the line-folded wait text never shows a ready header', @@ -71,6 +87,26 @@ describe('Codex 0.157 header readiness from captured bytes', () => { } ) + // Why: 0.157 discards input typed during its daemon start, behind the provisional header. + it.each(ALL_FIXTURES)( + '%s: never ready while the screen shows the provisional `model: loading` startup screen', + async (name) => { + let sawTextOnlyReadiness = false + for await (const frame of replayTranscript(readRuntimeFixture(name), 120, 40)) { + if (screenShowsProvisionalStartup(frame.screenLines)) { + sawTextOnlyReadiness ||= isKnownReadyPromptPreview(frame.waitText) + expect(isKnownReadyPromptBody(frame.waitText, 'codex', () => frame.screenLines)).toBe( + false + ) + } + } + // Presence precondition for the text-copy fixtures: the text rules alone would say ready here. + if (name === PLAIN || name === FRESH_HOME) { + expect(sawTextOnlyReadiness).toBe(true) + } + } + ) + // Why these sizes: grids out of step with the 120x40 recording garble the header (review of #23475). describe.each([ [120, 40], @@ -78,15 +114,21 @@ describe('Codex 0.157 header readiness from captured bytes', () => { [30, 50], [108, 30], [60, 5] - ])('at %ix%i the screen never takes readiness away from the text rules', (cols, rows) => { + ])('at %ix%i the screen never takes a settled header away from the text rules', (cols, rows) => { it.each(ALL_FIXTURES)('%s', async (name) => { + let settledFrames = 0 for await (const frame of replayTranscript(readRuntimeFixture(name), cols, rows)) { - if (isKnownReadyPromptPreview(frame.waitText)) { + if (isKnownReadyPromptSettled(frame.waitText)) { + settledFrames += 1 expect(isKnownReadyPromptBody(frame.waitText, 'codex', () => frame.screenLines)).toBe( true ) } } + // Presence precondition: the text-copy fixtures reach a settled header. + if (name === PLAIN || name === FRESH_HOME || name === NO_DAEMON) { + expect(settledFrames).toBeGreaterThan(0) + } }) }) @@ -175,6 +217,58 @@ describe('Codex 0.157 header readiness from captured bytes', () => { 15_000 ) + it('does not settle while Codex is still installing its daemon behind the provisional screen', async () => { + const data = readRuntimeFixture(FRESH_HOME) + const install = data.indexOf('Installing daemon') + // Presence precondition: the cut keeps the provisional header and stops before the live chat. + expect(install).toBeGreaterThan(0) + const provisional = data.slice(0, data.indexOf('\n', install) + 1) + expect(provisional).toMatch(/model:.*loading/) + const { runtime, handle } = await createTranscriptPane({ + paneTitle: 'Terminal', + foregroundProcess: 'codex', + launchAgent: 'codex', + data: provisional, + size: { cols: 120, rows: 40 } + }) + await expect( + runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 2_500 }) + ).rejects.toThrow(/timeout/) + }, 15_000) + + // Why no bytes: worker-start waits on a pane that has printed nothing yet, which is when the + // runtime asks for a visible-screen read instead of its own text copy. + it('does not settle from a visible-screen read of the provisional screen', async () => { + const { runtime, handle } = await createTranscriptPane({ + paneTitle: 'Terminal', + foregroundProcess: 'codex', + launchAgent: 'codex', + data: '', + size: { cols: 120, rows: 40 } + }) + const readVisibleScreen = vi.spyOn(runtime, 'readTerminal').mockResolvedValue({ + handle, + status: 'running', + tail: [ + '╭──────────────────────────────────────────╮', + '│ >_ OpenAI Codex (v0.157.0) │', + '│ model: loading /model to change │', + '│ directory: ~/repo/app │', + '╰──────────────────────────────────────────╯', + '› Ask Codex to do anything', + ' ? for shortcuts' + ], + truncated: false, + nextCursor: null, + source: 'screen' + }) + await expect( + runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 2_500 }) + ).rejects.toThrow(/timeout/) + // Presence precondition: the visible-screen probe actually ran. + expect(readVisibleScreen).toHaveBeenCalled() + }, 15_000) + it('keeps timing out on the garbled 80x24 default grid, as before', async () => { const { runtime, handle } = await codexPane(EFFORT_OVERRIDE) await expect( diff --git a/src/main/runtime/codex-startup-dialog-transcripts.test.ts b/src/main/runtime/codex-startup-dialog-transcripts.test.ts new file mode 100644 index 00000000000..01dbe447304 --- /dev/null +++ b/src/main/runtime/codex-startup-dialog-transcripts.test.ts @@ -0,0 +1,198 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RuntimeTerminalWaitBlockedReason } from '../../shared/runtime-types' +import { createTranscriptPane } from './agent-transcript-pane-test-harness' +import { + readRuntimeFixture, + replayTranscript, + type TranscriptReplayFrame +} from './agent-transcript-replay-test-harness' +import { detectTerminalWaitBlockedReason, isKnownReadyPromptBody } from './terminal-wait-detection' + +vi.mock('electron', () => ({ + BrowserWindow: { fromId: vi.fn(() => null) }, + webContents: { fromId: vi.fn(() => null) }, + ipcMain: { on: vi.fn(), removeListener: vi.fn() }, + app: { getPath: vi.fn(() => '/tmp') } +})) + +type StartupDialog = { + name: string + reason: RuntimeTerminalWaitBlockedReason + heading: string + keyRow: string +} + +// codex-cli 0.157.0 / 0.158.0 recordings at 120x40 on a fresh CODEX_HOME (see each .meta.json). +// Each dialog owns Enter, and none prints the `Press enter to …` wording older builds did. +const DIALOGS: StartupDialog[] = [ + { + // Recorded separately on 0.157.1 (STA-8834). + name: 'codex-0-157-1-update-dialog', + reason: 'agent-update-prompt', + heading: 'Update available ·', + keyRow: 'enter continue · esc skip' + }, + { + name: 'codex-0157-update-available-dialog', + reason: 'agent-update-prompt', + heading: 'Update available ·', + keyRow: 'enter continue · esc skip' + }, + { + name: 'codex-0158-update-available-dialog', + reason: 'agent-update-prompt', + heading: 'Update available ·', + keyRow: 'enter continue · esc skip' + }, + { + name: 'codex-0157-hooks-review-dialog', + reason: 'agent-hooks-review-prompt', + heading: 'Hooks need review', + keyRow: 'enter confirm · esc skip' + }, + { + name: 'codex-0158-hooks-review-dialog', + reason: 'agent-hooks-review-prompt', + heading: 'Hooks need review', + keyRow: 'enter confirm · esc skip' + }, + { + name: 'codex-0157-model-retired-dialog', + reason: 'codex-model-migration-prompt', + heading: 'is no longer available', + keyRow: 'enter/esc continue · ctrl+c quit' + }, + { + name: 'codex-0158-model-retired-dialog', + reason: 'codex-model-migration-prompt', + heading: 'is no longer offered', + keyRow: 'enter/esc continue · ctrl+c quit' + }, + { + name: 'codex-0158-model-announcement-dialog', + reason: 'codex-model-migration-prompt', + heading: 'Try new model', + keyRow: 'enter/esc confirm · ctrl+c quit' + } +] +const DIALOGS_0158 = DIALOGS.filter((dialog) => dialog.name.startsWith('codex-0158-')) +const LIVE_CHAT_FIXTURES = [ + 'codex-0157-plain-ready', + 'codex-0157-effort-override-embedded-warning', + 'codex-0157-config-override-embedded-warning', + 'codex-0157-no-daemon-effort-override', + 'codex-0157-fresh-home-daemon-install', + 'codex-0158-fresh-home-greeting' +] + +function screenText(frame: TranscriptReplayFrame): string { + return frame.screenLines.join('\n') +} + +async function lastFrame(data: string): Promise { + let last: TranscriptReplayFrame | null = null + for await (const frame of replayTranscript(data, 120, 40)) { + last = frame + } + return last +} + +// Why stitched: no capture spans answering a dialog. Codex repaints every cell once a startup +// dialog closes, so the 0.158 greeting capture's paints stand in for that repaint. +function answered(name: string): string { + const greeting = readRuntimeFixture('codex-0158-fresh-home-greeting') + return readRuntimeFixture(name) + greeting.slice(greeting.indexOf('\x1b[?2026h')) +} + +describe('Codex 0.157/0.158 startup dialogs from captured bytes', () => { + it.each(DIALOGS)( + '$name: reports $reason from its key row on, and never reads ready while it is up', + async ({ name, reason, heading, keyRow }) => { + let headingFrames = 0 + let keyRowFrames = 0 + for await (const frame of replayTranscript(readRuntimeFixture(name), 120, 40)) { + const screen = screenText(frame) + if (screen.includes(heading)) { + headingFrames += 1 + expect(isKnownReadyPromptBody(frame.waitText, 'codex', () => frame.screenLines)).toBe( + false + ) + } + if (keyRowFrames > 0 || screen.includes(keyRow)) { + keyRowFrames += 1 + expect(detectTerminalWaitBlockedReason(frame.waitText)).toBe(reason) + } + } + // Presence precondition: the dialog and its key row were painted, not just parsed. + expect(headingFrames).toBeGreaterThan(0) + expect(keyRowFrames).toBeGreaterThan(0) + } + ) + + it.each(DIALOGS_0158)( + '$name: stops reporting once Codex repaints its chat after it', + async ({ name, heading }) => { + const last = await lastFrame(answered(name)) + // Presence precondition: the answered dialog is still in the text copy. + expect(last?.waitText).toContain(heading.replace(' ·', '')) + expect(detectTerminalWaitBlockedReason(last?.waitText ?? '')).toBeNull() + } + ) + + it.each(DIALOGS)( + '$name: still reports $reason when Codex is relaunched in the same pane and shows it again', + async ({ name, reason }) => { + // Why: quitting Codex from a dialog leaves that copy in the text copy ahead of the relaunch. + const dialog = readRuntimeFixture(name) + const last = await lastFrame(`${dialog}\x1b[?1049l\r\n% codex\r\n${dialog}`) + expect(detectTerminalWaitBlockedReason(last?.waitText ?? '')).toBe(reason) + expect( + isKnownReadyPromptBody(last?.waitText ?? '', 'codex', () => last?.screenLines ?? null) + ).toBe(false) + } + ) + + it.each(LIVE_CHAT_FIXTURES)('%s: a live chat reports no dialog', async (name) => { + const waitText = (await lastFrame(readRuntimeFixture(name)))?.waitText ?? '' + expect(detectTerminalWaitBlockedReason(waitText)).toBeNull() + // Why these lines: chat can name a dialog, and Codex's own update notice and footer draw `·`. + const chat = [ + '› is there an update available, and do my hooks need review?', + '✨ Update available! 0.158.0 -> 0.159.0', + 'Run npm install -g @openai/codex to update.', + ' gpt-6-astra default · ~/repo', + ' ← for agents · ? for shortcuts' + ].join('\n') + expect(detectTerminalWaitBlockedReason(`${waitText}\n${chat}`)).toBeNull() + }) + + it('does not name a mid-session Codex popup a hooks review', () => { + // Why: Codex's rate-limit reset popup (and other pickers) ends `enter confirm · esc back`. + const popup = [ + ' Use this reset?', + ' 1. Yes, use reset Reset your weekly and 5-hour usage limits.', + '› 2. No, go back Choose a different reset', + ' enter confirm · esc back' + ].join('\n') + expect(detectTerminalWaitBlockedReason(popup)).not.toBe('agent-hooks-review-prompt') + }) + + describe('through the runtime', () => { + it.each(DIALOGS)( + '$name: stops a tui-idle wait as $reason instead of typing into it', + async ({ name, reason }) => { + const { runtime, handle } = await createTranscriptPane({ + paneTitle: 'Terminal', + foregroundProcess: 'codex', + launchAgent: 'codex', + data: readRuntimeFixture(name), + size: { cols: 120, rows: 40 } + }) + await expect( + runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 2_500 }) + ).resolves.toMatchObject({ satisfied: false, blockedReason: reason }) + }, + 15_000 + ) + }) +}) diff --git a/src/main/runtime/codex-terminal-readiness.ts b/src/main/runtime/codex-terminal-readiness.ts index 3b15c3359df..cdbc8903d21 100644 --- a/src/main/runtime/codex-terminal-readiness.ts +++ b/src/main/runtime/codex-terminal-readiness.ts @@ -34,6 +34,27 @@ export function findCodexScreenReadyPromptIndex(screen: string): number | null { : null } +// Why the text copy: 0.157 leaves its alternate screen while it starts its daemon, so the live +// screen shows no header then, while the text copy keeps the provisional one until the live chat +// paints its footer after it (a later model repaint rewrites only the value, never the label). +// Why `·`: every live footer row draws one (status row, `← for agents · ?`, `⚠ N warning · f2`); +// startup dialogs draw one too, which is why startup-dialog-blocked-signals.ts matches them first. +export function isCodexProvisionalStartupText(normalized: string): boolean { + const headerIndex = normalized.lastIndexOf('openai codex') + if (headerIndex === -1) { + return false + } + const loading = /model:\s+loading/.exec(normalized.slice(headerIndex)) + return loading !== null && !normalized.includes('·', headerIndex + loading.index) +} + +// Why: Codex repaints its whole screen, header included, once a startup dialog closes, and the +// dialog never draws the header; 0.158's header has no labels, so the header alone marks it answered. +export function findCodexHeaderIndex(normalized: string): number | null { + const index = normalized.lastIndexOf('openai codex (v') + return index === -1 ? null : index +} + /** * Tier 1b, codex panes only: the empty composer with no busy status row just above it and no * header load. Codex 0.158 dropped `model:`/`directory:`, and a long session scrolls the header diff --git a/src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts b/src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts index bb03b17eca3..4d70572eb2a 100644 --- a/src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts +++ b/src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts @@ -11,7 +11,7 @@ import { import { withTimeout } from './runtime-async-boundaries' import { detectTerminalWaitBlockedReason, - isKnownReadyPromptPreview + isKnownReadyPromptSettled } from './terminal-wait-detection' import type { RuntimeTerminalWait, @@ -80,7 +80,7 @@ export class OrcaRuntimeWithStartTuiIdleVisibleReadProbe extends OrcaRuntimeWith const ready = agent === 'antigravity' ? isAntigravityReadyPromptSnapshot(snapshotText) - : isKnownReadyPromptPreview(snapshotText) + : isKnownReadyPromptSettled(snapshotText) if (!blockedReason && !ready) { return } diff --git a/src/main/runtime/startup-dialog-blocked-signals.ts b/src/main/runtime/startup-dialog-blocked-signals.ts new file mode 100644 index 00000000000..e964205a9cc --- /dev/null +++ b/src/main/runtime/startup-dialog-blocked-signals.ts @@ -0,0 +1,76 @@ +import type { RuntimeTerminalWaitBlockedReason } from '../../shared/runtime-types' + +// Why rows, from each dialog's first `·` on: codex-terminal-readiness.ts takes a `·` after the +// startup header for the live chat's footer, so each dialog must be matched by the time that `·` +// lands. Why not headings: Codex 0.157+ paints them by cell diff over its startup screen, so the +// text copy can lose letters and spaces (`updat available`); these rows are fixed literals. +// Update: `Update available · 0.157.1 → 0.158.0`, then `enter continue · esc skip`. +const CODEX_UPDATE_ROW_RE = /available\s*·\s*\d+\.\d+|enter\s*continue\s*·\s*esc\s*skip/g +// Why not `esc back`: Codex's mid-session pickers end `enter confirm · esc back`. +const CODEX_HOOKS_REVIEW_KEY_ROW_RE = /enter\s*confirm\s*·(?!\s*esc\s*back)/g +// Why both verbs: the retired-model notice says `continue`, the new-model announcement `confirm`. +const CODEX_MODEL_MIGRATION_KEY_ROW_RE = /enter\/esc\s*(?:continue|confirm)\s*·/g + +function lastMatchIndex(text: string, row: RegExp): number { + let index = -1 + for (const match of text.matchAll(row)) { + index = match.index + } + return index +} + +// Why the last match, and the legacy wording too: an answered dialog stays in the text copy, and +// builds before 0.157 wrote `Press enter to continue/confirm`. +function findDialogIndex( + normalized: string, + legacyHeading: string, + legacyKeys: string, + row: RegExp +): number { + const rowIndex = lastMatchIndex(normalized, row) + const headingIndex = normalized.lastIndexOf(legacyHeading) + const legacyIndex = + headingIndex !== -1 && normalized.includes(legacyKeys, headingIndex) ? headingIndex : -1 + return Math.max(rowIndex, legacyIndex) +} + +// Why together: each startup dialog owns Enter before the chat exists, so a brief typed into one +// answers it (Codex's update dialog defaults to `Update now`). +export function findStartupDialogBlockedSignals( + normalized: string +): { reason: RuntimeTerminalWaitBlockedReason; index: number }[] { + const candidates: { reason: RuntimeTerminalWaitBlockedReason; index: number }[] = [] + const updateIndex = findDialogIndex( + normalized, + 'update available', + 'press enter to continue', + CODEX_UPDATE_ROW_RE + ) + if (updateIndex !== -1) { + candidates.push({ reason: 'agent-update-prompt', index: updateIndex }) + } + const cwdIndex = normalized.lastIndexOf('choose working directory to') + if (cwdIndex !== -1 && normalized.includes('press enter to continue', cwdIndex)) { + candidates.push({ reason: 'agent-cwd-prompt', index: cwdIndex }) + } + const modelMigrationIndex = findDialogIndex( + normalized, + 'codex just got an upgrade', + 'press enter to continue', + CODEX_MODEL_MIGRATION_KEY_ROW_RE + ) + if (modelMigrationIndex !== -1) { + candidates.push({ reason: 'codex-model-migration-prompt', index: modelMigrationIndex }) + } + const hooksIndex = findDialogIndex( + normalized, + 'hooks need review', + 'press enter to confirm', + CODEX_HOOKS_REVIEW_KEY_ROW_RE + ) + if (hooksIndex !== -1) { + // Why neutral: this matcher never inspects the agent -- 'hooks need review' is not Codex-only wording. + candidates.push({ reason: 'agent-hooks-review-prompt', index: hooksIndex }) + } + return candidates +} diff --git a/src/main/runtime/terminal-wait-detection.ts b/src/main/runtime/terminal-wait-detection.ts index 1540eef2d5f..2618a50279c 100644 --- a/src/main/runtime/terminal-wait-detection.ts +++ b/src/main/runtime/terminal-wait-detection.ts @@ -9,9 +9,12 @@ import type { RuntimeTerminalWaitBlockedReason } from '../../shared/runtime-type import type { TuiAgent } from '../../shared/tui-agent' import { findAntigravityReadyPromptIndex } from './antigravity-terminal-readiness' import { + findCodexHeaderIndex, findCodexScreenReadyPromptIndex, - isCodexComposerReadyScreen + isCodexComposerReadyScreen, + isCodexProvisionalStartupText } from './codex-terminal-readiness' +import { findStartupDialogBlockedSignals } from './startup-dialog-blocked-signals' import { startOfLastLines, startOfLastNonBlankLines } from './terminal-wait-tail-window' const EXPLICIT_IDLE_TITLE_RE = /(^|\s)(ready|idle|done)(\s|$|[.!?])/i @@ -52,6 +55,19 @@ export function isKnownReadyPromptPreview(preview: string): boolean { return isReadyPromptUnblocked(normalized, findKnownReadyPromptIndex(normalized)) } +/** + * The ready-prompt text rules for a pane about to take input. Unlike isKnownReadyPromptPreview + * (agent presence), Codex's provisional startup header does not count: 0.157 discards input typed + * behind it while its daemon starts. + */ +export function isKnownReadyPromptSettled(preview: string): boolean { + const normalized = preview.toLowerCase() + return ( + isReadyPromptUnblocked(normalized, findKnownReadyPromptIndex(normalized)) && + !isCodexProvisionalStartupText(normalized) + ) +} + /** * Tier 1 body evidence for every tui-idle site. `readScreenLines` yields the live emulator's * visible grid, or null when the runtime has no trustworthy one. @@ -69,7 +85,7 @@ export function isKnownReadyPromptBody( if (agent === 'qoder') { return isQoderComposerReady(readScreenLines()) } - if (isKnownReadyPromptPreview(waitText)) { + if (isKnownReadyPromptSettled(waitText)) { return true } // Why the agent gate: another agent's screen can merely mention "OpenAI Codex". @@ -139,6 +155,7 @@ export function findActionableTerminalWaitBlockedSignal( function findDismissedStartupModalIndex(normalized: string): number | null { const indexes = [ findCodexReadyPromptIndex(normalized), + findCodexHeaderIndex(normalized), findAntigravityReadyPromptIndex(normalized), findCursorActivePromptIndex(normalized), findMuseReadyPromptIndex(normalized) @@ -199,7 +216,7 @@ function findCodexReadyPromptIndex(normalized: string): number | null { } export const TERMINAL_WAIT_BLOCKED_SENTINEL_RE = - /update available|choose working directory to|codex just got an upgrade|hooks need review|do you trust|trust this|trusted workspace|press enter to (?:confirm|continue|view|insert)|press t to trust|permission required|requires permission|allow once|allow always|run this command\?/i + /update available|choose working directory to|codex just got an upgrade|available\s*·|esc\s*skip|enter\s*confirm\s*·|enter\/esc\s*(?:continue|confirm)|hooks need review|do you trust|trust this|trusted workspace|press enter to (?:confirm|continue|view|insert)|press t to trust|permission required|requires permission|allow once|allow always|run this command\?/i // Why text at all: cursor-agent has no approval hook, so the key-bound menu is the only authority. const CURSOR_APPROVAL_CHOICE_MARKERS = [ @@ -268,27 +285,7 @@ function findTerminalWaitBlockedSignal( function findBlockedSignalInLiveWindow( normalized: string ): { reason: RuntimeTerminalWaitBlockedReason; index: number } | null { - const candidates: { reason: RuntimeTerminalWaitBlockedReason; index: number }[] = [] - const updateIndex = normalized.lastIndexOf('update available') - if (updateIndex !== -1 && normalized.includes('press enter to continue', updateIndex)) { - candidates.push({ reason: 'agent-update-prompt', index: updateIndex }) - } - const cwdIndex = normalized.lastIndexOf('choose working directory to') - if (cwdIndex !== -1 && normalized.includes('press enter to continue', cwdIndex)) { - candidates.push({ reason: 'agent-cwd-prompt', index: cwdIndex }) - } - const modelMigrationIndex = normalized.lastIndexOf('codex just got an upgrade') - if ( - modelMigrationIndex !== -1 && - normalized.includes('press enter to continue', modelMigrationIndex) - ) { - candidates.push({ reason: 'codex-model-migration-prompt', index: modelMigrationIndex }) - } - const hooksIndex = normalized.lastIndexOf('hooks need review') - if (hooksIndex !== -1 && normalized.includes('press enter to confirm', hooksIndex)) { - // Why neutral: this matcher never inspects the agent -- 'hooks need review' is not Codex-only wording. - candidates.push({ reason: 'agent-hooks-review-prompt', index: hooksIndex }) - } + const candidates = findStartupDialogBlockedSignals(normalized) const trustIndex = Math.max( normalized.lastIndexOf('do you trust'), normalized.lastIndexOf('trust this'), From e1362ada4c33e7ef14709dff56564ea5dbcf5d98 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Tue, 29 Sep 2026 01:20:37 -0700 Subject: [PATCH 04/83] fix(terminal): stop inline-image decoders exhausting the renderer's wasm memory budget (#23499) V8 reserves an 8 GiB guard region per wasm memory inside its 1 TiB sandbox, so an Electron renderer can hold only ~124 live wasm memories regardless of free RAM. @xterm/addon-image instantiated a SIXEL decoder per terminal at activation (and kept IIP decoders after the first image), so ~120+ terminals exhausted the budget: new panes raised 'WebAssembly.instantiate(): Out of memory' rejections, and the next Kitty/IIP image threw 'WebAssembly.Memory(): could not allocate memory' out of the parser, permanently wedging that terminal's write queue. The addon-image source patch now borrows SIXEL decoders from a shared pool only while a sequence is open (color registers stay on the terminal), drops IIP decoders after each image, and turns a failed decoder allocation into a dropped image instead of a parser throw. Bundles regenerated with regenerate-xterm-patches.mjs --write. Co-authored-by: m4air --- .../@xterm__addon-image@0.10.0-beta.300.patch | 279 ++++++++++++++++-- ...erm__addon-image@0.10.0-beta.300.src.patch | 259 +++++++++++++++- .../xterm-image-wasm-budget-contract.test.mjs | 160 ++++++++++ docs/reference/xterm-patch-regeneration.md | 9 + pnpm-lock.yaml | 6 +- 5 files changed, 676 insertions(+), 37 deletions(-) create mode 100644 config/scripts/xterm-image-wasm-budget-contract.test.mjs diff --git a/config/patches/@xterm__addon-image@0.10.0-beta.300.patch b/config/patches/@xterm__addon-image@0.10.0-beta.300.patch index c44cb33d2d5..44d6ac32c14 100644 --- a/config/patches/@xterm__addon-image@0.10.0-beta.300.patch +++ b/config/patches/@xterm__addon-image@0.10.0-beta.300.patch @@ -1,24 +1,24 @@ diff --git a/lib/addon-image.js b/lib/addon-image.js -index 38cf9e8708a5f314b8d587e5428ce7facb0d4076..4807d674d75a5aeaba40cf86972ce0a6158a33f4 100644 +index 38cf9e8708a5f314b8d587e5428ce7facb0d4076..4c5f44e00b0972978d762df5990de86002537649 100644 --- a/lib/addon-image.js +++ b/lib/addon-image.js @@ -1,3 +1,3 @@ /*! For license information please see addon-image.js.LICENSE.txt */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ImageAddon=t():e.ImageAddon=t()}(globalThis,()=>(()=>{"use strict";var e={939(e,t){function A(e){return 255&e}function i(e){return e>>>8&255}function s(e){return e>>>16&255}function r(e,t,A,i=255){return((255&i)<<24|(255&A)<<16|(255&t)<<8|255&e)>>>0}function o(e,t,A){return Math.max(e,Math.min(A,t))}function a(e,t,A){return A<0&&(A+=1),A>1&&(A-=1),6*A<1?t+6*(e-t)*A:2*A<1?e:3*A<2?t+(e-t)*(4-6*A):t}function n(e,t,A){return(4278190080|Math.round(A/100*255)<<16|Math.round(t/100*255)<<8|Math.round(e/100*255))>>>0}Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_FOREGROUND=t.DEFAULT_BACKGROUND=t.PALETTE_ANSI_256=t.PALETTE_VT340_GREY=t.PALETTE_VT340_COLOR=t.normalizeHLS=t.normalizeRGB=t.nearestColorIndex=t.fromRGBA8888=t.toRGBA8888=t.alpha=t.blue=t.green=t.red=t.BIG_ENDIAN=void 0,t.BIG_ENDIAN=255===new Uint8Array(new Uint32Array([4278190080]).buffer)[0],t.BIG_ENDIAN&&console.warn("BE platform detected. This version of node-sixel works only on LE properly."),t.red=A,t.green=i,t.blue=s,t.alpha=function(e){return e>>>24&255},t.toRGBA8888=r,t.fromRGBA8888=function(e){return[255&e,e>>8&255,e>>16&255,e>>>24]},t.nearestColorIndex=function(e,t){const r=A(e),o=i(e),a=s(e);let n=Number.MAX_SAFE_INTEGER,h=-1;for(let e=0;e{const e=[r(0,0,0),r(205,0,0),r(0,205,0),r(205,205,0),r(0,0,238),r(205,0,205),r(0,250,205),r(229,229,229),r(127,127,127),r(255,0,0),r(0,255,0),r(255,255,0),r(92,92,255),r(255,0,255),r(0,255,255),r(255,255,255)],t=[0,95,135,175,215,255];for(let A=0;A<6;++A)for(let i=0;i<6;++i)for(let s=0;s<6;++s)e.push(r(t[A],t[i],t[s]));for(let t=8;t<=238;t+=10)e.push(r(t,t,t));return new Uint32Array(e)})(),t.DEFAULT_BACKGROUND=r(0,0,0,255),t.DEFAULT_FOREGROUND=r(255,255,255,255)},591(e,t,A){Object.defineProperty(t,"__esModule",{value:!0}),t.decodeAsync=t.decode=t.Decoder=t.DecoderAsync=void 0;const i=A(939),s=A(199),r=function(e){if("undefined"!=typeof Buffer)return Buffer.from(e,"base64");const t=atob(e),A=new Uint8Array(t.length);for(let e=0;e1,this.modeHandler=e=>1}handle_band(e){return this.bandHandler(e)}mode_parsed(e){return this.modeHandler(e)}}const h={memoryLimit:134217728,sixelColor:i.DEFAULT_FOREGROUND,fillColor:i.DEFAULT_BACKGROUND,palette:i.PALETTE_VT340_COLOR,paletteLimit:s.LIMITS.PALETTE_SIZE,truncate:!0};function g(e){const t=new n,A={env:{handle_band:t.handle_band.bind(t),mode_parsed:t.mode_parsed.bind(t)}};return WebAssembly.instantiate(o||r,A).then(A=>(o=o||A.module,new d(e,A.instance||A,t)))}t.DecoderAsync=g;class d{constructor(e,t,A){if(this._PIXEL_OFFSET=s.LIMITS.MAX_WIDTH+4,this._canvas=a,this._bandWidths=[],this._maxWidth=0,this._minWidth=s.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0,this._opts=Object.assign({},h,e),this._opts.paletteLimit>s.LIMITS.PALETTE_SIZE)throw new Error(`DecoderOptions.paletteLimit must not exceed ${s.LIMITS.PALETTE_SIZE}`);if(t)A.bandHandler=this._handle_band.bind(this),A.modeHandler=this._initCanvas.bind(this);else{const e=o||(o=new WebAssembly.Module(r));t=new WebAssembly.Instance(e,{env:{handle_band:this._handle_band.bind(this),mode_parsed:this._initCanvas.bind(this)}})}this._instance=t,this._wasm=this._instance.exports,this._chunk=new Uint8Array(this._wasm.memory.buffer,this._wasm.get_chunk_address(),s.LIMITS.CHUNK_SIZE),this._states=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_state_address(),12),this._palette=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_palette_address(),s.LIMITS.PALETTE_SIZE),this._palette.set(this._opts.palette),this._pSrc=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_p0_address()),this._wasm.init(i.DEFAULT_FOREGROUND,0,this._opts.paletteLimit,0)}get _fillColor(){return this._states[0]}get _truncate(){return this._states[8]}get _rasterWidth(){return this._states[6]}get _rasterHeight(){return this._states[7]}get _width(){return this._states[2]?this._states[2]-4:0}get _height(){return this._states[3]}get _level(){return this._states[9]}get _mode(){return this._states[10]}get _paletteLimit(){return this._states[11]}_initCanvas(e){if(2===e){const e=this.width*this.height;if(e>this._canvas.length){if(this._opts.memoryLimit&&4*e>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(e)}this._maxWidth=this._width}else if(1===e)if(2===this._level){const e=Math.min(this._rasterWidth,s.LIMITS.MAX_WIDTH)*this._rasterHeight;if(e>this._canvas.length){if(this._opts.memoryLimit&&4*e>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(e)}}else this._canvas.length<65536&&(this._canvas=new Uint32Array(65536));return 0}_realloc(e,t){const A=e+t;if(A>this._canvas.length){if(this._opts.memoryLimit&&4*A>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");const e=new Uint32Array(65536*Math.ceil(A/65536));e.set(this._canvas),this._canvas=e}}_handle_band(e){const t=this._PIXEL_OFFSET;let A=this._lastOffset;if(2===this._mode){let i=this.height-this._currentHeight,s=0;for(;s<6&&i>0;)this._canvas.set(this._pSrc.subarray(t*s,t*s+e),A+e*s),s++,i--;this._lastOffset+=e*s,this._currentHeight+=s}else if(1===this._mode){this._realloc(A,6*e),this._maxWidth=Math.max(this._maxWidth,e),this._minWidth=Math.min(this._minWidth,e);for(let i=0;i<6;++i)this._canvas.set(this._pSrc.subarray(t*i,t*i+e),A+e*i);this._bandWidths.push(e),this._lastOffset+=6*e,this._currentHeight+=6}return 0}get width(){return 1!==this._mode?this._width:Math.max(this._maxWidth,this._wasm.current_width())}get height(){return 1!==this._mode?this._height:this._wasm.current_width()?6*this._bandWidths.length+this._wasm.current_height():6*this._bandWidths.length}get palette(){return this._palette.subarray(0,this._paletteLimit)}get memoryUsage(){return this._canvas.byteLength+this._wasm.memory.buffer.byteLength+8*this._bandWidths.length}get properties(){return{width:this.width,height:this.height,mode:this._mode,level:this._level,truncate:!!this._truncate,paletteLimit:this._paletteLimit,fillColor:this._fillColor,memUsage:this.memoryUsage,rasterAttributes:{numerator:this._states[4],denominator:this._states[5],width:this._rasterWidth,height:this._rasterHeight}}}init(e=this._opts.fillColor,t=this._opts.palette,A=this._opts.paletteLimit,i=this._opts.truncate){this._wasm.init(this._opts.sixelColor,e,A,i?1:0),t&&this._palette.set(t.subarray(0,s.LIMITS.PALETTE_SIZE)),this._bandWidths.length=0,this._maxWidth=0,this._minWidth=s.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0}decode(e,t=0,A=e.length){let i=t;for(;i0){const A=this._PIXEL_OFFSET;let i=this._lastOffset,s=0;for(;s<6&&t>0;)this._canvas.set(this._pSrc.subarray(A*s,A*s+e),i+e*s),s++,t--;t&&this._canvas.fill(this._fillColor,i+e*s)}return this._canvas.subarray(0,this.width*this.height)}if(1===this._mode){if(this._minWidth===this._maxWidth){let t=!1;if(e)if(e!==this._minWidth)t=!0;else{const t=this._PIXEL_OFFSET;let A=this._lastOffset;this._realloc(A,6*e);for(let i=0;i<6;++i)this._canvas.set(this._pSrc.subarray(t*i,t*i+e),A+e*i)}if(!t)return this._canvas.subarray(0,this.width*this.height)}const t=new Uint32Array(this.width*this.height);t.fill(this._fillColor);let A=0,i=0;for(let e=0;e{if(this._disposed)return(0,i.toDisposable)(()=>{});const s={fn:e,thisArgs:t};this._listeners=this._listeners.slice(),this._listeners.push(s);const r=(0,i.toDisposable)(()=>{const e=this._listeners.indexOf(s);-1!==e&&(this._listeners=this._listeners.slice(),this._listeners.splice(e,1))});return A&&(Array.isArray(A)?A.push(r):A.add(r)),r}),this._event}fire(e){if(this._disposed||!this._listeners.length)return;if(1===this._listeners.length)return void this._listeners[0].fn.call(this._listeners[0].thisArgs,e);const t=this._listeners;for(let A=0,i=t.length;At.fire(e))},e.map=function(e,t){return(A,i,s)=>e(e=>A.call(i,t(e)),void 0,s)},e.any=function(...e){return(t,A,s)=>{const r=new i.DisposableStore;for(const i of e)r.add(i(e=>t.call(A,e)));return s&&(Array.isArray(s)?s.push(r):s.add(r)),r}},e.runAndSubscribe=function(e,t,A){return t(A),e(e=>t(e))}}(s||(t.EventUtils=s={}))},426(e,t){function A(e){return{dispose:e}}function i(e){if(!e)return e;if(Array.isArray(e)){for(const t of e)t.dispose();return[]}return e.dispose(),e}Object.defineProperty(t,"__esModule",{value:!0}),t.MutableDisposable=t.Disposable=t.DisposableStore=void 0,t.toDisposable=A,t.dispose=i,t.combinedDisposable=function(...e){return A(()=>i(e))};class s{constructor(){this._disposables=new Set,this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(e){return this._isDisposed?e.dispose():this._disposables.add(e),e}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(const e of this._disposables)e.dispose();this._disposables.clear()}}clear(){for(const e of this._disposables)e.dispose();this._disposables.clear()}}t.DisposableStore=s;class r{constructor(){this._store=new s}dispose(){this._store.dispose()}_register(e){return this._store.add(e)}}t.Disposable=r,r.None=Object.freeze({dispose(){}}),t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}}},795(e,t,A){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.IIPHandler=void 0;const s=A(463),r=A(699),o=i(A(669)),a=i(A(61)),n=A(389),h=A(462),g={type:0,name:"Unnamed file",size:0,width:"auto",height:"auto",preserveAspectRatio:1,inline:0};t.IIPHandler=class{constructor(e,t,A,i){this._opts=e,this._renderer=t,this._storage=A,this._coreTerminal=i,this._aborted=!1,this._hp=new n.HeaderParser,this._header=g,this._isMultipart=!1,this._abortMulti=!1;const s=Math.ceil(4*this._opts.iipSizeLimit/3),r=Math.min(1048576,s);this._dec=new o.default(4194304,s,r),this._qoiDec=new a.default(4194304)}reset(){this._hp.reset(),this._dec.release(),this._qoiDec.release()}start(){this._aborted=!1,this._hp.reset()}put(e,t,A){if(!this._aborted)if(4===this._hp.state)0!==this._dec.put(e.subarray(t,A))&&(this._dec.release(),this._aborted=!0);else{const i=this._hp.parse(e,t,A);if(-1===i)return void(this._aborted=!0);if(i>0){if(1===this._hp.fields.type){if(this._isMultipart&&(this._isMultipart=!1,this._abortMulti=!1,this._dec.release()),this._header=Object.assign({},g,this._hp.fields),!this._header.inline)return void(this._aborted=!0);this._dec.init()}else if(this._abortMulti)return void(this._aborted=!0);0!==this._dec.put(e.subarray(i,A))&&(this._dec.release(),this._aborted=!0,this._isMultipart&&(this._abortMulti=!0))}}}end(e){var t,A,i;if(this._aborted)return!0;if(4!==this._hp.state&&this._hp.end())return!0;const o=this._hp.fields.type;if(3===o)return!0;if(5===o){let e=r.CELL_SIZE_DEFAULT.width,A=r.CELL_SIZE_DEFAULT.height;this._renderer.dimensions&&(e=this._renderer.dimensions.css.canvas.width/this._coreTerminal.cols,A=this._renderer.dimensions.css.canvas.height/this._coreTerminal.rows);const s=null!==(i=null===(t=this._coreTerminal._core._coreBrowserService)||void 0===t?void 0:t.dpr)&&void 0!==i?i:1,o=`]1337;ReportCellSize=${A.toFixed(3)};${e.toFixed(3)};${s.toFixed(3)}\\`;return this._coreTerminal.input(o,!1),!0}if(2===o)return this._header=Object.assign({},g,this._hp.fields),this._isMultipart=!0,this._abortMulti=!1,this._dec.release(),this._dec.init(),!0;if(4===o){if(!this._isMultipart)return!0;if(this._isMultipart=!1,this._abortMulti||2!==this._header.type)return!0}let a,n,d=0,l=0,I=h.UNSUPPORTED_TYPE;if((a=e)&&((a=!this._dec.end())?(I=(0,h.imageType)(this._dec.data8),(a="unsupported"!==I.mime)?(d=I.width,l=I.height,(a=d&&l&&d*l(this._storage.addImage(e),!0)).catch(e=>(console.warn(`IIP: decoding error ${I.mime} ${I.width}x${I.height}`,e),!0))}_resize(e,t){var A,i,s,o;const a=(null===(A=this._renderer.dimensions)||void 0===A?void 0:A.css.cell.width)||r.CELL_SIZE_DEFAULT.width,n=(null===(i=this._renderer.dimensions)||void 0===i?void 0:i.css.cell.height)||r.CELL_SIZE_DEFAULT.height,h=(null===(s=this._renderer.dimensions)||void 0===s?void 0:s.css.canvas.width)||a*this._coreTerminal.cols,g=(null===(o=this._renderer.dimensions)||void 0===o?void 0:o.css.canvas.height)||n*this._coreTerminal.rows,d=this._dim(this._header.width,h,a),l=this._dim(this._header.height,g,n);if(!d&&!l){const A=h/e,i=(g-n)/t,s=Math.min(A,i);return s<1?[e*s,t*s]:[e,t]}return d?!this._header.preserveAspectRatio&&d&&l?[d,l]:[d,t*d/e]:[e*l/t,l]}_dim(e,t,A){return"auto"===e?0:e.endsWith("%")?parseInt(e.slice(0,-1),10)*t/100:e.endsWith("px")?parseInt(e.slice(0,-2),10):parseInt(e,10)*A}}},389(e,t){function A(e){let t="";for(let A=0;A57)throw new Error("illegal char");t=10*t+e[A]-48}return t}function s(e){const t=A(e);if(!t.match(/^((auto)|(\d+?((px)|(%)){0,1}))$/))throw new Error("illegal size");return t}Object.defineProperty(t,"__esModule",{value:!0}),t.HeaderParser=void 0;const r={inline:i,size:i,name:function(e){if("undefined"!=typeof Buffer)return Buffer.from(A(e),"base64").toString();const t=atob(A(e)),i=new Uint8Array(t.length);for(let e=0;e14)return-1;for(let h=t;h=d)return this._a();r[s++]=t}break;case 58:return 3!==i||this._storeValue(s)?(this.state=4,h+1):this._a();default:if(s>=d)return this._a();r[s++]=t}}return this.state=i,this._position=s,-2}_a(){return this.fields.type=0,this.state=1,-1}_storeKey(e){const t=A(this._buffer.subarray(0,e));return!!t&&(this._key=t,this.fields[t]=null,!0)}_storeValue(e){if(this._key){try{const t=this._buffer.slice(0,e);this.fields[this._key]=r[this._key]?r[this._key](t):t}catch(e){return!1}return!0}return!1}}},649(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.IIPImageStorage=void 0,t.IIPImageStorage=class{constructor(e){this._storage=e,this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"}}addImage(e){this._storage.addImage(e,this._addImageOpts)}}},462(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.UNSUPPORTED_TYPE=void 0,t.imageType=function(e){if(e.length<32)return t.UNSUPPORTED_TYPE;const A=new Uint32Array(e.buffer,e.byteOffset,8);if(1196314761===A[0]&&169478669===A[1]&&1380206665===A[3])return{mime:"image/png",width:e[16]<<24|e[17]<<16|e[18]<<8|e[19],height:e[20]<<24|e[21]<<16|e[22]<<8|e[23]};if(255===e[0]&&216===e[1]&&255===e[2]){const[t,A]=function(e){const t=e.length;let A=4,i=e[A]<<8|e[A+1];for(;;){if(A+=i,A>=t)return[0,0];if(255!==e[A])return[0,0];if(192===e[A+1]||194===e[A+1])return A+8>>14&16383)};case 32:return 157!==e[23]||1!==e[24]||42!==e[25]?t.UNSUPPORTED_TYPE:{mime:"image/webp",width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}return t.UNSUPPORTED_TYPE}if(1887007846===A[1]&&(1718187617===A[2]||1936291425===A[2])){let A=-1;const i=Math.min(e.length-16,1024);for(let t=8;t0&&i>0)return{mime:"image/avif",width:t,height:i}}return t.UNSUPPORTED_TYPE}return t.UNSUPPORTED_TYPE},t.UNSUPPORTED_TYPE={mime:"unsupported",width:0,height:0}},463(e,t,A){Object.defineProperty(t,"__esModule",{value:!0}),t.ImageRenderer=void 0;const i=A(939),s=A(426);class r extends s.Disposable{get canvas(){var e;return null===(e=this._layers.get("top"))||void 0===e?void 0:e.canvas}static createCanvas(e,t,A){const i=(null!=e?e:document).createElement("canvas");return i.width=0|t,i.height=0|A,i}static createImageData(e,t,A,i){if("function"!=typeof ImageData){const s=e.createImageData(t,A);return i&&s.data.set(new Uint8ClampedArray(i,0,t*A*4)),s}return i?new ImageData(new Uint8ClampedArray(i,0,t*A*4),t,A):new ImageData(t,A)}static createImageBitmap(e){return"function"!=typeof createImageBitmap?Promise.resolve(void 0):createImageBitmap(e)}constructor(e){super(),this._terminal=e,this._layers=new Map,this._optionsRefresh=this._register(new s.MutableDisposable),this._oldOpen=this._terminal._core.open,this._terminal._core.open=e=>{var t;null===(t=this._oldOpen)||void 0===t||t.call(this._terminal._core,e),this._open()},this._terminal._core.screenElement&&this._open(),this._optionsRefresh.value=this._terminal._core.optionsService.onOptionChange(e=>{var t;"fontSize"===e&&(this.rescaleCanvas(),null===(t=this._renderService)||void 0===t||t.refreshRows(0,this._terminal.rows))}),this._register((0,s.toDisposable)(()=>{var e;this.removeLayerFromDom(),this.removeLayerFromDom("bottom"),this._terminal._core&&this._oldOpen&&(this._terminal._core.open=this._oldOpen,this._oldOpen=void 0),this._renderService&&this._oldSetRenderer&&(this._renderService.setRenderer=this._oldSetRenderer,this._oldSetRenderer=void 0),this._renderService=void 0,this._layers.clear(),null===(e=this._placeholderBitmap)||void 0===e||e.close(),this._placeholderBitmap=void 0,this._placeholder=void 0}))}showPlaceholder(e){var t,A;e?this._placeholder||-1===this.cellSize.height||this._createPlaceHolder(Math.max(this.cellSize.height+1,24)):(null===(t=this._placeholderBitmap)||void 0===t||t.close(),this._placeholderBitmap=void 0,this._placeholder=void 0),null===(A=this._renderService)||void 0===A||A.refreshRows(0,this._terminal.rows)}get dimensions(){return this._terminal.dimensions}get cellSize(){var e,t;return{width:(null===(e=this.dimensions)||void 0===e?void 0:e.css.cell.width)||-1,height:(null===(t=this.dimensions)||void 0===t?void 0:t.css.cell.height)||-1}}clearLines(e,t,A){var i,s,r,o,a;const n=e*((null===(i=this.dimensions)||void 0===i?void 0:i.css.cell.height)||0),h=(null===(s=this.dimensions)||void 0===s?void 0:s.css.canvas.width)||0,g=(t+1-e)*((null===(r=this.dimensions)||void 0===r?void 0:r.css.cell.height)||0);A&&"top"!==A||null===(o=this._layers.get("top"))||void 0===o||o.clearRect(0,n,h,g),A&&"bottom"!==A||null===(a=this._layers.get("bottom"))||void 0===a||a.clearRect(0,n,h,g)}clearAll(e){if(!e||"top"===e){const e=this._layers.get("top");null==e||e.clearRect(0,0,e.canvas.width,e.canvas.height)}if(!e||"bottom"===e){const e=this._layers.get("bottom");null==e||e.clearRect(0,0,e.canvas.width,e.canvas.height)}}draw(e,t,A,i,s=1){const r=this._layers.get(e.layer);if(!r)return;const{width:o,height:a}=this.cellSize;if(-1===o||-1===a)return;this._rescaleImage(e,o,a);const n=e.actual,h=Math.ceil(n.width/o),g=t%h*o,d=Math.floor(t/h)*a,l=A*o,I=i*a,c=s*o+g>n.width?n.width-g:s*o,_=d+a>n.height?n.height-d:a;r.drawImage(n,Math.floor(g),Math.floor(d),Math.ceil(c),Math.ceil(_),Math.floor(l),Math.floor(I),Math.ceil(c),Math.ceil(_))}extractTile(e,t){const{width:A,height:i}=this.cellSize;if(-1===A||-1===i)return;this._rescaleImage(e,A,i);const s=e.actual,o=Math.ceil(s.width/A),a=t%o*A,n=Math.floor(t/o)*i,h=A+a>s.width?s.width-a:A,g=n+i>s.height?s.height-n:i,d=r.createCanvas(this.document,h,g),l=d.getContext("2d");return l?(l.drawImage(s,Math.floor(a),Math.floor(n),Math.floor(h),Math.floor(g),0,0,Math.floor(h),Math.floor(g)),d):void 0}drawPlaceholder(e,t,A=1){var i;const s=this._layers.get("top");if(s){const{width:r,height:o}=this.cellSize;if(-1===r||-1===o)return;if(this._placeholder?o>=this._placeholder.height&&this._createPlaceHolder(o+1):this._createPlaceHolder(Math.max(o+1,24)),!this._placeholder)return;s.drawImage(null!==(i=this._placeholderBitmap)&&void 0!==i?i:this._placeholder,e*r,t*o%2?0:1,r*A,o,e*r,t*o,r*A,o)}}rescaleCanvas(){var e,t;const A=(null===(e=this.dimensions)||void 0===e?void 0:e.css.canvas.width)||0,i=(null===(t=this.dimensions)||void 0===t?void 0:t.css.canvas.height)||0;for(const e of this._layers.values())e.canvas.width===A&&e.canvas.height===i||(e.canvas.width=A,e.canvas.height=i)}_rescaleImage(e,t,A){if(t===e.actualCellSize.width&&A===e.actualCellSize.height)return;const{width:i,height:s}=e.origCellSize;if(t===i&&A===s)return e.actual=e.orig,e.actualCellSize.width=i,void(e.actualCellSize.height=s);const o=r.createCanvas(this.document,Math.ceil(e.orig.width*t/i),Math.ceil(e.orig.height*A/s)),a=o.getContext("2d");a&&(a.drawImage(e.orig,0,0,o.width,o.height),e.actual=o,e.actualCellSize.width=t,e.actualCellSize.height=A)}_open(){this._renderService=this._terminal._core._renderService,this._oldSetRenderer=this._renderService.setRenderer.bind(this._renderService),this._renderService.setRenderer=e=>{var t;for(const e of[...this._layers.keys()])this.removeLayerFromDom(e);null===(t=this._oldSetRenderer)||void 0===t||t.call(this._renderService,e)}}insertLayerToDom(e="top"){var t,A;if(!this.document||!this._terminal._core.screenElement)return void console.warn("image addon: cannot insert output canvas to DOM, missing document or screenElement");if(this._layers.has(e))return;const i=r.createCanvas(this.document,(null===(t=this.dimensions)||void 0===t?void 0:t.css.canvas.width)||0,(null===(A=this.dimensions)||void 0===A?void 0:A.css.canvas.height)||0);i.classList.add(`xterm-image-layer-${e}`);const s=this._terminal._core.screenElement;s.style.isolation="isolate","bottom"===e?(i.style.zIndex="-1",s.insertBefore(i,s.firstChild)):(i.style.zIndex="0",s.appendChild(i));const o=i.getContext("2d",{alpha:!0});o?(this._layers.set(e,o),this.clearAll(e)):i.remove()}removeLayerFromDom(e="top"){const t=this._layers.get(e);t&&(t.canvas.remove(),this._layers.delete(e))}hasLayer(e){return this._layers.has(e)}_createPlaceHolder(e=24){var t;null===(t=this._placeholderBitmap)||void 0===t||t.close(),this._placeholderBitmap=void 0;const A=32,s=r.createCanvas(this.document,A,e),o=s.getContext("2d",{alpha:!1});if(!o)return;const a=r.createImageData(o,A,e),n=new Uint32Array(a.data.buffer),h=(0,i.toRGBA8888)(0,0,0),g=(0,i.toRGBA8888)(255,255,255);n.fill(h);for(let t=0;tthis._placeholderBitmap=e)}else this._placeholder=void 0}get document(){var e;return null===(e=this._terminal._core._coreBrowserService)||void 0===e?void 0:e.window.document}}t.ImageRenderer=r},699(e,t,A){Object.defineProperty(t,"__esModule",{value:!0}),t.ImageStorage=t.CELL_SIZE_DEFAULT=void 0;const i=A(463);t.CELL_SIZE_DEFAULT={width:7,height:14};class s{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get underlineVariantOffset(){const e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}get urlId(){return this._urlId}set urlId(e){this._urlId=e}constructor(e=0,t=0,A=-1,i=-1){this.imageId=A,this.tileId=i,this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new s(this._ext,this._urlId,this.imageId,this.tileId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId&&-1===this.imageId}}const r=new s;t.ImageStorage=class{constructor(e,t,A){this._terminal=e,this._renderer=t,this._opts=A,this._images=new Map,this._lastId=0,this._lowestId=0,this._fullyCleared=!1,this._needsFullClear=!1,this._pixelLimit=25e5;try{this.setLimit(this._opts.storageLimit)}catch(e){e instanceof Error&&console.error(e.message),console.warn(`storageLimit is set to ${this.getLimit()} MB`)}this._viewportMetrics={cols:this._terminal.cols,rows:this._terminal.rows}}dispose(){this.reset()}reset(){var e;for(const t of this._images.values())null===(e=t.marker)||void 0===e||e.dispose();this._images.clear(),this._renderer.clearAll()}getLimit(){return 4*this._pixelLimit/1e6}setLimit(e){if(e<.5||e>1e3)throw RangeError("invalid storageLimit, should be at least 0.5 MB and not exceed 1G");this._pixelLimit=e/4*1e6>>>0,this._evictOldest(0)}getUsage(){return 4*this._getStoredPixels()/1e6}_getStoredPixels(){let e=0;for(const t of this._images.values())t.orig&&(e+=t.orig.width*t.orig.height,t.actual&&t.actual!==t.orig&&(e+=t.actual.width*t.actual.height));return e}_delImg(e){var t;const A=this._images.get(e);A&&(this._images.delete(e),window.ImageBitmap&&A.orig instanceof ImageBitmap&&A.orig.close(),null===(t=this.onImageDeleted)||void 0===t||t.call(this,e))}wipeAlternate(){var e;const t=[];for(const[A,i]of this._images.entries())"alternate"===i.bufferType&&(null===(e=i.marker)||void 0===e||e.dispose(),t.push(A));for(const e of t)this._delImg(e);this._needsFullClear=!0,this._fullyCleared=!1}deleteImage(e){var t;const A=this._images.get(e);A&&(null===(t=A.marker)||void 0===t||t.dispose(),this._delImg(e))}addImage(e,A){var i,s;this._evictOldest(e.width*e.height);let r=this._renderer.cellSize;-1!==r.width&&-1!==r.height||(r=t.CELL_SIZE_DEFAULT);const o=Math.ceil(e.width/r.width),a=Math.ceil(e.height/r.height),n=++this._lastId,h=this._terminal._core.buffer,g=this._terminal.cols,d=this._terminal.rows,l=h.x,I=h.y;let c=l,_=0;A.scrolling||(h.x=0,h.y=0,c=0),this._terminal._core._inputHandler._dirtyRowTracker.markDirty(h.y);for(let e=0;e=g);++A)this._writeToCell(t,c+A,n,e*o+A),_++;if(A.scrolling)e=d)break;h.x=c}this._terminal._core._inputHandler._dirtyRowTracker.markDirty(h.y),A.scrolling?"iip"===A.cursorPos?h.x=Math.min(c+o,g):h.x=c:(h.x=l,h.y=I);const C=[];for(const[e,t]of this._images.entries())t.tileCount<1&&(null===(i=t.marker)||void 0===i||i.dispose(),C.push(e));for(const e of C)this._delImg(e);const B=this._terminal.registerMarker(0);null==B||B.onDispose(()=>{this._images.get(n)&&this._delImg(n)}),"alternate"===this._terminal.buffer.active.type&&this._evictOnAlternate();const Q={orig:e,origCellSize:r,actual:e,actualCellSize:Object.assign({},r),marker:B||void 0,tileCount:_,bufferType:this._terminal.buffer.active.type,layer:A.layer,zIndex:A.zIndex};return this._images.set(n,Q),null===(s=this.onImageAdded)||void 0===s||s.call(this),n}render(e){var t,A;let i=!1,s=!1;for(const e of this._images.values())if("bottom"===e.layer?s=!0:i=!0,i&&s)break;if(i&&!this._renderer.hasLayer("top")&&(this._renderer.insertLayerToDom("top"),!this._renderer.hasLayer("top")))return;if(s&&!this._renderer.hasLayer("bottom")&&this._renderer.insertLayerToDom("bottom"),this._renderer.rescaleCanvas(),!this._images.size)return this._fullyCleared||(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1),this._renderer.hasLayer("top")&&this._renderer.removeLayerFromDom("top"),void(this._renderer.hasLayer("bottom")&&this._renderer.removeLayerFromDom("bottom"));!i&&this._renderer.hasLayer("top")&&(this._renderer.clearAll("top"),this._renderer.removeLayerFromDom("top")),!s&&this._renderer.hasLayer("bottom")&&(this._renderer.clearAll("bottom"),this._renderer.removeLayerFromDom("bottom")),this._needsFullClear&&(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1);const{start:o,end:a}=e,n=this._terminal._core.buffer,h=this._terminal._core.cols;this._renderer.clearLines(o,a);const g=[],d=[];for(let e=o;e<=a;++e){const i=n.lines.get(e+n.ydisp);if(!i)return;for(let s=0;se.imgSpec.zIndex-t.imgSpec.zIndex);for(const e of d)this._renderer.drawPlaceholder(e.col,e.row,e.count);for(const e of g)this._renderer.draw(e.imgSpec,e.tileId,e.col,e.row,e.count)}viewportResize(e){var t,A;if(!this._images.size)return void(this._viewportMetrics=e);if(this._viewportMetrics.cols>=e.cols)return void(this._viewportMetrics=e);const i=this._terminal._core.buffer,s=i.lines.length,o=this._viewportMetrics.cols-1;for(let a=0;a=h)continue;let g=!1;for(let t=o+1;t>e.cols;++t)if(4194303&s._data[3*t+0]){g=!0;break}if(g)continue;const d=Math.min(e.cols,h-i.tileId%h+o);let l=i.tileId;for(let e=o+1;e>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255}o.set(i.PALETTE_VT340_COLOR),t.SixelHandler=class{constructor(e,t,A){this._opts=e,this._storage=t,this._coreTerminal=A,this._size=0,this._aborted=!1,(0,r.DecoderAsync)({memoryLimit:4*this._opts.pixelLimit,palette:o,paletteLimit:this._opts.sixelPaletteLimit}).then(e=>this._dec=e)}reset(){this._dec&&(this._dec.release(),this._dec._palette.fill(0),this._dec.init(0,o,this._opts.sixelPaletteLimit))}hook(e){var t;if(this._size=0,this._aborted=!1,this._dec){const A=1===e.params[1]?0:function(e,t){let A=0;if(!t)return A;if(e.isInverse())if(e.isFgDefault())A=a(t.foreground.rgba);else if(e.isFgRGB()){const t=e.constructor.toColorRGB(e.getFgColor());A=(0,i.toRGBA8888)(...t)}else A=a(t.ansi[e.getFgColor()].rgba);else if(e.isBgDefault())A=a(t.background.rgba);else if(e.isBgRGB()){const t=e.constructor.toColorRGB(e.getBgColor());A=(0,i.toRGBA8888)(...t)}else A=a(t.ansi[e.getBgColor()].rgba);return A}(this._coreTerminal._core._inputHandler._curAttrData,null===(t=this._coreTerminal._core._themeService)||void 0===t?void 0:t.colors);this._dec.init(A,null,this._opts.sixelPaletteLimit)}}put(e,t,A){if(!this._aborted&&this._dec){if(this._size+=A-t,this._size>this._opts.sixelSizeLimit)return console.warn("SIXEL: too much data, aborting"),this._aborted=!0,void this._dec.release();try{this._dec.decode(e,t,A)}catch(e){console.warn(`SIXEL: error while decoding image - ${e}`),this._aborted=!0,this._dec.release()}}}unhook(e){var t;if(this._aborted||!e||!this._dec)return!0;const A=this._dec.width,i=this._dec.height;if(!A||!i)return i&&this._storage.advanceCursor(i),!0;const r=s.ImageRenderer.createCanvas(void 0,A,i);return null===(t=r.getContext("2d"))||void 0===t||t.putImageData(new ImageData(this._dec.data8,A,i),0,0),this._dec.memoryUsage>4194304&&this._dec.release(),this._storage.addImage(r),!0}}},994(e,t,A){Object.defineProperty(t,"__esModule",{value:!0}),t.SixelImageStorage=void 0;const i=A(699);t.SixelImageStorage=class{constructor(e,t,A,i){this._storage=e,this._opts=t,this._renderer=A,this._terminal=i,this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"vt340"}}addImage(e){this._addImageOpts.scrolling=this._opts.sixelScrolling,this._storage.addImage(e,this._addImageOpts)}advanceCursor(e){if(this._opts.sixelScrolling){let t=this._renderer.cellSize;-1!==t.width&&-1!==t.height||(t=i.CELL_SIZE_DEFAULT);const A=Math.ceil(e/t.height);for(let e=1;e512)return void(this._aborted=!0);if(this._controlData.set(e.subarray(t,s),this._controlLength),this._controlLength+=r,!this._inControlData){if(this._parsedCommand=(0,a.parseKittyCommand)(this._parseControlDataString()),void 0!==this._parsedCommand.id&&void 0!==this._parsedCommand.imageNumber)return this._sendResponse(this._parsedCommand.id,"EINVAL:cannot specify both i and I keys",null!==(i=this._parsedCommand.quiet)&&void 0!==i?i:0),void(this._aborted=!0);if("d"===this._parsedCommand.action)return;const t=s+1;tthis._encodedSizeLimit){const e=null!==(n=this._activeDecoder)&&void 0!==n?n:null==g?void 0:g.decoder;return e&&e.release(),this._activeDecoder=null,g&&this._removePendingEntry(h),void(this._aborted=!0)}this._decodeError||((null==g?void 0:g.decoder)&&!this._activeDecoder&&(this._activeDecoder=g.decoder),this._activeDecoder||(this._activeDecoder=new o.default(4194304,this._maxEncodedBytes,this._initialEncodedBytes),this._activeDecoder.init()),0!==this._activeDecoder.put(e.subarray(t,A))&&(this._activeDecoder.release(),this._activeDecoder=null,this._decodeError=!0,g&&this._removePendingEntry(h)))}end(e){var t,A;if(this._aborted||!e)return this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),!0;if(this._inControlData)return this._handleNoPayloadCommand();const i=this._parsedCommand;if("d"===i.action)return this._handleDelete(i);const s=null!==(A=null!==(t=i.id)&&void 0!==t?t:this._lastPendingKey)&&void 0!==A?A:0,r=1===i.more,o=this._pendingTransmissions.get(s);if(r)return this._activeDecoder&&(o?(o.totalEncodedSize+=this._totalEncodedSize,o.decodeError=o.decodeError||this._decodeError):this._pendingTransmissions.set(s,{cmd:Object.assign({},i),decoder:this._activeDecoder,totalEncodedSize:this._totalEncodedSize,decodeError:this._decodeError}),this._lastPendingKey=s,this._activeDecoder=null),!0;o&&(this._lastPendingKey=void 0);let a=this._decodeError,n=i,h=this._activeDecoder;o&&(n=o.cmd,h=o.decoder,a=a||o.decodeError,this._pendingTransmissions.delete(s));let g=new Uint8Array(0);h&&(0!==h.end()&&(a=!0),g=h.data8),this._activeDecoder=null;const d=this._handleCommandWithBytesAndCmd(n,g,a);return h&&h.release(),d}_parseControlDataString(){let e="";for(let t=0;t0&&this._sendResponse(e.id,"OK",null!==(o=e.quiet)&&void 0!==o?o:0)),i}case"T":return this._handleTransmitDisplay(e,t,A);case"q":return this._handleQuery(e,t,A);case"p":return this._handlePlacement(e);default:return void 0!==e.id&&this._sendResponse(e.id,"EINVAL:unsupported action",null!==(a=e.quiet)&&void 0!==a?a:0),!0}}_handlePlacement(e){var t;if(void 0===e.id)return!0;const A=e.id,i=this._kittyStorage.getImage(A);return i?this._displayImage(i,e).then(t=>{var i;return this._sendResponse(A,t?"OK":"EINVAL:image rendering failed",null!==(i=e.quiet)&&void 0!==i?i:0,e.placementId),!0}):(this._sendResponse(A,"ENOENT:image not found",null!==(t=e.quiet)&&void 0!==t?t:0,e.placementId),!0)}_handleTransmit(e,t,A){var i,s,r,o,a,n;return"d"!==(null!==(i=e.transmission)&&void 0!==i?i:"d")?(void 0!==e.id&&this._sendResponse(e.id,"EINVAL:unsupported transmission medium",null!==(s=e.quiet)&&void 0!==s?s:0),!0):(A||0===t.length||this._kittyStorage.storeImage(e.id,{data:new Blob([t]),width:null!==(r=e.width)&&void 0!==r?r:0,height:null!==(o=e.height)&&void 0!==o?o:0,format:null!==(a=e.format)&&void 0!==a?a:32,compression:null!==(n=e.compression)&&void 0!==n?n:""}),!0)}_handleTransmitDisplay(e,t,A){var i,s;if(A)return void 0!==e.id&&this._sendResponse(e.id,"EINVAL:invalid base64 data",null!==(i=e.quiet)&&void 0!==i?i:0),!0;this._handleTransmit(e,t,A);const r=null!==(s=e.id)&&void 0!==s?s:this._kittyStorage.lastImageId,o=this._kittyStorage.getImage(r);if(o){const t=this._displayImage(o,e);return void 0!==e.id?t.then(t=>{var A;return this._sendResponse(r,t?"OK":"EINVAL:image rendering failed",null!==(A=e.quiet)&&void 0!==A?A:0),!0}):t.then(()=>!0)}return!0}_handleQuery(e,t,A){var i,s,r,o,a,n;const h=null!==(i=e.id)&&void 0!==i?i:0,g=null!==(s=e.quiet)&&void 0!==s?s:0;if("d"!==(null!==(r=e.transmission)&&void 0!==r?r:"d"))return this._sendResponse(h,"EINVAL:unsupported transmission medium",g),!0;if(A)return this._sendResponse(h,"EINVAL:invalid base64 data",g),!0;if(0===t.length)return this._sendResponse(h,"OK",g),!0;const d=null!==(o=e.format)&&void 0!==o?o:32;if(100===d)this._sendResponse(h,"OK",g);else{const A=null!==(a=e.width)&&void 0!==a?a:0,i=null!==(n=e.height)&&void 0!==n?n:0;if(!A||!i)return this._sendResponse(h,"EINVAL:width and height required for raw pixel data",g),!0;const s=A*i*(32===d?4:3);if(t.length=1)return;if(!s&&A>=2)return;const r=`_Gi=${e}${i?`,p=${i}`:""};${t}\\`;this._coreTerminal._core.coreService.triggerDataEvent(r)}_displayImage(e,t){return this._decodeAndDisplay(e,t).then(()=>!0).catch(()=>!1)}async _decodeAndDisplay(e,t){var A,i,o,a,n,h,g;let d=await this._createBitmap(e);try{const l=Math.max(0,null!==(o=t.x)&&void 0!==o?o:0),I=Math.max(0,null!==(a=t.y)&&void 0!==a?a:0),c=t.sourceWidth||d.width-l,_=t.sourceHeight||d.height-I,C=Math.max(0,d.width-l),B=Math.max(0,d.height-I),Q=Math.max(0,Math.min(c,C)),m=Math.max(0,Math.min(_,B));if(0===Q||0===m)throw new Error("invalid source rectangle");if(0!==l||0!==I||Q!==d.width||m!==d.height){const e=await createImageBitmap(d,l,I,Q,m);d.close(),d=e}const E=(null===(A=this._renderer.dimensions)||void 0===A?void 0:A.css.cell.width)||r.CELL_SIZE_DEFAULT.width,u=(null===(i=this._renderer.dimensions)||void 0===i?void 0:i.css.cell.height)||r.CELL_SIZE_DEFAULT.height;let w,p;void 0!==t.columns&&void 0!==t.rows?(w=t.columns,p=t.rows):void 0!==t.columns?(w=t.columns,p=Math.max(1,Math.ceil(d.height/d.width*(w*E)/u))):void 0!==t.rows?(p=t.rows,w=Math.max(1,Math.ceil(d.width/d.height*(p*u)/E))):(w=Math.ceil(d.width/E),p=Math.ceil(d.height/u));let f=d.width,D=d.height;if(void 0===t.columns&&void 0===t.rows||(f=Math.round(w*E),D=Math.round(p*u)),f*D>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");const y=this._coreTerminal._core.buffer,v=y.x,k=y.y,M=y.ybase,b=void 0!==t.zIndex&&t.zIndex<0?"bottom":"top";if(f!==d.width||D!==d.height){const e=await createImageBitmap(d,{resizeWidth:f,resizeHeight:D});d.close(),d=e}const S=Math.min(Math.max(0,null!==(n=t.xOffset)&&void 0!==n?n:0),E-1),L=Math.min(Math.max(0,null!==(h=t.yOffset)&&void 0!==h?h:0),u-1);if(0!==S||0!==L){const e=void 0!==t.columns?Math.round(w*E):d.width+S,A=void 0!==t.rows?Math.round(p*u):d.height+L,i=s.ImageRenderer.createCanvas(window.document,e,A),r=i.getContext("2d");if(!r)throw new Error("Failed to create offset canvas context");r.drawImage(d,S,L);const o=await createImageBitmap(i);if(i.width=i.height=0,d.close(),d=o,f=d.width,D=d.height,f*D>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");void 0===t.columns&&(w=Math.ceil(d.width/E)),void 0===t.rows&&(p=Math.ceil(d.height/u))}const N=null!==(g=t.zIndex)&&void 0!==g?g:0;if(this._kittyStorage.addImage(e.id,d,!0,b,N),d=void 0,1===t.cursorMovement){const e=y.ybase-M;y.x=v,y.y=Math.max(k-e,0)}else y.x=Math.min(v+w,this._coreTerminal.cols)}catch(e){throw null==d||d.close(),e}}async _createBitmap(e){let t=new Uint8Array(await e.data.arrayBuffer());if("z"===e.compression&&(t=await this._decompressZlib(t)),100===e.format){const e=new Blob([t],{type:"image/png"});if(!window.createImageBitmap){const t=URL.createObjectURL(e),A=new Image;return new Promise((e,i)=>{A.addEventListener("load",()=>{var r;URL.revokeObjectURL(t);const o=s.ImageRenderer.createCanvas(window.document,A.width,A.height);null===(r=o.getContext("2d"))||void 0===r||r.drawImage(A,0,0),createImageBitmap(o).then(e).catch(i)}),A.addEventListener("error",()=>{URL.revokeObjectURL(t),i(new Error("Failed to load image"))}),A.src=t})}return createImageBitmap(e)}const A=e.width,i=e.height;if(!A||!i)throw new Error("Width and height required for raw pixel data");const r=A*i*(32===e.format?4:3);if(t.length>>24|t<<8,h[l++]=4278190080|t>>>16|A<<16,h[l++]=4278190080|A>>>8}let I=3*g,c=4*g;for(let e=g;ee+t.length,0),a=new Uint8Array(o);let n=0;for(const e of s)a.set(e,n),n+=e.length;return a}get images(){return this._kittyStorage.images}get _kittyIdToStorageId(){return this._kittyStorage.kittyIdToStorageId}get pendingTransmissions(){return this._pendingTransmissions}}},470(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.parseKittyCommand=function(e){const t={},A=e.split(",");for(const e of A){const A=e.indexOf("=");if(-1===A)continue;const i=e.substring(0,A),s=e.substring(A+1);if("a"===i){t.action=s;continue}if("o"===i){t.compression=s;continue}if("t"===i){t.transmission=s;continue}if("d"===i){t.deleteSelector=s;continue}const r=parseInt(s,10);switch(i){case"f":t.format=r;break;case"i":t.id=r;break;case"I":t.imageNumber=r;break;case"s":t.width=r;break;case"v":t.height=r;break;case"x":t.x=r;break;case"y":t.y=r;break;case"w":t.sourceWidth=r;break;case"h":t.sourceHeight=r;break;case"X":t.xOffset=r;break;case"Y":t.yOffset=r;break;case"c":t.columns=r;break;case"r":t.rows=r;break;case"m":t.more=r;break;case"q":t.quiet=r;break;case"C":t.cursorMovement=r;break;case"z":t.zIndex=r;break;case"p":t.placementId=r}}return t}},235(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.KittyImageStorage=void 0;class A{constructor(e){this._storage=e,this._nextImageId=1,this._images=new Map,this._kittyIdToStorageId=new Map,this._storageIdToKittyId=new Map,this._handleStorageImageDeleted=e=>{const t=this._storageIdToKittyId.get(e);void 0!==t&&(this._kittyIdToStorageId.delete(t),this._storageIdToKittyId.delete(e),this._images.delete(t))},this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"},this._previousOnImageDeleted=this._storage.onImageDeleted,this._wrappedOnImageDeleted=e=>{var t;null===(t=this._previousOnImageDeleted)||void 0===t||t.call(this,e),this._handleStorageImageDeleted(e)},this._storage.onImageDeleted=this._wrappedOnImageDeleted}reset(){this._nextImageId=1,this._images.clear(),this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}dispose(){this.reset(),this._storage.onImageDeleted===this._wrappedOnImageDeleted&&(this._storage.onImageDeleted=this._previousOnImageDeleted)}storeImage(e,t){const i=null!=e?e:this._nextImageId++,s=this._kittyIdToStorageId.get(i);return void 0!==s&&(this._storage.deleteImage(s),this._kittyIdToStorageId.delete(i),this._storageIdToKittyId.delete(s)),!this._images.has(i)&&this._images.size>=A._maxStoredImages&&this._evictUndisplayedImages(),this._images.set(i,Object.assign(Object.assign({},t),{id:i})),i}addImage(e,t,A,i,s){const r=this._kittyIdToStorageId.get(e);void 0!==r&&this._storageIdToKittyId.delete(r),this._addImageOpts.scrolling=A,this._addImageOpts.layer=i,this._addImageOpts.zIndex=s;const o=this._storage.addImage(t,this._addImageOpts);this._kittyIdToStorageId.set(e,o),this._storageIdToKittyId.set(o,e)}getImage(e){return this._images.get(e)}deleteById(e){this._images.delete(e);const t=this._kittyIdToStorageId.get(e);void 0!==t&&(this._storage.deleteImage(t),this._kittyIdToStorageId.delete(e),this._storageIdToKittyId.delete(t))}deleteAll(){this._images.clear();for(const e of this._kittyIdToStorageId.values())this._storage.deleteImage(e);this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}get images(){return this._images}get kittyIdToStorageId(){return this._kittyIdToStorageId}get lastImageId(){return this._nextImageId-1}_evictUndisplayedImages(){for(const[e]of this._images){if(this._images.size<=A._maxStoredImages/2)break;this._kittyIdToStorageId.has(e)||this._images.delete(e)}}}t.KittyImageStorage=A,A._maxStoredImages=256},669(e,t,A){Object.defineProperty(t,"__esModule",{value:!0});const i=(0,A(552).InWasm)({s:1,t:0,d:"AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML"}),s=new Uint8Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map(e=>e.charCodeAt(0))),r=new Uint32Array(1024);r.fill(4278190080);for(let e=0;e>4|(e<<4&255)<<8;for(let e=0;e>2<<8|(e<<6&255)<<16;for(let e=0;ethis.maxBytes||this.maxBytes>4294901760)throw new Error("invalid byte settings")}get data8(){return this._inst?this._d.subarray(0,this._m32[1282]):o}release(){this._inst&&(this._bytes>this.keepSize?this._inst=this._m32=this._d=this._mem=null:(this._m32[1280]=0,this._m32[1281]=0,this._m32[1282]=0))}init(e,t){if(this.maxBytes=null!=e?e:this.maxBytes,this._bytes=null!=t?t:Math.min(this._bytes,this.maxBytes),this._bytes>this.maxBytes||this.maxBytes>4294901760)throw Error("invalid byte settings");let A=this._m32;const s=this._bytes+5152;this._inst?this._mem.buffer.byteLengththis.maxBytes)return-3;let e=this._bytes;for(;(e*=2)this._mem.buffer.byteLength){const t=Math.ceil((e+5152-this._mem.buffer.byteLength)/65536);this._mem.grow(t),this._m32=new Uint32Array(this._mem.buffer,0),this._d=new Uint8Array(this._mem.buffer,5152)}this._bytes=e}return 0}put(e){if(!this._inst||this._ended)return-2;if(this._realloc(e.length))return-3;const t=this._m32;return this._d.set(e,t[1280]),t[1280]+=e.length,t[1280]-t[1281]>=131072?this._inst.exports.dec():0}end(){return this._ended=!0,this._inst?this._inst.exports.end():-2}get loadedBytes(){return this._inst?this._m32[1280]:0}get freeBytes(){return this._inst?this.maxBytes-this._m32[1280]:0}}},61(e,t,A){Object.defineProperty(t,"__esModule",{value:!0});const i=(0,A(552).InWasm)({s:1,t:0,d:"AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=="});t.default=class{constructor(e){this.keepSize=e,this.width=0,this.height=0}decode(e){this.width=e[4]<<24|e[5]<<16|e[6]<<8|e[7],this.height=e[8]<<24|e[9]<<16|e[10]<<8|e[11];const t=this.width*this.height,A=4*t,s=e.length,r=Math.max(A,s)+(Math.min(A,s)>>1)+4096;this._inst?this._mem.buffer.byteLengththis.keepSize&&(this._inst=this._d=this._mem=null)}}},552(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.InWasm=function(e){if(e.d){const{t,s:i,d:s}=e;let r,o;const a=WebAssembly;return 0===t?i?e=>new a.Instance(o||(o=new a.Module(r||(r=A(s)))),e):e=>o?a.instantiate(o,e):a.instantiate(r||(r=A(s)),e).then(e=>(o=e.module)&&e.instance):1===t?i?()=>o||(o=new a.Module(r||(r=A(s)))):()=>o?Promise.resolve(o):a.compile(r||(r=A(s))).then(e=>o=e):i?()=>r||(r=A(s)):()=>Promise.resolve(r||(r=A(s)))}if("undefined"==typeof _wasmCtx)throw new Error('must run "inwasm"');_wasmCtx.add(e)};let A=e=>{if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64");const t=atob(e),A=new Uint8Array(t.length);for(let e=0;e{var e=i;Object.defineProperty(e,"__esModule",{value:!0}),e.ImageAddon=void 0;const t=A(414),s=A(795),r=A(463),o=A(699),a=A(23),n=A(235),h=A(566),g=A(994),d=A(649),l={enableSizeReports:!0,pixelLimit:16777216,sixelSupport:!0,sixelScrolling:!0,sixelPaletteLimit:4096,sixelSizeLimit:33554432,storageLimit:128,showPlaceholder:!0,iipSupport:!0,iipSizeLimit:33554432,kittySupport:!0,kittySizeLimit:33554432};e.ImageAddon=class{constructor(e){this._disposables=[],this._handlers=new Map,this._onImageAdded=new t.Emitter,this.onImageAdded=this._onImageAdded.event,this._opts=Object.assign({},l,e),this._defaultOpts=Object.assign({},l,e)}dispose(){for(const e of this._disposables)e.dispose();this._disposables.length=0,this._handlers.clear(),this._onImageAdded.dispose()}_disposeLater(...e){for(const t of e)this._disposables.push(t)}activate(e){var t;if(this._terminal=e,this._renderer=new r.ImageRenderer(e),this._storage=new o.ImageStorage(e,this._renderer,this._opts),this._storage.onImageAdded=()=>this._onImageAdded.fire(),this._opts.enableSizeReports){const A=null!==(t=e.options.windowOptions)&&void 0!==t?t:{};A.getWinSizePixels=!0,A.getCellSizePixels=!0,A.getWinSizeChars=!0,e.options.windowOptions=A}if(this._disposeLater(this._renderer,this._storage,e.parser.registerCsiHandler({prefix:"?",final:"h"},e=>this._decset(e)),e.parser.registerCsiHandler({prefix:"?",final:"l"},e=>this._decrst(e)),e.parser.registerCsiHandler({final:"c"},e=>this._da1(e)),e.parser.registerCsiHandler({prefix:"?",final:"S"},e=>this._xtermGraphicsAttributes(e)),e.onRender(e=>{var t;return null===(t=this._storage)||void 0===t?void 0:t.render(e)}),e.parser.registerCsiHandler({intermediates:"!",final:"p"},()=>this.reset()),e.parser.registerEscHandler({final:"c"},()=>this.reset()),e._core._inputHandler.onRequestReset(()=>this.reset()),e.buffer.onBufferChange(()=>{var e;return null===(e=this._storage)||void 0===e?void 0:e.wipeAlternate()}),e.onResize(e=>{var t;return null===(t=this._storage)||void 0===t?void 0:t.viewportResize(e)})),this._opts.sixelSupport){const t=new g.SixelImageStorage(this._storage,this._opts,this._renderer,e),A=new h.SixelHandler(this._opts,t,e);this._handlers.set("sixel",A),this._disposeLater(e._core._inputHandler._parser.registerDcsHandler({final:"q"},A))}if(this._opts.iipSupport){const t=new d.IIPImageStorage(this._storage),A=new s.IIPHandler(this._opts,this._renderer,t,e);this._handlers.set("iip",A),this._disposeLater(e._core._inputHandler._parser.registerOscHandler(1337,A))}if(this._opts.kittySupport){const t=new n.KittyImageStorage(this._storage),A=new a.KittyGraphicsHandler(this._opts,this._renderer,t,e);this._handlers.set("kitty",A),this._disposeLater(t,A,e._core._inputHandler._parser.registerApcHandler({final:"G"},A))}}reset(){var e;this._opts.sixelScrolling=this._defaultOpts.sixelScrolling,this._opts.sixelPaletteLimit=this._defaultOpts.sixelPaletteLimit,null===(e=this._storage)||void 0===e||e.reset();for(const e of this._handlers.values())e.reset();return!1}get storageLimit(){var e;return(null===(e=this._storage)||void 0===e?void 0:e.getLimit())||-1}set storageLimit(e){var t;null===(t=this._storage)||void 0===t||t.setLimit(e),this._opts.storageLimit=e}get storageUsage(){return this._storage?this._storage.getUsage():-1}get showPlaceholder(){return this._opts.showPlaceholder}set showPlaceholder(e){var t;this._opts.showPlaceholder=e,null===(t=this._renderer)||void 0===t||t.showPlaceholder(e)}getImageAtBufferCell(e,t){var A;return null===(A=this._storage)||void 0===A?void 0:A.getImageAtBufferCell(e,t)}extractTileAtBufferCell(e,t){var A;return null===(A=this._storage)||void 0===A?void 0:A.extractTileAtBufferCell(e,t)}_report(e){var t;null===(t=this._terminal)||void 0===t||t._core.input(e,!1)}_decset(e){for(let t=0;t2&&!(e[2]instanceof Array)&&e[2]<=4096?(this._opts.sixelPaletteLimit=e[2],this._report(`[?${e[0]};0;${this._opts.sixelPaletteLimit}S`)):this._report(`[?${e[0]};2S`),!0;case 4:return this._report(`[?${e[0]};0;4096S`),!0;default:return this._report(`[?${e[0]};2S`),!0}if(2===e[0])switch(e[1]){case 1:let n=null===(A=null===(t=this._renderer)||void 0===t?void 0:t.dimensions)||void 0===A?void 0:A.css.canvas.width,h=null===(s=null===(i=this._renderer)||void 0===i?void 0:i.dimensions)||void 0===s?void 0:s.css.canvas.height;if(!n||!h){const e=o.CELL_SIZE_DEFAULT;n=((null===(r=this._terminal)||void 0===r?void 0:r.cols)||80)*e.width,h=((null===(a=this._terminal)||void 0===a?void 0:a.rows)||24)*e.height}if(n*h(()=>{"use strict";var e={939(e,t){function i(e){return 255&e}function A(e){return e>>>8&255}function s(e){return e>>>16&255}function r(e,t,i,A=255){return((255&A)<<24|(255&i)<<16|(255&t)<<8|255&e)>>>0}function o(e,t,i){return Math.max(e,Math.min(i,t))}function a(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),6*i<1?t+6*(e-t)*i:2*i<1?e:3*i<2?t+(e-t)*(4-6*i):t}function n(e,t,i){return(4278190080|Math.round(i/100*255)<<16|Math.round(t/100*255)<<8|Math.round(e/100*255))>>>0}Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_FOREGROUND=t.DEFAULT_BACKGROUND=t.PALETTE_ANSI_256=t.PALETTE_VT340_GREY=t.PALETTE_VT340_COLOR=t.normalizeHLS=t.normalizeRGB=t.nearestColorIndex=t.fromRGBA8888=t.toRGBA8888=t.alpha=t.blue=t.green=t.red=t.BIG_ENDIAN=void 0,t.BIG_ENDIAN=255===new Uint8Array(new Uint32Array([4278190080]).buffer)[0],t.BIG_ENDIAN&&console.warn("BE platform detected. This version of node-sixel works only on LE properly."),t.red=i,t.green=A,t.blue=s,t.alpha=function(e){return e>>>24&255},t.toRGBA8888=r,t.fromRGBA8888=function(e){return[255&e,e>>8&255,e>>16&255,e>>>24]},t.nearestColorIndex=function(e,t){const r=i(e),o=A(e),a=s(e);let n=Number.MAX_SAFE_INTEGER,h=-1;for(let e=0;e{const e=[r(0,0,0),r(205,0,0),r(0,205,0),r(205,205,0),r(0,0,238),r(205,0,205),r(0,250,205),r(229,229,229),r(127,127,127),r(255,0,0),r(0,255,0),r(255,255,0),r(92,92,255),r(255,0,255),r(0,255,255),r(255,255,255)],t=[0,95,135,175,215,255];for(let i=0;i<6;++i)for(let A=0;A<6;++A)for(let s=0;s<6;++s)e.push(r(t[i],t[A],t[s]));for(let t=8;t<=238;t+=10)e.push(r(t,t,t));return new Uint32Array(e)})(),t.DEFAULT_BACKGROUND=r(0,0,0,255),t.DEFAULT_FOREGROUND=r(255,255,255,255)},591(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.decodeAsync=t.decode=t.Decoder=t.DecoderAsync=void 0;const A=i(939),s=i(199),r=function(e){if("undefined"!=typeof Buffer)return Buffer.from(e,"base64");const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e1,this.modeHandler=e=>1}handle_band(e){return this.bandHandler(e)}mode_parsed(e){return this.modeHandler(e)}}const h={memoryLimit:134217728,sixelColor:A.DEFAULT_FOREGROUND,fillColor:A.DEFAULT_BACKGROUND,palette:A.PALETTE_VT340_COLOR,paletteLimit:s.LIMITS.PALETTE_SIZE,truncate:!0};function g(e){const t=new n,i={env:{handle_band:t.handle_band.bind(t),mode_parsed:t.mode_parsed.bind(t)}};return WebAssembly.instantiate(o||r,i).then(i=>(o=o||i.module,new d(e,i.instance||i,t)))}t.DecoderAsync=g;class d{constructor(e,t,i){if(this._PIXEL_OFFSET=s.LIMITS.MAX_WIDTH+4,this._canvas=a,this._bandWidths=[],this._maxWidth=0,this._minWidth=s.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0,this._opts=Object.assign({},h,e),this._opts.paletteLimit>s.LIMITS.PALETTE_SIZE)throw new Error(`DecoderOptions.paletteLimit must not exceed ${s.LIMITS.PALETTE_SIZE}`);if(t)i.bandHandler=this._handle_band.bind(this),i.modeHandler=this._initCanvas.bind(this);else{const e=o||(o=new WebAssembly.Module(r));t=new WebAssembly.Instance(e,{env:{handle_band:this._handle_band.bind(this),mode_parsed:this._initCanvas.bind(this)}})}this._instance=t,this._wasm=this._instance.exports,this._chunk=new Uint8Array(this._wasm.memory.buffer,this._wasm.get_chunk_address(),s.LIMITS.CHUNK_SIZE),this._states=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_state_address(),12),this._palette=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_palette_address(),s.LIMITS.PALETTE_SIZE),this._palette.set(this._opts.palette),this._pSrc=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_p0_address()),this._wasm.init(A.DEFAULT_FOREGROUND,0,this._opts.paletteLimit,0)}get _fillColor(){return this._states[0]}get _truncate(){return this._states[8]}get _rasterWidth(){return this._states[6]}get _rasterHeight(){return this._states[7]}get _width(){return this._states[2]?this._states[2]-4:0}get _height(){return this._states[3]}get _level(){return this._states[9]}get _mode(){return this._states[10]}get _paletteLimit(){return this._states[11]}_initCanvas(e){if(2===e){const e=this.width*this.height;if(e>this._canvas.length){if(this._opts.memoryLimit&&4*e>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(e)}this._maxWidth=this._width}else if(1===e)if(2===this._level){const e=Math.min(this._rasterWidth,s.LIMITS.MAX_WIDTH)*this._rasterHeight;if(e>this._canvas.length){if(this._opts.memoryLimit&&4*e>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(e)}}else this._canvas.length<65536&&(this._canvas=new Uint32Array(65536));return 0}_realloc(e,t){const i=e+t;if(i>this._canvas.length){if(this._opts.memoryLimit&&4*i>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");const e=new Uint32Array(65536*Math.ceil(i/65536));e.set(this._canvas),this._canvas=e}}_handle_band(e){const t=this._PIXEL_OFFSET;let i=this._lastOffset;if(2===this._mode){let A=this.height-this._currentHeight,s=0;for(;s<6&&A>0;)this._canvas.set(this._pSrc.subarray(t*s,t*s+e),i+e*s),s++,A--;this._lastOffset+=e*s,this._currentHeight+=s}else if(1===this._mode){this._realloc(i,6*e),this._maxWidth=Math.max(this._maxWidth,e),this._minWidth=Math.min(this._minWidth,e);for(let A=0;A<6;++A)this._canvas.set(this._pSrc.subarray(t*A,t*A+e),i+e*A);this._bandWidths.push(e),this._lastOffset+=6*e,this._currentHeight+=6}return 0}get width(){return 1!==this._mode?this._width:Math.max(this._maxWidth,this._wasm.current_width())}get height(){return 1!==this._mode?this._height:this._wasm.current_width()?6*this._bandWidths.length+this._wasm.current_height():6*this._bandWidths.length}get palette(){return this._palette.subarray(0,this._paletteLimit)}get memoryUsage(){return this._canvas.byteLength+this._wasm.memory.buffer.byteLength+8*this._bandWidths.length}get properties(){return{width:this.width,height:this.height,mode:this._mode,level:this._level,truncate:!!this._truncate,paletteLimit:this._paletteLimit,fillColor:this._fillColor,memUsage:this.memoryUsage,rasterAttributes:{numerator:this._states[4],denominator:this._states[5],width:this._rasterWidth,height:this._rasterHeight}}}init(e=this._opts.fillColor,t=this._opts.palette,i=this._opts.paletteLimit,A=this._opts.truncate){this._wasm.init(this._opts.sixelColor,e,i,A?1:0),t&&this._palette.set(t.subarray(0,s.LIMITS.PALETTE_SIZE)),this._bandWidths.length=0,this._maxWidth=0,this._minWidth=s.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0}decode(e,t=0,i=e.length){let A=t;for(;A0){const i=this._PIXEL_OFFSET;let A=this._lastOffset,s=0;for(;s<6&&t>0;)this._canvas.set(this._pSrc.subarray(i*s,i*s+e),A+e*s),s++,t--;t&&this._canvas.fill(this._fillColor,A+e*s)}return this._canvas.subarray(0,this.width*this.height)}if(1===this._mode){if(this._minWidth===this._maxWidth){let t=!1;if(e)if(e!==this._minWidth)t=!0;else{const t=this._PIXEL_OFFSET;let i=this._lastOffset;this._realloc(i,6*e);for(let A=0;A<6;++A)this._canvas.set(this._pSrc.subarray(t*A,t*A+e),i+e*A)}if(!t)return this._canvas.subarray(0,this.width*this.height)}const t=new Uint32Array(this.width*this.height);t.fill(this._fillColor);let i=0,A=0;for(let e=0;e{if(this._disposed)return(0,A.toDisposable)(()=>{});const s={fn:e,thisArgs:t};this._listeners=this._listeners.slice(),this._listeners.push(s);const r=(0,A.toDisposable)(()=>{const e=this._listeners.indexOf(s);-1!==e&&(this._listeners=this._listeners.slice(),this._listeners.splice(e,1))});return i&&(Array.isArray(i)?i.push(r):i.add(r)),r}),this._event}fire(e){if(this._disposed||!this._listeners.length)return;if(1===this._listeners.length)return void this._listeners[0].fn.call(this._listeners[0].thisArgs,e);const t=this._listeners;for(let i=0,A=t.length;it.fire(e))},e.map=function(e,t){return(i,A,s)=>e(e=>i.call(A,t(e)),void 0,s)},e.any=function(...e){return(t,i,s)=>{const r=new A.DisposableStore;for(const A of e)r.add(A(e=>t.call(i,e)));return s&&(Array.isArray(s)?s.push(r):s.add(r)),r}},e.runAndSubscribe=function(e,t,i){return t(i),e(e=>t(e))}}(s||(t.EventUtils=s={}))},426(e,t){function i(e){return{dispose:e}}function A(e){if(!e)return e;if(Array.isArray(e)){for(const t of e)t.dispose();return[]}return e.dispose(),e}Object.defineProperty(t,"__esModule",{value:!0}),t.MutableDisposable=t.Disposable=t.DisposableStore=void 0,t.toDisposable=i,t.dispose=A,t.combinedDisposable=function(...e){return i(()=>A(e))};class s{constructor(){this._disposables=new Set,this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(e){return this._isDisposed?e.dispose():this._disposables.add(e),e}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(const e of this._disposables)e.dispose();this._disposables.clear()}}clear(){for(const e of this._disposables)e.dispose();this._disposables.clear()}}t.DisposableStore=s;class r{constructor(){this._store=new s}dispose(){this._store.dispose()}_register(e){return this._store.add(e)}}t.Disposable=r,r.None=Object.freeze({dispose(){}}),t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}}},795(e,t,i){var A=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.IIPHandler=void 0;const s=i(463),r=i(699),o=A(i(669)),a=A(i(61)),n=i(389),h=i(462),g={type:0,name:"Unnamed file",size:0,width:"auto",height:"auto",preserveAspectRatio:1,inline:0};t.IIPHandler=class{constructor(e,t,i,A){this._opts=e,this._renderer=t,this._storage=i,this._coreTerminal=A,this._generation=0,this._aborted=!1,this._hp=new n.HeaderParser,this._header=g,this._isMultipart=!1,this._abortMulti=!1;const s=Math.ceil(4*this._opts.iipSizeLimit/3),r=Math.min(1048576,s);this._dec=new o.default(4194304,s,r),this._qoiDec=new a.default(4194304)}reset(){this._generation++,this._hp.reset(),this._dec.release(),this._qoiDec.release()}start(){this._aborted=!1,this._hp.reset()}put(e,t,i){if(!this._aborted)if(4===this._hp.state)0!==this._dec.put(e.subarray(t,i))&&(this._dec.release(),this._aborted=!0);else{const A=this._hp.parse(e,t,i);if(-1===A)return void(this._aborted=!0);if(A>0){if(1===this._hp.fields.type){if(this._isMultipart&&(this._isMultipart=!1,this._abortMulti=!1,this._dec.release()),this._header=Object.assign({},g,this._hp.fields),!this._header.inline)return void(this._aborted=!0);this._dec.init()}else if(this._abortMulti)return void(this._aborted=!0);0!==this._dec.put(e.subarray(A,i))&&(this._dec.release(),this._aborted=!0,this._isMultipart&&(this._abortMulti=!0))}}}end(e){var t,i,A;if(this._aborted)return!0;if(4!==this._hp.state&&this._hp.end())return!0;const o=this._hp.fields.type;if(3===o)return!0;if(5===o){let e=r.CELL_SIZE_DEFAULT.width,i=r.CELL_SIZE_DEFAULT.height;this._renderer.dimensions&&(e=this._renderer.dimensions.css.canvas.width/this._coreTerminal.cols,i=this._renderer.dimensions.css.canvas.height/this._coreTerminal.rows);const s=null!==(A=null===(t=this._coreTerminal._core._coreBrowserService)||void 0===t?void 0:t.dpr)&&void 0!==A?A:1,o=`]1337;ReportCellSize=${i.toFixed(3)};${e.toFixed(3)};${s.toFixed(3)}\\`;return this._coreTerminal.input(o,!1),!0}if(2===o)return this._header=Object.assign({},g,this._hp.fields),this._isMultipart=!0,this._abortMulti=!1,this._dec.release(),this._dec.init(),!0;if(4===o){if(!this._isMultipart)return!0;if(this._isMultipart=!1,this._abortMulti||2!==this._header.type)return!0}let a,n,d=0,l=0,I=h.UNSUPPORTED_TYPE;if((a=e)&&((a=!this._dec.end())?(I=(0,h.imageType)(this._dec.data8),(a="unsupported"!==I.mime)?(d=I.width,l=I.height,(a=d&&l&&d*lc!==this._generation?(e.close(),!0):(this._storage.addImage(e),!0)).catch(e=>(console.warn(`IIP: decoding error ${I.mime} ${I.width}x${I.height}`,e),!0))}_resize(e,t){var i,A,s,o;const a=(null===(i=this._renderer.dimensions)||void 0===i?void 0:i.css.cell.width)||r.CELL_SIZE_DEFAULT.width,n=(null===(A=this._renderer.dimensions)||void 0===A?void 0:A.css.cell.height)||r.CELL_SIZE_DEFAULT.height,h=(null===(s=this._renderer.dimensions)||void 0===s?void 0:s.css.canvas.width)||a*this._coreTerminal.cols,g=(null===(o=this._renderer.dimensions)||void 0===o?void 0:o.css.canvas.height)||n*this._coreTerminal.rows,d=this._dim(this._header.width,h,a),l=this._dim(this._header.height,g,n);if(!d&&!l){const i=h/e,A=(g-n)/t,s=Math.min(i,A);return s<1?[e*s,t*s]:[e,t]}return d?!this._header.preserveAspectRatio&&d&&l?[d,l]:[d,t*d/e]:[e*l/t,l]}_dim(e,t,i){return"auto"===e?0:e.endsWith("%")?parseInt(e.slice(0,-1),10)*t/100:e.endsWith("px")?parseInt(e.slice(0,-2),10):parseInt(e,10)*i}}},389(e,t){function i(e){let t="";for(let i=0;i57)throw new Error("illegal char");t=10*t+e[i]-48}return t}function s(e){const t=i(e);if(!t.match(/^((auto)|(\d+?((px)|(%)){0,1}))$/))throw new Error("illegal size");return t}Object.defineProperty(t,"__esModule",{value:!0}),t.HeaderParser=void 0;const r={inline:A,size:A,name:function(e){if("undefined"!=typeof Buffer)return Buffer.from(i(e),"base64").toString();const t=atob(i(e)),A=new Uint8Array(t.length);for(let e=0;e14)return-1;for(let h=t;h=d)return this._a();r[s++]=t}break;case 58:return 3!==A||this._storeValue(s)?(this.state=4,h+1):this._a();default:if(s>=d)return this._a();r[s++]=t}}return this.state=A,this._position=s,-2}_a(){return this.fields.type=0,this.state=1,-1}_storeKey(e){const t=i(this._buffer.subarray(0,e));return!!t&&(this._key=t,this.fields[t]=null,!0)}_storeValue(e){if(this._key){try{const t=this._buffer.slice(0,e);this.fields[this._key]=r[this._key]?r[this._key](t):t}catch(e){return!1}return!0}return!1}}},649(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.IIPImageStorage=void 0,t.IIPImageStorage=class{constructor(e){this._storage=e,this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"}}addImage(e){this._storage.addImage(e,this._addImageOpts)}}},462(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.UNSUPPORTED_TYPE=void 0,t.imageType=function(e){if(e.length<32)return t.UNSUPPORTED_TYPE;const i=new Uint32Array(e.buffer,e.byteOffset,8);if(1196314761===i[0]&&169478669===i[1]&&1380206665===i[3])return{mime:"image/png",width:e[16]<<24|e[17]<<16|e[18]<<8|e[19],height:e[20]<<24|e[21]<<16|e[22]<<8|e[23]};if(255===e[0]&&216===e[1]&&255===e[2]){const[t,i]=function(e){const t=e.length;let i=4,A=e[i]<<8|e[i+1];for(;;){if(i+=A,i>=t)return[0,0];if(255!==e[i])return[0,0];if(192===e[i+1]||194===e[i+1])return i+8>>14&16383)};case 32:return 157!==e[23]||1!==e[24]||42!==e[25]?t.UNSUPPORTED_TYPE:{mime:"image/webp",width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}return t.UNSUPPORTED_TYPE}if(1887007846===i[1]&&(1718187617===i[2]||1936291425===i[2])){let i=-1;const A=Math.min(e.length-16,1024);for(let t=8;t0&&A>0)return{mime:"image/avif",width:t,height:A}}return t.UNSUPPORTED_TYPE}return t.UNSUPPORTED_TYPE},t.UNSUPPORTED_TYPE={mime:"unsupported",width:0,height:0}},463(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.ImageRenderer=void 0;const A=i(939),s=i(426);class r extends s.Disposable{get canvas(){var e;return null===(e=this._layers.get("top"))||void 0===e?void 0:e.canvas}static createCanvas(e,t,i){const A=(null!=e?e:document).createElement("canvas");return A.width=0|t,A.height=0|i,A}static createImageData(e,t,i,A){if("function"!=typeof ImageData){const s=e.createImageData(t,i);return A&&s.data.set(new Uint8ClampedArray(A,0,t*i*4)),s}return A?new ImageData(new Uint8ClampedArray(A,0,t*i*4),t,i):new ImageData(t,i)}static createImageBitmap(e){return"function"!=typeof createImageBitmap?Promise.resolve(void 0):createImageBitmap(e)}constructor(e){super(),this._terminal=e,this._layers=new Map,this._optionsRefresh=this._register(new s.MutableDisposable),this._oldOpen=this._terminal._core.open,this._terminal._core.open=e=>{var t;null===(t=this._oldOpen)||void 0===t||t.call(this._terminal._core,e),this._open()},this._terminal._core.screenElement&&this._open(),this._optionsRefresh.value=this._terminal._core.optionsService.onOptionChange(e=>{var t;"fontSize"===e&&(this.rescaleCanvas(),null===(t=this._renderService)||void 0===t||t.refreshRows(0,this._terminal.rows))}),this._register((0,s.toDisposable)(()=>{var e;this.removeLayerFromDom(),this.removeLayerFromDom("bottom"),this._terminal._core&&this._oldOpen&&(this._terminal._core.open=this._oldOpen,this._oldOpen=void 0),this._renderService&&this._oldSetRenderer&&(this._renderService.setRenderer=this._oldSetRenderer,this._oldSetRenderer=void 0),this._renderService=void 0,this._layers.clear(),null===(e=this._placeholderBitmap)||void 0===e||e.close(),this._placeholderBitmap=void 0,this._placeholder=void 0}))}showPlaceholder(e){var t,i;e?this._placeholder||-1===this.cellSize.height||this._createPlaceHolder(Math.max(this.cellSize.height+1,24)):(null===(t=this._placeholderBitmap)||void 0===t||t.close(),this._placeholderBitmap=void 0,this._placeholder=void 0),null===(i=this._renderService)||void 0===i||i.refreshRows(0,this._terminal.rows)}get dimensions(){return this._terminal.dimensions}get cellSize(){var e,t;return{width:(null===(e=this.dimensions)||void 0===e?void 0:e.css.cell.width)||-1,height:(null===(t=this.dimensions)||void 0===t?void 0:t.css.cell.height)||-1}}clearLines(e,t,i){var A,s,r,o,a;const n=e*((null===(A=this.dimensions)||void 0===A?void 0:A.css.cell.height)||0),h=(null===(s=this.dimensions)||void 0===s?void 0:s.css.canvas.width)||0,g=(t+1-e)*((null===(r=this.dimensions)||void 0===r?void 0:r.css.cell.height)||0);i&&"top"!==i||null===(o=this._layers.get("top"))||void 0===o||o.clearRect(0,n,h,g),i&&"bottom"!==i||null===(a=this._layers.get("bottom"))||void 0===a||a.clearRect(0,n,h,g)}clearAll(e){if(!e||"top"===e){const e=this._layers.get("top");null==e||e.clearRect(0,0,e.canvas.width,e.canvas.height)}if(!e||"bottom"===e){const e=this._layers.get("bottom");null==e||e.clearRect(0,0,e.canvas.width,e.canvas.height)}}draw(e,t,i,A,s=1){const r=this._layers.get(e.layer);if(!r)return;const{width:o,height:a}=this.cellSize;if(-1===o||-1===a)return;this._rescaleImage(e,o,a);const n=e.actual,{width:h,height:g}=e.actualCellSize,d=Math.ceil(n.width/h),l=t%d*h,I=Math.floor(t/d)*g,c=i*o,_=A*a,C=s*h+l>n.width?n.width-l:s*h,B=I+g>n.height?n.height-I:g;r.drawImage(n,Math.floor(l),Math.floor(I),Math.ceil(C),Math.ceil(B),Math.floor(c),Math.floor(_),Math.ceil(C*o/h),Math.ceil(B*a/g))}extractTile(e,t){const{width:i,height:A}=this.cellSize;if(-1===i||-1===A)return;this._rescaleImage(e,i,A);const s=e.actual,{width:o,height:a}=e.actualCellSize,n=Math.ceil(s.width/o),h=t%n*o,g=Math.floor(t/n)*a,d=o+h>s.width?s.width-h:o,l=g+a>s.height?s.height-g:a,I=r.createCanvas(this.document,Math.ceil(d*i/o),Math.ceil(l*A/a)),c=I.getContext("2d");return c?(c.drawImage(s,Math.floor(h),Math.floor(g),Math.floor(d),Math.floor(l),0,0,I.width,I.height),I):void 0}drawPlaceholder(e,t,i=1){var A;const s=this._layers.get("top");if(s){const{width:r,height:o}=this.cellSize;if(-1===r||-1===o)return;if(this._placeholder?o>=this._placeholder.height&&this._createPlaceHolder(o+1):this._createPlaceHolder(Math.max(o+1,24)),!this._placeholder)return;s.drawImage(null!==(A=this._placeholderBitmap)&&void 0!==A?A:this._placeholder,e*r,t*o%2?0:1,r*i,o,e*r,t*o,r*i,o)}}rescaleCanvas(){var e,t;const i=(null===(e=this.dimensions)||void 0===e?void 0:e.css.canvas.width)||0,A=(null===(t=this.dimensions)||void 0===t?void 0:t.css.canvas.height)||0;for(const e of this._layers.values())e.canvas.width===i&&e.canvas.height===A||(e.canvas.width=i,e.canvas.height=A)}_rescaleImage(e,t,i){if(t===e.actualCellSize.width&&i===e.actualCellSize.height)return;const{width:A,height:s}=e.origCellSize;if(t===A&&i===s)return e.actual=e.orig,e.actualCellSize.width=A,void(e.actualCellSize.height=s);const o=Math.ceil(e.orig.width*t/A),a=Math.ceil(e.orig.height*i/s);if(o*a>e.orig.width*e.orig.height)return e.actual=e.orig,e.actualCellSize.width=A,void(e.actualCellSize.height=s);const n=r.createCanvas(this.document,o,a),h=n.getContext("2d");h&&(h.drawImage(e.orig,0,0,n.width,n.height),e.actual=n,e.actualCellSize.width=t,e.actualCellSize.height=i)}_open(){this._renderService=this._terminal._core._renderService,this._oldSetRenderer=this._renderService.setRenderer.bind(this._renderService),this._renderService.setRenderer=e=>{var t;for(const e of[...this._layers.keys()])this.removeLayerFromDom(e);null===(t=this._oldSetRenderer)||void 0===t||t.call(this._renderService,e)}}insertLayerToDom(e="top"){var t,i;if(!this.document||!this._terminal._core.screenElement)return void console.warn("image addon: cannot insert output canvas to DOM, missing document or screenElement");if(this._layers.has(e))return;const A=r.createCanvas(this.document,(null===(t=this.dimensions)||void 0===t?void 0:t.css.canvas.width)||0,(null===(i=this.dimensions)||void 0===i?void 0:i.css.canvas.height)||0);A.classList.add(`xterm-image-layer-${e}`);const s=this._terminal._core.screenElement;s.style.isolation="isolate","bottom"===e?(A.style.zIndex="-1",s.insertBefore(A,s.firstChild)):(A.style.zIndex="0",s.appendChild(A));const o=A.getContext("2d",{alpha:!0});o?(this._layers.set(e,o),this.clearAll(e)):A.remove()}removeLayerFromDom(e="top"){const t=this._layers.get(e);t&&(t.canvas.remove(),this._layers.delete(e))}hasLayer(e){return this._layers.has(e)}_createPlaceHolder(e=24){var t;null===(t=this._placeholderBitmap)||void 0===t||t.close(),this._placeholderBitmap=void 0;const i=32,s=r.createCanvas(this.document,i,e),o=s.getContext("2d",{alpha:!1});if(!o)return;const a=r.createImageData(o,i,e),n=new Uint32Array(a.data.buffer),h=(0,A.toRGBA8888)(0,0,0),g=(0,A.toRGBA8888)(255,255,255);n.fill(h);for(let t=0;t{this._placeholder!==I?null==e||e.close():this._placeholderBitmap=e}).catch(()=>{})}get document(){var e;return null===(e=this._terminal._core._coreBrowserService)||void 0===e?void 0:e.window.document}}t.ImageRenderer=r},699(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.ImageStorage=t.CELL_SIZE_DEFAULT=void 0;const A=i(463);t.CELL_SIZE_DEFAULT={width:7,height:14};class s{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get underlineVariantOffset(){const e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}get urlId(){return this._urlId}set urlId(e){this._urlId=e}constructor(e=0,t=0,i=-1,A=-1){this.imageId=i,this.tileId=A,this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new s(this._ext,this._urlId,this.imageId,this.tileId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId&&-1===this.imageId}}const r=new s;t.ImageStorage=class{constructor(e,t,i){this._terminal=e,this._renderer=t,this._opts=i,this._images=new Map,this._lastId=0,this._lowestId=0,this._fullyCleared=!1,this._needsFullClear=!1,this._pixelLimit=25e5;try{this.setLimit(this._opts.storageLimit)}catch(e){e instanceof Error&&console.error(e.message),console.warn(`storageLimit is set to ${this.getLimit()} MB`)}this._viewportMetrics={cols:this._terminal.cols,rows:this._terminal.rows}}dispose(){this.reset()}reset(){var e;for(const t of this._images.values())null===(e=t.marker)||void 0===e||e.dispose();this._images.clear(),this._renderer.clearAll()}getLimit(){return 4*this._pixelLimit/1e6}setLimit(e){if(e<.5||e>1e3)throw RangeError("invalid storageLimit, should be at least 0.5 MB and not exceed 1G");this._pixelLimit=e/4*1e6>>>0,this._evictOldest(0)}getUsage(){return 4*this._getStoredPixels()/1e6}_getStoredPixels(){let e=0;for(const t of this._images.values())t.orig&&(e+=t.orig.width*t.orig.height,t.actual&&t.actual!==t.orig&&(e+=t.actual.width*t.actual.height));return e}_delImg(e){var t;const i=this._images.get(e);i&&(this._images.delete(e),window.ImageBitmap&&i.orig instanceof ImageBitmap&&i.orig.close(),null===(t=this.onImageDeleted)||void 0===t||t.call(this,e))}wipeAlternate(){var e;const t=[];for(const[i,A]of this._images.entries())"alternate"===A.bufferType&&(null===(e=A.marker)||void 0===e||e.dispose(),t.push(i));for(const e of t)this._delImg(e);this._needsFullClear=!0,this._fullyCleared=!1}deleteImage(e){var t;const i=this._images.get(e);i&&(null===(t=i.marker)||void 0===t||t.dispose(),this._delImg(e))}addImage(e,i){var A,s;this._evictOldest(e.width*e.height);let r=this._renderer.cellSize;-1!==r.width&&-1!==r.height||(r=t.CELL_SIZE_DEFAULT);const o=Math.ceil(e.width/r.width),a=Math.ceil(e.height/r.height),n=++this._lastId,h=this._terminal._core.buffer,g=this._terminal.cols,d=this._terminal.rows,l=h.x,I=h.y;let c=l,_=0;i.scrolling||(h.x=0,h.y=0,c=0),this._terminal._core._inputHandler._dirtyRowTracker.markDirty(h.y);for(let e=0;e=g);++i)this._writeToCell(t,c+i,n,e*o+i),_++;if(i.scrolling)e=d)break;h.x=c}this._terminal._core._inputHandler._dirtyRowTracker.markDirty(h.y),i.scrolling?"iip"===i.cursorPos?h.x=Math.min(c+o,g):h.x=c:(h.x=l,h.y=I);const C=[];for(const[e,t]of this._images.entries())t.tileCount<1&&(null===(A=t.marker)||void 0===A||A.dispose(),C.push(e));for(const e of C)this._delImg(e);const B=this._terminal.registerMarker(0);null==B||B.onDispose(()=>{this._images.get(n)&&this._delImg(n)}),"alternate"===this._terminal.buffer.active.type&&this._evictOnAlternate();const Q={orig:e,origCellSize:r,actual:e,actualCellSize:Object.assign({},r),marker:B||void 0,tileCount:_,bufferType:this._terminal.buffer.active.type,layer:i.layer,zIndex:i.zIndex};return this._images.set(n,Q),null===(s=this.onImageAdded)||void 0===s||s.call(this),n}render(e){var t,i;let A=!1,s=!1;for(const e of this._images.values())if("bottom"===e.layer?s=!0:A=!0,A&&s)break;if(A&&!this._renderer.hasLayer("top")&&(this._renderer.insertLayerToDom("top"),!this._renderer.hasLayer("top")))return;if(s&&!this._renderer.hasLayer("bottom")&&this._renderer.insertLayerToDom("bottom"),this._renderer.rescaleCanvas(),!this._images.size)return this._fullyCleared||(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1),this._renderer.hasLayer("top")&&this._renderer.removeLayerFromDom("top"),void(this._renderer.hasLayer("bottom")&&this._renderer.removeLayerFromDom("bottom"));!A&&this._renderer.hasLayer("top")&&(this._renderer.clearAll("top"),this._renderer.removeLayerFromDom("top")),!s&&this._renderer.hasLayer("bottom")&&(this._renderer.clearAll("bottom"),this._renderer.removeLayerFromDom("bottom")),this._needsFullClear&&(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1);const{start:o,end:a}=e,n=this._terminal._core.buffer,h=this._terminal._core.cols;this._renderer.clearLines(o,a);const g=[],d=[];for(let e=o;e<=a;++e){const A=n.lines.get(e+n.ydisp);if(!A)return;for(let s=0;se.imgSpec.zIndex-t.imgSpec.zIndex);for(const e of d)this._renderer.drawPlaceholder(e.col,e.row,e.count);for(const e of g)this._renderer.draw(e.imgSpec,e.tileId,e.col,e.row,e.count)}viewportResize(e){var t,i;if(!this._images.size)return void(this._viewportMetrics=e);if(this._viewportMetrics.cols>=e.cols)return void(this._viewportMetrics=e);const A=this._terminal._core.buffer,s=A.lines.length,o=this._viewportMetrics.cols-1;for(let a=0;a=h)continue;let g=!1;for(let t=o+1;t>e.cols;++t)if(4194303&s._data[3*t+0]){g=!0;break}if(g)continue;const d=Math.min(e.cols,h-A.tileId%h+o);let l=A.tileId;for(let e=o+1;e>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255}o.set(A.PALETTE_VT340_COLOR),t.SixelHandler=class{constructor(e,t,i){this._opts=e,this._storage=t,this._coreTerminal=i,this._size=0,this._aborted=!1,(0,r.DecoderAsync)({memoryLimit:4*this._opts.pixelLimit,palette:o,paletteLimit:this._opts.sixelPaletteLimit}).then(e=>this._dec=e)}reset(){this._dec&&(this._dec.release(),this._dec._palette.fill(0),this._dec.init(0,o,this._opts.sixelPaletteLimit))}hook(e){var t;if(this._size=0,this._aborted=!1,this._dec){const i=1===e.params[1]?0:function(e,t){let i=0;if(!t)return i;if(e.isInverse())if(e.isFgDefault())i=a(t.foreground.rgba);else if(e.isFgRGB()){const t=e.constructor.toColorRGB(e.getFgColor());i=(0,A.toRGBA8888)(...t)}else i=a(t.ansi[e.getFgColor()].rgba);else if(e.isBgDefault())i=a(t.background.rgba);else if(e.isBgRGB()){const t=e.constructor.toColorRGB(e.getBgColor());i=(0,A.toRGBA8888)(...t)}else i=a(t.ansi[e.getBgColor()].rgba);return i}(this._coreTerminal._core._inputHandler._curAttrData,null===(t=this._coreTerminal._core._themeService)||void 0===t?void 0:t.colors);this._dec.init(i,null,this._opts.sixelPaletteLimit)}}put(e,t,i){if(!this._aborted&&this._dec){if(this._size+=i-t,this._size>this._opts.sixelSizeLimit)return console.warn("SIXEL: too much data, aborting"),this._aborted=!0,void this._dec.release();try{this._dec.decode(e,t,i)}catch(e){console.warn(`SIXEL: error while decoding image - ${e}`),this._aborted=!0,this._dec.release()}}}unhook(e){var t;if(this._aborted||!e||!this._dec)return!0;const i=this._dec.width,A=this._dec.height;if(!i||!A)return A&&this._storage.advanceCursor(A),!0;const r=s.ImageRenderer.createCanvas(void 0,i,A);return null===(t=r.getContext("2d"))||void 0===t||t.putImageData(new ImageData(this._dec.data8,i,A),0,0),this._dec.memoryUsage>4194304&&this._dec.release(),this._storage.addImage(r),!0}}},994(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.SixelImageStorage=void 0;const A=i(699);t.SixelImageStorage=class{constructor(e,t,i,A){this._storage=e,this._opts=t,this._renderer=i,this._terminal=A,this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"vt340"}}addImage(e){this._addImageOpts.scrolling=this._opts.sixelScrolling,this._storage.addImage(e,this._addImageOpts)}advanceCursor(e){if(this._opts.sixelScrolling){let t=this._renderer.cellSize;-1!==t.width&&-1!==t.height||(t=A.CELL_SIZE_DEFAULT);const i=Math.ceil(e/t.height);for(let e=1;e512)return void(this._aborted=!0);if(this._controlData.set(e.subarray(t,s),this._controlLength),this._controlLength+=r,!this._inControlData){if(this._parsedCommand=(0,n.parseKittyCommand)(this._parseControlDataString()),void 0!==this._parsedCommand.id&&void 0!==this._parsedCommand.imageNumber)return this._sendResponse(this._parsedCommand.id,"EINVAL:cannot specify both i and I keys",null!==(A=this._parsedCommand.quiet)&&void 0!==A?A:0),void(this._aborted=!0);if("d"===this._parsedCommand.action)return;const t=s+1;tthis._encodedSizeLimit){const e=null!==(h=this._activeDecoder)&&void 0!==h?h:null==I?void 0:I.decoder;return e&&e.release(),this._activeDecoder=null,I&&this._removePendingEntry(l),void(this._aborted=!0)}if(!this._decodeError){if((null==I?void 0:I.decoder)&&!this._activeDecoder&&(this._activeDecoder=I.decoder),!this._activeDecoder){const e=this._maxEncodedBytes+131072;if(e>1e6*this._opts.storageLimit)return this._aborted=!0,void(void 0!==(null===(s=this._parsedCommand)||void 0===s?void 0:s.id)&&this._sendResponse(this._parsedCommand.id,"ENOMEM:pending image budget exceeded",null!==(g=this._parsedCommand.quiet)&&void 0!==g?g:0));const t=Math.max(1,Math.floor(1e6*this._opts.storageLimit/e));for(;this._pendingTransmissions.size>=t;){const e=this._pendingTransmissions.entries().next().value;if(!e)break;e[1].decoder.release(),this._removePendingEntry(e[0]),void 0!==e[1].cmd.id&&this._sendResponse(e[1].cmd.id,"ENOMEM:pending image budget exceeded",null!==(d=e[1].cmd.quiet)&&void 0!==d?d:0)}this._activeDecoder=new a.default(4194304,this._maxEncodedBytes,this._initialEncodedBytes),this._activeDecoder.init()}0!==this._activeDecoder.put(e.subarray(t,i))&&(this._activeDecoder.release(),this._activeDecoder=null,this._decodeError=!0,I&&this._removePendingEntry(l))}}end(e){var t,i;if(this._aborted||!e)return this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),!0;if(this._inControlData)return this._handleNoPayloadCommand();const A=this._parsedCommand;if("d"===A.action)return this._handleDelete(A);const s=null!==(i=null!==(t=A.id)&&void 0!==t?t:this._lastPendingKey)&&void 0!==i?i:0,r=1===A.more,o=this._pendingTransmissions.get(s);if(r)return this._activeDecoder&&(o?(o.totalEncodedSize+=this._totalEncodedSize,o.decodeError=o.decodeError||this._decodeError):this._pendingTransmissions.set(s,{cmd:Object.assign({},A),decoder:this._activeDecoder,totalEncodedSize:this._totalEncodedSize,decodeError:this._decodeError}),this._lastPendingKey=s,this._activeDecoder=null),!0;o&&(this._lastPendingKey=void 0);let a=this._decodeError,n=A,h=this._activeDecoder;o&&(n=o.cmd,h=o.decoder,a=a||o.decodeError,this._pendingTransmissions.delete(s));let g=new Uint8Array(0);h&&(0!==h.end()&&(a=!0),g=h.data8),this._activeDecoder=null;const d=this._handleCommandWithBytesAndCmd(n,g,a);return h&&h.release(),d}_parseControlDataString(){let e="";for(let t=0;t0&&this._sendResponse(e.id,"OK",null!==(o=e.quiet)&&void 0!==o?o:0)),A}case"T":return this._handleTransmitDisplay(e,t,i);case"q":return this._handleQuery(e,t,i);case"p":return this._handlePlacement(e);default:return void 0!==e.id&&this._sendResponse(e.id,"EINVAL:unsupported action",null!==(a=e.quiet)&&void 0!==a?a:0),!0}}_handlePlacement(e){var t;if(void 0===e.id)return!0;const i=e.id,A=this._kittyStorage.getImage(i);return A?this._displayImage(A,e).then(t=>{var A;return this._sendResponse(i,t?"OK":"EINVAL:image rendering failed",null!==(A=e.quiet)&&void 0!==A?A:0,e.placementId),!0}):(this._sendResponse(i,"ENOENT:image not found",null!==(t=e.quiet)&&void 0!==t?t:0,e.placementId),!0)}_handleTransmit(e,t,i){var A,s,r,o,a,n;return"d"!==(null!==(A=e.transmission)&&void 0!==A?A:"d")?(void 0!==e.id&&this._sendResponse(e.id,"EINVAL:unsupported transmission medium",null!==(s=e.quiet)&&void 0!==s?s:0),!0):(i||0===t.length||this._kittyStorage.storeImage(e.id,{data:new Blob([t]),width:null!==(r=e.width)&&void 0!==r?r:0,height:null!==(o=e.height)&&void 0!==o?o:0,format:null!==(a=e.format)&&void 0!==a?a:32,compression:null!==(n=e.compression)&&void 0!==n?n:""}),!0)}_handleTransmitDisplay(e,t,i){var A,s;if(i)return void 0!==e.id&&this._sendResponse(e.id,"EINVAL:invalid base64 data",null!==(A=e.quiet)&&void 0!==A?A:0),!0;this._handleTransmit(e,t,i);const r=null!==(s=e.id)&&void 0!==s?s:this._kittyStorage.lastImageId,o=this._kittyStorage.getImage(r);if(o){const t=this._displayImage(o,e);return void 0!==e.id?t.then(t=>{var i;return this._sendResponse(r,t?"OK":"EINVAL:image rendering failed",null!==(i=e.quiet)&&void 0!==i?i:0),!0}):t.then(()=>!0)}return!0}_handleQuery(e,t,i){var A,s,r,o,a,n;const h=null!==(A=e.id)&&void 0!==A?A:0,g=null!==(s=e.quiet)&&void 0!==s?s:0;if("d"!==(null!==(r=e.transmission)&&void 0!==r?r:"d"))return this._sendResponse(h,"EINVAL:unsupported transmission medium",g),!0;if(i)return this._sendResponse(h,"EINVAL:invalid base64 data",g),!0;if(0===t.length)return this._sendResponse(h,"OK",g),!0;const d=null!==(o=e.format)&&void 0!==o?o:32;if(100===d)this._sendResponse(h,"OK",g);else{const i=null!==(a=e.width)&&void 0!==a?a:0,A=null!==(n=e.height)&&void 0!==n?n:0;if(!i||!A)return this._sendResponse(h,"EINVAL:width and height required for raw pixel data",g),!0;const s=i*A*(32===d?4:3);if(t.length=1)return;if(!s&&i>=2)return;const r=`_Gi=${e}${A?`,p=${A}`:""};${t}\\`;this._coreTerminal._core.coreService.triggerDataEvent(r)}_displayImage(e,t){return this._decodeAndDisplay(e,t).then(()=>!0).catch(()=>!1)}async _decodeAndDisplay(e,t){var i,A,o,a,n,h,g;const d=this._generation;let l=await this._createBitmap(e);try{if(d!==this._generation)throw new Error("image decode canceled");const I=Math.max(0,null!==(o=t.x)&&void 0!==o?o:0),c=Math.max(0,null!==(a=t.y)&&void 0!==a?a:0),_=t.sourceWidth||l.width-I,C=t.sourceHeight||l.height-c,B=Math.max(0,l.width-I),Q=Math.max(0,l.height-c),m=Math.max(0,Math.min(_,B)),E=Math.max(0,Math.min(C,Q));if(0===m||0===E)throw new Error("invalid source rectangle");if(0!==I||0!==c||m!==l.width||E!==l.height){const e=await createImageBitmap(l,I,c,m,E);l.close(),l=e}const u=(null===(i=this._renderer.dimensions)||void 0===i?void 0:i.css.cell.width)||r.CELL_SIZE_DEFAULT.width,p=(null===(A=this._renderer.dimensions)||void 0===A?void 0:A.css.cell.height)||r.CELL_SIZE_DEFAULT.height;let w,f;void 0!==t.columns&&void 0!==t.rows?(w=t.columns,f=t.rows):void 0!==t.columns?(w=t.columns,f=Math.max(1,Math.ceil(l.height/l.width*(w*u)/p))):void 0!==t.rows?(f=t.rows,w=Math.max(1,Math.ceil(l.width/l.height*(f*p)/u))):(w=Math.ceil(l.width/u),f=Math.ceil(l.height/p));let D=l.width,y=l.height;if(void 0===t.columns&&void 0===t.rows||(D=Math.round(w*u),y=Math.round(f*p)),D*y>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");const v=this._coreTerminal._core.buffer,k=v.x,M=v.y,b=v.ybase,S=void 0!==t.zIndex&&t.zIndex<0?"bottom":"top";if(D!==l.width||y!==l.height){const e=await createImageBitmap(l,{resizeWidth:D,resizeHeight:y});l.close(),l=e}const L=Math.min(Math.max(0,null!==(n=t.xOffset)&&void 0!==n?n:0),u-1),N=Math.min(Math.max(0,null!==(h=t.yOffset)&&void 0!==h?h:0),p-1);if(0!==L||0!==N){const e=void 0!==t.columns?Math.round(w*u):l.width+L,i=void 0!==t.rows?Math.round(f*p):l.height+N,A=s.ImageRenderer.createCanvas(window.document,e,i),r=A.getContext("2d");if(!r)throw new Error("Failed to create offset canvas context");r.drawImage(l,L,N);const o=await createImageBitmap(A);if(A.width=A.height=0,l.close(),l=o,D=l.width,y=l.height,D*y>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");void 0===t.columns&&(w=Math.ceil(l.width/u)),void 0===t.rows&&(f=Math.ceil(l.height/p))}if(d!==this._generation)throw new Error("image decode canceled");const G=null!==(g=t.zIndex)&&void 0!==g?g:0;if(this._kittyStorage.addImage(e.id,l,!0,S,G),l=void 0,1===t.cursorMovement){const e=v.ybase-b;v.x=k,v.y=Math.max(M-e,0)}else v.x=Math.min(k+w,this._coreTerminal.cols)}catch(e){throw null==l||l.close(),e}}async _createBitmap(e){let t=new Uint8Array(await e.data.arrayBuffer());if("z"===e.compression&&(t=await this._decompressZlib(t)),100===e.format){const e=(0,o.imageType)(t);if("image/png"!==e.mime||!(e.width>0)||!(e.height>0)||e.width*e.height>this._opts.pixelLimit)throw new RangeError("PNG exceeds pixel limit or has invalid dimensions");const i=new Blob([t],{type:"image/png"});if(!window.createImageBitmap){const e=URL.createObjectURL(i),t=new Image;return new Promise((i,A)=>{t.addEventListener("load",()=>{var r;URL.revokeObjectURL(e);const o=s.ImageRenderer.createCanvas(window.document,t.width,t.height);null===(r=o.getContext("2d"))||void 0===r||r.drawImage(t,0,0),createImageBitmap(o).then(i).catch(A)}),t.addEventListener("error",()=>{URL.revokeObjectURL(e),A(new Error("Failed to load image"))}),t.src=e})}return createImageBitmap(i)}const i=e.width,A=e.height;if(!i||!A)throw new Error("Width and height required for raw pixel data");const r=i*A*(32===e.format?4:3);if(t.length>>24|t<<8,g[I++]=4278190080|t>>>16|i<<16,g[I++]=4278190080|i>>>8}let c=3*d,_=4*d;for(let e=d;e=e.length)return void t.close();const i=Math.min(A+4096,e.length);t.enqueue(new Uint8Array(e.subarray(A,i))),A=i}}).pipeThrough(new DecompressionStream(t)).getReader(),r=[];let o=0;try{for(;;){const{done:e,value:t}=await s.read();if(e)break;if(o+=t.byteLength,o>i)throw await s.cancel().catch(()=>{}),new RangeError("decompressed image exceeds byte limit");r.push(t)}}finally{s.releaseLock()}const a=new Uint8Array(o);let n=0;for(const e of r)a.set(e,n),n+=e.length;return a}get images(){return this._kittyStorage.images}get _kittyIdToStorageId(){return this._kittyStorage.kittyIdToStorageId}get pendingTransmissions(){return this._pendingTransmissions}}},470(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.parseKittyCommand=function(e){const t={},i=e.split(",");for(const e of i){const i=e.indexOf("=");if(-1===i)continue;const A=e.substring(0,i),s=e.substring(i+1);if("a"===A){t.action=s;continue}if("o"===A){t.compression=s;continue}if("t"===A){t.transmission=s;continue}if("d"===A){t.deleteSelector=s;continue}const r=parseInt(s,10);switch(A){case"f":t.format=r;break;case"i":t.id=r;break;case"I":t.imageNumber=r;break;case"s":t.width=r;break;case"v":t.height=r;break;case"x":t.x=r;break;case"y":t.y=r;break;case"w":t.sourceWidth=r;break;case"h":t.sourceHeight=r;break;case"X":t.xOffset=r;break;case"Y":t.yOffset=r;break;case"c":t.columns=r;break;case"r":t.rows=r;break;case"m":t.more=r;break;case"q":t.quiet=r;break;case"C":t.cursorMovement=r;break;case"z":t.zIndex=r;break;case"p":t.placementId=r}}return t}},235(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.KittyImageStorage=void 0;class i{constructor(e){this._storage=e,this._nextImageId=1,this._images=new Map,this._kittyIdToStorageId=new Map,this._storageIdToKittyId=new Map,this._handleStorageImageDeleted=e=>{const t=this._storageIdToKittyId.get(e);void 0!==t&&(this._kittyIdToStorageId.delete(t),this._storageIdToKittyId.delete(e),this._images.delete(t))},this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"},this._previousOnImageDeleted=this._storage.onImageDeleted,this._wrappedOnImageDeleted=e=>{var t;null===(t=this._previousOnImageDeleted)||void 0===t||t.call(this,e),this._handleStorageImageDeleted(e)},this._storage.onImageDeleted=this._wrappedOnImageDeleted}reset(){this._nextImageId=1,this._images.clear(),this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}dispose(){this.reset(),this._storage.onImageDeleted===this._wrappedOnImageDeleted&&(this._storage.onImageDeleted=this._previousOnImageDeleted)}storeImage(e,t){const A=null!=e?e:this._nextImageId++,s=this._kittyIdToStorageId.get(A);void 0!==s&&(this._storage.deleteImage(s),this._kittyIdToStorageId.delete(A),this._storageIdToKittyId.delete(s)),!this._images.has(A)&&this._images.size>=i._maxStoredImages&&this._evictUndisplayedImages();const r=1e6*this._storage.getLimit();this._images.delete(A);let o=0;for(const e of this._images.values())o+=e.data.size;for(const e of[!1,!0])for(const[i,A]of this._images){if(o+t.data.size<=r)break;this._kittyIdToStorageId.has(i)===e&&(o-=A.data.size,this.deleteById(i))}return this._images.set(A,Object.assign(Object.assign({},t),{id:A})),A}addImage(e,t,i,A,s){const r=this._kittyIdToStorageId.get(e);void 0!==r&&this._storageIdToKittyId.delete(r),this._addImageOpts.scrolling=i,this._addImageOpts.layer=A,this._addImageOpts.zIndex=s;const o=this._storage.addImage(t,this._addImageOpts);this._kittyIdToStorageId.set(e,o),this._storageIdToKittyId.set(o,e)}getImage(e){return this._images.get(e)}deleteById(e){this._images.delete(e);const t=this._kittyIdToStorageId.get(e);void 0!==t&&(this._storage.deleteImage(t),this._kittyIdToStorageId.delete(e),this._storageIdToKittyId.delete(t))}deleteAll(){this._images.clear();for(const e of this._kittyIdToStorageId.values())this._storage.deleteImage(e);this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}get images(){return this._images}get kittyIdToStorageId(){return this._kittyIdToStorageId}get lastImageId(){return this._nextImageId-1}_evictUndisplayedImages(){for(const[e]of this._images){if(this._images.size<=i._maxStoredImages/2)break;this._kittyIdToStorageId.has(e)||this._images.delete(e)}}}t.KittyImageStorage=i,i._maxStoredImages=256},669(e,t,i){Object.defineProperty(t,"__esModule",{value:!0});const A=(0,i(552).InWasm)({s:1,t:0,d:"AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML"}),s=new Uint8Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map(e=>e.charCodeAt(0))),r=new Uint32Array(1024);r.fill(4278190080);for(let e=0;e>4|(e<<4&255)<<8;for(let e=0;e>2<<8|(e<<6&255)<<16;for(let e=0;ethis.maxBytes||this.maxBytes>4294901760)throw new Error("invalid byte settings")}get data8(){return this._inst?this._d.subarray(0,this._m32[1282]):o}release(){this._inst&&(this._bytes>this.keepSize?this._inst=this._m32=this._d=this._mem=null:(this._m32[1280]=0,this._m32[1281]=0,this._m32[1282]=0))}init(e,t){if(this.maxBytes=null!=e?e:this.maxBytes,this._bytes=null!=t?t:Math.min(this._bytes,this.maxBytes),this._bytes>this.maxBytes||this.maxBytes>4294901760)throw Error("invalid byte settings");let i=this._m32;const s=this._bytes+5152;this._inst?this._mem.buffer.byteLengththis.maxBytes)return-3;let e=this._bytes;for(;(e*=2)this._mem.buffer.byteLength){const t=Math.ceil((e+5152-this._mem.buffer.byteLength)/65536);this._mem.grow(t),this._m32=new Uint32Array(this._mem.buffer,0),this._d=new Uint8Array(this._mem.buffer,5152)}this._bytes=e}return 0}put(e){if(!this._inst||this._ended)return-2;if(this._realloc(e.length))return-3;const t=this._m32;return this._d.set(e,t[1280]),t[1280]+=e.length,t[1280]-t[1281]>=131072?this._inst.exports.dec():0}end(){return this._ended=!0,this._inst?this._inst.exports.end():-2}get loadedBytes(){return this._inst?this._m32[1280]:0}get freeBytes(){return this._inst?this.maxBytes-this._m32[1280]:0}}},61(e,t,i){Object.defineProperty(t,"__esModule",{value:!0});const A=(0,i(552).InWasm)({s:1,t:0,d:"AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=="});t.default=class{constructor(e){this.keepSize=e,this.width=0,this.height=0}decode(e){this.width=e[4]<<24|e[5]<<16|e[6]<<8|e[7],this.height=e[8]<<24|e[9]<<16|e[10]<<8|e[11];const t=this.width*this.height,i=4*t,s=e.length,r=Math.max(i,s)+(Math.min(i,s)>>1)+4096;this._inst?this._mem.buffer.byteLengththis.keepSize&&(this._inst=this._d=this._mem=null)}}},552(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.InWasm=function(e){if(e.d){const{t,s:A,d:s}=e;let r,o;const a=WebAssembly;return 0===t?A?e=>new a.Instance(o||(o=new a.Module(r||(r=i(s)))),e):e=>o?a.instantiate(o,e):a.instantiate(r||(r=i(s)),e).then(e=>(o=e.module)&&e.instance):1===t?A?()=>o||(o=new a.Module(r||(r=i(s)))):()=>o?Promise.resolve(o):a.compile(r||(r=i(s))).then(e=>o=e):A?()=>r||(r=i(s)):()=>Promise.resolve(r||(r=i(s)))}if("undefined"==typeof _wasmCtx)throw new Error('must run "inwasm"');_wasmCtx.add(e)};let i=e=>{if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64");const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e{var e=A;Object.defineProperty(e,"__esModule",{value:!0}),e.ImageAddon=void 0;const t=i(414),s=i(795),r=i(463),o=i(699),a=i(23),n=i(235),h=i(566),g=i(994),d=i(649),l={enableSizeReports:!0,pixelLimit:16777216,sixelSupport:!0,sixelScrolling:!0,sixelPaletteLimit:4096,sixelSizeLimit:33554432,storageLimit:128,showPlaceholder:!0,iipSupport:!0,iipSizeLimit:33554432,kittySupport:!0,kittySizeLimit:33554432};e.ImageAddon=class{constructor(e){this._disposables=[],this._handlers=new Map,this._onImageAdded=new t.Emitter,this.onImageAdded=this._onImageAdded.event,this._opts=Object.assign({},l,e),this._defaultOpts=Object.assign({},l,e)}dispose(){for(const e of this._handlers.values())e.reset();for(const e of this._disposables)e.dispose();this._disposables.length=0,this._handlers.clear(),this._onImageAdded.dispose()}_disposeLater(...e){for(const t of e)this._disposables.push(t)}activate(e){var t;if(this._terminal=e,this._renderer=new r.ImageRenderer(e),this._storage=new o.ImageStorage(e,this._renderer,this._opts),this._storage.onImageAdded=()=>this._onImageAdded.fire(),this._opts.enableSizeReports){const i=null!==(t=e.options.windowOptions)&&void 0!==t?t:{};i.getWinSizePixels=!0,i.getCellSizePixels=!0,i.getWinSizeChars=!0,e.options.windowOptions=i}if(this._disposeLater(this._renderer,this._storage,e.parser.registerCsiHandler({prefix:"?",final:"h"},e=>this._decset(e)),e.parser.registerCsiHandler({prefix:"?",final:"l"},e=>this._decrst(e)),e.parser.registerCsiHandler({final:"c"},e=>this._da1(e)),e.parser.registerCsiHandler({prefix:"?",final:"S"},e=>this._xtermGraphicsAttributes(e)),e.onRender(e=>{var t;return null===(t=this._storage)||void 0===t?void 0:t.render(e)}),e.parser.registerCsiHandler({intermediates:"!",final:"p"},()=>this.reset()),e.parser.registerEscHandler({final:"c"},()=>this.reset()),e._core._inputHandler.onRequestReset(()=>this.reset()),e.buffer.onBufferChange(()=>{var e;return null===(e=this._storage)||void 0===e?void 0:e.wipeAlternate()}),e.onResize(e=>{var t;return null===(t=this._storage)||void 0===t?void 0:t.viewportResize(e)})),this._opts.sixelSupport){const t=new g.SixelImageStorage(this._storage,this._opts,this._renderer,e),i=new h.SixelHandler(this._opts,t,e);this._handlers.set("sixel",i),this._disposeLater(e._core._inputHandler._parser.registerDcsHandler({final:"q"},i))}if(this._opts.iipSupport){const t=new d.IIPImageStorage(this._storage),i=new s.IIPHandler(this._opts,this._renderer,t,e);this._handlers.set("iip",i),this._disposeLater(e._core._inputHandler._parser.registerOscHandler(1337,i))}if(this._opts.kittySupport){const t=new n.KittyImageStorage(this._storage),i=new a.KittyGraphicsHandler(this._opts,this._renderer,t,e);this._handlers.set("kitty",i),this._disposeLater(t,i,e._core._inputHandler._parser.registerApcHandler({final:"G"},i))}}reset(){var e;this._opts.sixelScrolling=this._defaultOpts.sixelScrolling,this._opts.sixelPaletteLimit=this._defaultOpts.sixelPaletteLimit,null===(e=this._storage)||void 0===e||e.reset();for(const e of this._handlers.values())e.reset();return!1}get storageLimit(){var e;return(null===(e=this._storage)||void 0===e?void 0:e.getLimit())||-1}set storageLimit(e){var t;null===(t=this._storage)||void 0===t||t.setLimit(e),this._opts.storageLimit=e}get storageUsage(){return this._storage?this._storage.getUsage():-1}get showPlaceholder(){return this._opts.showPlaceholder}set showPlaceholder(e){var t;this._opts.showPlaceholder=e,null===(t=this._renderer)||void 0===t||t.showPlaceholder(e)}getImageAtBufferCell(e,t){var i;return null===(i=this._storage)||void 0===i?void 0:i.getImageAtBufferCell(e,t)}extractTileAtBufferCell(e,t){var i;return null===(i=this._storage)||void 0===i?void 0:i.extractTileAtBufferCell(e,t)}_report(e){var t;null===(t=this._terminal)||void 0===t||t._core.input(e,!1)}_decset(e){for(let t=0;t2&&!(e[2]instanceof Array)&&e[2]<=4096?(this._opts.sixelPaletteLimit=e[2],this._report(`[?${e[0]};0;${this._opts.sixelPaletteLimit}S`)):this._report(`[?${e[0]};2S`),!0;case 4:return this._report(`[?${e[0]};0;4096S`),!0;default:return this._report(`[?${e[0]};2S`),!0}if(2===e[0])switch(e[1]){case 1:let n=null===(i=null===(t=this._renderer)||void 0===t?void 0:t.dimensions)||void 0===i?void 0:i.css.canvas.width,h=null===(s=null===(A=this._renderer)||void 0===A?void 0:A.dimensions)||void 0===s?void 0:s.css.canvas.height;if(!n||!h){const e=o.CELL_SIZE_DEFAULT;n=((null===(r=this._terminal)||void 0===r?void 0:r.cols)||80)*e.width,h=((null===(a=this._terminal)||void 0===a?void 0:a.rows)||24)*e.height}if(n*h(()=>{"use strict";var e={939(e,t){function i(e){return 255&e}function A(e){return e>>>8&255}function s(e){return e>>>16&255}function r(e,t,i,A=255){return((255&A)<<24|(255&i)<<16|(255&t)<<8|255&e)>>>0}function o(e,t,i){return Math.max(e,Math.min(i,t))}function a(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),6*i<1?t+6*(e-t)*i:2*i<1?e:3*i<2?t+(e-t)*(4-6*i):t}function n(e,t,i){return(4278190080|Math.round(i/100*255)<<16|Math.round(t/100*255)<<8|Math.round(e/100*255))>>>0}Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_FOREGROUND=t.DEFAULT_BACKGROUND=t.PALETTE_ANSI_256=t.PALETTE_VT340_GREY=t.PALETTE_VT340_COLOR=t.normalizeHLS=t.normalizeRGB=t.nearestColorIndex=t.fromRGBA8888=t.toRGBA8888=t.alpha=t.blue=t.green=t.red=t.BIG_ENDIAN=void 0,t.BIG_ENDIAN=255===new Uint8Array(new Uint32Array([4278190080]).buffer)[0],t.BIG_ENDIAN&&console.warn("BE platform detected. This version of node-sixel works only on LE properly."),t.red=i,t.green=A,t.blue=s,t.alpha=function(e){return e>>>24&255},t.toRGBA8888=r,t.fromRGBA8888=function(e){return[255&e,e>>8&255,e>>16&255,e>>>24]},t.nearestColorIndex=function(e,t){const r=i(e),o=A(e),a=s(e);let n=Number.MAX_SAFE_INTEGER,h=-1;for(let e=0;e{const e=[r(0,0,0),r(205,0,0),r(0,205,0),r(205,205,0),r(0,0,238),r(205,0,205),r(0,250,205),r(229,229,229),r(127,127,127),r(255,0,0),r(0,255,0),r(255,255,0),r(92,92,255),r(255,0,255),r(0,255,255),r(255,255,255)],t=[0,95,135,175,215,255];for(let i=0;i<6;++i)for(let A=0;A<6;++A)for(let s=0;s<6;++s)e.push(r(t[i],t[A],t[s]));for(let t=8;t<=238;t+=10)e.push(r(t,t,t));return new Uint32Array(e)})(),t.DEFAULT_BACKGROUND=r(0,0,0,255),t.DEFAULT_FOREGROUND=r(255,255,255,255)},591(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.decodeAsync=t.decode=t.Decoder=t.DecoderAsync=void 0;const A=i(939),s=i(199),r=function(e){if("undefined"!=typeof Buffer)return Buffer.from(e,"base64");const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e1,this.modeHandler=e=>1}handle_band(e){return this.bandHandler(e)}mode_parsed(e){return this.modeHandler(e)}}const h={memoryLimit:134217728,sixelColor:A.DEFAULT_FOREGROUND,fillColor:A.DEFAULT_BACKGROUND,palette:A.PALETTE_VT340_COLOR,paletteLimit:s.LIMITS.PALETTE_SIZE,truncate:!0};function g(e){const t=new n,i={env:{handle_band:t.handle_band.bind(t),mode_parsed:t.mode_parsed.bind(t)}};return WebAssembly.instantiate(o||r,i).then(i=>(o=o||i.module,new d(e,i.instance||i,t)))}t.DecoderAsync=g;class d{constructor(e,t,i){if(this._PIXEL_OFFSET=s.LIMITS.MAX_WIDTH+4,this._canvas=a,this._bandWidths=[],this._maxWidth=0,this._minWidth=s.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0,this._opts=Object.assign({},h,e),this._opts.paletteLimit>s.LIMITS.PALETTE_SIZE)throw new Error(`DecoderOptions.paletteLimit must not exceed ${s.LIMITS.PALETTE_SIZE}`);if(t)i.bandHandler=this._handle_band.bind(this),i.modeHandler=this._initCanvas.bind(this);else{const e=o||(o=new WebAssembly.Module(r));t=new WebAssembly.Instance(e,{env:{handle_band:this._handle_band.bind(this),mode_parsed:this._initCanvas.bind(this)}})}this._instance=t,this._wasm=this._instance.exports,this._chunk=new Uint8Array(this._wasm.memory.buffer,this._wasm.get_chunk_address(),s.LIMITS.CHUNK_SIZE),this._states=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_state_address(),12),this._palette=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_palette_address(),s.LIMITS.PALETTE_SIZE),this._palette.set(this._opts.palette),this._pSrc=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_p0_address()),this._wasm.init(A.DEFAULT_FOREGROUND,0,this._opts.paletteLimit,0)}get _fillColor(){return this._states[0]}get _truncate(){return this._states[8]}get _rasterWidth(){return this._states[6]}get _rasterHeight(){return this._states[7]}get _width(){return this._states[2]?this._states[2]-4:0}get _height(){return this._states[3]}get _level(){return this._states[9]}get _mode(){return this._states[10]}get _paletteLimit(){return this._states[11]}_initCanvas(e){if(2===e){const e=this.width*this.height;if(e>this._canvas.length){if(this._opts.memoryLimit&&4*e>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(e)}this._maxWidth=this._width}else if(1===e)if(2===this._level){const e=Math.min(this._rasterWidth,s.LIMITS.MAX_WIDTH)*this._rasterHeight;if(e>this._canvas.length){if(this._opts.memoryLimit&&4*e>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(e)}}else this._canvas.length<65536&&(this._canvas=new Uint32Array(65536));return 0}_realloc(e,t){const i=e+t;if(i>this._canvas.length){if(this._opts.memoryLimit&&4*i>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");const e=new Uint32Array(65536*Math.ceil(i/65536));e.set(this._canvas),this._canvas=e}}_handle_band(e){const t=this._PIXEL_OFFSET;let i=this._lastOffset;if(2===this._mode){let A=this.height-this._currentHeight,s=0;for(;s<6&&A>0;)this._canvas.set(this._pSrc.subarray(t*s,t*s+e),i+e*s),s++,A--;this._lastOffset+=e*s,this._currentHeight+=s}else if(1===this._mode){this._realloc(i,6*e),this._maxWidth=Math.max(this._maxWidth,e),this._minWidth=Math.min(this._minWidth,e);for(let A=0;A<6;++A)this._canvas.set(this._pSrc.subarray(t*A,t*A+e),i+e*A);this._bandWidths.push(e),this._lastOffset+=6*e,this._currentHeight+=6}return 0}get width(){return 1!==this._mode?this._width:Math.max(this._maxWidth,this._wasm.current_width())}get height(){return 1!==this._mode?this._height:this._wasm.current_width()?6*this._bandWidths.length+this._wasm.current_height():6*this._bandWidths.length}get palette(){return this._palette.subarray(0,this._paletteLimit)}get memoryUsage(){return this._canvas.byteLength+this._wasm.memory.buffer.byteLength+8*this._bandWidths.length}get properties(){return{width:this.width,height:this.height,mode:this._mode,level:this._level,truncate:!!this._truncate,paletteLimit:this._paletteLimit,fillColor:this._fillColor,memUsage:this.memoryUsage,rasterAttributes:{numerator:this._states[4],denominator:this._states[5],width:this._rasterWidth,height:this._rasterHeight}}}init(e=this._opts.fillColor,t=this._opts.palette,i=this._opts.paletteLimit,A=this._opts.truncate){this._wasm.init(this._opts.sixelColor,e,i,A?1:0),t&&this._palette.set(t.subarray(0,s.LIMITS.PALETTE_SIZE)),this._bandWidths.length=0,this._maxWidth=0,this._minWidth=s.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0}decode(e,t=0,i=e.length){let A=t;for(;A0){const i=this._PIXEL_OFFSET;let A=this._lastOffset,s=0;for(;s<6&&t>0;)this._canvas.set(this._pSrc.subarray(i*s,i*s+e),A+e*s),s++,t--;t&&this._canvas.fill(this._fillColor,A+e*s)}return this._canvas.subarray(0,this.width*this.height)}if(1===this._mode){if(this._minWidth===this._maxWidth){let t=!1;if(e)if(e!==this._minWidth)t=!0;else{const t=this._PIXEL_OFFSET;let i=this._lastOffset;this._realloc(i,6*e);for(let A=0;A<6;++A)this._canvas.set(this._pSrc.subarray(t*A,t*A+e),i+e*A)}if(!t)return this._canvas.subarray(0,this.width*this.height)}const t=new Uint32Array(this.width*this.height);t.fill(this._fillColor);let i=0,A=0;for(let e=0;e{if(this._disposed)return(0,A.toDisposable)(()=>{});const s={fn:e,thisArgs:t};this._listeners=this._listeners.slice(),this._listeners.push(s);const r=(0,A.toDisposable)(()=>{const e=this._listeners.indexOf(s);-1!==e&&(this._listeners=this._listeners.slice(),this._listeners.splice(e,1))});return i&&(Array.isArray(i)?i.push(r):i.add(r)),r}),this._event}fire(e){if(this._disposed||!this._listeners.length)return;if(1===this._listeners.length)return void this._listeners[0].fn.call(this._listeners[0].thisArgs,e);const t=this._listeners;for(let i=0,A=t.length;it.fire(e))},e.map=function(e,t){return(i,A,s)=>e(e=>i.call(A,t(e)),void 0,s)},e.any=function(...e){return(t,i,s)=>{const r=new A.DisposableStore;for(const A of e)r.add(A(e=>t.call(i,e)));return s&&(Array.isArray(s)?s.push(r):s.add(r)),r}},e.runAndSubscribe=function(e,t,i){return t(i),e(e=>t(e))}}(s||(t.EventUtils=s={}))},426(e,t){function i(e){return{dispose:e}}function A(e){if(!e)return e;if(Array.isArray(e)){for(const t of e)t.dispose();return[]}return e.dispose(),e}Object.defineProperty(t,"__esModule",{value:!0}),t.MutableDisposable=t.Disposable=t.DisposableStore=void 0,t.toDisposable=i,t.dispose=A,t.combinedDisposable=function(...e){return i(()=>A(e))};class s{constructor(){this._disposables=new Set,this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(e){return this._isDisposed?e.dispose():this._disposables.add(e),e}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(const e of this._disposables)e.dispose();this._disposables.clear()}}clear(){for(const e of this._disposables)e.dispose();this._disposables.clear()}}t.DisposableStore=s;class r{constructor(){this._store=new s}dispose(){this._store.dispose()}_register(e){return this._store.add(e)}}t.Disposable=r,r.None=Object.freeze({dispose(){}}),t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}}},795(e,t,i){var A=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.IIPHandler=void 0;const s=i(463),r=i(699),o=A(i(669)),a=A(i(61)),n=i(389),h=i(462),g={type:0,name:"Unnamed file",size:0,width:"auto",height:"auto",preserveAspectRatio:1,inline:0};t.IIPHandler=class{constructor(e,t,i,A){this._opts=e,this._renderer=t,this._storage=i,this._coreTerminal=A,this._generation=0,this._aborted=!1,this._hp=new n.HeaderParser,this._header=g,this._isMultipart=!1,this._abortMulti=!1;const s=Math.ceil(4*this._opts.iipSizeLimit/3),r=Math.min(1048576,s);this._dec=new o.default(0,s,r),this._qoiDec=new a.default(0)}reset(){this._generation++,this._hp.reset(),this._dec.release(),this._qoiDec.release()}start(){this._aborted=!1,this._hp.reset()}put(e,t,i){if(!this._aborted)if(4===this._hp.state)0!==this._dec.put(e.subarray(t,i))&&(this._dec.release(),this._aborted=!0);else{const A=this._hp.parse(e,t,i);if(-1===A)return void(this._aborted=!0);if(A>0){if(1===this._hp.fields.type){if(this._isMultipart&&(this._isMultipart=!1,this._abortMulti=!1,this._dec.release()),this._header=Object.assign({},g,this._hp.fields),!this._header.inline)return void(this._aborted=!0);if(!this._initDecoder())return void(this._aborted=!0)}else if(this._abortMulti)return void(this._aborted=!0);0!==this._dec.put(e.subarray(A,i))&&(this._dec.release(),this._aborted=!0,this._isMultipart&&(this._abortMulti=!0))}}}end(e){var t,i,A;if(this._aborted)return!0;if(4!==this._hp.state&&this._hp.end())return!0;const o=this._hp.fields.type;if(3===o)return!0;if(5===o){let e=r.CELL_SIZE_DEFAULT.width,i=r.CELL_SIZE_DEFAULT.height;this._renderer.dimensions&&(e=this._renderer.dimensions.css.canvas.width/this._coreTerminal.cols,i=this._renderer.dimensions.css.canvas.height/this._coreTerminal.rows);const s=null!==(A=null===(t=this._coreTerminal._core._coreBrowserService)||void 0===t?void 0:t.dpr)&&void 0!==A?A:1,o=`]1337;ReportCellSize=${i.toFixed(3)};${e.toFixed(3)};${s.toFixed(3)}\\`;return this._coreTerminal.input(o,!1),!0}if(2===o)return this._header=Object.assign({},g,this._hp.fields),this._isMultipart=!0,this._abortMulti=!1,this._dec.release(),this._initDecoder()||(this._abortMulti=!0),!0;if(4===o){if(!this._isMultipart)return!0;if(this._isMultipart=!1,this._abortMulti||2!==this._header.type)return!0}let a,n,d=0,l=0,I=h.UNSUPPORTED_TYPE;if((a=e)&&((a=!this._dec.end())?(I=(0,h.imageType)(this._dec.data8),(a="unsupported"!==I.mime)?(d=I.width,l=I.height,(a=d&&l&&d*lc!==this._generation?(e.close(),!0):(this._storage.addImage(e),!0)).catch(e=>(console.warn(`IIP: decoding error ${I.mime} ${I.width}x${I.height}`,e),!0))}_initDecoder(){try{return this._dec.init(),!0}catch(e){return console.warn("IIP: could not allocate decoder",e),this._dec.release(),!1}}_resize(e,t){var i,A,s,o;const a=(null===(i=this._renderer.dimensions)||void 0===i?void 0:i.css.cell.width)||r.CELL_SIZE_DEFAULT.width,n=(null===(A=this._renderer.dimensions)||void 0===A?void 0:A.css.cell.height)||r.CELL_SIZE_DEFAULT.height,h=(null===(s=this._renderer.dimensions)||void 0===s?void 0:s.css.canvas.width)||a*this._coreTerminal.cols,g=(null===(o=this._renderer.dimensions)||void 0===o?void 0:o.css.canvas.height)||n*this._coreTerminal.rows,d=this._dim(this._header.width,h,a),l=this._dim(this._header.height,g,n);if(!d&&!l){const i=h/e,A=(g-n)/t,s=Math.min(i,A);return s<1?[e*s,t*s]:[e,t]}return d?!this._header.preserveAspectRatio&&d&&l?[d,l]:[d,t*d/e]:[e*l/t,l]}_dim(e,t,i){return"auto"===e?0:e.endsWith("%")?parseInt(e.slice(0,-1),10)*t/100:e.endsWith("px")?parseInt(e.slice(0,-2),10):parseInt(e,10)*i}}},389(e,t){function i(e){let t="";for(let i=0;i57)throw new Error("illegal char");t=10*t+e[i]-48}return t}function s(e){const t=i(e);if(!t.match(/^((auto)|(\d+?((px)|(%)){0,1}))$/))throw new Error("illegal size");return t}Object.defineProperty(t,"__esModule",{value:!0}),t.HeaderParser=void 0;const r={inline:A,size:A,name:function(e){if("undefined"!=typeof Buffer)return Buffer.from(i(e),"base64").toString();const t=atob(i(e)),A=new Uint8Array(t.length);for(let e=0;e14)return-1;for(let h=t;h=d)return this._a();r[s++]=t}break;case 58:return 3!==A||this._storeValue(s)?(this.state=4,h+1):this._a();default:if(s>=d)return this._a();r[s++]=t}}return this.state=A,this._position=s,-2}_a(){return this.fields.type=0,this.state=1,-1}_storeKey(e){const t=i(this._buffer.subarray(0,e));return!!t&&(this._key=t,this.fields[t]=null,!0)}_storeValue(e){if(this._key){try{const t=this._buffer.slice(0,e);this.fields[this._key]=r[this._key]?r[this._key](t):t}catch(e){return!1}return!0}return!1}}},649(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.IIPImageStorage=void 0,t.IIPImageStorage=class{constructor(e){this._storage=e,this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"}}addImage(e){this._storage.addImage(e,this._addImageOpts)}}},462(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.UNSUPPORTED_TYPE=void 0,t.imageType=function(e){if(e.length<32)return t.UNSUPPORTED_TYPE;const i=new Uint32Array(e.buffer,e.byteOffset,8);if(1196314761===i[0]&&169478669===i[1]&&1380206665===i[3])return{mime:"image/png",width:e[16]<<24|e[17]<<16|e[18]<<8|e[19],height:e[20]<<24|e[21]<<16|e[22]<<8|e[23]};if(255===e[0]&&216===e[1]&&255===e[2]){const[t,i]=function(e){const t=e.length;let i=4,A=e[i]<<8|e[i+1];for(;;){if(i+=A,i>=t)return[0,0];if(255!==e[i])return[0,0];if(192===e[i+1]||194===e[i+1])return i+8>>14&16383)};case 32:return 157!==e[23]||1!==e[24]||42!==e[25]?t.UNSUPPORTED_TYPE:{mime:"image/webp",width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}return t.UNSUPPORTED_TYPE}if(1887007846===i[1]&&(1718187617===i[2]||1936291425===i[2])){let i=-1;const A=Math.min(e.length-16,1024);for(let t=8;t0&&A>0)return{mime:"image/avif",width:t,height:A}}return t.UNSUPPORTED_TYPE}return t.UNSUPPORTED_TYPE},t.UNSUPPORTED_TYPE={mime:"unsupported",width:0,height:0}},463(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.ImageRenderer=void 0;const A=i(939),s=i(426);class r extends s.Disposable{get canvas(){var e;return null===(e=this._layers.get("top"))||void 0===e?void 0:e.canvas}static createCanvas(e,t,i){const A=(null!=e?e:document).createElement("canvas");return A.width=0|t,A.height=0|i,A}static createImageData(e,t,i,A){if("function"!=typeof ImageData){const s=e.createImageData(t,i);return A&&s.data.set(new Uint8ClampedArray(A,0,t*i*4)),s}return A?new ImageData(new Uint8ClampedArray(A,0,t*i*4),t,i):new ImageData(t,i)}static createImageBitmap(e){return"function"!=typeof createImageBitmap?Promise.resolve(void 0):createImageBitmap(e)}constructor(e){super(),this._terminal=e,this._layers=new Map,this._optionsRefresh=this._register(new s.MutableDisposable),this._oldOpen=this._terminal._core.open,this._terminal._core.open=e=>{var t;null===(t=this._oldOpen)||void 0===t||t.call(this._terminal._core,e),this._open()},this._terminal._core.screenElement&&this._open(),this._optionsRefresh.value=this._terminal._core.optionsService.onOptionChange(e=>{var t;"fontSize"===e&&(this.rescaleCanvas(),null===(t=this._renderService)||void 0===t||t.refreshRows(0,this._terminal.rows))}),this._register((0,s.toDisposable)(()=>{var e;this.removeLayerFromDom(),this.removeLayerFromDom("bottom"),this._terminal._core&&this._oldOpen&&(this._terminal._core.open=this._oldOpen,this._oldOpen=void 0),this._renderService&&this._oldSetRenderer&&(this._renderService.setRenderer=this._oldSetRenderer,this._oldSetRenderer=void 0),this._renderService=void 0,this._layers.clear(),null===(e=this._placeholderBitmap)||void 0===e||e.close(),this._placeholderBitmap=void 0,this._placeholder=void 0}))}showPlaceholder(e){var t,i;e?this._placeholder||-1===this.cellSize.height||this._createPlaceHolder(Math.max(this.cellSize.height+1,24)):(null===(t=this._placeholderBitmap)||void 0===t||t.close(),this._placeholderBitmap=void 0,this._placeholder=void 0),null===(i=this._renderService)||void 0===i||i.refreshRows(0,this._terminal.rows)}get dimensions(){return this._terminal.dimensions}get cellSize(){var e,t;return{width:(null===(e=this.dimensions)||void 0===e?void 0:e.css.cell.width)||-1,height:(null===(t=this.dimensions)||void 0===t?void 0:t.css.cell.height)||-1}}clearLines(e,t,i){var A,s,r,o,a;const n=e*((null===(A=this.dimensions)||void 0===A?void 0:A.css.cell.height)||0),h=(null===(s=this.dimensions)||void 0===s?void 0:s.css.canvas.width)||0,g=(t+1-e)*((null===(r=this.dimensions)||void 0===r?void 0:r.css.cell.height)||0);i&&"top"!==i||null===(o=this._layers.get("top"))||void 0===o||o.clearRect(0,n,h,g),i&&"bottom"!==i||null===(a=this._layers.get("bottom"))||void 0===a||a.clearRect(0,n,h,g)}clearAll(e){if(!e||"top"===e){const e=this._layers.get("top");null==e||e.clearRect(0,0,e.canvas.width,e.canvas.height)}if(!e||"bottom"===e){const e=this._layers.get("bottom");null==e||e.clearRect(0,0,e.canvas.width,e.canvas.height)}}draw(e,t,i,A,s=1){const r=this._layers.get(e.layer);if(!r)return;const{width:o,height:a}=this.cellSize;if(-1===o||-1===a)return;this._rescaleImage(e,o,a);const n=e.actual,{width:h,height:g}=e.actualCellSize,d=Math.ceil(n.width/h),l=t%d*h,I=Math.floor(t/d)*g,c=i*o,_=A*a,C=s*h+l>n.width?n.width-l:s*h,B=I+g>n.height?n.height-I:g;r.drawImage(n,Math.floor(l),Math.floor(I),Math.ceil(C),Math.ceil(B),Math.floor(c),Math.floor(_),Math.ceil(C*o/h),Math.ceil(B*a/g))}extractTile(e,t){const{width:i,height:A}=this.cellSize;if(-1===i||-1===A)return;this._rescaleImage(e,i,A);const s=e.actual,{width:o,height:a}=e.actualCellSize,n=Math.ceil(s.width/o),h=t%n*o,g=Math.floor(t/n)*a,d=o+h>s.width?s.width-h:o,l=g+a>s.height?s.height-g:a,I=r.createCanvas(this.document,Math.ceil(d*i/o),Math.ceil(l*A/a)),c=I.getContext("2d");return c?(c.drawImage(s,Math.floor(h),Math.floor(g),Math.floor(d),Math.floor(l),0,0,I.width,I.height),I):void 0}drawPlaceholder(e,t,i=1){var A;const s=this._layers.get("top");if(s){const{width:r,height:o}=this.cellSize;if(-1===r||-1===o)return;if(this._placeholder?o>=this._placeholder.height&&this._createPlaceHolder(o+1):this._createPlaceHolder(Math.max(o+1,24)),!this._placeholder)return;s.drawImage(null!==(A=this._placeholderBitmap)&&void 0!==A?A:this._placeholder,e*r,t*o%2?0:1,r*i,o,e*r,t*o,r*i,o)}}rescaleCanvas(){var e,t;const i=(null===(e=this.dimensions)||void 0===e?void 0:e.css.canvas.width)||0,A=(null===(t=this.dimensions)||void 0===t?void 0:t.css.canvas.height)||0;for(const e of this._layers.values())e.canvas.width===i&&e.canvas.height===A||(e.canvas.width=i,e.canvas.height=A)}_rescaleImage(e,t,i){if(t===e.actualCellSize.width&&i===e.actualCellSize.height)return;const{width:A,height:s}=e.origCellSize;if(t===A&&i===s)return e.actual=e.orig,e.actualCellSize.width=A,void(e.actualCellSize.height=s);const o=Math.ceil(e.orig.width*t/A),a=Math.ceil(e.orig.height*i/s);if(o*a>e.orig.width*e.orig.height)return e.actual=e.orig,e.actualCellSize.width=A,void(e.actualCellSize.height=s);const n=r.createCanvas(this.document,o,a),h=n.getContext("2d");h&&(h.drawImage(e.orig,0,0,n.width,n.height),e.actual=n,e.actualCellSize.width=t,e.actualCellSize.height=i)}_open(){this._renderService=this._terminal._core._renderService,this._oldSetRenderer=this._renderService.setRenderer.bind(this._renderService),this._renderService.setRenderer=e=>{var t;for(const e of[...this._layers.keys()])this.removeLayerFromDom(e);null===(t=this._oldSetRenderer)||void 0===t||t.call(this._renderService,e)}}insertLayerToDom(e="top"){var t,i;if(!this.document||!this._terminal._core.screenElement)return void console.warn("image addon: cannot insert output canvas to DOM, missing document or screenElement");if(this._layers.has(e))return;const A=r.createCanvas(this.document,(null===(t=this.dimensions)||void 0===t?void 0:t.css.canvas.width)||0,(null===(i=this.dimensions)||void 0===i?void 0:i.css.canvas.height)||0);A.classList.add(`xterm-image-layer-${e}`);const s=this._terminal._core.screenElement;s.style.isolation="isolate","bottom"===e?(A.style.zIndex="-1",s.insertBefore(A,s.firstChild)):(A.style.zIndex="0",s.appendChild(A));const o=A.getContext("2d",{alpha:!0});o?(this._layers.set(e,o),this.clearAll(e)):A.remove()}removeLayerFromDom(e="top"){const t=this._layers.get(e);t&&(t.canvas.remove(),this._layers.delete(e))}hasLayer(e){return this._layers.has(e)}_createPlaceHolder(e=24){var t;null===(t=this._placeholderBitmap)||void 0===t||t.close(),this._placeholderBitmap=void 0;const i=32,s=r.createCanvas(this.document,i,e),o=s.getContext("2d",{alpha:!1});if(!o)return;const a=r.createImageData(o,i,e),n=new Uint32Array(a.data.buffer),h=(0,A.toRGBA8888)(0,0,0),g=(0,A.toRGBA8888)(255,255,255);n.fill(h);for(let t=0;t{this._placeholder!==I?null==e||e.close():this._placeholderBitmap=e}).catch(()=>{})}get document(){var e;return null===(e=this._terminal._core._coreBrowserService)||void 0===e?void 0:e.window.document}}t.ImageRenderer=r},699(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.ImageStorage=t.CELL_SIZE_DEFAULT=void 0;const A=i(463);t.CELL_SIZE_DEFAULT={width:7,height:14};class s{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get underlineVariantOffset(){const e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}get urlId(){return this._urlId}set urlId(e){this._urlId=e}constructor(e=0,t=0,i=-1,A=-1){this.imageId=i,this.tileId=A,this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new s(this._ext,this._urlId,this.imageId,this.tileId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId&&-1===this.imageId}}const r=new s;t.ImageStorage=class{constructor(e,t,i){this._terminal=e,this._renderer=t,this._opts=i,this._images=new Map,this._lastId=0,this._lowestId=0,this._fullyCleared=!1,this._needsFullClear=!1,this._pixelLimit=25e5;try{this.setLimit(this._opts.storageLimit)}catch(e){e instanceof Error&&console.error(e.message),console.warn(`storageLimit is set to ${this.getLimit()} MB`)}this._viewportMetrics={cols:this._terminal.cols,rows:this._terminal.rows}}dispose(){this.reset()}reset(){var e;for(const t of this._images.values())null===(e=t.marker)||void 0===e||e.dispose();this._images.clear(),this._renderer.clearAll()}getLimit(){return 4*this._pixelLimit/1e6}setLimit(e){if(e<.5||e>1e3)throw RangeError("invalid storageLimit, should be at least 0.5 MB and not exceed 1G");this._pixelLimit=e/4*1e6>>>0,this._evictOldest(0)}getUsage(){return 4*this._getStoredPixels()/1e6}_getStoredPixels(){let e=0;for(const t of this._images.values())t.orig&&(e+=t.orig.width*t.orig.height,t.actual&&t.actual!==t.orig&&(e+=t.actual.width*t.actual.height));return e}_delImg(e){var t;const i=this._images.get(e);i&&(this._images.delete(e),window.ImageBitmap&&i.orig instanceof ImageBitmap&&i.orig.close(),null===(t=this.onImageDeleted)||void 0===t||t.call(this,e))}wipeAlternate(){var e;const t=[];for(const[i,A]of this._images.entries())"alternate"===A.bufferType&&(null===(e=A.marker)||void 0===e||e.dispose(),t.push(i));for(const e of t)this._delImg(e);this._needsFullClear=!0,this._fullyCleared=!1}deleteImage(e){var t;const i=this._images.get(e);i&&(null===(t=i.marker)||void 0===t||t.dispose(),this._delImg(e))}addImage(e,i){var A,s;this._evictOldest(e.width*e.height);let r=this._renderer.cellSize;-1!==r.width&&-1!==r.height||(r=t.CELL_SIZE_DEFAULT);const o=Math.ceil(e.width/r.width),a=Math.ceil(e.height/r.height),n=++this._lastId,h=this._terminal._core.buffer,g=this._terminal.cols,d=this._terminal.rows,l=h.x,I=h.y;let c=l,_=0;i.scrolling||(h.x=0,h.y=0,c=0),this._terminal._core._inputHandler._dirtyRowTracker.markDirty(h.y);for(let e=0;e=g);++i)this._writeToCell(t,c+i,n,e*o+i),_++;if(i.scrolling)e=d)break;h.x=c}this._terminal._core._inputHandler._dirtyRowTracker.markDirty(h.y),i.scrolling?"iip"===i.cursorPos?h.x=Math.min(c+o,g):h.x=c:(h.x=l,h.y=I);const C=[];for(const[e,t]of this._images.entries())t.tileCount<1&&(null===(A=t.marker)||void 0===A||A.dispose(),C.push(e));for(const e of C)this._delImg(e);const B=this._terminal.registerMarker(0);null==B||B.onDispose(()=>{this._images.get(n)&&this._delImg(n)}),"alternate"===this._terminal.buffer.active.type&&this._evictOnAlternate();const Q={orig:e,origCellSize:r,actual:e,actualCellSize:Object.assign({},r),marker:B||void 0,tileCount:_,bufferType:this._terminal.buffer.active.type,layer:i.layer,zIndex:i.zIndex};return this._images.set(n,Q),null===(s=this.onImageAdded)||void 0===s||s.call(this),n}render(e){var t,i;let A=!1,s=!1;for(const e of this._images.values())if("bottom"===e.layer?s=!0:A=!0,A&&s)break;if(A&&!this._renderer.hasLayer("top")&&(this._renderer.insertLayerToDom("top"),!this._renderer.hasLayer("top")))return;if(s&&!this._renderer.hasLayer("bottom")&&this._renderer.insertLayerToDom("bottom"),this._renderer.rescaleCanvas(),!this._images.size)return this._fullyCleared||(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1),this._renderer.hasLayer("top")&&this._renderer.removeLayerFromDom("top"),void(this._renderer.hasLayer("bottom")&&this._renderer.removeLayerFromDom("bottom"));!A&&this._renderer.hasLayer("top")&&(this._renderer.clearAll("top"),this._renderer.removeLayerFromDom("top")),!s&&this._renderer.hasLayer("bottom")&&(this._renderer.clearAll("bottom"),this._renderer.removeLayerFromDom("bottom")),this._needsFullClear&&(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1);const{start:o,end:a}=e,n=this._terminal._core.buffer,h=this._terminal._core.cols;this._renderer.clearLines(o,a);const g=[],d=[];for(let e=o;e<=a;++e){const A=n.lines.get(e+n.ydisp);if(!A)return;for(let s=0;se.imgSpec.zIndex-t.imgSpec.zIndex);for(const e of d)this._renderer.drawPlaceholder(e.col,e.row,e.count);for(const e of g)this._renderer.draw(e.imgSpec,e.tileId,e.col,e.row,e.count)}viewportResize(e){var t,i;if(!this._images.size)return void(this._viewportMetrics=e);if(this._viewportMetrics.cols>=e.cols)return void(this._viewportMetrics=e);const A=this._terminal._core.buffer,s=A.lines.length,o=this._viewportMetrics.cols-1;for(let a=0;a=h)continue;let g=!1;for(let t=o+1;t>e.cols;++t)if(4194303&s._data[3*t+0]){g=!0;break}if(g)continue;const d=Math.min(e.cols,h-A.tileId%h+o);let l=A.tileId;for(let e=o+1;e4194304&&e.release();const A=null!==(i=n.get(t))&&void 0!==i?i:[];A.length<2&&(A.push(e),n.set(t,A))}function d(e){return A.BIG_ENDIAN?e:(255&e)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255}t.SixelHandler=class{constructor(e,t,i){var A;this._opts=e,this._storage=t,this._coreTerminal=i,this._size=0,this._aborted=!1,this._decMemoryLimit=0,this._palette=new Uint32Array(o.LIMITS.PALETTE_SIZE),this._palette.set(a),A=4*this._opts.pixelLimit,h||(h=!0,(0,r.DecoderAsync)({memoryLimit:A,palette:a}).then(e=>g(e,A),()=>{h=!1}))}reset(){this._returnDecoder(),this._palette.fill(0),this._palette.set(a)}hook(e){var t;this._size=0,this._aborted=!1,this._returnDecoder();const i=4*this._opts.pixelLimit;try{this._dec=function(e){var t,i;return null!==(i=null===(t=n.get(e))||void 0===t?void 0:t.pop())&&void 0!==i?i:new r.Decoder({memoryLimit:e,palette:a})}(i)}catch(e){return console.warn(`SIXEL: could not allocate decoder - ${e}`),void(this._aborted=!0)}this._decMemoryLimit=i;const s=1===e.params[1]?0:function(e,t){let i=0;if(!t)return i;if(e.isInverse())if(e.isFgDefault())i=d(t.foreground.rgba);else if(e.isFgRGB()){const t=e.constructor.toColorRGB(e.getFgColor());i=(0,A.toRGBA8888)(...t)}else i=d(t.ansi[e.getFgColor()].rgba);else if(e.isBgDefault())i=d(t.background.rgba);else if(e.isBgRGB()){const t=e.constructor.toColorRGB(e.getBgColor());i=(0,A.toRGBA8888)(...t)}else i=d(t.ansi[e.getBgColor()].rgba);return i}(this._coreTerminal._core._inputHandler._curAttrData,null===(t=this._coreTerminal._core._themeService)||void 0===t?void 0:t.colors);this._dec.init(s,this._palette,this._opts.sixelPaletteLimit)}_returnDecoder(){const e=this._dec;e&&(this._dec=void 0,this._palette.set(e.palette),g(e,this._decMemoryLimit))}put(e,t,i){if(!this._aborted&&this._dec){if(this._size+=i-t,this._size>this._opts.sixelSizeLimit)return console.warn("SIXEL: too much data, aborting"),this._aborted=!0,void this._dec.release();try{this._dec.decode(e,t,i)}catch(e){console.warn(`SIXEL: error while decoding image - ${e}`),this._aborted=!0,this._dec.release()}}}unhook(e){try{return this._unhook(e)}finally{this._returnDecoder()}}_unhook(e){var t;if(this._aborted||!e||!this._dec)return!0;const i=this._dec.width,A=this._dec.height;if(!i||!A)return A&&this._storage.advanceCursor(A),!0;const r=s.ImageRenderer.createCanvas(void 0,i,A);return null===(t=r.getContext("2d"))||void 0===t||t.putImageData(new ImageData(this._dec.data8,i,A),0,0),this._storage.addImage(r),!0}}},994(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.SixelImageStorage=void 0;const A=i(699);t.SixelImageStorage=class{constructor(e,t,i,A){this._storage=e,this._opts=t,this._renderer=i,this._terminal=A,this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"vt340"}}addImage(e){this._addImageOpts.scrolling=this._opts.sixelScrolling,this._storage.addImage(e,this._addImageOpts)}advanceCursor(e){if(this._opts.sixelScrolling){let t=this._renderer.cellSize;-1!==t.width&&-1!==t.height||(t=A.CELL_SIZE_DEFAULT);const i=Math.ceil(e/t.height);for(let e=1;e512)return void(this._aborted=!0);if(this._controlData.set(e.subarray(t,s),this._controlLength),this._controlLength+=r,!this._inControlData){if(this._parsedCommand=(0,n.parseKittyCommand)(this._parseControlDataString()),void 0!==this._parsedCommand.id&&void 0!==this._parsedCommand.imageNumber)return this._sendResponse(this._parsedCommand.id,"EINVAL:cannot specify both i and I keys",null!==(A=this._parsedCommand.quiet)&&void 0!==A?A:0),void(this._aborted=!0);if("d"===this._parsedCommand.action)return;const t=s+1;tthis._encodedSizeLimit){const e=null!==(g=this._activeDecoder)&&void 0!==g?g:null==_?void 0:_.decoder;return e&&e.release(),this._activeDecoder=null,_&&this._removePendingEntry(c),void(this._aborted=!0)}if(!this._decodeError){if((null==_?void 0:_.decoder)&&!this._activeDecoder&&(this._activeDecoder=_.decoder),!this._activeDecoder){const e=this._maxEncodedBytes+131072;if(e>1e6*this._opts.storageLimit)return this._aborted=!0,void(void 0!==(null===(s=this._parsedCommand)||void 0===s?void 0:s.id)&&this._sendResponse(this._parsedCommand.id,"ENOMEM:pending image budget exceeded",null!==(d=this._parsedCommand.quiet)&&void 0!==d?d:0));const t=Math.max(1,Math.floor(1e6*this._opts.storageLimit/e));for(;this._pendingTransmissions.size>=t;){const e=this._pendingTransmissions.entries().next().value;if(!e)break;e[1].decoder.release(),this._removePendingEntry(e[0]),void 0!==e[1].cmd.id&&this._sendResponse(e[1].cmd.id,"ENOMEM:pending image budget exceeded",null!==(l=e[1].cmd.quiet)&&void 0!==l?l:0)}const i=new a.default(4194304,this._maxEncodedBytes,this._initialEncodedBytes);try{i.init()}catch(e){return console.warn("KITTY: could not allocate decoder",e),this._aborted=!0,void(void 0!==(null===(r=this._parsedCommand)||void 0===r?void 0:r.id)&&this._sendResponse(this._parsedCommand.id,"ENOMEM:could not allocate decoder",null!==(I=this._parsedCommand.quiet)&&void 0!==I?I:0))}this._activeDecoder=i}0!==this._activeDecoder.put(e.subarray(t,i))&&(this._activeDecoder.release(),this._activeDecoder=null,this._decodeError=!0,_&&this._removePendingEntry(c))}}end(e){var t,i;if(this._aborted||!e)return this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),!0;if(this._inControlData)return this._handleNoPayloadCommand();const A=this._parsedCommand;if("d"===A.action)return this._handleDelete(A);const s=null!==(i=null!==(t=A.id)&&void 0!==t?t:this._lastPendingKey)&&void 0!==i?i:0,r=1===A.more,o=this._pendingTransmissions.get(s);if(r)return this._activeDecoder&&(o?(o.totalEncodedSize+=this._totalEncodedSize,o.decodeError=o.decodeError||this._decodeError):this._pendingTransmissions.set(s,{cmd:Object.assign({},A),decoder:this._activeDecoder,totalEncodedSize:this._totalEncodedSize,decodeError:this._decodeError}),this._lastPendingKey=s,this._activeDecoder=null),!0;o&&(this._lastPendingKey=void 0);let a=this._decodeError,n=A,h=this._activeDecoder;o&&(n=o.cmd,h=o.decoder,a=a||o.decodeError,this._pendingTransmissions.delete(s));let g=new Uint8Array(0);h&&(0!==h.end()&&(a=!0),g=h.data8),this._activeDecoder=null;const d=this._handleCommandWithBytesAndCmd(n,g,a);return h&&h.release(),d}_parseControlDataString(){let e="";for(let t=0;t0&&this._sendResponse(e.id,"OK",null!==(o=e.quiet)&&void 0!==o?o:0)),A}case"T":return this._handleTransmitDisplay(e,t,i);case"q":return this._handleQuery(e,t,i);case"p":return this._handlePlacement(e);default:return void 0!==e.id&&this._sendResponse(e.id,"EINVAL:unsupported action",null!==(a=e.quiet)&&void 0!==a?a:0),!0}}_handlePlacement(e){var t;if(void 0===e.id)return!0;const i=e.id,A=this._kittyStorage.getImage(i);return A?this._displayImage(A,e).then(t=>{var A;return this._sendResponse(i,t?"OK":"EINVAL:image rendering failed",null!==(A=e.quiet)&&void 0!==A?A:0,e.placementId),!0}):(this._sendResponse(i,"ENOENT:image not found",null!==(t=e.quiet)&&void 0!==t?t:0,e.placementId),!0)}_handleTransmit(e,t,i){var A,s,r,o,a,n;return"d"!==(null!==(A=e.transmission)&&void 0!==A?A:"d")?(void 0!==e.id&&this._sendResponse(e.id,"EINVAL:unsupported transmission medium",null!==(s=e.quiet)&&void 0!==s?s:0),!0):(i||0===t.length||this._kittyStorage.storeImage(e.id,{data:new Blob([t]),width:null!==(r=e.width)&&void 0!==r?r:0,height:null!==(o=e.height)&&void 0!==o?o:0,format:null!==(a=e.format)&&void 0!==a?a:32,compression:null!==(n=e.compression)&&void 0!==n?n:""}),!0)}_handleTransmitDisplay(e,t,i){var A,s;if(i)return void 0!==e.id&&this._sendResponse(e.id,"EINVAL:invalid base64 data",null!==(A=e.quiet)&&void 0!==A?A:0),!0;this._handleTransmit(e,t,i);const r=null!==(s=e.id)&&void 0!==s?s:this._kittyStorage.lastImageId,o=this._kittyStorage.getImage(r);if(o){const t=this._displayImage(o,e);return void 0!==e.id?t.then(t=>{var i;return this._sendResponse(r,t?"OK":"EINVAL:image rendering failed",null!==(i=e.quiet)&&void 0!==i?i:0),!0}):t.then(()=>!0)}return!0}_handleQuery(e,t,i){var A,s,r,o,a,n;const h=null!==(A=e.id)&&void 0!==A?A:0,g=null!==(s=e.quiet)&&void 0!==s?s:0;if("d"!==(null!==(r=e.transmission)&&void 0!==r?r:"d"))return this._sendResponse(h,"EINVAL:unsupported transmission medium",g),!0;if(i)return this._sendResponse(h,"EINVAL:invalid base64 data",g),!0;if(0===t.length)return this._sendResponse(h,"OK",g),!0;const d=null!==(o=e.format)&&void 0!==o?o:32;if(100===d)this._sendResponse(h,"OK",g);else{const i=null!==(a=e.width)&&void 0!==a?a:0,A=null!==(n=e.height)&&void 0!==n?n:0;if(!i||!A)return this._sendResponse(h,"EINVAL:width and height required for raw pixel data",g),!0;const s=i*A*(32===d?4:3);if(t.length=1)return;if(!s&&i>=2)return;const r=`_Gi=${e}${A?`,p=${A}`:""};${t}\\`;this._coreTerminal._core.coreService.triggerDataEvent(r)}_displayImage(e,t){return this._decodeAndDisplay(e,t).then(()=>!0).catch(()=>!1)}async _decodeAndDisplay(e,t){var i,A,o,a,n,h,g;const d=this._generation;let l=await this._createBitmap(e);try{if(d!==this._generation)throw new Error("image decode canceled");const I=Math.max(0,null!==(o=t.x)&&void 0!==o?o:0),c=Math.max(0,null!==(a=t.y)&&void 0!==a?a:0),_=t.sourceWidth||l.width-I,C=t.sourceHeight||l.height-c,B=Math.max(0,l.width-I),Q=Math.max(0,l.height-c),m=Math.max(0,Math.min(_,B)),u=Math.max(0,Math.min(C,Q));if(0===m||0===u)throw new Error("invalid source rectangle");if(0!==I||0!==c||m!==l.width||u!==l.height){const e=await createImageBitmap(l,I,c,m,u);l.close(),l=e}const E=(null===(i=this._renderer.dimensions)||void 0===i?void 0:i.css.cell.width)||r.CELL_SIZE_DEFAULT.width,p=(null===(A=this._renderer.dimensions)||void 0===A?void 0:A.css.cell.height)||r.CELL_SIZE_DEFAULT.height;let w,f;void 0!==t.columns&&void 0!==t.rows?(w=t.columns,f=t.rows):void 0!==t.columns?(w=t.columns,f=Math.max(1,Math.ceil(l.height/l.width*(w*E)/p))):void 0!==t.rows?(f=t.rows,w=Math.max(1,Math.ceil(l.width/l.height*(f*p)/E))):(w=Math.ceil(l.width/E),f=Math.ceil(l.height/p));let D=l.width,y=l.height;if(void 0===t.columns&&void 0===t.rows||(D=Math.round(w*E),y=Math.round(f*p)),D*y>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");const v=this._coreTerminal._core.buffer,M=v.x,k=v.y,b=v.ybase,S=void 0!==t.zIndex&&t.zIndex<0?"bottom":"top";if(D!==l.width||y!==l.height){const e=await createImageBitmap(l,{resizeWidth:D,resizeHeight:y});l.close(),l=e}const L=Math.min(Math.max(0,null!==(n=t.xOffset)&&void 0!==n?n:0),E-1),N=Math.min(Math.max(0,null!==(h=t.yOffset)&&void 0!==h?h:0),p-1);if(0!==L||0!==N){const e=void 0!==t.columns?Math.round(w*E):l.width+L,i=void 0!==t.rows?Math.round(f*p):l.height+N,A=s.ImageRenderer.createCanvas(window.document,e,i),r=A.getContext("2d");if(!r)throw new Error("Failed to create offset canvas context");r.drawImage(l,L,N);const o=await createImageBitmap(A);if(A.width=A.height=0,l.close(),l=o,D=l.width,y=l.height,D*y>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");void 0===t.columns&&(w=Math.ceil(l.width/E)),void 0===t.rows&&(f=Math.ceil(l.height/p))}if(d!==this._generation)throw new Error("image decode canceled");const G=null!==(g=t.zIndex)&&void 0!==g?g:0;if(this._kittyStorage.addImage(e.id,l,!0,S,G),l=void 0,1===t.cursorMovement){const e=v.ybase-b;v.x=M,v.y=Math.max(k-e,0)}else v.x=Math.min(M+w,this._coreTerminal.cols)}catch(e){throw null==l||l.close(),e}}async _createBitmap(e){let t=new Uint8Array(await e.data.arrayBuffer());if("z"===e.compression&&(t=await this._decompressZlib(t)),100===e.format){const e=(0,o.imageType)(t);if("image/png"!==e.mime||!(e.width>0)||!(e.height>0)||e.width*e.height>this._opts.pixelLimit)throw new RangeError("PNG exceeds pixel limit or has invalid dimensions");const i=new Blob([t],{type:"image/png"});if(!window.createImageBitmap){const e=URL.createObjectURL(i),t=new Image;return new Promise((i,A)=>{t.addEventListener("load",()=>{var r;URL.revokeObjectURL(e);const o=s.ImageRenderer.createCanvas(window.document,t.width,t.height);null===(r=o.getContext("2d"))||void 0===r||r.drawImage(t,0,0),createImageBitmap(o).then(i).catch(A)}),t.addEventListener("error",()=>{URL.revokeObjectURL(e),A(new Error("Failed to load image"))}),t.src=e})}return createImageBitmap(i)}const i=e.width,A=e.height;if(!i||!A)throw new Error("Width and height required for raw pixel data");const r=i*A*(32===e.format?4:3);if(t.length>>24|t<<8,g[I++]=4278190080|t>>>16|i<<16,g[I++]=4278190080|i>>>8}let c=3*d,_=4*d;for(let e=d;e=e.length)return void t.close();const i=Math.min(A+4096,e.length);t.enqueue(new Uint8Array(e.subarray(A,i))),A=i}}).pipeThrough(new DecompressionStream(t)).getReader(),r=[];let o=0;try{for(;;){const{done:e,value:t}=await s.read();if(e)break;if(o+=t.byteLength,o>i)throw await s.cancel().catch(()=>{}),new RangeError("decompressed image exceeds byte limit");r.push(t)}}finally{s.releaseLock()}const a=new Uint8Array(o);let n=0;for(const e of r)a.set(e,n),n+=e.length;return a}get images(){return this._kittyStorage.images}get _kittyIdToStorageId(){return this._kittyStorage.kittyIdToStorageId}get pendingTransmissions(){return this._pendingTransmissions}}},470(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.parseKittyCommand=function(e){const t={},i=e.split(",");for(const e of i){const i=e.indexOf("=");if(-1===i)continue;const A=e.substring(0,i),s=e.substring(i+1);if("a"===A){t.action=s;continue}if("o"===A){t.compression=s;continue}if("t"===A){t.transmission=s;continue}if("d"===A){t.deleteSelector=s;continue}const r=parseInt(s,10);switch(A){case"f":t.format=r;break;case"i":t.id=r;break;case"I":t.imageNumber=r;break;case"s":t.width=r;break;case"v":t.height=r;break;case"x":t.x=r;break;case"y":t.y=r;break;case"w":t.sourceWidth=r;break;case"h":t.sourceHeight=r;break;case"X":t.xOffset=r;break;case"Y":t.yOffset=r;break;case"c":t.columns=r;break;case"r":t.rows=r;break;case"m":t.more=r;break;case"q":t.quiet=r;break;case"C":t.cursorMovement=r;break;case"z":t.zIndex=r;break;case"p":t.placementId=r}}return t}},235(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.KittyImageStorage=void 0;class i{constructor(e){this._storage=e,this._nextImageId=1,this._images=new Map,this._kittyIdToStorageId=new Map,this._storageIdToKittyId=new Map,this._handleStorageImageDeleted=e=>{const t=this._storageIdToKittyId.get(e);void 0!==t&&(this._kittyIdToStorageId.delete(t),this._storageIdToKittyId.delete(e),this._images.delete(t))},this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"},this._previousOnImageDeleted=this._storage.onImageDeleted,this._wrappedOnImageDeleted=e=>{var t;null===(t=this._previousOnImageDeleted)||void 0===t||t.call(this,e),this._handleStorageImageDeleted(e)},this._storage.onImageDeleted=this._wrappedOnImageDeleted}reset(){this._nextImageId=1,this._images.clear(),this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}dispose(){this.reset(),this._storage.onImageDeleted===this._wrappedOnImageDeleted&&(this._storage.onImageDeleted=this._previousOnImageDeleted)}storeImage(e,t){const A=null!=e?e:this._nextImageId++,s=this._kittyIdToStorageId.get(A);void 0!==s&&(this._storage.deleteImage(s),this._kittyIdToStorageId.delete(A),this._storageIdToKittyId.delete(s)),!this._images.has(A)&&this._images.size>=i._maxStoredImages&&this._evictUndisplayedImages();const r=1e6*this._storage.getLimit();this._images.delete(A);let o=0;for(const e of this._images.values())o+=e.data.size;for(const e of[!1,!0])for(const[i,A]of this._images){if(o+t.data.size<=r)break;this._kittyIdToStorageId.has(i)===e&&(o-=A.data.size,this.deleteById(i))}return this._images.set(A,Object.assign(Object.assign({},t),{id:A})),A}addImage(e,t,i,A,s){const r=this._kittyIdToStorageId.get(e);void 0!==r&&this._storageIdToKittyId.delete(r),this._addImageOpts.scrolling=i,this._addImageOpts.layer=A,this._addImageOpts.zIndex=s;const o=this._storage.addImage(t,this._addImageOpts);this._kittyIdToStorageId.set(e,o),this._storageIdToKittyId.set(o,e)}getImage(e){return this._images.get(e)}deleteById(e){this._images.delete(e);const t=this._kittyIdToStorageId.get(e);void 0!==t&&(this._storage.deleteImage(t),this._kittyIdToStorageId.delete(e),this._storageIdToKittyId.delete(t))}deleteAll(){this._images.clear();for(const e of this._kittyIdToStorageId.values())this._storage.deleteImage(e);this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}get images(){return this._images}get kittyIdToStorageId(){return this._kittyIdToStorageId}get lastImageId(){return this._nextImageId-1}_evictUndisplayedImages(){for(const[e]of this._images){if(this._images.size<=i._maxStoredImages/2)break;this._kittyIdToStorageId.has(e)||this._images.delete(e)}}}t.KittyImageStorage=i,i._maxStoredImages=256},669(e,t,i){Object.defineProperty(t,"__esModule",{value:!0});const A=(0,i(552).InWasm)({s:1,t:0,d:"AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML"}),s=new Uint8Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map(e=>e.charCodeAt(0))),r=new Uint32Array(1024);r.fill(4278190080);for(let e=0;e>4|(e<<4&255)<<8;for(let e=0;e>2<<8|(e<<6&255)<<16;for(let e=0;ethis.maxBytes||this.maxBytes>4294901760)throw new Error("invalid byte settings")}get data8(){return this._inst?this._d.subarray(0,this._m32[1282]):o}release(){this._inst&&(this._bytes>this.keepSize?this._inst=this._m32=this._d=this._mem=null:(this._m32[1280]=0,this._m32[1281]=0,this._m32[1282]=0))}init(e,t){if(this.maxBytes=null!=e?e:this.maxBytes,this._bytes=null!=t?t:Math.min(this._bytes,this.maxBytes),this._bytes>this.maxBytes||this.maxBytes>4294901760)throw Error("invalid byte settings");let i=this._m32;const s=this._bytes+5152;this._inst?this._mem.buffer.byteLengththis.maxBytes)return-3;let e=this._bytes;for(;(e*=2)this._mem.buffer.byteLength){const t=Math.ceil((e+5152-this._mem.buffer.byteLength)/65536);this._mem.grow(t),this._m32=new Uint32Array(this._mem.buffer,0),this._d=new Uint8Array(this._mem.buffer,5152)}this._bytes=e}return 0}put(e){if(!this._inst||this._ended)return-2;if(this._realloc(e.length))return-3;const t=this._m32;return this._d.set(e,t[1280]),t[1280]+=e.length,t[1280]-t[1281]>=131072?this._inst.exports.dec():0}end(){return this._ended=!0,this._inst?this._inst.exports.end():-2}get loadedBytes(){return this._inst?this._m32[1280]:0}get freeBytes(){return this._inst?this.maxBytes-this._m32[1280]:0}}},61(e,t,i){Object.defineProperty(t,"__esModule",{value:!0});const A=(0,i(552).InWasm)({s:1,t:0,d:"AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=="});t.default=class{constructor(e){this.keepSize=e,this.width=0,this.height=0}decode(e){this.width=e[4]<<24|e[5]<<16|e[6]<<8|e[7],this.height=e[8]<<24|e[9]<<16|e[10]<<8|e[11];const t=this.width*this.height,i=4*t,s=e.length,r=Math.max(i,s)+(Math.min(i,s)>>1)+4096;this._inst?this._mem.buffer.byteLengththis.keepSize&&(this._inst=this._d=this._mem=null)}}},552(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.InWasm=function(e){if(e.d){const{t,s:A,d:s}=e;let r,o;const a=WebAssembly;return 0===t?A?e=>new a.Instance(o||(o=new a.Module(r||(r=i(s)))),e):e=>o?a.instantiate(o,e):a.instantiate(r||(r=i(s)),e).then(e=>(o=e.module)&&e.instance):1===t?A?()=>o||(o=new a.Module(r||(r=i(s)))):()=>o?Promise.resolve(o):a.compile(r||(r=i(s))).then(e=>o=e):A?()=>r||(r=i(s)):()=>Promise.resolve(r||(r=i(s)))}if("undefined"==typeof _wasmCtx)throw new Error('must run "inwasm"');_wasmCtx.add(e)};let i=e=>{if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);if("undefined"!=typeof Buffer)return Buffer.from(e,"base64");const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e{var e=A;Object.defineProperty(e,"__esModule",{value:!0}),e.ImageAddon=void 0;const t=i(414),s=i(795),r=i(463),o=i(699),a=i(23),n=i(235),h=i(566),g=i(994),d=i(649),l={enableSizeReports:!0,pixelLimit:16777216,sixelSupport:!0,sixelScrolling:!0,sixelPaletteLimit:4096,sixelSizeLimit:33554432,storageLimit:128,showPlaceholder:!0,iipSupport:!0,iipSizeLimit:33554432,kittySupport:!0,kittySizeLimit:33554432};e.ImageAddon=class{constructor(e){this._disposables=[],this._handlers=new Map,this._onImageAdded=new t.Emitter,this.onImageAdded=this._onImageAdded.event,this._opts=Object.assign({},l,e),this._defaultOpts=Object.assign({},l,e)}dispose(){for(const e of this._handlers.values())e.reset();for(const e of this._disposables)e.dispose();this._disposables.length=0,this._handlers.clear(),this._onImageAdded.dispose()}_disposeLater(...e){for(const t of e)this._disposables.push(t)}activate(e){var t;if(this._terminal=e,this._renderer=new r.ImageRenderer(e),this._storage=new o.ImageStorage(e,this._renderer,this._opts),this._storage.onImageAdded=()=>this._onImageAdded.fire(),this._opts.enableSizeReports){const i=null!==(t=e.options.windowOptions)&&void 0!==t?t:{};i.getWinSizePixels=!0,i.getCellSizePixels=!0,i.getWinSizeChars=!0,e.options.windowOptions=i}if(this._disposeLater(this._renderer,this._storage,e.parser.registerCsiHandler({prefix:"?",final:"h"},e=>this._decset(e)),e.parser.registerCsiHandler({prefix:"?",final:"l"},e=>this._decrst(e)),e.parser.registerCsiHandler({final:"c"},e=>this._da1(e)),e.parser.registerCsiHandler({prefix:"?",final:"S"},e=>this._xtermGraphicsAttributes(e)),e.onRender(e=>{var t;return null===(t=this._storage)||void 0===t?void 0:t.render(e)}),e.parser.registerCsiHandler({intermediates:"!",final:"p"},()=>this.reset()),e.parser.registerEscHandler({final:"c"},()=>this.reset()),e._core._inputHandler.onRequestReset(()=>this.reset()),e.buffer.onBufferChange(()=>{var e;return null===(e=this._storage)||void 0===e?void 0:e.wipeAlternate()}),e.onResize(e=>{var t;return null===(t=this._storage)||void 0===t?void 0:t.viewportResize(e)})),this._opts.sixelSupport){const t=new g.SixelImageStorage(this._storage,this._opts,this._renderer,e),i=new h.SixelHandler(this._opts,t,e);this._handlers.set("sixel",i),this._disposeLater(e._core._inputHandler._parser.registerDcsHandler({final:"q"},i))}if(this._opts.iipSupport){const t=new d.IIPImageStorage(this._storage),i=new s.IIPHandler(this._opts,this._renderer,t,e);this._handlers.set("iip",i),this._disposeLater(e._core._inputHandler._parser.registerOscHandler(1337,i))}if(this._opts.kittySupport){const t=new n.KittyImageStorage(this._storage),i=new a.KittyGraphicsHandler(this._opts,this._renderer,t,e);this._handlers.set("kitty",i),this._disposeLater(t,i,e._core._inputHandler._parser.registerApcHandler({final:"G"},i))}}reset(){var e;this._opts.sixelScrolling=this._defaultOpts.sixelScrolling,this._opts.sixelPaletteLimit=this._defaultOpts.sixelPaletteLimit,null===(e=this._storage)||void 0===e||e.reset();for(const e of this._handlers.values())e.reset();return!1}get storageLimit(){var e;return(null===(e=this._storage)||void 0===e?void 0:e.getLimit())||-1}set storageLimit(e){var t;null===(t=this._storage)||void 0===t||t.setLimit(e),this._opts.storageLimit=e}get storageUsage(){return this._storage?this._storage.getUsage():-1}get showPlaceholder(){return this._opts.showPlaceholder}set showPlaceholder(e){var t;this._opts.showPlaceholder=e,null===(t=this._renderer)||void 0===t||t.showPlaceholder(e)}getImageAtBufferCell(e,t){var i;return null===(i=this._storage)||void 0===i?void 0:i.getImageAtBufferCell(e,t)}extractTileAtBufferCell(e,t){var i;return null===(i=this._storage)||void 0===i?void 0:i.extractTileAtBufferCell(e,t)}_report(e){var t;null===(t=this._terminal)||void 0===t||t._core.input(e,!1)}_decset(e){for(let t=0;t2&&!(e[2]instanceof Array)&&e[2]<=4096?(this._opts.sixelPaletteLimit=e[2],this._report(`[?${e[0]};0;${this._opts.sixelPaletteLimit}S`)):this._report(`[?${e[0]};2S`),!0;case 4:return this._report(`[?${e[0]};0;4096S`),!0;default:return this._report(`[?${e[0]};2S`),!0}if(2===e[0])switch(e[1]){case 1:let n=null===(i=null===(t=this._renderer)||void 0===t?void 0:t.dimensions)||void 0===i?void 0:i.css.canvas.width,h=null===(s=null===(A=this._renderer)||void 0===A?void 0:A.dimensions)||void 0===s?void 0:s.css.canvas.height;if(!n||!h){const e=o.CELL_SIZE_DEFAULT;n=((null===(r=this._terminal)||void 0===r?void 0:r.cols)||80)*e.width,h=((null===(a=this._terminal)||void 0===a?void 0:a.rows)||24)*e.height}if(n*h {\nreturn ","\"use strict\";\n/**\n * Copyright (c) 2019 Joerg Breitbart.\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DEFAULT_FOREGROUND = exports.DEFAULT_BACKGROUND = exports.PALETTE_ANSI_256 = exports.PALETTE_VT340_GREY = exports.PALETTE_VT340_COLOR = exports.normalizeHLS = exports.normalizeRGB = exports.nearestColorIndex = exports.fromRGBA8888 = exports.toRGBA8888 = exports.alpha = exports.blue = exports.green = exports.red = exports.BIG_ENDIAN = void 0;\n// FIXME: cleanup this mess, move things either to decoder/encoder, keep only shared things\n// system endianess\nexports.BIG_ENDIAN = new Uint8Array(new Uint32Array([0xFF000000]).buffer)[0] === 0xFF;\nif (exports.BIG_ENDIAN) {\n console.warn('BE platform detected. This version of node-sixel works only on LE properly.');\n}\n// channel values\nfunction red(n) {\n return n & 0xFF;\n}\nexports.red = red;\nfunction green(n) {\n return (n >>> 8) & 0xFF;\n}\nexports.green = green;\nfunction blue(n) {\n return (n >>> 16) & 0xFF;\n}\nexports.blue = blue;\nfunction alpha(n) {\n return (n >>> 24) & 0xFF;\n}\nexports.alpha = alpha;\n/**\n * Convert RGB channels to native color RGBA8888.\n */\nfunction toRGBA8888(r, g, b, a = 255) {\n return ((a & 0xFF) << 24 | (b & 0xFF) << 16 | (g & 0xFF) << 8 | (r & 0xFF)) >>> 0; // ABGR32\n}\nexports.toRGBA8888 = toRGBA8888;\n/**\n * Convert native color to [r, g, b, a].\n */\nfunction fromRGBA8888(color) {\n return [color & 0xFF, (color >> 8) & 0xFF, (color >> 16) & 0xFF, color >>> 24];\n}\nexports.fromRGBA8888 = fromRGBA8888;\n/**\n * Get index of nearest color in `palette` for `color`.\n * Uses euclidean distance without any luminescence correction.\n */\nfunction nearestColorIndex(color, palette) {\n const r = red(color);\n const g = green(color);\n const b = blue(color);\n let min = Number.MAX_SAFE_INTEGER;\n let idx = -1;\n // use euclidean distance (manhattan gives very poor results)\n for (let i = 0; i < palette.length; ++i) {\n const dr = r - palette[i][0];\n const dg = g - palette[i][1];\n const db = b - palette[i][2];\n const d = dr * dr + dg * dg + db * db;\n if (!d)\n return i;\n if (d < min) {\n min = d;\n idx = i;\n }\n }\n return idx;\n}\nexports.nearestColorIndex = nearestColorIndex;\n// color conversions\n// HLS taken from: http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl\nfunction clamp(low, high, value) {\n return Math.max(low, Math.min(value, high));\n}\nfunction h2c(t1, t2, c) {\n if (c < 0)\n c += 1;\n if (c > 1)\n c -= 1;\n return c * 6 < 1\n ? t2 + (t1 - t2) * 6 * c\n : c * 2 < 1\n ? t1\n : c * 3 < 2\n ? t2 + (t1 - t2) * (4 - c * 6)\n : t2;\n}\nfunction HLStoRGB(h, l, s) {\n if (!s) {\n const v = Math.round(l * 255);\n return toRGBA8888(v, v, v);\n }\n const t1 = l < 0.5 ? l * (1 + s) : l + s - l * s;\n const t2 = 2 * l - t1;\n return toRGBA8888(clamp(0, 255, Math.round(h2c(t1, t2, h + 1 / 3) * 255)), clamp(0, 255, Math.round(h2c(t1, t2, h) * 255)), clamp(0, 255, Math.round(h2c(t1, t2, h - 1 / 3) * 255)));\n}\n/**\n * Normalize SIXEL RGB values (percent based, 0-100) to RGBA8888.\n */\nfunction normalizeRGB(r, g, b) {\n return (0xFF000000 | Math.round(b / 100 * 255) << 16 | Math.round(g / 100 * 255) << 8 | Math.round(r / 100 * 255)) >>> 0; // ABGR32\n}\nexports.normalizeRGB = normalizeRGB;\n/**\n * Normalize SIXEL HLS values to RGBA8888. Applies hue correction of +240°.\n */\nfunction normalizeHLS(h, l, s) {\n // Note: hue value is turned by 240° in VT340, all values given as fractions\n return HLStoRGB((h + 240 % 360) / 360, l / 100, s / 100);\n}\nexports.normalizeHLS = normalizeHLS;\n/**\n * default palettes\n */\n// FIXME: move palettes to Decoder.ts\n/**\n * 16 predefined color registers of VT340 (values in %):\n * ```\n * R G B\n * 0 Black 0 0 0\n * 1 Blue 20 20 80\n * 2 Red 80 13 13\n * 3 Green 20 80 20\n * 4 Magenta 80 20 80\n * 5 Cyan 20 80 80\n * 6 Yellow 80 80 20\n * 7 Gray 50% 53 53 53\n * 8 Gray 25% 26 26 26\n * 9 Blue* 33 33 60\n * 10 Red* 60 26 26\n * 11 Green* 33 60 33\n * 12 Magenta* 60 33 60\n * 13 Cyan* 33 60 60\n * 14 Yellow* 60 60 33\n * 15 Gray 75% 80 80 80\n * ```\n * (*) less saturated\n *\n * @see https://vt100.net/docs/vt3xx-gp/chapter2.html#S2.4\n*/\nexports.PALETTE_VT340_COLOR = new Uint32Array([\n normalizeRGB(0, 0, 0),\n normalizeRGB(20, 20, 80),\n normalizeRGB(80, 13, 13),\n normalizeRGB(20, 80, 20),\n normalizeRGB(80, 20, 80),\n normalizeRGB(20, 80, 80),\n normalizeRGB(80, 80, 20),\n normalizeRGB(53, 53, 53),\n normalizeRGB(26, 26, 26),\n normalizeRGB(33, 33, 60),\n normalizeRGB(60, 26, 26),\n normalizeRGB(33, 60, 33),\n normalizeRGB(60, 33, 60),\n normalizeRGB(33, 60, 60),\n normalizeRGB(60, 60, 33),\n normalizeRGB(80, 80, 80)\n]);\n/**\n * 16 predefined monochrome registers of VT340 (values in %):\n * ```\n * R G B\n * 0 Black 0 0 0\n * 1 Gray-2 13 13 13\n * 2 Gray-4 26 26 26\n * 3 Gray-6 40 40 40\n * 4 Gray-1 6 6 6\n * 5 Gray-3 20 20 20\n * 6 Gray-5 33 33 33\n * 7 White 7 46 46 46\n * 8 Black 0 0 0 0\n * 9 Gray-2 13 13 13\n * 10 Gray-4 26 26 26\n * 11 Gray-6 40 40 40\n * 12 Gray-1 6 6 6\n * 13 Gray-3 20 20 20\n * 14 Gray-5 33 33 33\n * 15 White 7 46 46 46\n * ```\n *\n * @see https://vt100.net/docs/vt3xx-gp/chapter2.html#S2.4\n */\nexports.PALETTE_VT340_GREY = new Uint32Array([\n normalizeRGB(0, 0, 0),\n normalizeRGB(13, 13, 13),\n normalizeRGB(26, 26, 26),\n normalizeRGB(40, 40, 40),\n normalizeRGB(6, 6, 6),\n normalizeRGB(20, 20, 20),\n normalizeRGB(33, 33, 33),\n normalizeRGB(46, 46, 46),\n normalizeRGB(0, 0, 0),\n normalizeRGB(13, 13, 13),\n normalizeRGB(26, 26, 26),\n normalizeRGB(40, 40, 40),\n normalizeRGB(6, 6, 6),\n normalizeRGB(20, 20, 20),\n normalizeRGB(33, 33, 33),\n normalizeRGB(46, 46, 46)\n]);\n/**\n * 256 predefined ANSI colors.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit\n */\nexports.PALETTE_ANSI_256 = (() => {\n // 16 lower colors (taken from xterm)\n const p = [\n toRGBA8888(0, 0, 0),\n toRGBA8888(205, 0, 0),\n toRGBA8888(0, 205, 0),\n toRGBA8888(205, 205, 0),\n toRGBA8888(0, 0, 238),\n toRGBA8888(205, 0, 205),\n toRGBA8888(0, 250, 205),\n toRGBA8888(229, 229, 229),\n toRGBA8888(127, 127, 127),\n toRGBA8888(255, 0, 0),\n toRGBA8888(0, 255, 0),\n toRGBA8888(255, 255, 0),\n toRGBA8888(92, 92, 255),\n toRGBA8888(255, 0, 255),\n toRGBA8888(0, 255, 255),\n toRGBA8888(255, 255, 255),\n ];\n // colors up to 232\n const d = [0, 95, 135, 175, 215, 255];\n for (let r = 0; r < 6; ++r) {\n for (let g = 0; g < 6; ++g) {\n for (let b = 0; b < 6; ++b) {\n p.push(toRGBA8888(d[r], d[g], d[b]));\n }\n }\n }\n // grey scale to up 255\n for (let v = 8; v <= 238; v += 10) {\n p.push(toRGBA8888(v, v, v));\n }\n return new Uint32Array(p);\n})();\n/**\n * Background: Black by default.\n * Foreground: White by default.\n *\n * Background color is used whenever a fill color is needed and not explicitly set.\n * Foreground color is used as default initial sixel color.\n */\nexports.DEFAULT_BACKGROUND = toRGBA8888(0, 0, 0, 255);\nexports.DEFAULT_FOREGROUND = toRGBA8888(255, 255, 255, 255);\n//# sourceMappingURL=Colors.js.map","\"use strict\";\n/**\n * Copyright (c) 2021 Joerg Breitbart.\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.decodeAsync = exports.decode = exports.Decoder = exports.DecoderAsync = void 0;\nconst Colors_1 = require(\"./Colors\");\nconst wasm_1 = require(\"./wasm\");\n/* istanbul ignore next */\nfunction decodeBase64(s) {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(s, 'base64');\n }\n const bytestring = atob(s);\n const result = new Uint8Array(bytestring.length);\n for (let i = 0; i < result.length; ++i) {\n result[i] = bytestring.charCodeAt(i);\n }\n return result;\n}\nconst WASM_BYTES = decodeBase64(wasm_1.LIMITS.BYTES);\nlet WASM_MODULE;\n// empty canvas\nconst NULL_CANVAS = new Uint32Array();\n// proxy for lazy binding of decoder methods to wasm env callbacks\nclass CallbackProxy {\n constructor() {\n this.bandHandler = (width) => 1;\n this.modeHandler = (mode) => 1;\n }\n handle_band(width) {\n return this.bandHandler(width);\n }\n mode_parsed(mode) {\n return this.modeHandler(mode);\n }\n}\n// default decoder options\nconst DEFAULT_OPTIONS = {\n memoryLimit: 2048 * 65536,\n sixelColor: Colors_1.DEFAULT_FOREGROUND,\n fillColor: Colors_1.DEFAULT_BACKGROUND,\n palette: Colors_1.PALETTE_VT340_COLOR,\n paletteLimit: wasm_1.LIMITS.PALETTE_SIZE,\n truncate: true\n};\n/**\n * Create a decoder instance asynchronously.\n * To be used in the browser main thread.\n */\nfunction DecoderAsync(opts) {\n const cbProxy = new CallbackProxy();\n const importObj = {\n env: {\n handle_band: cbProxy.handle_band.bind(cbProxy),\n mode_parsed: cbProxy.mode_parsed.bind(cbProxy)\n }\n };\n return WebAssembly.instantiate(WASM_MODULE || WASM_BYTES, importObj)\n .then((inst) => {\n WASM_MODULE = WASM_MODULE || inst.module;\n return new Decoder(opts, inst.instance || inst, cbProxy);\n });\n}\nexports.DecoderAsync = DecoderAsync;\n/**\n * Decoder - web assembly based sixel stream decoder.\n *\n * Usage pattern:\n * - call `init` to initialize decoder for new image\n * - feed data chunks to `decode` or `decodeString`\n * - grab pixels from `data32`\n * - optional: call `release` to free memory (e.g. after big images)\n * - start over with next image by calling `init`\n *\n * Properties:\n * - max width of 2^14 - 4 pixels (compile time setting in wasm)\n * - no explicit height limit (only limited by memory)\n * - max 4096 colors palette (compile time setting in wasm)\n *\n * Explanation operation modes:\n * - M1 Mode chosen for level 1 images (no raster attributes),\n * or for level 2 images with `truncate=false`.\n * - M2 Mode chosen for level 2 images with `truncate=true` (default).\n * While this mode is not fully spec conform (decoder not expected to truncate),\n * it is what spec conform encoders should create (should not excess raster).\n * This mode has several advantages:\n * - ~15% faster decoding speed\n * - image dimensions can be evaluated early without processing the whole data\n * - faster pixel access in `data32` (precalulated)\n * - image height is not reported as multiple of 6 pixels\n * - M0 Undecided mode state after `init`.\n * The level of an image is determined during early decoding based on the fact,\n * whether the data contains valid raster attributes before any sixel data.\n * Until then the mode of an image is marked as M0, meaning the real operation mode\n * could not be decided yet.\n */\nclass Decoder {\n /**\n * Synchonous ctor. Can be called from nodejs or a webworker context.\n * For instantiation in the browser main thread use `WasmDecoderAsync` instead.\n */\n constructor(opts, _instance, _cbProxy) {\n this._PIXEL_OFFSET = wasm_1.LIMITS.MAX_WIDTH + 4;\n this._canvas = NULL_CANVAS;\n this._bandWidths = [];\n this._maxWidth = 0;\n this._minWidth = wasm_1.LIMITS.MAX_WIDTH;\n this._lastOffset = 0;\n this._currentHeight = 0;\n this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);\n if (this._opts.paletteLimit > wasm_1.LIMITS.PALETTE_SIZE) {\n throw new Error(`DecoderOptions.paletteLimit must not exceed ${wasm_1.LIMITS.PALETTE_SIZE}`);\n }\n if (!_instance) {\n const module = WASM_MODULE || (WASM_MODULE = new WebAssembly.Module(WASM_BYTES));\n _instance = new WebAssembly.Instance(module, {\n env: {\n handle_band: this._handle_band.bind(this),\n mode_parsed: this._initCanvas.bind(this)\n }\n });\n }\n else {\n _cbProxy.bandHandler = this._handle_band.bind(this);\n _cbProxy.modeHandler = this._initCanvas.bind(this);\n }\n this._instance = _instance;\n this._wasm = this._instance.exports;\n this._chunk = new Uint8Array(this._wasm.memory.buffer, this._wasm.get_chunk_address(), wasm_1.LIMITS.CHUNK_SIZE);\n this._states = new Uint32Array(this._wasm.memory.buffer, this._wasm.get_state_address(), 12);\n this._palette = new Uint32Array(this._wasm.memory.buffer, this._wasm.get_palette_address(), wasm_1.LIMITS.PALETTE_SIZE);\n this._palette.set(this._opts.palette);\n this._pSrc = new Uint32Array(this._wasm.memory.buffer, this._wasm.get_p0_address());\n this._wasm.init(Colors_1.DEFAULT_FOREGROUND, 0, this._opts.paletteLimit, 0);\n }\n // some readonly parser states for internal usage\n get _fillColor() { return this._states[0]; }\n get _truncate() { return this._states[8]; }\n get _rasterWidth() { return this._states[6]; }\n get _rasterHeight() { return this._states[7]; }\n get _width() { return this._states[2] ? this._states[2] - 4 : 0; }\n get _height() { return this._states[3]; }\n get _level() { return this._states[9]; }\n get _mode() { return this._states[10]; }\n get _paletteLimit() { return this._states[11]; }\n _initCanvas(mode) {\n if (mode === 2 /* M2 */) {\n const pixels = this.width * this.height;\n if (pixels > this._canvas.length) {\n if (this._opts.memoryLimit && pixels * 4 > this._opts.memoryLimit) {\n this.release();\n throw new Error('image exceeds memory limit');\n }\n this._canvas = new Uint32Array(pixels);\n }\n this._maxWidth = this._width;\n }\n else if (mode === 1 /* M1 */) {\n if (this._level === 2) {\n // got raster attributes, use them as initial size hint\n const pixels = Math.min(this._rasterWidth, wasm_1.LIMITS.MAX_WIDTH) * this._rasterHeight;\n if (pixels > this._canvas.length) {\n if (this._opts.memoryLimit && pixels * 4 > this._opts.memoryLimit) {\n this.release();\n throw new Error('image exceeds memory limit');\n }\n this._canvas = new Uint32Array(pixels);\n }\n }\n else {\n // else fallback to generic resizing, starting with 256*256 pixels\n if (this._canvas.length < 65536) {\n this._canvas = new Uint32Array(65536);\n }\n }\n }\n return 0; // 0 - continue, 1 - abort right away\n }\n _realloc(offset, additionalPixels) {\n const pixels = offset + additionalPixels;\n if (pixels > this._canvas.length) {\n if (this._opts.memoryLimit && pixels * 4 > this._opts.memoryLimit) {\n this.release();\n throw new Error('image exceeds memory limit');\n }\n // extend in 65536 pixel blocks\n const newCanvas = new Uint32Array(Math.ceil(pixels / 65536) * 65536);\n newCanvas.set(this._canvas);\n this._canvas = newCanvas;\n }\n }\n _handle_band(width) {\n const adv = this._PIXEL_OFFSET;\n let offset = this._lastOffset;\n if (this._mode === 2 /* M2 */) {\n let remaining = this.height - this._currentHeight;\n let c = 0;\n while (c < 6 && remaining > 0) {\n this._canvas.set(this._pSrc.subarray(adv * c, adv * c + width), offset + width * c);\n c++;\n remaining--;\n }\n this._lastOffset += width * c;\n this._currentHeight += c;\n }\n else if (this._mode === 1 /* M1 */) {\n this._realloc(offset, width * 6);\n this._maxWidth = Math.max(this._maxWidth, width);\n this._minWidth = Math.min(this._minWidth, width);\n for (let i = 0; i < 6; ++i) {\n this._canvas.set(this._pSrc.subarray(adv * i, adv * i + width), offset + width * i);\n }\n this._bandWidths.push(width);\n this._lastOffset += width * 6;\n this._currentHeight += 6;\n }\n return 0; // 0 - continue, 1 - abort right away\n }\n /**\n * Width of the image data.\n * Returns the rasterWidth in level2/truncating mode,\n * otherwise the max width, that has been seen so far.\n */\n get width() {\n return this._mode !== 1 /* M1 */\n ? this._width\n : Math.max(this._maxWidth, this._wasm.current_width());\n }\n /**\n * Height of the image data.\n * Returns the rasterHeight in level2/truncating mode,\n * otherwise height touched by sixels.\n */\n get height() {\n return this._mode !== 1 /* M1 */\n ? this._height\n : this._wasm.current_width()\n ? this._bandWidths.length * 6 + this._wasm.current_height()\n : this._bandWidths.length * 6;\n }\n /**\n * Get active palette colors as RGBA8888[] (borrowed).\n */\n get palette() {\n return this._palette.subarray(0, this._paletteLimit);\n }\n /**\n * Get the memory used by the decoder.\n *\n * This is a rough estimate accounting the wasm instance memory\n * and pixel buffers held on JS side (real value will be slightly\n * higher due to JS book-keeping).\n * Note that the decoder does not free ressources on its own,\n * call `release` to free excess memory.\n */\n get memoryUsage() {\n return this._canvas.byteLength + this._wasm.memory.buffer.byteLength + 8 * this._bandWidths.length;\n }\n /**\n * Get various properties of the decoder and the current image.\n */\n get properties() {\n return {\n width: this.width,\n height: this.height,\n mode: this._mode,\n level: this._level,\n truncate: !!this._truncate,\n paletteLimit: this._paletteLimit,\n fillColor: this._fillColor,\n memUsage: this.memoryUsage,\n rasterAttributes: {\n numerator: this._states[4],\n denominator: this._states[5],\n width: this._rasterWidth,\n height: this._rasterHeight,\n }\n };\n }\n /**\n * Initialize decoder for next image. Must be called before\n * any calls to `decode` or `decodeString`.\n */\n // FIXME: reorder arguments, better palette handling\n init(fillColor = this._opts.fillColor, palette = this._opts.palette, paletteLimit = this._opts.paletteLimit, truncate = this._opts.truncate) {\n this._wasm.init(this._opts.sixelColor, fillColor, paletteLimit, truncate ? 1 : 0);\n if (palette) {\n this._palette.set(palette.subarray(0, wasm_1.LIMITS.PALETTE_SIZE));\n }\n this._bandWidths.length = 0;\n this._maxWidth = 0;\n this._minWidth = wasm_1.LIMITS.MAX_WIDTH;\n this._lastOffset = 0;\n this._currentHeight = 0;\n }\n /**\n * Decode next chunk of data from start to end index (exclusive).\n * @throws Will throw if the image exceeds the memory limit.\n */\n decode(data, start = 0, end = data.length) {\n let p = start;\n while (p < end) {\n const length = Math.min(end - p, wasm_1.LIMITS.CHUNK_SIZE);\n this._chunk.set(data.subarray(p, p += length));\n this._wasm.decode(0, length);\n }\n }\n /**\n * Decode next chunk of string data from start to end index (exclusive).\n * Note: Decoding from string data is rather slow, use `decode` with byte data instead.\n * @throws Will throw if the image exceeds the memory limit.\n */\n decodeString(data, start = 0, end = data.length) {\n let p = start;\n while (p < end) {\n const length = Math.min(end - p, wasm_1.LIMITS.CHUNK_SIZE);\n for (let i = 0, j = p; i < length; ++i, ++j) {\n this._chunk[i] = data.charCodeAt(j);\n }\n p += length;\n this._wasm.decode(0, length);\n }\n }\n /**\n * Get current pixel data as 32-bit typed array (RGBA8888).\n * Also peeks into pixel data of the current band, that got not pushed yet.\n */\n get data32() {\n if (this._mode === 0 /* M0 */ || !this.width || !this.height) {\n return NULL_CANVAS;\n }\n // get width of pending band to peek into left-over data\n const currentWidth = this._wasm.current_width();\n if (this._mode === 2 /* M2 */) {\n let remaining = this.height - this._currentHeight;\n if (remaining > 0) {\n const adv = this._PIXEL_OFFSET;\n let offset = this._lastOffset;\n let c = 0;\n while (c < 6 && remaining > 0) {\n this._canvas.set(this._pSrc.subarray(adv * c, adv * c + currentWidth), offset + currentWidth * c);\n c++;\n remaining--;\n }\n if (remaining) {\n this._canvas.fill(this._fillColor, offset + currentWidth * c);\n }\n }\n return this._canvas.subarray(0, this.width * this.height);\n }\n if (this._mode === 1 /* M1 */) {\n if (this._minWidth === this._maxWidth) {\n let escape = false;\n if (currentWidth) {\n if (currentWidth !== this._minWidth) {\n escape = true;\n }\n else {\n const adv = this._PIXEL_OFFSET;\n let offset = this._lastOffset;\n this._realloc(offset, currentWidth * 6);\n for (let i = 0; i < 6; ++i) {\n this._canvas.set(this._pSrc.subarray(adv * i, adv * i + currentWidth), offset + currentWidth * i);\n }\n }\n }\n if (!escape) {\n return this._canvas.subarray(0, this.width * this.height);\n }\n }\n // worst case: re-align pixels if we have bands with different width\n // This is somewhat allocation intensive, any way to do that in-place, and just once?\n const final = new Uint32Array(this.width * this.height);\n final.fill(this._fillColor);\n let finalOffset = 0;\n let start = 0;\n for (let i = 0; i < this._bandWidths.length; ++i) {\n const bw = this._bandWidths[i];\n for (let p = 0; p < 6; ++p) {\n final.set(this._canvas.subarray(start, start += bw), finalOffset);\n finalOffset += this.width;\n }\n }\n // also handle left-over pixels of the current band\n if (currentWidth) {\n const adv = this._PIXEL_OFFSET;\n // other than finished bands, this runs only up to currentHeight\n const currentHeight = this._wasm.current_height();\n for (let i = 0; i < currentHeight; ++i) {\n final.set(this._pSrc.subarray(adv * i, adv * i + currentWidth), finalOffset + this.width * i);\n }\n }\n return final;\n }\n // fallthrough for all not handled cases\n return NULL_CANVAS;\n }\n /**\n * Same as `data32`, but returning pixel data as Uint8ClampedArray suitable\n * for direct usage with `ImageData`.\n */\n get data8() {\n return new Uint8ClampedArray(this.data32.buffer, 0, this.width * this.height * 4);\n }\n /**\n * Release image ressources on JS side held by the decoder.\n *\n * The decoder tries to re-use memory ressources of a previous image\n * to lower allocation and GC pressure. Decoding a single big image\n * will grow the memory usage of the decoder permanently.\n * Call `release` to reset the internal buffers and free the memory.\n * Note that this destroys the image data, call it when done processing\n * a rather big image, otherwise it is not needed. Use `memoryUsage`\n * to decide, whether the held memory is still within your limits.\n * This does not affect the wasm module (operates on static memory).\n */\n release() {\n this._canvas = NULL_CANVAS;\n this._bandWidths.length = 0;\n this._maxWidth = 0;\n this._minWidth = wasm_1.LIMITS.MAX_WIDTH;\n // also nullify parser states in wasm to avoid\n // width/height reporting potential out-of-bound values\n this._wasm.init(Colors_1.DEFAULT_FOREGROUND, 0, this._opts.paletteLimit, 0);\n }\n}\nexports.Decoder = Decoder;\n/**\n * Convenient decoding functions for easier usage.\n *\n * These can be used for casual decoding of sixel images,\n * that dont come in as stream chunks.\n * Note that the functions instantiate a stream decoder for every call,\n * which comes with a performance penalty of ~25%.\n */\n/**\n * Decode function with synchronous wasm loading.\n * Can be used in a web worker or in nodejs. Does not work reliable in normal browser context.\n * @throws Will throw if the image exceeds the memory limit.\n */\nfunction decode(data, opts) {\n const dec = new Decoder(opts);\n dec.init();\n typeof data === 'string' ? dec.decodeString(data) : dec.decode(data);\n return {\n width: dec.width,\n height: dec.height,\n data32: dec.data32,\n data8: dec.data8\n };\n}\nexports.decode = decode;\n/**\n * Decode function with asynchronous wasm loading.\n * Use this version in normal browser context.\n * @throws Will throw if the image exceeds the memory limit.\n */\nasync function decodeAsync(data, opts) {\n const dec = await DecoderAsync(opts);\n dec.init();\n typeof data === 'string' ? dec.decodeString(data) : dec.decode(data);\n return {\n width: dec.width,\n height: dec.height,\n data32: dec.data32,\n data8: dec.data8\n };\n}\nexports.decodeAsync = decodeAsync;\n//# sourceMappingURL=Decoder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LIMITS = void 0;\nexports.LIMITS = {\n CHUNK_SIZE: 16384,\n PALETTE_SIZE: 4096,\n MAX_WIDTH: 16384,\n BYTES: 'AGFzbQEAAAABJAdgAAF/YAJ/fwBgA39/fwF/YAF/AX9gAABgBH9/f38AYAF/AAIlAgNlbnYLaGFuZGxlX2JhbmQAAwNlbnYLbW9kZV9wYXJzZWQAAwMTEgQAAAAAAQQBAQUBAAACAgAGAwQFAXABBwcFBAEBBwcGCAF/AUGAihoLB9wBDgZtZW1vcnkCABFnZXRfc3RhdGVfYWRkcmVzcwADEWdldF9jaHVua19hZGRyZXNzAAQOZ2V0X3AwX2FkZHJlc3MABRNnZXRfcGFsZXR0ZV9hZGRyZXNzAAYEaW5pdAALBmRlY29kZQAMDWN1cnJlbnRfd2lkdGgADQ5jdXJyZW50X2hlaWdodAAOGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtfaW5pdGlhbGl6ZQACCXN0YWNrU2F2ZQARDHN0YWNrUmVzdG9yZQASCnN0YWNrQWxsb2MAEwkMAQBBAQsGCgcJDxACDAEBCq5UEgMAAQsFAEGgCAsGAEGQiQELBgBBsIkCCwUAQZAJC+okAQh/QeQIKAIAIQVB4AgoAgAhA0HoCCgCACEIIAFBkIkBaiIJQf8BOgAAIAAgAUgEQCAAQZCJAWohBgNAIAMhBCAGQQFqIQECQCAGLQAAQf8AcSIDQTBrQQlLBEAgASEGDAELQewIKAIAQQJ0QewIaiICKAIAIQADQCACIAMgAEEKbGpBM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DAEHoigIgADcDAEHgigIgADcDAEHYigIgADcDAEHQigIgADcDAEHIigIgADcDAEHAigIgADcDAEG4igIgADcDAEGwigIgADcDAEGoigIgADcDAEGgigIgADcDAEGYigIgADcDAEGQigIgADcDAEGIigIgADcDAEGAigIgADcDAEH4iQIgADcDAEHwiQIgADcDAEHoiQIgADcDAEHgiQIgADcDAEHYiQIgADcDAEHQiQIgADcDAEHIiQIgADcDAEHAiQIgADcDAEG4iQIgADcDAEGwiQIgADcDAEGoCCgCACIEQf8AakGAAW0hCAJAIARBgQFIDQBBASEBIAhBAiAIQQJKG0EBayICQQFxIQMgBEGBAk4EQCACQX5xIQIDQCABQQl0IgdBEHJBoIkCakGwiQJBgAT8CgAAIAdBsI0CakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsLIANFDQAgAUEJdEEQckGgiQJqQbCJAkGABPwKAAALAkAgBEEBSA0AIAhBASAIQQFKGyIDQQFxIQUCQCADQQFrIgdFBEBBACEBDAELIANB/v///wdxIQJBACEBA0AgAUEJdCIGQRByQbCJBmpBsIkCQYAE/AoAACAGQZAEckGwiQZqQbCJAkGABPwKAAAgAUECaiEBIAJBAmsiAg0ACwsgBQRAIAFBCXRBEHJBsIkGakGwiQJBgAT8CgAACyAEQQFIDQAgA0EBcSEFIAcEfyADQf7///8HcSECQQAhAQNAIAFBCXQiBkEQckHAiQpqQbCJAkGABPwKAAAgBkGQBHJBwIkKakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsgAUEHdEEEcgVBBAshASAFBEAgAUECdEHAiQpqQbCJAkGABPwKAAALIARBAUgNACADQQFxIQUgBwR/IANB/v///wdxIQJBACEBA0AgAUEJdCIGQRByQdCJDmpBsIkCQYAE/AoAACAGQZAEckHQiQ5qQbCJAkGABPwKAAAgAUECaiEBIAJBAmsiAg0ACyABQQd0QQRyBUEECyEBIAUEQCABQQJ0QdCJDmpBsIkCQYAE/AoAAAsgBEEBSA0AIANBAXEhBSAHBH8gA0H+////B3EhAkE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KVIgNDAAAAP10EQCADIAZDAACAP5KUDAELIAYgA0MAAIA/IAaTlJILIQcgAyADkiEGAkAgBUOrqqo+kiIEQwAAAABdBEAgBEMAAIA/kiEEDAELIARDAACAP15FDQAgBEMAAIC/kiEECyAGIAeTIQMgBUMAAAAAXSEAAn8CfSADIAcgA5NDAADAQJQgBJSSIARDq6oqPl0NABogByAEQwAAAD9dDQAaIAMgBEOrqio/XUUNABogAyAHIAOTIARDAADAwJRDAACAQJKUkgtDAAB/Q5RDAAAAP5IiBkMAAIBPXSAGQwAAAABgcQRAIAapDAELQQALIQECQCAABEAgBUMAAIA/kiEEDAELIAUiBEMAAIA/XkUNACAFQwAAgL+SIQQLIAVDq6qqvpIiBUMAAAAAXSECAn8CfSADIAcgA5NDAADAQJQgBJSSIARDq6oqPl0NABogByAEQwAAAD9dDQAaIAMgBEOrqio/XUUNABogAyAHIAOTIARDAADAwJRDAACAQJKUkgtDAAB/Q5RDAAAAP5IiBkMAAIBPXSAGQwAAAABgcQRAIAapDAELQQALIQACQCACBEAgBUMAAIA/kiEFDAELIAVDAACAP15FDQAgBUMAAIC/kiEFCwJAIAVDq6oqPl0EQCADIAcgA5NDAADAQJQgBZSSIQcMAQsgBUMAAAA/XQ0AIAVDq6oqP11FBEAgAyEHDAELIAMgByADkyAFQwAAwMCUQwAAgECSlJIhBwsgAEEIdAJ/IAdDAAB/Q5RDAAAAP5IiBkMAAIBPXSAGQwAAAABgcQRAIAapDAELQQALQRB0ciABcgtBgICAeHILNwAgAEH/AWxBMmpB5ABtIAFB/wFsQTJqQeQAbUEIdHIgAkH/AWxBMmpB5ABtQRB0ckGAgIB4cgsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwsYAQBBgAgLEQEAAAACAAAAAwAAAAQAAAAF'\n};\n//# sourceMappingURL=wasm.js.map","/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal event utilities for xterm.js core.\n * Simplified from VS Code's event.ts - no leak detection/profiling.\n */\n\nimport { IDisposable, DisposableStore, toDisposable } from './Lifecycle';\n\nexport interface IEvent {\n (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable;\n}\n\nexport class Emitter {\n private _listeners: { fn: (e: T) => any, thisArgs: any }[] = [];\n private _disposed = false;\n private _event: IEvent | undefined;\n\n public get event(): IEvent {\n if (this._event) {\n return this._event;\n }\n this._event = (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n if (this._disposed) {\n return toDisposable(() => {});\n }\n\n const entry = { fn: listener, thisArgs };\n this._listeners = this._listeners.slice();\n this._listeners.push(entry);\n\n const result = toDisposable(() => {\n const idx = this._listeners.indexOf(entry);\n if (idx !== -1) {\n this._listeners = this._listeners.slice();\n this._listeners.splice(idx, 1);\n }\n });\n\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(result);\n } else {\n disposables.add(result);\n }\n }\n\n return result;\n };\n return this._event;\n }\n\n public fire(event: T): void {\n if (this._disposed || !this._listeners.length) {\n return;\n }\n if (this._listeners.length === 1) {\n this._listeners[0].fn.call(this._listeners[0].thisArgs, event);\n return;\n }\n const listeners = this._listeners;\n for (let i = 0, len = listeners.length; i < len; ++i) {\n listeners[i].fn.call(listeners[i].thisArgs, event);\n }\n }\n\n public dispose(): void {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._listeners.length = 0;\n }\n}\n\nexport namespace EventUtils {\n export function forward(from: IEvent, to: Emitter): IDisposable {\n return from(e => to.fire(e));\n }\n\n export function map(event: IEvent, map: (i: I) => O): IEvent {\n return (listener: (e: O) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n return event(i => listener.call(thisArgs, map(i)), undefined, disposables);\n };\n }\n\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent {\n return (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n const store = new DisposableStore();\n for (const event of events) {\n store.add(event(e => listener.call(thisArgs, e)));\n }\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(store);\n } else {\n disposables.add(store);\n }\n }\n return store;\n };\n }\n\n export function runAndSubscribe(event: IEvent, handler: (e: T) => void, initial: T): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void, initial?: T): IDisposable {\n handler(initial);\n return event(e => handler(e));\n }\n}\n","/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal lifecycle utilities for xterm.js core.\n * Simplified from VS Code's lifecycle.ts - no tracking/leak detection.\n */\n\nexport interface IDisposable {\n dispose(): void;\n}\n\nexport function toDisposable(fn: () => void): IDisposable {\n return { dispose: fn };\n}\n\nexport function dispose(disposable: T): T;\nexport function dispose(disposable: T | undefined): T | undefined;\nexport function dispose(disposables: T[]): T[];\nexport function dispose(arg: T | T[] | undefined): T | T[] | undefined {\n if (!arg) {\n return arg;\n }\n if (Array.isArray(arg)) {\n for (const d of arg) {\n d.dispose();\n }\n return [];\n }\n arg.dispose();\n return arg;\n}\n\nexport function combinedDisposable(...disposables: IDisposable[]): IDisposable {\n return toDisposable(() => dispose(disposables));\n}\n\nexport class DisposableStore implements IDisposable {\n private readonly _disposables = new Set();\n private _isDisposed = false;\n\n public get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n public add(o: T): T {\n if (this._isDisposed) {\n o.dispose();\n } else {\n this._disposables.add(o);\n }\n return o;\n }\n\n public dispose(): void {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n\n public clear(): void {\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n}\n\nexport abstract class Disposable implements IDisposable {\n public static readonly None: IDisposable = Object.freeze({ dispose() { } });\n\n protected readonly _store = new DisposableStore();\n\n public dispose(): void {\n this._store.dispose();\n }\n\n protected _register(o: T): T {\n return this._store.add(o);\n }\n}\n\nexport class MutableDisposable implements IDisposable {\n private _value: T | undefined;\n private _isDisposed = false;\n\n public get value(): T | undefined {\n return this._isDisposed ? undefined : this._value;\n }\n\n public set value(value: T | undefined) {\n if (this._isDisposed || value === this._value) {\n return;\n }\n this._value?.dispose();\n this._value = value;\n }\n\n public clear(): void {\n this.value = undefined;\n }\n\n public dispose(): void {\n this._isDisposed = true;\n this._value?.dispose();\n this._value = undefined;\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IImageAddonOptions, IOscHandler, IResetHandler, ITerminalExt } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { CELL_SIZE_DEFAULT } from './ImageStorage';\nimport Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport QoiDecoder from 'xterm-wasm-parts/lib/qoi/QoiDecoder.wasm';\nimport { HeaderParser, IHeaderFields, HeaderState, SequenceType } from './IIPHeaderParser';\nimport { imageType, UNSUPPORTED_TYPE } from './IIPMetrics';\n\n// Local const enum mirror - esbuild can't inline const enums from external packages\nconst enum DecoderConst {\n // Limit held memory in base64 decoder (encoded bytes).\n KEEP_DATA = 4194304,\n // Initial buffer allocation for the decoder.\n INITIAL_DATA = 1048576,\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n OK = 0\n}\n\n// default IIP header values\nconst DEFAULT_HEADER: IHeaderFields = {\n type: SequenceType.INVALID,\n name: 'Unnamed file',\n size: 0,\n width: 'auto',\n height: 'auto',\n preserveAspectRatio: 1,\n inline: 0\n};\n\n\nexport class IIPHandler implements IOscHandler, IResetHandler {\n private _aborted = false;\n private _hp = new HeaderParser();\n private _header: IHeaderFields = DEFAULT_HEADER;\n private _dec: Base64Decoder;\n private _qoiDec: QoiDecoder;\n private _isMultipart = false;\n private _abortMulti = false;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _storage: IIPImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n const maxEncodedBytes = Math.ceil(this._opts.iipSizeLimit * 4 / 3);\n const initialBytes = Math.min(DecoderConst.INITIAL_DATA, maxEncodedBytes);\n this._dec = new Base64Decoder(DecoderConst.KEEP_DATA, maxEncodedBytes, initialBytes);\n this._qoiDec = new QoiDecoder(DecoderConst.KEEP_DATA);\n }\n\n public reset(): void {\n this._hp.reset();\n this._dec.release();\n this._qoiDec.release();\n }\n\n public start(): void {\n this._aborted = false;\n this._hp.reset();\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (this._hp.state === HeaderState.END) {\n if ((this._dec.put(data.subarray(start, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n }\n } else {\n const dataPos = this._hp.parse(data, start, end);\n if (dataPos === -1) {\n this._aborted = true;\n return;\n }\n if (dataPos > 0) {\n const seqType = this._hp.fields.type;\n if (seqType === SequenceType.FILE) {\n if (this._isMultipart) {\n this._isMultipart = false;\n this._abortMulti = false;\n this._dec.release();\n }\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n if (!this._header.inline) {\n this._aborted = true;\n return;\n }\n this._dec.init();\n } else if (this._abortMulti) {\n this._aborted = true;\n return;\n }\n if ((this._dec.put(data.subarray(dataPos, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n if (this._isMultipart) this._abortMulti = true;\n }\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted) return true;\n\n if (this._hp.state !== HeaderState.END) {\n if (this._hp.end()) return true;\n }\n const seqType = this._hp.fields.type;\n\n if (seqType === SequenceType.FILEPART) return true;\n\n if (seqType === SequenceType.REPORTCELLSIZE) {\n // OSC 1337 ; ReportCellSize=[height];[width];[scale] ST\n let w = CELL_SIZE_DEFAULT.width;\n let h = CELL_SIZE_DEFAULT.height;\n if (this._renderer.dimensions) {\n w = this._renderer.dimensions.css.canvas.width / this._coreTerminal.cols;\n h = this._renderer.dimensions.css.canvas.height / this._coreTerminal.rows;\n }\n const scale = this._coreTerminal._core._coreBrowserService?.dpr ?? 1;\n const report = `\\x1b]1337;ReportCellSize=${h.toFixed(3)};${w.toFixed(3)};${scale.toFixed(3)}\\x1b\\\\`;\n this._coreTerminal.input(report, false);\n return true;\n }\n\n if (seqType === SequenceType.MULTIPARTFILE) {\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n this._isMultipart = true;\n this._abortMulti = false;\n this._dec.release();\n this._dec.init();\n return true;\n }\n\n if (seqType === SequenceType.FILEEND) {\n if (!this._isMultipart) return true;\n this._isMultipart = false;\n if (this._abortMulti || this._header.type !== SequenceType.MULTIPARTFILE) return true;\n }\n\n // fallthrough for SequenceType.FILE & SequenceType.FILEEND\n\n let w = 0;\n let h = 0;\n\n // early exit condition chain\n let cond: number | boolean;\n let metrics = UNSUPPORTED_TYPE;\n if (cond = success) {\n if (cond = !this._dec.end()) {\n metrics = imageType(this._dec.data8);\n if (cond = metrics.mime !== 'unsupported') {\n w = metrics.width;\n h = metrics.height;\n if (cond = w && h && w * h < this._opts.pixelLimit) {\n [w, h] = this._resize(w, h).map(Math.floor);\n cond = w && h && w * h < this._opts.pixelLimit;\n } else {\n console.warn(`IIP: image dimension issue ${metrics.width}x${metrics.height}`);\n }\n } else {\n console.warn('IIP: unsupported image type');\n }\n } else {\n console.warn('IIP: error during BASE64 decoding');\n }\n }\n if (!cond) {\n this._dec.release();\n return true;\n }\n\n let blob: Blob | ImageData;\n if (metrics.mime === 'image/qoi') {\n const data = this._qoiDec.decode(this._dec.data8);\n blob = new ImageData(\n new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength),\n this._qoiDec.width,\n this._qoiDec.height\n );\n this._qoiDec.release();\n if (w === this._qoiDec.width && h === this._qoiDec.height) {\n // use fast-path if we don't need to rescale\n this._dec.release();\n const canvas = ImageRenderer.createCanvas(undefined, this._qoiDec.width, this._qoiDec.height);\n canvas.getContext('2d')?.putImageData(blob, 0, 0);\n this._storage.addImage(canvas);\n return true;\n }\n } else {\n blob = new Blob([this._dec.data8], { type: metrics.mime });\n }\n this._dec.release();\n return createImageBitmap(blob, { resizeWidth: w, resizeHeight: h })\n .then(bm => {\n this._storage.addImage(bm);\n return true;\n })\n .catch(e => {\n console.warn(`IIP: decoding error ${metrics.mime} ${metrics.width}x${metrics.height}`, e);\n return true;\n });\n }\n\n private _resize(w: number, h: number): [number, number] {\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n const width = this._renderer.dimensions?.css.canvas.width || cw * this._coreTerminal.cols;\n const height = this._renderer.dimensions?.css.canvas.height || ch * this._coreTerminal.rows;\n\n const rw = this._dim(this._header.width!, width, cw);\n const rh = this._dim(this._header.height!, height, ch);\n if (!rw && !rh) {\n const wf = width / w; // TODO: should this respect initial cursor offset?\n const hf = (height - ch) / h; // TODO: fix offset issues from float cell height\n const f = Math.min(wf, hf);\n return f < 1 ? [w * f, h * f] : [w, h];\n }\n return !rw\n ? [w * rh / h, rh]\n : this._header.preserveAspectRatio || !rw || !rh\n ? [rw, h * rw / w] : [rw, rh];\n }\n\n private _dim(s: string, total: number, cdim: number): number {\n if (s === 'auto') return 0;\n if (s.endsWith('%')) return parseInt(s.slice(0, -1), 10) * total / 100;\n if (s.endsWith('px')) return parseInt(s.slice(0, -2), 10);\n return parseInt(s, 10) * cdim;\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n// eslint-disable-next-line\ndeclare const Buffer: any;\n\nexport const enum HeaderState {\n START = 0,\n ABORT = 1,\n KEY = 2,\n VALUE = 3,\n END = 4\n}\n\nexport const enum SequenceType {\n INVALID = 0,\n FILE = 1,\n MULTIPARTFILE = 2,\n FILEPART = 3,\n FILEEND = 4,\n REPORTCELLSIZE = 5\n}\n\nexport interface IHeaderFields {\n [key: string]: number | string | Uint32Array | null | undefined;\n // sequence type\n type: SequenceType;\n // base-64 encoded filename. Defaults to \"Unnamed file\".\n name: string;\n // File size in bytes. The file transfer will be canceled if this size is exceeded.\n size: number;\n /**\n * Optional width and height to render:\n * - N: N character cells.\n * - Npx: N pixels.\n * - N%: N percent of the session's width or height.\n * - auto: The image's inherent size will be used to determine an appropriate dimension.\n */\n width?: string;\n height?: string;\n // Optional, defaults to 1 respecting aspect ratio (width takes precedence).\n preserveAspectRatio?: number;\n // Optional, defaults to 0. If set to 1, the file will be displayed inline, else downloaded\n // (download not supported).\n inline?: number;\n}\n\n// field value decoders\n\n// ASCII bytes to string\nfunction toStr(data: Uint32Array): string {\n let s = '';\n for (let i = 0; i < data.length; ++i) {\n s += String.fromCharCode(data[i]);\n }\n return s;\n}\n\n// digits to integer\nfunction toInt(data: Uint32Array): number {\n let v = 0;\n for (let i = 0; i < data.length; ++i) {\n if (data[i] < 48 || data[i] > 57) {\n throw new Error('illegal char');\n }\n v = v * 10 + data[i] - 48;\n }\n return v;\n}\n\n// check for correct size entry\nfunction toSize(data: Uint32Array): string {\n const v = toStr(data);\n if (!v.match(/^((auto)|(\\d+?((px)|(%)){0,1}))$/)) {\n throw new Error('illegal size');\n }\n return v;\n}\n\n// name is base64 encoded utf-8\nfunction toName(data: Uint32Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(toStr(data), 'base64').toString();\n }\n const bs = atob(toStr(data));\n const b = new Uint8Array(bs.length);\n for (let i = 0; i < b.length; ++i) {\n b[i] = bs.charCodeAt(i);\n }\n return new TextDecoder().decode(b);\n}\n\nconst DECODERS: {[key: string]: (v: Uint32Array) => number | string} = {\n inline: toInt,\n size: toInt,\n name: toName,\n width: toSize,\n height: toSize,\n preserveAspectRatio: toInt\n};\n\n\n// sequence type markers\n// File\nconst FILE_MARKER = [70, 105, 108, 101];\n// MultipartFile\nconst MULTIPARTFILE_MARKER = [77, 117, 108, 116, 105, 112, 97, 114, 116, 70, 105, 108, 101];\n// FilePart\nconst FILEPART_MARKER = [70, 105, 108, 101, 80, 97, 114, 116];\n// FileEnd\nconst FILEEND_MARKER = [70, 105, 108, 101, 69, 110, 100];\n// ReportCellSize\nconst REPORTCELLSIZE_MARKER = [82, 101, 112, 111, 114, 116, 67, 101, 108, 108, 83, 105, 122, 101];\n\n// max allowed chars for sequence header\nconst MAX_FIELDCHARS = 1024;\n\n\nexport class HeaderParser {\n public state: HeaderState = HeaderState.START;\n private _buffer = new Uint32Array(MAX_FIELDCHARS);\n private _position = 0;\n private _key = '';\n public fields: {[key: string]: number | string | Uint32Array | null | undefined} = {};\n\n public reset(): void {\n this._buffer.fill(0);\n this.state = HeaderState.START;\n this._position = 0;\n this.fields = {};\n this._key = '';\n }\n\n public end(): number {\n if (this.state === HeaderState.START) {\n if (this._position === FILEEND_MARKER.length) {\n for (let k = 0; k < FILEEND_MARKER.length; ++k) {\n if (this._buffer[k] !== FILEEND_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEEND;\n this.state = HeaderState.END;\n return 0;\n }\n if (this._position === REPORTCELLSIZE_MARKER.length) {\n for (let k = 0; k < REPORTCELLSIZE_MARKER.length; ++k) {\n if (this._buffer[k] !== REPORTCELLSIZE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.REPORTCELLSIZE;\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n if (this.state === HeaderState.END) return 0;\n if (this.state === HeaderState.VALUE\n && this.fields.type === SequenceType.MULTIPARTFILE\n ) {\n if (!this._storeValue(this._position)) return this._a();\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n\n public parse(data: Uint32Array, start: number, end: number): number {\n let state = this.state;\n let pos = this._position;\n const buffer = this._buffer;\n if (state === HeaderState.ABORT || state === HeaderState.END) return -1;\n if (state === HeaderState.START && pos > 14) return -1;\n for (let i = start; i < end; ++i) {\n const c = data[i];\n switch (c) {\n case 59: // ;\n if (!this._storeValue(pos)) return this._a();\n state = HeaderState.KEY;\n pos = 0;\n break;\n case 61: // =\n if (state === HeaderState.START) {\n if (buffer[0] === 70) {\n // 'File' or 'FilePart'\n let k = 0;\n for (; k < FILE_MARKER.length; ++k) {\n if (buffer[k] !== FILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILE;\n if (pos === FILEPART_MARKER.length) {\n for (; k < FILEPART_MARKER.length; ++k) {\n if (buffer[k] !== FILEPART_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEPART;\n this.state = HeaderState.END;\n return i + 1;\n }\n } else if (buffer[0] === 77) {\n // 'MultipartFile'\n for (let k = 0; k < MULTIPARTFILE_MARKER.length; ++k) {\n if (buffer[k] !== MULTIPARTFILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.MULTIPARTFILE;\n } else {\n return this._a();\n }\n state = HeaderState.KEY;\n pos = 0;\n } else if (state === HeaderState.KEY) {\n if (!this._storeKey(pos)) return this._a();\n state = HeaderState.VALUE;\n pos = 0;\n } else if (state === HeaderState.VALUE) {\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n break;\n case 58: // :\n if (state === HeaderState.VALUE) {\n if (!this._storeValue(pos)) return this._a();\n }\n this.state = HeaderState.END;\n return i + 1;\n default:\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n }\n this.state = state;\n this._position = pos;\n return -2;\n }\n\n private _a(): number {\n this.fields.type = SequenceType.INVALID;\n this.state = HeaderState.ABORT;\n return -1;\n }\n\n private _storeKey(pos: number): boolean {\n const k = toStr(this._buffer.subarray(0, pos));\n if (k) {\n this._key = k;\n this.fields[k] = null;\n return true;\n }\n return false;\n }\n\n private _storeValue(pos: number): boolean {\n if (this._key) {\n try {\n const v = this._buffer.slice(0, pos);\n this.fields[this._key] = DECODERS[this._key] ? DECODERS[this._key](v) : v;\n } catch {\n return false;\n }\n return true;\n }\n return false;\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IAddImageOpts } from './Types';\nimport { ImageStorage } from './ImageStorage';\n\n/**\n * IIP (iTerm Image Protocol) specific image storage controller.\n *\n * Wraps the shared ImageStorage with IIP protocol semantics:\n * - Always uses scrolling mode (cursor advances with image)\n */\nexport class IIPImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n constructor(\n private readonly _storage: ImageStorage\n ) {}\n\n /**\n * Add an IIP image to storage.\n * Always uses scrolling mode — cursor advances past the image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._storage.addImage(img, this._addImageOpts);\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n\nexport type ImageType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/qoi' | 'image/webp' | 'image/avif' | 'unsupported' | '';\n\nexport interface IMetrics {\n mime: ImageType;\n width: number;\n height: number;\n}\n\nexport const UNSUPPORTED_TYPE: IMetrics = {\n mime: 'unsupported',\n width: 0,\n height: 0\n};\n\nexport function imageType(d: Uint8Array): IMetrics {\n if (d.length < 32) {\n return UNSUPPORTED_TYPE;\n }\n const d32 = new Uint32Array(d.buffer, d.byteOffset, 8);\n // PNG: 89 50 4E 47 0D 0A 1A 0A (8 first bytes == magic number for PNG)\n // + first chunk must be IHDR\n if (d32[0] === 0x474E5089 && d32[1] === 0x0A1A0A0D && d32[3] === 0x52444849) {\n return {\n mime: 'image/png',\n width: d[16] << 24 | d[17] << 16 | d[18] << 8 | d[19],\n height: d[20] << 24 | d[21] << 16 | d[22] << 8 | d[23]\n };\n }\n // JPEG: FF D8 FF\n if (d[0] === 0xFF && d[1] === 0xD8 && d[2] === 0xFF) {\n const [width, height] = jpgSize(d);\n return { mime: 'image/jpeg', width, height };\n }\n // GIF: GIF87a or GIF89a\n if (d32[0] === 0x38464947 && (d[4] === 0x37 || d[4] === 0x39) && d[5] === 0x61) {\n return {\n mime: 'image/gif',\n width: d[7] << 8 | d[6],\n height: d[9] << 8 | d[8]\n };\n }\n // QOI: qoif\n if (d32[0] === 0x66696F71) {\n return {\n mime: 'image/qoi',\n width: d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7],\n height: d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11]\n };\n }\n // WEBP: RIFF | xxxx | WEBP | VP8x\n if (d32[0] === 0x46464952 && d32[2] === 0x50424557 && (d32[3] & 0xFFFFFF) === 0x385056) {\n switch (d[15]) {\n case 0x58: // Extended WebP VP8X --> \"X\"\n return {\n mime: 'image/webp',\n width: (d[24] | d[25] << 8 | d[26] << 16) + 1,\n height: (d[27] | d[28] << 8 | d[29] << 16) + 1\n };\n case 0x4C: // Lossless WebP VP8L --> \"L\"\n if (d[20] !== 0x2f) return UNSUPPORTED_TYPE;\n const dim = d[21] | d[22] << 8 | d[23] << 16 | d[24] << 24;\n return {\n mime: 'image/webp',\n width: (dim & 0x3FFF) + 1,\n height: (dim >>> 14 & 0x3FFF) + 1\n };\n case 0x20: // Lossy WebP VP8 --> \" \"\n if (d[23] !== 0x9d || d[24] !== 0x01 || d[25] !== 0x2a) return UNSUPPORTED_TYPE;\n return {\n mime: 'image/webp',\n width: (d[26] | d[27] << 8) & 0x3FFF,\n height: (d[28] | d[29] << 8) & 0x3FFF\n };\n }\n return UNSUPPORTED_TYPE;\n }\n // AVIF: Box size | ftyp | avif/avis\n if (d32[1] === 0x70797466 && (d32[2] === 0x66697661 || d32[2] === 0x73697661)) {\n let pos = -1;\n // search for ispe box within first 1024 bytes\n const limit = Math.min(d.length - 16, 1024);\n for (let i = 8; i < limit; i++) {\n // scan for ispe\n if (d[i] === 0x69 && d[i + 1] === 0x73 && d[i + 2] === 0x70 && d[i + 3] === 0x65) {\n pos = i;\n break;\n }\n }\n if (pos !== -1) {\n // dimensions are in BE at +8 (width) at +12 (height)\n const width =\n d[pos + 8] << 24 |\n d[pos + 9] << 16 |\n d[pos + 10] << 8 |\n d[pos + 11];\n const height =\n d[pos + 12] << 24 |\n d[pos + 13] << 16 |\n d[pos + 14] << 8 |\n d[pos + 15];\n if (width > 0 && height > 0) {\n return { mime: 'image/avif', width, height };\n }\n }\n return UNSUPPORTED_TYPE;\n }\n return UNSUPPORTED_TYPE;\n}\n\n\nfunction jpgSize(d: Uint8Array): [number, number] {\n const len = d.length;\n let i = 4;\n let blockLength = d[i] << 8 | d[i + 1];\n while (true) {\n i += blockLength;\n if (i >= len) {\n // exhausted without size info\n return [0, 0];\n }\n if (d[i] !== 0xFF) {\n return [0, 0];\n }\n if (d[i + 1] === 0xC0 || d[i + 1] === 0xC2) {\n if (i + 8 < len) {\n return [\n d[i + 7] << 8 | d[i + 8],\n d[i + 5] << 8 | d[i + 6]\n ];\n }\n return [0, 0];\n }\n i += 2;\n blockLength = d[i] << 8 | d[i + 1];\n }\n}\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { toRGBA8888 } from 'sixel/lib/Colors';\nimport { IDisposable } from '@xterm/xterm';\nimport { ICellSize, ImageLayer, ITerminalExt, IImageSpec, IRenderDimensions, IRenderService } from './Types';\nimport { Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';\n\nconst enum Constants {\n PLACEHOLDER_LENGTH = 4096,\n PLACEHOLDER_HEIGHT = 24\n}\n\n/**\n * ImageRenderer - terminal frontend extension:\n * - provide primitives for canvas, ImageData, Bitmap (static)\n * - add canvas layer to DOM (browser only for now)\n * - draw image tiles onRender\n */\nexport class ImageRenderer extends Disposable implements IDisposable {\n /** @deprecated Kept for backward compat — points to top layer canvas. */\n public get canvas(): HTMLCanvasElement | undefined { return this._layers.get('top')?.canvas; }\n private _layers = new Map();\n private _placeholder: HTMLCanvasElement | undefined;\n private _placeholderBitmap: ImageBitmap | undefined;\n private _optionsRefresh = this._register(new MutableDisposable());\n private _oldOpen: ((parent: HTMLElement) => void) | undefined;\n private _renderService: IRenderService | undefined;\n private _oldSetRenderer: ((renderer: any) => void) | undefined;\n\n // drawing primitive - canvas\n public static createCanvas(localDocument: Document | undefined, width: number, height: number): HTMLCanvasElement {\n /**\n * NOTE: We normally dont care, from which document the canvas\n * gets created, so we can fall back to global document,\n * if the terminal has no document associated yet.\n * This way early image loads before calling .open keep working\n * (still discouraged though, as the metrics will be screwed up).\n * Only the DOM output canvas should be on the terminal's document,\n * which gets explicitly checked in `insertLayerToDom`.\n */\n const canvas = (localDocument ?? document).createElement('canvas');\n canvas.width = width | 0;\n canvas.height = height | 0;\n return canvas;\n }\n\n // drawing primitive - ImageData with optional buffer\n public static createImageData(ctx: CanvasRenderingContext2D, width: number, height: number, buffer?: ArrayBuffer): ImageData {\n if (typeof ImageData !== 'function') {\n const imgData = ctx.createImageData(width, height);\n if (buffer) {\n imgData.data.set(new Uint8ClampedArray(buffer, 0, width * height * 4));\n }\n return imgData;\n }\n return buffer\n ? new ImageData(new Uint8ClampedArray(buffer, 0, width * height * 4), width, height)\n : new ImageData(width, height);\n }\n\n // drawing primitive - ImageBitmap\n public static createImageBitmap(img: ImageBitmapSource): Promise {\n if (typeof createImageBitmap !== 'function') {\n return Promise.resolve(undefined);\n }\n return createImageBitmap(img);\n }\n\n\n constructor(private _terminal: ITerminalExt) {\n super();\n this._oldOpen = this._terminal._core.open;\n this._terminal._core.open = (parent: HTMLElement): void => {\n this._oldOpen?.call(this._terminal._core, parent);\n this._open();\n };\n if (this._terminal._core.screenElement) {\n this._open();\n }\n // hack to spot fontSize changes\n this._optionsRefresh.value = this._terminal._core.optionsService.onOptionChange(option => {\n if (option === 'fontSize') {\n this.rescaleCanvas();\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n });\n this._register(toDisposable(() => {\n this.removeLayerFromDom();\n this.removeLayerFromDom('bottom');\n if (this._terminal._core && this._oldOpen) {\n this._terminal._core.open = this._oldOpen;\n this._oldOpen = undefined;\n }\n if (this._renderService && this._oldSetRenderer) {\n this._renderService.setRenderer = this._oldSetRenderer;\n this._oldSetRenderer = undefined;\n }\n this._renderService = undefined;\n this._layers.clear();\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }));\n }\n\n /**\n * Enable the placeholder.\n */\n public showPlaceholder(value: boolean): void {\n if (value) {\n if (!this._placeholder && this.cellSize.height !== -1) {\n this._createPlaceHolder(Math.max(this.cellSize.height + 1, Constants.PLACEHOLDER_HEIGHT));\n }\n } else {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n\n /**\n * Dimensions of the terminal.\n * Forwarded from internal render service.\n */\n public get dimensions(): IRenderDimensions | undefined {\n return this._terminal.dimensions;\n }\n\n /**\n * Current cell size (float).\n */\n public get cellSize(): ICellSize {\n return {\n width: this.dimensions?.css.cell.width || -1,\n height: this.dimensions?.css.cell.height || -1\n };\n }\n\n /**\n * Clear a region of the image layer canvas.\n */\n public clearLines(start: number, end: number, layer?: ImageLayer): void {\n const y = start * (this.dimensions?.css.cell.height || 0);\n const w = this.dimensions?.css.canvas.width || 0;\n const h = (end + 1 - start) * (this.dimensions?.css.cell.height || 0);\n if (!layer || layer === 'top') {\n this._layers.get('top')?.clearRect(0, y, w, h);\n }\n if (!layer || layer === 'bottom') {\n this._layers.get('bottom')?.clearRect(0, y, w, h);\n }\n }\n\n /**\n * Clear whole image canvas.\n */\n public clearAll(layer?: ImageLayer): void {\n if (!layer || layer === 'top') {\n const ctx = this._layers.get('top');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n if (!layer || layer === 'bottom') {\n const ctx = this._layers.get('bottom');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n }\n\n /**\n * Draw neighboring tiles on the image layer canvas.\n */\n public draw(imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get(imgSpec.layer);\n if (!ctx) {\n return;\n }\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const cols = Math.ceil(img.width / width);\n\n const sx = (tileId % cols) * width;\n const sy = Math.floor(tileId / cols) * height;\n const dx = col * width;\n const dy = row * height;\n\n // safari bug: never access image source out of bounds\n const finalWidth = count * width + sx > img.width ? img.width - sx : count * width;\n const finalHeight = sy + height > img.height ? img.height - sy : height;\n\n // Floor all pixel offsets to get stable tile mapping without any overflows.\n // Note: For not pixel perfect aligned cells like in the DOM renderer\n // this will move a tile slightly to the top/left (subpixel range, thus ignore it).\n // FIX #34: avoid striping on displays with pixelDeviceRatio != 1 by ceiling height and width\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.ceil(finalWidth), Math.ceil(finalHeight),\n Math.floor(dx), Math.floor(dy), Math.ceil(finalWidth), Math.ceil(finalHeight)\n );\n }\n\n /**\n * Extract a single tile from an image.\n */\n public extractTile(imgSpec: IImageSpec, tileId: number): HTMLCanvasElement | undefined {\n const { width, height } = this.cellSize;\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const cols = Math.ceil(img.width / width);\n const sx = (tileId % cols) * width;\n const sy = Math.floor(tileId / cols) * height;\n const finalWidth = width + sx > img.width ? img.width - sx : width;\n const finalHeight = sy + height > img.height ? img.height - sy : height;\n\n const canvas = ImageRenderer.createCanvas(this.document, finalWidth, finalHeight);\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.floor(finalWidth), Math.floor(finalHeight),\n 0, 0, Math.floor(finalWidth), Math.floor(finalHeight)\n );\n return canvas;\n }\n }\n\n /**\n * Draw a line with placeholder on the image layer canvas.\n */\n public drawPlaceholder(col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get('top');\n if (ctx) {\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n if (!this._placeholder) {\n this._createPlaceHolder(Math.max(height + 1, Constants.PLACEHOLDER_HEIGHT));\n } else if (height >= this._placeholder!.height) {\n this._createPlaceHolder(height + 1);\n }\n if (!this._placeholder) return;\n ctx.drawImage(\n this._placeholderBitmap ?? this._placeholder!,\n col * width,\n (row * height) % 2 ? 0 : 1, // needs %2 offset correction\n width * count,\n height,\n col * width,\n row * height,\n width * count,\n height\n );\n }\n }\n\n /**\n * Rescale image layer canvas if needed.\n * Checked once from `ImageStorage.render`.\n */\n public rescaleCanvas(): void {\n const w = this.dimensions?.css.canvas.width || 0;\n const h = this.dimensions?.css.canvas.height || 0;\n for (const ctx of this._layers.values()) {\n if (ctx.canvas.width !== w || ctx.canvas.height !== h) {\n ctx.canvas.width = w;\n ctx.canvas.height = h;\n }\n }\n }\n\n /**\n * Rescale image in storage if needed.\n */\n private _rescaleImage(spec: IImageSpec, currentWidth: number, currentHeight: number): void {\n if (currentWidth === spec.actualCellSize.width && currentHeight === spec.actualCellSize.height) {\n return;\n }\n const { width: originalWidth, height: originalHeight } = spec.origCellSize;\n if (currentWidth === originalWidth && currentHeight === originalHeight) {\n spec.actual = spec.orig;\n spec.actualCellSize.width = originalWidth;\n spec.actualCellSize.height = originalHeight;\n return;\n }\n const canvas = ImageRenderer.createCanvas(\n this.document,\n Math.ceil(spec.orig!.width * currentWidth / originalWidth),\n Math.ceil(spec.orig!.height * currentHeight / originalHeight)\n );\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(spec.orig!, 0, 0, canvas.width, canvas.height);\n spec.actual = canvas;\n spec.actualCellSize.width = currentWidth;\n spec.actualCellSize.height = currentHeight;\n }\n }\n\n /**\n * Lazy init for the renderer.\n */\n private _open(): void {\n this._renderService = this._terminal._core._renderService;\n this._oldSetRenderer = this._renderService.setRenderer.bind(this._renderService);\n this._renderService.setRenderer = (renderer: any) => {\n for (const key of [...this._layers.keys()]) {\n this.removeLayerFromDom(key);\n }\n this._oldSetRenderer?.call(this._renderService, renderer);\n };\n }\n\n public insertLayerToDom(layer: ImageLayer = 'top'): void {\n // make sure that the terminal is attached to a document and to DOM\n if (!this.document || !this._terminal._core.screenElement) {\n console.warn('image addon: cannot insert output canvas to DOM, missing document or screenElement');\n return;\n }\n if (this._layers.has(layer)) {\n return;\n }\n const canvas = ImageRenderer.createCanvas(\n this.document, this.dimensions?.css.canvas.width || 0,\n this.dimensions?.css.canvas.height || 0\n );\n canvas.classList.add(`xterm-image-layer-${layer}`);\n const screenElement = this._terminal._core.screenElement;\n // Use isolation to create a stacking context without overriding z-index,\n // which would conflict with integrators (e.g. VS Code) that set their\n // own z-index on the screen element.\n screenElement.style.isolation = 'isolate';\n if (layer === 'bottom') {\n // Use z-index:-1 so it paints behind non-positioned text elements.\n // The screen element needs to be a stacking context (via isolation)\n // to contain the negative z-index, otherwise it would go behind the\n // entire terminal.\n canvas.style.zIndex = '-1';\n screenElement.insertBefore(canvas, screenElement.firstChild);\n } else {\n // Explicit z-index ensures the image canvas reliably stacks above\n // the text layer (DOM renderer rows). z-index: 0 is below the\n // selection overlay (z-index: 1).\n canvas.style.zIndex = '0';\n screenElement.appendChild(canvas);\n }\n const ctx = canvas.getContext('2d', { alpha: true });\n if (!ctx) {\n canvas.remove();\n return;\n }\n this._layers.set(layer, ctx);\n this.clearAll(layer);\n }\n\n public removeLayerFromDom(layer: ImageLayer = 'top'): void {\n const ctx = this._layers.get(layer);\n if (ctx) {\n ctx.canvas.remove();\n this._layers.delete(layer);\n }\n }\n\n public hasLayer(layer: ImageLayer): boolean {\n return this._layers.has(layer);\n }\n\n private _createPlaceHolder(height: number = Constants.PLACEHOLDER_HEIGHT): void {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n\n // create blueprint to fill placeholder with\n const bWidth = 32; // must be 2^n\n const blueprint = ImageRenderer.createCanvas(this.document, bWidth, height);\n const ctx = blueprint.getContext('2d', { alpha: false });\n if (!ctx) return;\n const imgData = ImageRenderer.createImageData(ctx, bWidth, height);\n const d32 = new Uint32Array(imgData.data.buffer);\n const black = toRGBA8888(0, 0, 0);\n const white = toRGBA8888(255, 255, 255);\n d32.fill(black);\n for (let y = 0; y < height; ++y) {\n const shift = y % 2;\n const offset = y * bWidth;\n for (let x = 0; x < bWidth; x += 2) {\n d32[offset + x + shift] = white;\n }\n }\n ctx.putImageData(imgData, 0, 0);\n\n // create placeholder line, width aligned to blueprint width\n const width = (screen.width + bWidth - 1) & ~(bWidth - 1) || Constants.PLACEHOLDER_LENGTH;\n this._placeholder = ImageRenderer.createCanvas(this.document, width, height);\n const ctx2 = this._placeholder.getContext('2d', { alpha: false });\n if (!ctx2) {\n this._placeholder = undefined;\n return;\n }\n for (let i = 0; i < width; i += bWidth) {\n ctx2.drawImage(blueprint, i, 0);\n }\n ImageRenderer.createImageBitmap(this._placeholder).then(bitmap => this._placeholderBitmap = bitmap);\n }\n\n public get document(): Document | undefined {\n return this._terminal._core._coreBrowserService?.window.document;\n }\n}\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageRenderer } from './ImageRenderer';\nimport {\n ITerminalExt, IExtendedAttrsImage, IImageAddonOptions, IImageSpec,\n IBufferLineExt, BgFlags, Cell, Content, ICellSize, ExtFlags, Attributes,\n UnderlineStyle, IAddImageOpts\n} from './Types';\n\n\n// fallback default cell size\nexport const CELL_SIZE_DEFAULT: ICellSize = {\n width: 7,\n height: 14\n};\n\n/**\n * Extend extended attribute to also hold image tile information.\n *\n * Object definition is copied from base repo to fully mimick its behavior.\n * Image data is added as additional public properties `imageId` and `tileId`.\n */\nclass ExtendedAttrsImage implements IExtendedAttrsImage {\n private _ext: number = 0;\n public get ext(): number {\n if (this._urlId) {\n return (\n (this._ext & ~ExtFlags.UNDERLINE_STYLE) |\n (this.underlineStyle << 26)\n );\n }\n return this._ext;\n }\n public set ext(value: number) { this._ext = value; }\n\n public get underlineStyle(): UnderlineStyle {\n // Always return the URL style if it has one\n if (this._urlId) {\n return UnderlineStyle.DASHED;\n }\n return (this._ext & ExtFlags.UNDERLINE_STYLE) >> 26;\n }\n public set underlineStyle(value: UnderlineStyle) {\n this._ext &= ~ExtFlags.UNDERLINE_STYLE;\n this._ext |= (value << 26) & ExtFlags.UNDERLINE_STYLE;\n }\n\n public get underlineColor(): number {\n return this._ext & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n public set underlineColor(value: number) {\n this._ext &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n this._ext |= value & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n\n public get underlineVariantOffset(): number {\n const val = (this._ext & ExtFlags.VARIANT_OFFSET) >> 29;\n if (val < 0) {\n return val ^ 0xFFFFFFF8;\n }\n return val;\n }\n public set underlineVariantOffset(value: number) {\n this._ext &= ~ExtFlags.VARIANT_OFFSET;\n this._ext |= (value << 29) & ExtFlags.VARIANT_OFFSET;\n }\n\n private _urlId: number = 0;\n public get urlId(): number {\n return this._urlId;\n }\n public set urlId(value: number) {\n this._urlId = value;\n }\n\n constructor(\n ext: number = 0,\n urlId: number = 0,\n public imageId = -1,\n public tileId = -1\n ) {\n this._ext = ext;\n this._urlId = urlId;\n }\n\n public clone(): IExtendedAttrsImage {\n /**\n * Technically we dont need a clone variant of ExtendedAttrsImage,\n * as we never clone a cell holding image data.\n * Note: Clone is only meant to be used by the InputHandler for\n * sticky attributes, which is never the case for image data.\n * We still provide a proper clone method to reflect the full ext attr\n * state in case there are future use cases for clone.\n */\n return new ExtendedAttrsImage(this._ext, this._urlId, this.imageId, this.tileId);\n }\n\n public isEmpty(): boolean {\n return this.underlineStyle === UnderlineStyle.NONE && this._urlId === 0 && this.imageId === -1;\n }\n}\nconst EMPTY_ATTRS = new ExtendedAttrsImage();\n\n\n/**\n * ImageStorage - extension of CoreTerminal:\n * - hold image data\n * - write/read image data to/from buffer\n *\n * TODO: image composition for overwrites\n */\nexport class ImageStorage implements IDisposable {\n // storage\n private _images: Map = new Map();\n // last used id\n private _lastId = 0;\n // last evicted id\n private _lowestId = 0;\n // whether a full clear happened before\n private _fullyCleared = false;\n // whether render should do a full clear\n private _needsFullClear = false;\n // hard limit of stored pixels (fallback limit of 10 MB)\n private _pixelLimit: number = 2500000;\n\n private _viewportMetrics: { cols: number, rows: number };\n public onImageAdded: (() => void) | undefined;\n public onImageDeleted: ((storageId: number) => void) | undefined;\n\n constructor(\n private _terminal: ITerminalExt,\n private _renderer: ImageRenderer,\n private _opts: IImageAddonOptions\n ) {\n try {\n this.setLimit(this._opts.storageLimit);\n } catch (e: unknown) {\n if (e instanceof Error) {\n console.error(e.message);\n }\n console.warn(`storageLimit is set to ${this.getLimit()} MB`);\n }\n this._viewportMetrics = {\n cols: this._terminal.cols,\n rows: this._terminal.rows\n };\n }\n\n public dispose(): void {\n this.reset();\n }\n\n public reset(): void {\n for (const spec of this._images.values()) {\n spec.marker?.dispose();\n }\n // NOTE: marker.dispose above already calls ImageBitmap.close\n // therefore we can just wipe the map here\n this._images.clear();\n this._renderer.clearAll();\n }\n\n public getLimit(): number {\n return this._pixelLimit * 4 / 1000000;\n }\n\n public setLimit(value: number): void {\n if (value < 0.5 || value > 1000) {\n throw RangeError('invalid storageLimit, should be at least 0.5 MB and not exceed 1G');\n }\n this._pixelLimit = (value / 4 * 1000000) >>> 0;\n this._evictOldest(0);\n }\n\n public getUsage(): number {\n return this._getStoredPixels() * 4 / 1000000;\n }\n\n private _getStoredPixels(): number {\n let storedPixels = 0;\n for (const spec of this._images.values()) {\n if (spec.orig) {\n storedPixels += spec.orig.width * spec.orig.height;\n if (spec.actual && spec.actual !== spec.orig) {\n storedPixels += spec.actual.width * spec.actual.height;\n }\n }\n }\n return storedPixels;\n }\n\n private _delImg(id: number): void {\n const spec = this._images.get(id);\n if (!spec) return;\n this._images.delete(id);\n // FIXME: really ugly workaround to get bitmaps deallocated :(\n if (window.ImageBitmap && spec.orig instanceof ImageBitmap) {\n spec.orig.close();\n }\n this.onImageDeleted?.(id);\n }\n\n /**\n * Wipe canvas and images on alternate buffer.\n */\n public wipeAlternate(): void {\n // remove all alternate tagged images\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate') {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n // mark canvas to be wiped on next render\n this._needsFullClear = true;\n this._fullyCleared = false;\n }\n\n /**\n * Delete an image by its internal storage ID.\n * Used by protocols that support explicit deletion (e.g. Kitty a=d).\n */\n public deleteImage(id: number): void {\n const spec = this._images.get(id);\n if (spec) {\n spec.marker?.dispose();\n this._delImg(id);\n }\n }\n\n /**\n * Method to add an image to the storage.\n * @param img - The image to add (canvas or bitmap).\n * @param opts - Options for addImage:\n * - scrolling: When true, cursor advances with the image.\n * When false, image is placed at ORIGIN and cursor does not move.\n * - layer: Which canvas layer to render on ('top' or 'bottom').\n * - zIndex: Z-index for image layering within the same layer.\n * - cursorPos: 'vt340' for bottom-left, 'iip' for bottom.right.\n * @returns The internal image ID assigned to the stored image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap, opts: IAddImageOpts): number {\n // never allow storage to exceed memory limit\n this._evictOldest(img.width * img.height);\n\n // calc rows x cols needed to display the image\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const cols = Math.ceil(img.width / cellSize.width);\n const rows = Math.ceil(img.height / cellSize.height);\n\n const imageId = ++this._lastId;\n\n const buffer = this._terminal._core.buffer;\n const termCols = this._terminal.cols;\n const termRows = this._terminal.rows;\n const originX = buffer.x;\n const originY = buffer.y;\n let offset = originX;\n let tileCount = 0;\n\n if (!opts.scrolling) {\n buffer.x = 0;\n buffer.y = 0;\n offset = 0;\n }\n\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(buffer.y + buffer.ybase);\n for (let col = 0; col < cols; ++col) {\n if (offset + col >= termCols) break;\n this._writeToCell(line as IBufferLineExt, offset + col, imageId, row * cols + col);\n tileCount++;\n }\n if (opts.scrolling) {\n if (row < rows - 1) this._terminal._core._inputHandler.lineFeed();\n } else {\n if (++buffer.y >= termRows) break;\n }\n buffer.x = offset;\n }\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n\n // cursor positioning modes\n if (opts.scrolling) {\n if (opts.cursorPos === 'iip') {\n buffer.x = Math.min(offset + cols, termCols);\n } else {\n buffer.x = offset;\n }\n } else {\n buffer.x = originX;\n buffer.y = originY;\n }\n\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.tileCount < 1) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n\n // eviction marker:\n // delete the image when the marker gets disposed\n const endMarker = this._terminal.registerMarker(0);\n endMarker?.onDispose(() => {\n const spec = this._images.get(imageId);\n if (spec) {\n this._delImg(imageId);\n }\n });\n\n // since markers do not work on alternate for some reason,\n // we evict images here manually\n if (this._terminal.buffer.active.type === 'alternate') {\n this._evictOnAlternate();\n }\n\n // create storage entry\n const imgSpec: IImageSpec = {\n orig: img,\n origCellSize: cellSize,\n actual: img,\n actualCellSize: { ...cellSize }, // clone needed, since later modified\n marker: endMarker || undefined,\n tileCount,\n bufferType: this._terminal.buffer.active.type,\n layer: opts.layer,\n zIndex: opts.zIndex\n };\n\n // finally add the image\n this._images.set(imageId, imgSpec);\n this.onImageAdded?.();\n return imageId;\n }\n\n\n /**\n * Render method. Collects buffer information and triggers\n * canvas updates.\n */\n // TODO: Should we move this to the ImageRenderer?\n public render(range: { start: number, end: number }): void {\n // Determine which layers have images\n let hasTopImages = false;\n let hasBottomImages = false;\n for (const spec of this._images.values()) {\n if (spec.layer === 'bottom') {\n hasBottomImages = true;\n } else {\n hasTopImages = true;\n }\n if (hasTopImages && hasBottomImages) break;\n }\n\n // Lazily insert layers that are needed\n if (hasTopImages && !this._renderer.hasLayer('top')) {\n this._renderer.insertLayerToDom('top');\n if (!this._renderer.hasLayer('top')) return;\n }\n if (hasBottomImages && !this._renderer.hasLayer('bottom')) {\n this._renderer.insertLayerToDom('bottom');\n }\n\n // rescale if needed\n this._renderer.rescaleCanvas();\n\n // exit early if we dont have any images to test for\n if (!this._images.size) {\n if (!this._fullyCleared) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n if (this._renderer.hasLayer('top')) {\n this._renderer.removeLayerFromDom('top');\n }\n if (this._renderer.hasLayer('bottom')) {\n this._renderer.removeLayerFromDom('bottom');\n }\n return;\n }\n\n // Remove layers no longer needed\n if (!hasTopImages && this._renderer.hasLayer('top')) {\n this._renderer.clearAll('top');\n this._renderer.removeLayerFromDom('top');\n }\n if (!hasBottomImages && this._renderer.hasLayer('bottom')) {\n this._renderer.clearAll('bottom');\n this._renderer.removeLayerFromDom('bottom');\n }\n\n // buffer switches force a full clear\n if (this._needsFullClear) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n\n const { start, end } = range;\n const buffer = this._terminal._core.buffer;\n const cols = this._terminal._core.cols;\n\n // clear drawing area\n this._renderer.clearLines(start, end);\n\n // Collect draw calls so we can sort by z-index (lower z drawn first).\n const drawCalls: { imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number }[] = [];\n const placeholderCalls: { col: number, row: number, count: number }[] = [];\n\n // walk all cells in viewport and collect tiles found\n for (let row = start; row <= end; ++row) {\n const line = buffer.lines.get(row + buffer.ydisp) as IBufferLineExt;\n if (!line) return;\n for (let col = 0; col < cols; ++col) {\n if (line.getBg(col) & BgFlags.HAS_EXTENDED) {\n let e: IExtendedAttrsImage = line._extendedAttrs[col] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (e.tileId !== -1) {\n const startTile = e.tileId;\n const startCol = col;\n let count = 1;\n /**\n * merge tiles to the right into a single draw call, if:\n * - not at end of line\n * - cell has same image id\n * - cell has consecutive tile id\n */\n while (\n ++col < cols\n && (line.getBg(col) & BgFlags.HAS_EXTENDED)\n && (e = line._extendedAttrs[col] ?? EMPTY_ATTRS)\n && (e.imageId === imageId)\n && (e.tileId === startTile + count)\n ) {\n count++;\n }\n col--;\n if (imgSpec) {\n if (imgSpec.actual) {\n drawCalls.push({ imgSpec, tileId: startTile, col: startCol, row, count });\n }\n } else if (this._opts.showPlaceholder) {\n placeholderCalls.push({ col: startCol, row, count });\n }\n this._fullyCleared = false;\n }\n }\n }\n }\n\n // Sort by z-index so lower z draws first (higher z renders on top)\n drawCalls.sort((a, b) => a.imgSpec.zIndex - b.imgSpec.zIndex);\n\n // Draw placeholders first (lowest priority)\n for (const call of placeholderCalls) {\n this._renderer.drawPlaceholder(call.col, call.row, call.count);\n }\n\n // Draw images in z-index order\n for (const call of drawCalls) {\n this._renderer.draw(call.imgSpec, call.tileId, call.col, call.row, call.count);\n }\n }\n\n public viewportResize(metrics: { cols: number, rows: number }): void {\n // exit early if we have nothing in storage\n if (!this._images.size) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // handle only viewport width enlargements, exit all other cases\n // TODO: needs patch for tile counter\n if (this._viewportMetrics.cols >= metrics.cols) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // walk scrollbuffer at old col width to find all possible expansion matches\n const buffer = this._terminal._core.buffer;\n const rows = buffer.lines.length;\n const oldCol = this._viewportMetrics.cols - 1;\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(row) as IBufferLineExt;\n if (line.getBg(oldCol) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[oldCol] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (!imgSpec) {\n continue;\n }\n // found an image tile at oldCol, check if it qualifies for right exapansion\n const tilesPerRow = Math.ceil((imgSpec.actual?.width || 0) / imgSpec.actualCellSize.width);\n if ((e.tileId % tilesPerRow) + 1 >= tilesPerRow) {\n continue;\n }\n // expand only if right side is empty (nothing got wrapped from below)\n let hasData = false;\n for (let rightCol = oldCol + 1; rightCol > metrics.cols; ++rightCol) {\n if (line._data[rightCol * Cell.SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK) {\n hasData = true;\n break;\n }\n }\n if (hasData) {\n continue;\n }\n // do right expansion on terminal buffer\n const end = Math.min(metrics.cols, tilesPerRow - (e.tileId % tilesPerRow) + oldCol);\n let lastTile = e.tileId;\n for (let expandCol = oldCol + 1; expandCol < end; ++expandCol) {\n this._writeToCell(line as IBufferLineExt, expandCol, imageId, ++lastTile);\n imgSpec.tileCount++;\n }\n }\n }\n // store new viewport metrics\n this._viewportMetrics = metrics;\n }\n\n /**\n * Retrieve original canvas at buffer position.\n */\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1) {\n const orig = this._images.get(e.imageId)?.orig;\n if (window.ImageBitmap && orig instanceof ImageBitmap) {\n const canvas = ImageRenderer.createCanvas(window.document, orig.width, orig.height);\n canvas.getContext('2d')?.drawImage(orig, 0, 0, orig.width, orig.height);\n return canvas;\n }\n return orig as HTMLCanvasElement;\n }\n }\n }\n\n /**\n * Extract active single tile at buffer position.\n */\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1 && e.tileId !== -1) {\n const spec = this._images.get(e.imageId);\n if (spec) {\n return this._renderer.extractTile(spec, e.tileId);\n }\n }\n }\n }\n\n // TODO: Do we need some blob offloading tricks here to avoid early eviction?\n // also see https://stackoverflow.com/questions/28307789/is-there-any-limitation-on-javascript-max-blob-size\n private _evictOldest(room: number): number {\n const used = this._getStoredPixels();\n let current = used;\n while (this._pixelLimit < current + room && this._images.size) {\n const spec = this._images.get(++this._lowestId);\n if (spec && spec.orig) {\n current -= spec.orig.width * spec.orig.height;\n if (spec.actual && spec.orig !== spec.actual) {\n current -= spec.actual.width * spec.actual.height;\n }\n spec.marker?.dispose();\n this._delImg(this._lowestId);\n }\n }\n return used - current;\n }\n\n private _writeToCell(line: IBufferLineExt, x: number, imageId: number, tileId: number): void {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const old = line._extendedAttrs[x];\n if (old) {\n if (old.imageId !== undefined) {\n // found an old ExtendedAttrsImage, since we know that\n // they are always isolated instances (single cell usage),\n // we can re-use it and just update their id entries\n const oldSpec = this._images.get(old.imageId);\n if (oldSpec) {\n // early eviction for in-viewport overwrites\n oldSpec.tileCount--;\n }\n old.imageId = imageId;\n old.tileId = tileId;\n return;\n }\n // found a plain ExtendedAttrs instance, clone it to new entry\n line._extendedAttrs[x] = new ExtendedAttrsImage(old.ext, old.urlId, imageId, tileId);\n return;\n }\n }\n // fall-through: always create new ExtendedAttrsImage entry\n line._data[x * Cell.SIZE + Cell.BG] |= BgFlags.HAS_EXTENDED;\n line._extendedAttrs[x] = new ExtendedAttrsImage(0, 0, imageId, tileId);\n }\n\n private _evictOnAlternate(): void {\n // nullify tile count of all images on alternate buffer\n for (const spec of this._images.values()) {\n if (spec.bufferType === 'alternate') {\n spec.tileCount = 0;\n }\n }\n // re-count tiles on whole buffer\n const buffer = this._terminal._core.buffer;\n for (let y = 0; y < this._terminal.rows; ++y) {\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (!line) {\n continue;\n }\n for (let x = 0; x < this._terminal.cols; ++x) {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const imgId = line._extendedAttrs[x]?.imageId;\n if (imgId) {\n const spec = this._images.get(imgId);\n if (spec) {\n spec.tileCount++;\n }\n }\n }\n }\n }\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate' && !spec.tileCount) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n }\n}\n","/**\n * Copyright (c) 2020, 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IDcsHandler, IParams, IImageAddonOptions, ITerminalExt, AttributeData, IResetHandler, ReadonlyColorSet } from './Types';\nimport { toRGBA8888, BIG_ENDIAN, PALETTE_ANSI_256, PALETTE_VT340_COLOR } from 'sixel/lib/Colors';\nimport { RGBA8888 } from 'sixel/lib/Types';\nimport { ImageRenderer } from './ImageRenderer';\n\nimport { DecoderAsync, Decoder } from 'sixel/lib/Decoder';\n\n// always free decoder ressources after decoding if it exceeds this limit\nconst MEM_PERMA_LIMIT = 4194304; // 1024 pixels * 1024 pixels * 4 channels = 4MB\n\n// custom default palette: VT340 (lower 16 colors) + ANSI256 (up to 256) + zeroed (up to 4096)\nconst DEFAULT_PALETTE = PALETTE_ANSI_256;\nDEFAULT_PALETTE.set(PALETTE_VT340_COLOR);\n\n\nexport class SixelHandler implements IDcsHandler, IResetHandler {\n private _size = 0;\n private _aborted = false;\n private _dec: Decoder | undefined;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _storage: SixelImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n DecoderAsync({\n memoryLimit: this._opts.pixelLimit * 4,\n palette: DEFAULT_PALETTE,\n paletteLimit: this._opts.sixelPaletteLimit\n }).then(d => this._dec = d);\n }\n\n public reset(): void {\n /**\n * reset sixel decoder to defaults:\n * - release all memory\n * - nullify palette (4096)\n * - apply default palette (256)\n */\n if (this._dec) {\n this._dec.release();\n // FIXME: missing interface on decoder to nullify full palette\n (this._dec as any)._palette.fill(0);\n this._dec.init(0, DEFAULT_PALETTE, this._opts.sixelPaletteLimit);\n }\n }\n\n public hook(params: IParams): void {\n this._size = 0;\n this._aborted = false;\n if (this._dec) {\n const fillColor = params.params[1] === 1 ? 0 : extractActiveBg(\n this._coreTerminal._core._inputHandler._curAttrData,\n this._coreTerminal._core._themeService?.colors);\n this._dec.init(fillColor, null, this._opts.sixelPaletteLimit);\n }\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted || !this._dec) {\n return;\n }\n this._size += end - start;\n if (this._size > this._opts.sixelSizeLimit) {\n console.warn(`SIXEL: too much data, aborting`);\n this._aborted = true;\n this._dec.release();\n return;\n }\n try {\n this._dec.decode(data, start, end);\n } catch (e) {\n console.warn(`SIXEL: error while decoding image - ${e}`);\n this._aborted = true;\n this._dec.release();\n }\n }\n\n public unhook(success: boolean): boolean | Promise {\n if (this._aborted || !success || !this._dec) {\n return true;\n }\n\n const width = this._dec.width;\n const height = this._dec.height;\n\n // partial fix for https://github.com/jerch/xterm-addon-image/issues/37\n if (!width || !height) {\n if (height) {\n this._storage.advanceCursor(height);\n }\n return true;\n }\n\n const canvas = ImageRenderer.createCanvas(undefined, width, height);\n canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8 as Uint8ClampedArray, width, height), 0, 0);\n if (this._dec.memoryUsage > MEM_PERMA_LIMIT) {\n this._dec.release();\n }\n this._storage.addImage(canvas);\n return true;\n }\n}\n\n\n/**\n * Some helpers to extract current terminal colors.\n */\n\n// get currently active background color from terminal\n// also respect INVERSE setting\nfunction extractActiveBg(attr: AttributeData, colors: ReadonlyColorSet | undefined): RGBA8888 {\n let bg = 0;\n if (!colors) {\n // FIXME: theme service is prolly not available yet,\n // happens if .open() was not called yet (bug in core?)\n return bg;\n }\n if (attr.isInverse()) {\n if (attr.isFgDefault()) {\n bg = convertLe(colors.foreground.rgba);\n } else if (attr.isFgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getFgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getFgColor()].rgba);\n }\n } else {\n if (attr.isBgDefault()) {\n bg = convertLe(colors.background.rgba);\n } else if (attr.isBgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getBgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getBgColor()].rgba);\n }\n }\n return bg;\n}\n\n// rgba values on the color managers are always in BE, thus convert to LE\nfunction convertLe(color: number): RGBA8888 {\n if (BIG_ENDIAN) return color;\n return (color & 0xFF) << 24 | (color >>> 8 & 0xFF) << 16 | (color >>> 16 & 0xFF) << 8 | color >>> 24 & 0xFF;\n}\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { IImageAddonOptions, ITerminalExt, IAddImageOpts } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\n\n/**\n * Sixel-specific image storage controller.\n *\n * Wraps the shared ImageStorage with sixel protocol semantics:\n * - Cursor behavior governed by DECSET 80 (sixelScrolling option)\n * - advanceCursor for empty sixels carrying only height\n */\nexport class SixelImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'vt340' };\n constructor(\n private readonly _storage: ImageStorage,\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _terminal: ITerminalExt\n ) {}\n\n /**\n * Add a sixel image to storage.\n * Cursor behavior depends on the sixelScrolling option (DECSET 80).\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._addImageOpts.scrolling = this._opts.sixelScrolling;\n this._storage.addImage(img, this._addImageOpts);\n }\n\n /**\n * Only advance text cursor.\n * This is an edge case from empty sixels carrying only a height but no pixels.\n * Partially fixes https://github.com/jerch/xterm-addon-image/issues/37.\n */\n public advanceCursor(height: number): void {\n if (this._opts.sixelScrolling) {\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const rows = Math.ceil(height / cellSize.height);\n for (let i = 1; i < rows; ++i) {\n this._terminal._core._inputHandler.lineFeed();\n }\n }\n }\n}\n","/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { IApcHandler, IImageAddonOptions, IResetHandler, ITerminalExt, ImageLayer } from '../Types';\nimport { ImageRenderer } from '../ImageRenderer';\nimport { CELL_SIZE_DEFAULT } from '../ImageStorage';\nimport { KittyImageStorage } from './KittyImageStorage';\nimport Base64Decoder, { type DecodeStatus } from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport {\n KittyAction,\n KittyFormat,\n KittyCompression,\n IKittyCommand,\n IPendingTransmission,\n IKittyImageData,\n KittyPixelConstants,\n parseKittyCommand\n} from './KittyGraphicsTypes';\n\nconst enum Constants {\n // Memory limit for base64 decoder (4MB, same as IIPHandler)\n DECODER_KEEP_DATA = 4194304,\n DECODER_INITIAL_DATA = 4194304, // 4MB\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n DECODER_OK = 0,\n // Maximum control data size\n MAX_CONTROL_DATA_SIZE = 512,\n // Semicolon codepoint\n SEMICOLON = 0x3B\n}\n\nconst DECODER_OK = Constants.DECODER_OK as unknown as DecodeStatus.OK;\n\n// Kitty graphics protocol handler with streaming base64 decoding.\nexport class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDisposable {\n private _aborted = false;\n private _decodeError = false;\n\n private _activeDecoder: Base64Decoder | null = null;\n private readonly _maxEncodedBytes: number;\n private readonly _initialEncodedBytes: number;\n\n // Streaming related states\n\n // True while receiving control data (before semicolon).\n private _inControlData = true;\n\n // Buffer for control data.\n private _controlData = new Uint32Array(Constants.MAX_CONTROL_DATA_SIZE);\n private _controlLength = 0;\n\n // Pre-calculated encoded size limit\n private _encodedSizeLimit = 0;\n private _totalEncodedSize = 0;\n\n // Parsed command. These are the control data before semicolon.\n private _parsedCommand: IKittyCommand | null = null;\n\n // Storage related states\n\n private _pendingTransmissions: Map = new Map();\n // Tracks the pending key of the most recently started chunked upload.\n // Per spec, subsequent chunks only need m= (and optionally q=), without i=.\n // When a chunk arrives with no i=, this key is used to find the pending upload.\n private _lastPendingKey: number | undefined;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _kittyStorage: KittyImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n // Convert decoded size limit -> max encoded bytes.\n this._maxEncodedBytes = Math.ceil(this._opts.kittySizeLimit * 4 / 3);\n // ensure we preallocate more than configured limit while using 4mb initial size.\n this._initialEncodedBytes = Math.min(Constants.DECODER_INITIAL_DATA, this._maxEncodedBytes);\n }\n\n public reset(): void {\n this._cleanupAllPending();\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n this._kittyStorage.reset();\n }\n\n public dispose(): void {\n this.reset();\n }\n\n private _removePendingEntry(key: number): void {\n this._pendingTransmissions.delete(key);\n if (this._lastPendingKey === key) {\n this._lastPendingKey = undefined;\n }\n }\n\n private _cleanupAllPending(): void {\n for (const pending of this._pendingTransmissions.values()) {\n pending.decoder.release();\n }\n this._pendingTransmissions.clear();\n this._lastPendingKey = undefined;\n }\n\n public start(): void {\n this._aborted = false;\n this._decodeError = false;\n this._inControlData = true;\n this._controlLength = 0;\n this._parsedCommand = null;\n // Pre-calculate encoded limit once: base64 is 4 bytes encoded → 3 bytes decoded\n this._encodedSizeLimit = this._maxEncodedBytes;\n this._totalEncodedSize = 0;\n this._activeDecoder = null;\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (!this._inControlData) {\n this._streamPayload(data, start, end);\n } else {\n // Scan for semicolon\n let controlEnd = end;\n for (let i = start; i < end; i++) {\n if (data[i] === Constants.SEMICOLON) {\n this._inControlData = false;\n controlEnd = i;\n break;\n }\n }\n\n // Copy control data\n const copyLength = controlEnd - start;\n if (this._controlLength + copyLength > Constants.MAX_CONTROL_DATA_SIZE) {\n this._aborted = true;\n return;\n }\n this._controlData.set(data.subarray(start, controlEnd), this._controlLength);\n this._controlLength += copyLength;\n\n if (!this._inControlData) {\n // Found semicolon - parse control data early for validation\n this._parsedCommand = parseKittyCommand(this._parseControlDataString());\n\n // Early validation: i+I conflict\n if (this._parsedCommand.id !== undefined && this._parsedCommand.imageNumber !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'EINVAL:cannot specify both i and I keys', this._parsedCommand.quiet ?? 0);\n this._aborted = true;\n return;\n }\n\n // Delete action doesn't need payload - skip streaming\n if (this._parsedCommand.action === KittyAction.DELETE) {\n return;\n }\n\n // Stream remaining as payload\n const payloadStart = controlEnd + 1;\n if (payloadStart < end) {\n this._streamPayload(data, payloadStart, end);\n }\n }\n }\n }\n\n // Stream payload bytes into the base64 decoder.\n private _streamPayload(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n // Check size limit (compare encoded bytes against pre-calculated limit)\n // Include cumulative size from pending transmission for multi-chunk images.\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = this._parsedCommand?.id ?? this._lastPendingKey ?? 0;\n const pending = this._pendingTransmissions.get(pendingKey);\n const previousEncodedSize = pending?.totalEncodedSize ?? 0;\n this._totalEncodedSize += end - start;\n const cumulativeEncodedSize = previousEncodedSize + this._totalEncodedSize;\n if (cumulativeEncodedSize > this._encodedSizeLimit) {\n const decoderToRelease = this._activeDecoder ?? pending?.decoder;\n if (decoderToRelease) {\n decoderToRelease.release();\n }\n this._activeDecoder = null;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n this._aborted = true;\n return;\n }\n\n if (this._decodeError) return;\n\n if (pending?.decoder && !this._activeDecoder) {\n this._activeDecoder = pending.decoder;\n }\n if (!this._activeDecoder) {\n this._activeDecoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes);\n this._activeDecoder.init();\n }\n\n if (this._activeDecoder.put(data.subarray(start, end)) !== DECODER_OK) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n this._decodeError = true;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted || !success) {\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n return true;\n }\n\n // No semicolon = no payload (delete, capability query)\n if (this._inControlData) {\n return this._handleNoPayloadCommand();\n }\n\n // Use command parsed early in put() - i+I already validated there\n const cmd = this._parsedCommand!;\n\n // Delete action was handled by skipping payload - just execute\n if (cmd.action === KittyAction.DELETE) {\n return this._handleDelete(cmd);\n }\n\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = cmd.id ?? this._lastPendingKey ?? 0;\n const isMoreComing = cmd.more === 1;\n const pending = this._pendingTransmissions.get(pendingKey);\n\n if (isMoreComing) {\n if (this._activeDecoder) {\n if (pending) {\n pending.totalEncodedSize += this._totalEncodedSize;\n pending.decodeError = pending.decodeError || this._decodeError;\n } else {\n this._pendingTransmissions.set(pendingKey, {\n cmd: { ...cmd },\n decoder: this._activeDecoder,\n totalEncodedSize: this._totalEncodedSize,\n decodeError: this._decodeError\n });\n }\n this._lastPendingKey = pendingKey;\n this._activeDecoder = null;\n }\n return true;\n }\n\n // Final chunk received — clear the last pending key\n if (pending) {\n this._lastPendingKey = undefined;\n }\n\n let decodeError = this._decodeError;\n let finalCmd = cmd;\n let decoder = this._activeDecoder;\n\n if (pending) {\n finalCmd = pending.cmd;\n decoder = pending.decoder;\n decodeError = decodeError || pending.decodeError;\n this._pendingTransmissions.delete(pendingKey);\n }\n\n let imageBytes = new Uint8Array(0);\n if (decoder) {\n if (decoder.end() !== DECODER_OK) {\n decodeError = true;\n }\n imageBytes = decoder.data8;\n }\n this._activeDecoder = null;\n\n // Handle command first — handlers create Blob/ImageData from imageBytes,\n // which copies the data. Only then is it safe to release the decoder's\n // wasm memory that imageBytes points into.\n const result = this._handleCommandWithBytesAndCmd(finalCmd, imageBytes, decodeError);\n if (decoder) {\n decoder.release();\n }\n return result;\n }\n\n // Command handling\n\n private _parseControlDataString(): string {\n let str = '';\n for (let i = 0; i < this._controlLength; i++) {\n str += String.fromCodePoint(this._controlData[i]);\n }\n return str;\n }\n\n private _handleNoPayloadCommand(): boolean | Promise {\n const cmd = parseKittyCommand(this._parseControlDataString());\n\n // Per spec: specifying both i and I is an error\n if (cmd.id !== undefined && cmd.imageNumber !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:cannot specify both i and I keys', cmd.quiet ?? 0);\n return true;\n }\n\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.DELETE:\n return this._handleDelete(cmd);\n case KittyAction.QUERY:\n this._sendResponse(cmd.id ?? 0, 'OK', cmd.quiet ?? 0);\n return true;\n case KittyAction.PLACEMENT:\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handleCommandWithBytesAndCmd(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.TRANSMIT: {\n const result = this._handleTransmit(cmd, bytes, decodeError);\n // Only send response when _handleTransmit didn't already respond\n // (it handles unsupported transmission medium responses internally)\n if ((cmd.transmission ?? 'd') === 'd' && cmd.id !== undefined) {\n if (decodeError) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n } else if (bytes.length > 0) {\n this._sendResponse(cmd.id, 'OK', cmd.quiet ?? 0);\n }\n }\n return result;\n }\n case KittyAction.TRANSMIT_DISPLAY:\n return this._handleTransmitDisplay(cmd, bytes, decodeError);\n case KittyAction.QUERY:\n return this._handleQuery(cmd, bytes, decodeError);\n case KittyAction.PLACEMENT:\n // a=p ignores any payload — image data was already transmitted\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handlePlacement(cmd: IKittyCommand): boolean | Promise {\n if (cmd.id === undefined) {\n return true;\n }\n const id = cmd.id;\n const image = this._kittyStorage.getImage(id);\n if (!image) {\n this._sendResponse(id, 'ENOENT:image not found', cmd.quiet ?? 0, cmd.placementId);\n return true;\n }\n const result = this._displayImage(image, cmd);\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0, cmd.placementId);\n return true;\n });\n }\n\n private _handleTransmit(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n // TODO: Support file-based transmission modes (t=f, t=t, t=s)\n // Currently only supports direct transmission (t=d, the default).\n // - t=f (file): Payload is base64-encoded file path. Terminal reads image from that path.\n // - t=t (temp file): Payload is base64-encoded path in temp directory. Terminal reads, deletes.\n // - t=s: Payload is base64-encoded POSIX shm name. Terminal reads from shared memory.\n // These modes require filesystem/IPC access not available in browsers. For Node.js/Electron:\n // 1. Check cmd.transmission (t key) before treating bytes as image data\n // 2. For t=f/t/s: decode bytes as UTF-8 string (the path/name), then read file contents\n // 3. For t=d: treat bytes as image data (current behavior)\n // When implementing, also update _handleQuery to accept these transmission mediums.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported transmission medium', cmd.quiet ?? 0);\n }\n return true;\n }\n\n if (decodeError || bytes.length === 0) return true;\n\n this._kittyStorage.storeImage(cmd.id, {\n data: new Blob([bytes as BlobPart]),\n width: cmd.width ?? 0,\n height: cmd.height ?? 0,\n format: (cmd.format ?? KittyFormat.RGBA) as 24 | 32 | 100,\n compression: cmd.compression ?? ''\n });\n return true;\n }\n\n private _handleTransmitDisplay(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n if (decodeError) {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n }\n return true;\n }\n\n this._handleTransmit(cmd, bytes, decodeError);\n\n const id = cmd.id ?? this._kittyStorage.lastImageId;\n const image = this._kittyStorage.getImage(id);\n if (image) {\n const result = this._displayImage(image, cmd);\n if (cmd.id !== undefined) {\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0);\n return true;\n });\n }\n return result.then(() => true);\n }\n return true;\n }\n\n private _handleQuery(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n const id = cmd.id ?? 0;\n const quiet = cmd.quiet ?? 0;\n\n // Per spec: reject unsupported transmission mediums (only t=d is supported atm)\n // TODO: When filesystem support is added (Node.js/Electron), update this to accept\n // t=f (file), t=t (temp file), and t=s (shared memory) and respond OK for queries.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n this._sendResponse(id, 'EINVAL:unsupported transmission medium', quiet);\n return true;\n }\n\n // Check decode error first (invalid base64)\n if (decodeError) {\n this._sendResponse(id, 'EINVAL:invalid base64 data', quiet);\n return true;\n }\n\n // Capability query (no payload) - just respond OK\n if (bytes.length === 0) {\n this._sendResponse(id, 'OK', quiet);\n return true;\n }\n\n const format = cmd.format ?? KittyFormat.RGBA;\n\n if (format === KittyFormat.PNG) {\n this._sendResponse(id, 'OK', quiet);\n } else {\n const width = cmd.width ?? 0;\n const height = cmd.height ?? 0;\n\n if (!width || !height) {\n this._sendResponse(id, 'EINVAL:width and height required for raw pixel data', quiet);\n return true;\n }\n\n const bytesPerPixel = format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n this._sendResponse(id, `EINVAL:insufficient pixel data`, quiet);\n return true;\n }\n\n this._sendResponse(id, 'OK', quiet);\n }\n return true;\n }\n\n private _handleDelete(cmd: IKittyCommand): boolean {\n // Per spec: default delete selector is 'a' (delete all visible placements)\n const selector = cmd.deleteSelector ?? 'a';\n\n // TODO: Distinguish lowercase (delete placements only) from uppercase\n // (delete placements + free stored image data). Currently both variants\n // free everything since we don't separate stored data from placements.\n switch (selector) {\n case 'a':\n case 'A':\n this._cleanupAllPending();\n this._kittyStorage.deleteAll();\n break;\n case 'i':\n case 'I':\n // TODO: When placement id tracking is implemented (see TODO in\n // KittyImageStorage), d=i with p= should delete only that\n // specific placement, while d=i without p should delete all\n // placements for the image.\n if (cmd.id !== undefined) {\n const pending = this._pendingTransmissions.get(cmd.id);\n if (pending) {\n pending.decoder.release();\n }\n this._removePendingEntry(cmd.id);\n this._kittyStorage.deleteById(cmd.id);\n }\n break;\n default:\n // Unsupported selectors (c, n, p, q, r, x, y, z, f) — ignore for now\n break;\n }\n return true;\n }\n\n private _sendResponse(id: number, message: string, quiet: number, placementId?: number): void {\n const isOk = message === 'OK';\n if (isOk && quiet >= 1) return;\n if (!isOk && quiet >= 2) return;\n\n const pPart = placementId ? `,p=${placementId}` : '';\n const response = `\\x1b_Gi=${id}${pPart};${message}\\x1b\\\\`;\n this._coreTerminal._core.coreService.triggerDataEvent(response);\n }\n\n // Image display\n\n private _displayImage(image: IKittyImageData, cmd: IKittyCommand): Promise {\n return this._decodeAndDisplay(image, cmd)\n .then(() => true)\n .catch(() => false);\n }\n\n private async _decodeAndDisplay(image: IKittyImageData, cmd: IKittyCommand): Promise {\n let bitmap: ImageBitmap | undefined = await this._createBitmap(image);\n\n try {\n const cropX = Math.max(0, cmd.x ?? 0);\n const cropY = Math.max(0, cmd.y ?? 0);\n const cropW = cmd.sourceWidth || (bitmap.width - cropX);\n const cropH = cmd.sourceHeight || (bitmap.height - cropY);\n\n const maxCropW = Math.max(0, bitmap.width - cropX);\n const maxCropH = Math.max(0, bitmap.height - cropY);\n const finalCropW = Math.max(0, Math.min(cropW, maxCropW));\n const finalCropH = Math.max(0, Math.min(cropH, maxCropH));\n\n if (finalCropW === 0 || finalCropH === 0) {\n throw new Error('invalid source rectangle');\n }\n\n if (cropX !== 0 || cropY !== 0 || finalCropW !== bitmap.width || finalCropH !== bitmap.height) {\n const cropped = await createImageBitmap(bitmap, cropX, cropY, finalCropW, finalCropH);\n bitmap.close();\n bitmap = cropped;\n }\n\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n\n // Per spec: c/r default to image's natural cell dimensions.\n // If only one of c/r is specified, compute the other from image aspect ratio.\n let imgCols: number;\n let imgRows: number;\n if (cmd.columns !== undefined && cmd.rows !== undefined) {\n imgCols = cmd.columns;\n imgRows = cmd.rows;\n } else if (cmd.columns !== undefined) {\n imgCols = cmd.columns;\n imgRows = Math.max(1, Math.ceil((bitmap.height / bitmap.width) * (imgCols * cw) / ch));\n } else if (cmd.rows !== undefined) {\n imgRows = cmd.rows;\n imgCols = Math.max(1, Math.ceil((bitmap.width / bitmap.height) * (imgRows * ch) / cw));\n } else {\n imgCols = Math.ceil(bitmap.width / cw);\n imgRows = Math.ceil(bitmap.height / ch);\n }\n\n let w = bitmap.width;\n let h = bitmap.height;\n\n // Scale bitmap to fit placement rectangle when c/r are specified\n if (cmd.columns !== undefined || cmd.rows !== undefined) {\n w = Math.round(imgCols * cw);\n h = Math.round(imgRows * ch);\n }\n\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n\n // Save cursor position before addImage modifies it\n const buffer = this._coreTerminal._core.buffer;\n const savedX = buffer.x;\n const savedY = buffer.y;\n const savedYbase = buffer.ybase;\n\n // Determine layer based on z-index: negative = behind text, 0+ = on top.\n // When z<0 we always use the bottom layer even without allowTransparency —\n // the image will simply be hidden behind the opaque text background, which\n // is the correct behavior (client asked for \"behind text\").\n const wantsBottom = cmd.zIndex !== undefined && cmd.zIndex < 0;\n const layer: ImageLayer = wantsBottom ? 'bottom' : 'top';\n\n if (w !== bitmap.width || h !== bitmap.height) {\n const scaled = await createImageBitmap(bitmap, { resizeWidth: w, resizeHeight: h });\n bitmap.close();\n bitmap = scaled;\n }\n\n // Per spec: X/Y are pixel offsets within the first cell, so clamp to cell dimensions\n const xOffset = Math.min(Math.max(0, cmd.xOffset ?? 0), cw - 1);\n const yOffset = Math.min(Math.max(0, cmd.yOffset ?? 0), ch - 1);\n if (xOffset !== 0 || yOffset !== 0) {\n // Per spec: X/Y is not added to c/r area. When c/r are explicit, the\n // total placement area remains c*cw × r*ch pixels and the offset image\n // is clipped to fit. When c/r are unset, the padded canvas determines\n // the natural cell dimensions.\n const canvasW = (cmd.columns !== undefined) ? Math.round(imgCols * cw) : bitmap.width + xOffset;\n const canvasH = (cmd.rows !== undefined) ? Math.round(imgRows * ch) : bitmap.height + yOffset;\n const offsetCanvas = ImageRenderer.createCanvas(window.document, canvasW, canvasH);\n const offsetCtx = offsetCanvas.getContext('2d');\n if (!offsetCtx) {\n throw new Error('Failed to create offset canvas context');\n }\n offsetCtx.drawImage(bitmap, xOffset, yOffset);\n\n const offsetBitmap = await createImageBitmap(offsetCanvas);\n offsetCanvas.width = offsetCanvas.height = 0;\n bitmap.close();\n bitmap = offsetBitmap;\n w = bitmap.width;\n h = bitmap.height;\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n if (cmd.columns === undefined) {\n imgCols = Math.ceil(bitmap.width / cw);\n }\n if (cmd.rows === undefined) {\n imgRows = Math.ceil(bitmap.height / ch);\n }\n }\n\n const zIndex = cmd.zIndex ?? 0;\n this._kittyStorage.addImage(image.id, bitmap, true, layer, zIndex);\n bitmap = undefined; // ownership transferred to storage\n\n // Kitty cursor movement\n // Per spec: cursor placed at first column after last image column,\n // on the last row of the image. C=1 means don't move cursor.\n if (cmd.cursorMovement === 1) {\n // C=1: restore cursor to position before image was placed\n const scrolled = buffer.ybase - savedYbase;\n buffer.x = savedX;\n // Can't restore cursor to scrollback?\n buffer.y = Math.max(savedY - scrolled, 0);\n } else {\n // Default (C=0): advance cursor horizontally past the image\n // addImage already positioned cursor on the last row via lineFeeds\n buffer.x = Math.min(savedX + imgCols, this._coreTerminal.cols);\n }\n } catch (e) {\n bitmap?.close();\n throw e;\n }\n }\n\n // Create ImageBitmap from already-decoded image data.\n private async _createBitmap(image: IKittyImageData): Promise {\n let bytes: Uint8Array = new Uint8Array(await image.data.arrayBuffer());\n\n if (image.compression === KittyCompression.ZLIB) {\n bytes = await this._decompressZlib(bytes);\n }\n\n if (image.format === KittyFormat.PNG) {\n const blob = new Blob([bytes as BlobPart], { type: 'image/png' });\n if (!window.createImageBitmap) {\n const url = URL.createObjectURL(blob);\n const img = new Image();\n return new Promise((resolve, reject) => {\n img.addEventListener('load', () => {\n URL.revokeObjectURL(url);\n const canvas = ImageRenderer.createCanvas(window.document, img.width, img.height);\n canvas.getContext('2d')?.drawImage(img, 0, 0);\n createImageBitmap(canvas).then(resolve).catch(reject);\n });\n img.addEventListener('error', () => {\n URL.revokeObjectURL(url);\n reject(new Error('Failed to load image'));\n });\n img.src = url;\n });\n }\n return createImageBitmap(blob);\n }\n\n // Raw pixel data\n const width = image.width;\n const height = image.height;\n\n if (!width || !height) {\n throw new Error('Width and height required for raw pixel data');\n }\n\n const bytesPerPixel = image.format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n throw new Error('Insufficient pixel data');\n }\n\n const pixelCount = width * height;\n\n if (image.format === KittyFormat.RGBA) {\n // RGBA: use bytes directly — no copy needed\n return createImageBitmap(new ImageData(new Uint8ClampedArray(bytes.buffer as ArrayBuffer, bytes.byteOffset, pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA), width, height));\n }\n\n // RGB→RGBA: interleave alpha using uint32 block processing (4 pixels per iteration).\n // 3 uint32 reads + 4 uint32 writes per 4 pixels vs 28 byte reads/writes — ~6x faster.\n // Assumes little-endian (all modern browsers/Node.js).\n const data = new Uint8ClampedArray(pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA);\n const src32 = new Uint32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4));\n const dst32 = new Uint32Array(data.buffer);\n const alignedPixels = pixelCount & ~3; // round down to multiple of 4\n\n let srcOffset = 0;\n let dstOffset = 0;\n for (let i = 0; i < alignedPixels; i += 4) {\n const b0 = src32[srcOffset++];\n const b1 = src32[srcOffset++];\n const b2 = src32[srcOffset++];\n // Little-endian: pixel bytes are [R,G,B] → uint32 ABGR layout\n dst32[dstOffset++] = 0xFF000000 | b0;\n dst32[dstOffset++] = 0xFF000000 | (b0 >>> 24) | (b1 << 8);\n dst32[dstOffset++] = 0xFF000000 | (b1 >>> 16) | (b2 << 16);\n dst32[dstOffset++] = 0xFF000000 | (b2 >>> 8);\n }\n\n // Handle remaining 1–3 pixels\n let srcByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n let dstByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n for (let i = alignedPixels; i < pixelCount; i++) {\n data[dstByte] = bytes[srcByte];\n data[dstByte + 1] = bytes[srcByte + 1];\n data[dstByte + 2] = bytes[srcByte + 2];\n data[dstByte + 3] = KittyPixelConstants.ALPHA_OPAQUE;\n srcByte += KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n dstByte += KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n }\n\n return createImageBitmap(new ImageData(data, width, height));\n }\n\n private async _decompressZlib(compressed: Uint8Array): Promise {\n try {\n return await this._decompress(compressed, 'deflate');\n } catch {\n return await this._decompress(compressed, 'deflate-raw');\n }\n }\n\n private async _decompress(compressed: Uint8Array, format: 'deflate' | 'deflate-raw'): Promise {\n const ds = new DecompressionStream(format);\n const writer = ds.writable.getWriter();\n writer.write(compressed as BufferSource);\n writer.close();\n\n const chunks: Uint8Array[] = [];\n const reader = ds.readable.getReader();\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n }\n\n public get images(): ReadonlyMap {\n return this._kittyStorage.images;\n }\n\n public get _kittyIdToStorageId(): ReadonlyMap {\n return this._kittyStorage.kittyIdToStorageId;\n }\n\n public get pendingTransmissions(): ReadonlyMap {\n return this._pendingTransmissions;\n }\n}\n","/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Kitty graphics protocol types, constants, and parsing utilities.\n */\n\nimport type Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\n\n// Kitty graphics protocol action types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'a'.\nexport const enum KittyAction {\n TRANSMIT = 't',\n TRANSMIT_DISPLAY = 'T',\n QUERY = 'q',\n PLACEMENT = 'p',\n DELETE = 'd'\n}\n\n// Kitty graphics protocol format types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyFormat {\n RGB = 24,\n RGBA = 32,\n PNG = 100\n}\n\n// Kitty graphics protocol compression types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'o'.\nexport const enum KittyCompression {\n NONE = '',\n ZLIB = 'z'\n}\n\n// Kitty graphics protocol control data keys.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyKey {\n // Action to perform (t=transmit, T=transmit+display, q=query, p=placement, d=delete)\n ACTION = 'a',\n // Image format (24=RGB, 32=RGBA, 100=PNG)\n FORMAT = 'f',\n // Image ID for referencing stored images\n ID = 'i',\n // Image number (alternative to ID, terminal assigns ID)\n IMAGE_NUMBER = 'I',\n // Source image width in pixels\n WIDTH = 's',\n // Source image height in pixels\n HEIGHT = 'v',\n // The left edge (in pixels) of the image area to display\n X_OFFSET = 'x',\n // The top edge (in pixels) of the image area to display\n Y_OFFSET = 'y',\n // Width (in pixels) of the source rectangle to display\n SOURCE_WIDTH = 'w',\n // Height (in pixels) of the source rectangle to display\n SOURCE_HEIGHT = 'h',\n // Horizontal offset (in pixels) within the first cell\n X_PLACEMENT_OFFSET = 'X',\n // Vertical offset (in pixels) within the first cell\n Y_PLACEMENT_OFFSET = 'Y',\n // Number of terminal columns to display the image over\n COLUMNS = 'c',\n // Number of terminal rows to display the image over\n ROWS = 'r',\n // More data flag (1=more chunks coming, 0=final chunk)\n MORE = 'm',\n // Compression type (z=zlib). This is essential for chunking larger images.\n COMPRESSION = 'o',\n // Quiet mode (1=suppress OK responses, 2=suppress error responses)\n QUIET = 'q',\n // Cursor movement policy (0=move cursor after image, 1=don't move cursor)\n CURSOR_MOVEMENT = 'C',\n // Z-index for image layering (negative = behind text, 0+ = on top)\n Z_INDEX = 'z',\n // Transmission medium (d=direct, f=file, t=temp file, s=shared memory)\n TRANSMISSION = 't',\n // Delete selector (a/A=all, i/I=by id, c/C=at cursor, etc.) — only used when a=d\n DELETE_SELECTOR = 'd',\n // Placement ID for targeting specific placements\n PLACEMENT_ID = 'p'\n}\n\n// Pixel format constants\nexport const enum KittyPixelConstants {\n BYTES_PER_PIXEL_RGB = 3,\n BYTES_PER_PIXEL_RGBA = 4,\n ALPHA_OPAQUE = 255\n}\n\n// Parsed Kitty graphics command.\nexport interface IKittyCommand {\n action?: string;\n format?: number;\n id?: number;\n imageNumber?: number;\n width?: number;\n height?: number;\n x?: number;\n y?: number;\n sourceWidth?: number;\n sourceHeight?: number;\n xOffset?: number;\n yOffset?: number;\n columns?: number;\n rows?: number;\n more?: number;\n quiet?: number;\n cursorMovement?: number;\n zIndex?: number;\n transmission?: string;\n deleteSelector?: string;\n placementId?: number;\n compression?: string;\n payload?: string;\n}\n\n// Pending chunked transmission state.\n// Stores metadata from the first chunk while accumulating decoded payload data.\nexport interface IPendingTransmission {\n // The parsed command from the first chunk (contains action, format, dimensions, etc.)\n cmd: IKittyCommand;\n // Decoder used across chunked payloads\n decoder: Base64Decoder;\n // Total encoded (base64) bytes received across all chunks - for size limit enforcement\n totalEncodedSize: number;\n // Whether any chunk has failed to decode\n decodeError: boolean;\n}\n\n// Stored Kitty image data.\nexport interface IKittyImageData {\n id: number;\n // Decoded image data stored as Blob (off JS heap) to avoid 2GB heap limit\n data: Blob;\n width: number;\n height: number;\n format: 24 | 32 | 100;\n compression?: string;\n}\n\n// Parses Kitty graphics control data into a command object.\nexport function parseKittyCommand(data: string): IKittyCommand {\n const cmd: IKittyCommand = {};\n const parts = data.split(',');\n\n for (const part of parts) {\n const eqIdx = part.indexOf('=');\n if (eqIdx === -1) continue;\n\n const key = part.substring(0, eqIdx);\n const value = part.substring(eqIdx + 1);\n\n // Handle string keys first\n if (key === KittyKey.ACTION) {\n cmd.action = value;\n continue;\n }\n if (key === KittyKey.COMPRESSION) {\n cmd.compression = value;\n continue;\n }\n if (key === KittyKey.TRANSMISSION) {\n cmd.transmission = value;\n continue;\n }\n if (key === KittyKey.DELETE_SELECTOR) {\n cmd.deleteSelector = value;\n continue;\n }\n const numValue = parseInt(value, 10);\n switch (key) {\n case KittyKey.FORMAT: cmd.format = numValue; break;\n case KittyKey.ID: cmd.id = numValue; break;\n case KittyKey.IMAGE_NUMBER: cmd.imageNumber = numValue; break;\n case KittyKey.WIDTH: cmd.width = numValue; break;\n case KittyKey.HEIGHT: cmd.height = numValue; break;\n case KittyKey.X_OFFSET: cmd.x = numValue; break;\n case KittyKey.Y_OFFSET: cmd.y = numValue; break;\n case KittyKey.SOURCE_WIDTH: cmd.sourceWidth = numValue; break;\n case KittyKey.SOURCE_HEIGHT: cmd.sourceHeight = numValue; break;\n case KittyKey.X_PLACEMENT_OFFSET: cmd.xOffset = numValue; break;\n case KittyKey.Y_PLACEMENT_OFFSET: cmd.yOffset = numValue; break;\n case KittyKey.COLUMNS: cmd.columns = numValue; break;\n case KittyKey.ROWS: cmd.rows = numValue; break;\n case KittyKey.MORE: cmd.more = numValue; break;\n case KittyKey.QUIET: cmd.quiet = numValue; break;\n case KittyKey.CURSOR_MOVEMENT: cmd.cursorMovement = numValue; break;\n case KittyKey.Z_INDEX: cmd.zIndex = numValue; break;\n case KittyKey.PLACEMENT_ID: cmd.placementId = numValue; break;\n }\n }\n\n return cmd;\n}\n","/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageStorage } from '../ImageStorage';\nimport { ImageLayer, IAddImageOpts } from '../Types';\nimport { IKittyImageData } from './KittyGraphicsTypes';\n\n// Kitty-specific image storage controller.\n//\n// Wraps shared ImageStorage with kitty protocol semantics:\n// - tracks transmitted image payloads by kitty image id\n// - tracks kitty image id -> shared ImageStorage id mapping for displayed images\n// - mirrors shared-storage evictions into kitty maps\n// - applies protocol-level undisplayed-image eviction policy\nexport class KittyImageStorage implements IDisposable {\n private static readonly _maxStoredImages = 256;\n\n private _nextImageId = 1;\n private readonly _images: Map = new Map();\n // TODO: Support multiple placements per image. The kitty spec identifies\n // placements by an (image id, placement id) pair — same i + different p\n // values should coexist, and same i + same p should replace the prior\n // placement. Currently we track only one storage entry per kitty image id,\n // so multiple placements of the same image overwrite each other. Fixing\n // this requires changing these maps to Map>\n // (kittyId → placementId → storageId) and updating addImage/deleteById\n // accordingly. The underlying shared ImageStorage would also need to\n // support multiple entries per logical image.\n private readonly _kittyIdToStorageId: Map = new Map();\n private readonly _storageIdToKittyId: Map = new Map();\n\n private readonly _previousOnImageDeleted: ((storageId: number) => void) | undefined;\n private readonly _wrappedOnImageDeleted: (storageId: number) => void;\n private readonly _handleStorageImageDeleted = (storageId: number): void => {\n const kittyId = this._storageIdToKittyId.get(storageId);\n if (kittyId !== undefined) {\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n this._images.delete(kittyId);\n }\n };\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n\n constructor(\n private readonly _storage: ImageStorage\n ) {\n this._previousOnImageDeleted = this._storage.onImageDeleted;\n this._wrappedOnImageDeleted = (storageId: number) => {\n this._previousOnImageDeleted?.(storageId);\n this._handleStorageImageDeleted(storageId);\n };\n this._storage.onImageDeleted = this._wrappedOnImageDeleted;\n }\n\n public reset(): void {\n this._nextImageId = 1;\n this._images.clear();\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public dispose(): void {\n this.reset();\n if (this._storage.onImageDeleted === this._wrappedOnImageDeleted) {\n this._storage.onImageDeleted = this._previousOnImageDeleted;\n }\n }\n\n public storeImage(id: number | undefined, imageData: Omit): number {\n const imageId = id ?? this._nextImageId++;\n\n const oldStorageId = this._kittyIdToStorageId.get(imageId);\n if (oldStorageId !== undefined) {\n this._storage.deleteImage(oldStorageId);\n this._kittyIdToStorageId.delete(imageId);\n this._storageIdToKittyId.delete(oldStorageId);\n }\n\n if (!this._images.has(imageId) && this._images.size >= KittyImageStorage._maxStoredImages) {\n this._evictUndisplayedImages();\n }\n\n this._images.set(imageId, {\n ...imageData,\n id: imageId\n });\n return imageId;\n }\n\n public addImage(kittyId: number, image: HTMLCanvasElement | ImageBitmap, scrolling: boolean, layer: ImageLayer, zIndex: number): void {\n // Clean up stale reverse-mapping from a previous placement of the same\n // kitty image. The old shared-storage entry is kept (it may still be\n // visible on screen) but its reverse mapping is removed so that eviction\n // of the old entry won't incorrectly delete the kitty image data.\n const oldStorageId = this._kittyIdToStorageId.get(kittyId);\n if (oldStorageId !== undefined) {\n this._storageIdToKittyId.delete(oldStorageId);\n }\n this._addImageOpts.scrolling = scrolling;\n this._addImageOpts.layer = layer;\n this._addImageOpts.zIndex = zIndex;\n const storageId = this._storage.addImage(image, this._addImageOpts);\n this._kittyIdToStorageId.set(kittyId, storageId);\n this._storageIdToKittyId.set(storageId, kittyId);\n }\n\n public getImage(kittyId: number): IKittyImageData | undefined {\n return this._images.get(kittyId);\n }\n\n public deleteById(kittyId: number): void {\n this._images.delete(kittyId);\n const storageId = this._kittyIdToStorageId.get(kittyId);\n if (storageId !== undefined) {\n this._storage.deleteImage(storageId);\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n }\n }\n\n public deleteAll(): void {\n this._images.clear();\n for (const storageId of this._kittyIdToStorageId.values()) {\n this._storage.deleteImage(storageId);\n }\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public get images(): ReadonlyMap {\n return this._images;\n }\n\n public get kittyIdToStorageId(): ReadonlyMap {\n return this._kittyIdToStorageId;\n }\n\n public get lastImageId(): number {\n return this._nextImageId - 1;\n }\n\n private _evictUndisplayedImages(): void {\n for (const [kittyId] of this._images) {\n if (this._images.size <= KittyImageStorage._maxStoredImages / 2) {\n break;\n }\n if (!this._kittyIdToStorageId.has(kittyId)) {\n this._images.delete(kittyId);\n }\n }\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023, 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\n/**\n * wasm base64 decoder.\n */\nconst wasmDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#828e69684093b2c6:rdef-start:\"decode\"*/{s:1,t:0,d:'AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML'}/*inwasm#828e69684093b2c6:rdef-end:\"decode\"*/);\n// SIMD version (speedup ~1.4x, not covered by tests yet)\n/*\nconst wasmDecode = InWasm({\n name: 'decode',\n type: OutputType.INSTANCE,\n mode: OutputMode.SYNC,\n srctype: 'Clang-C',\n imports: {\n env: { memory: new WebAssembly.Memory({ initial: 1 }) }\n },\n exports: {\n dec: () => 0,\n end: () => 0\n },\n compile: {\n switches: ['-msimd128', '-Wl,-z,stack-size=0', '-Wl,--stack-first']\n },\n code: `\n #include \n typedef struct {\n unsigned int wp;\n unsigned int sp;\n unsigned int dp;\n unsigned int e_size;\n unsigned int dummy[4];\n unsigned char data[0];\n } State;\n\n unsigned int *D0 = (unsigned int *) ${P32.D0 * 4};\n unsigned int *D1 = (unsigned int *) ${P32.D1 * 4};\n unsigned int *D2 = (unsigned int *) ${P32.D2 * 4};\n unsigned int *D3 = (unsigned int *) ${P32.D3 * 4};\n State *state = (State *) ${P32.STATE * 4};\n\n #define packed_byte(x) wasm_i8x16_splat((char) x)\n #define packed_dword(x) wasm_i32x4_splat(x)\n #define masked(x, mask) wasm_v128_and(x, wasm_i32x4_splat(mask))\n\n __attribute__((noinline)) int dec() {\n unsigned int nsp = (state->wp - 1) & ~3;\n unsigned char *src = state->data + state->sp;\n unsigned char *end = state->data + nsp;\n unsigned char *dst = state->data + state->dp;\n unsigned int error = 0;\n\n v128_t err = wasm_i8x16_splat(0);\n unsigned char *end16 = state->data + (nsp & ~15);\n while (src < end16) {\n v128_t data = wasm_v128_load((v128_t *) src);\n\n // wasm-simd rewrite of http://0x80.pl/notesen/2016-01-17-sse-base64-decoding.html#vector-lookup-pshufb\n const v128_t higher_nibble = wasm_u32x4_shr(data, 4) & packed_byte(0x0f);\n const char linv = 1;\n const char hinv = 0;\n\n const v128_t lower_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n linv, linv, 0x2b, 0x30,\n 0x41, 0x50, 0x61, 0x70,\n linv, linv, linv, linv,\n linv, linv, linv, linv\n );\n const v128_t upper_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n hinv, hinv, 0x2b, 0x39,\n 0x4f, 0x5a, 0x6f, 0x7a,\n hinv, hinv, hinv, hinv,\n hinv, hinv, hinv, hinv\n );\n // the difference between the shift and lower bound\n const v128_t shift_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n 0x00, 0x00, 0x3e - 0x2b, 0x34 - 0x30,\n 0x00 - 0x41, 0x0f - 0x50, 0x1a - 0x61, 0x29 - 0x70,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00\n );\n\n const v128_t upper_bound = wasm_i8x16_swizzle(upper_bound_LUT, higher_nibble);\n const v128_t lower_bound = wasm_i8x16_swizzle(lower_bound_LUT, higher_nibble);\n\n const v128_t below = wasm_i8x16_lt(data, lower_bound);\n const v128_t above = wasm_i8x16_gt(data, upper_bound);\n const v128_t eq_2f = wasm_i8x16_eq(data, packed_byte(0x2f));\n\n // in_range = not (below or above) or eq_2f\n // outside = not in_range = below or above and not eq_2f (from deMorgan law)\n const v128_t outside = wasm_v128_andnot(eq_2f, above | below);\n err = wasm_v128_or(err, outside);\n\n const v128_t shift = wasm_i8x16_swizzle(shift_LUT, higher_nibble);\n const v128_t t0 = wasm_i8x16_add(data, shift);\n v128_t v = wasm_i8x16_add(t0, wasm_v128_and(eq_2f, packed_byte(-3)));\n\n // pack bytes\n const v128_t ca = masked(v, 0x003f003f);\n const v128_t db = masked(v, 0x3f003f00);\n const v128_t t00 = wasm_v128_or(wasm_u32x4_shr(db, 8), wasm_i32x4_shl(ca, 6));\n v128_t res = wasm_v128_or(wasm_u32x4_shr(t00, 16), wasm_i32x4_shl(t00, 12));\n res = wasm_i8x16_swizzle(res, wasm_i8x16_const(2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, 16, 16, 16, 16));\n\n wasm_v128_store((v128_t *) dst, res);\n dst += 12;\n src += 16;\n }\n //if (wasm_i8x16_bitmask(err) != 0) return -1;\n if (wasm_v128_any_true(err)) return -1;\n\n // operate on 4-byte blocks\n while (src < end) {\n error |= *((unsigned int *) dst) = D0[src[0]] | D1[src[1]] | D2[src[2]] | D3[src[3]];\n dst += 3;\n src += 4;\n }\n if (error >> 24) return -1;\n state->sp = nsp;\n state->dp = dst - state->data;\n return 0;\n }\n\n int end() {\n int rem = state->wp - state->sp;\n if (rem > 4 && dec()) return -1;\n rem = state->wp - state->sp;\n if (rem < 2) return -1;\n\n unsigned char *src = state->data + state->sp;\n if (rem == 4) {\n if (src[3] == 61) rem--;\n if (src[2] == 61) rem--;\n }\n unsigned int accu = D0[src[0]] | D1[src[1]];\n int dp = 1;\n if (rem > 2) {\n accu |= D2[src[2]];\n dp++;\n if (rem == 4) {\n accu |= D3[src[3]];\n dp++;\n }\n }\n if (accu >> 24) return -1;\n *((unsigned int *) (state->data + state->dp)) = accu;\n state->dp += dp;\n return 0;\n }\n `\n});\n*/\n// base64 map\nconst MAP = new Uint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n .split('')\n .map(el => el.charCodeAt(0)));\n// init decoder maps in LE order\nconst D = new Uint32Array(1024);\nD.fill(0xFF000000);\nfor (let i = 0; i < MAP.length; ++i)\n D[MAP[i]] = i << 2;\nfor (let i = 0; i < MAP.length; ++i)\n D[256 + MAP[i]] = i >> 4 | ((i << 4) & 0xFF) << 8;\nfor (let i = 0; i < MAP.length; ++i)\n D[512 + MAP[i]] = (i >> 2) << 8 | ((i << 6) & 0xFF) << 16;\nfor (let i = 0; i < MAP.length; ++i)\n D[768 + MAP[i]] = i << 16;\nconst EMPTY = new Uint8Array(0);\n/**\n * base64 stream decoder.\n *\n * Features / assumptions:\n * - lazy chunkwise decoding\n * - errors out on any non base64 chars (no support for NL formatted base64)\n * - decodes in wasm\n * - inplace decoding to save memory\n * - supports a keepSize for lazy memory release\n */\nclass Base64Decoder {\n /**\n * @param keepSize Keep the wasm instance below this limit when calling `release()`.\n * @param maxBytes Max allowed bytes to allocate.\n * @param initialBytes Initial bytes to allocate.\n */\n constructor(keepSize, maxBytes, initialBytes) {\n this._inst = null;\n this._ended = true;\n this._bytes = 0;\n this.keepSize = keepSize !== null && keepSize !== void 0 ? keepSize : 1048576 /* Bytes.KEEP */;\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : 4294901760 /* Bytes.MAX */;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : 32768 /* Bytes.INITIAL */;\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw new Error('invalid byte settings');\n }\n }\n /**\n * Currently decoded bytes (borrowed).\n * Must be accessed before calling `release` or `init`.\n */\n get data8() {\n return this._inst ? this._d.subarray(0, this._m32[1282 /* P32.STATE_DP */]) : EMPTY;\n }\n /**\n * Release memory conditionally based on `keepSize`.\n * If memory gets released, also the wasm instance will be freed and recreated on next `init`,\n * otherwise the instance will be reused.\n */\n release() {\n if (!this._inst)\n return;\n if (this._bytes > this.keepSize) {\n this._inst = this._m32 = this._d = this._mem = null;\n }\n else {\n this._m32[1280 /* P32.STATE_WP */] = 0;\n this._m32[1281 /* P32.STATE_SP */] = 0;\n this._m32[1282 /* P32.STATE_DP */] = 0;\n }\n }\n /**\n * Initializes the decoder for new base64 data.\n * Must be called before doing any decoding attempts.\n * The method will either spawn a new wasm instance or grow\n * the needed memory of an existing instance.\n * @param maxBytes Max allowed bytes to allocate (overwrites ctor value).\n * @param initialBytes Initial bytes to allocate (overwrites ctor value).\n */\n init(maxBytes, initialBytes) {\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : this.maxBytes;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : Math.min(this._bytes, this.maxBytes);\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw Error('invalid byte settings');\n }\n let m = this._m32;\n const bytes = this._bytes + 5152 /* Bytes._DATA_OFFSET */;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmDecode({ env: { memory: this._mem } });\n m = new Uint32Array(this._mem.buffer, 0);\n m.set(D, 256 /* P32.D0 */);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n m = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n m[1280 /* P32.STATE_WP */] = 0;\n m[1281 /* P32.STATE_SP */] = 0;\n m[1282 /* P32.STATE_DP */] = 0;\n this._m32 = m;\n this._ended = false;\n }\n /**\n * Realloc memory. Realloc only happens, if the requested\n * size doesn't fit in the current memory.\n * The new size will be capped by `maxBytes`.\n * @param requested Bytes to be stored.\n */\n _realloc(requested) {\n const needed = this._m32[1280 /* P32.STATE_WP */] + requested;\n if (this._bytes < needed) {\n if (needed > this.maxBytes) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n let newSize = this._bytes;\n while ((newSize *= 2) < needed) { }\n newSize = Math.min(newSize, this.maxBytes);\n if (newSize < needed) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n if (newSize + 5152 /* Bytes._DATA_OFFSET */ > this._mem.buffer.byteLength) {\n const addPages = Math.ceil((newSize + 5152 /* Bytes._DATA_OFFSET */ - this._mem.buffer.byteLength) / 65536);\n this._mem.grow(addPages);\n this._m32 = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n this._bytes = newSize;\n }\n return 0 /* DecodeStatus.OK */;\n }\n /**\n * Put bytes in `data` into the decoder.\n * Additionally decodes the payload, if it reached 2^17 bytes.\n * The return value indicates the type of issue.\n * @param data Bytes to be loaded.\n */\n put(data) {\n if (!this._inst || this._ended) {\n return -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n if (this._realloc(data.length)) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n const m = this._m32;\n this._d.set(data, m[1280 /* P32.STATE_WP */]);\n m[1280 /* P32.STATE_WP */] += data.length;\n // max chunk in input handler is 2^17, try to run in \"tandem mode\"\n return m[1280 /* P32.STATE_WP */] - m[1281 /* P32.STATE_SP */] >= 131072\n ? this._inst.exports.dec()\n : 0 /* DecodeStatus.OK */;\n }\n /**\n * End the current decoding.\n * Also decodes leftover payload from previous put calls.\n */\n end() {\n this._ended = true;\n return this._inst\n ? this._inst.exports.end()\n : -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n /**\n * Bytes loaded into the decoder.\n */\n get loadedBytes() {\n return this._inst\n ? this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n /**\n * Free bytes to feed to the decoder.\n */\n get freeBytes() {\n return this._inst\n ? this.maxBytes - this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n}\nexports.default = Base64Decoder;\n//# sourceMappingURL=Base64Decoder.wasm.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\nconst wasmQoiDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#459f9e1bfb80b1a8:rdef-start:\"qoi_decode\"*/{s:1,t:0,d:'AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=='}/*inwasm#459f9e1bfb80b1a8:rdef-end:\"qoi_decode\"*/);\nclass QoiDecoder {\n constructor(keepSize) {\n this.keepSize = keepSize;\n this.width = 0;\n this.height = 0;\n }\n decode(d) {\n this.width = d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7];\n this.height = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];\n const pixels = this.width * this.height;\n const ib = pixels * 4;\n const dl = d.length;\n /**\n * byte/offset calculation:\n * To save some memory we dont reserve full memory for decoded + encoded,\n * but place encoded at the end of decoded plus 50% security distance\n * to avoid reads before writes positions:\n *\n * encoded < decoded (good compression)\n * enc ####################\n * dec #######################################\n * ^ ^\n * DST_P CHUNK_P\n *\n * encoded > decoded (degenerated compression, should not happen)\n * enc ##############################\n * dec ####################\n * ^ ^\n * DST_P CHUNK_P\n *\n * There is still a chance for overlapping r/w positions in case the compressed\n * data has very different pixel progression, yet the 50% security distance\n * should deal with that, as QOI will bloat data by 25% at max (RGB -> OP byte + RGB).\n * Since we always assume RGBA at decoding stage, the possible bloat reduces to 20% at max.\n */\n const bytes = Math.max(ib, dl) + (Math.min(ib, dl) >> 1) + 4096;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmQoiDecode({ env: { memory: this._mem } });\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n this._d = null;\n }\n if (!this._d) {\n this._d = new Uint8Array(this._mem.buffer);\n }\n // put src data at the end of memory, also align to 256\n const chunkP = (this._mem.buffer.byteLength - dl) & ~0xFF;\n this._d.set(d, chunkP);\n this._inst.exports.dec(chunkP, dl, pixels);\n return this._d.subarray(1024 /* P8.DST_P */, 1024 /* P8.DST_P */ + ib);\n }\n release() {\n if (!this._inst)\n return;\n if (this._mem.buffer.byteLength > this.keepSize) {\n this._inst = this._d = this._mem = null;\n }\n }\n}\nexports.default = QoiDecoder;\n//# sourceMappingURL=QoiDecoder.wasm.js.map","\"use strict\";\n/**\n * Copyright (c) 2022, 2026 Joerg Breitbart\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InWasm = InWasm;\nlet z = (s) => {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(s);\n if (typeof Buffer !== 'undefined')\n return Buffer.from(s, 'base64');\n const b = atob(s);\n const r = new Uint8Array(b.length);\n for (let i = 0; i < r.length; ++i)\n r[i] = b.charCodeAt(i);\n return r;\n};\nfunction InWasm(def) {\n if (def.d) {\n const { t, s, d } = def;\n let b;\n let m;\n const W = WebAssembly;\n if (t === 0 /* OutputType.INSTANCE */) {\n if (s)\n return (e) => new W.Instance(m || (m = new W.Module(b || (b = z(d)))), e);\n return (e) => m\n ? W.instantiate(m, e)\n : W.instantiate(b || (b = z(d)), e).then(r => (m = r.module) && r.instance);\n }\n if (t === 1 /* OutputType.MODULE */) {\n if (s)\n return () => m || (m = new W.Module(b || (b = z(d))));\n return () => m\n ? Promise.resolve(m)\n : W.compile(b || (b = z(d))).then(r => m = r);\n }\n if (s)\n return () => b || (b = z(d));\n return () => Promise.resolve(b || (b = z(d)));\n }\n if (typeof _wasmCtx === 'undefined')\n throw new Error('must run \"inwasm\"');\n _wasmCtx.add(def);\n}\n//# sourceMappingURL=index.js.map","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport type { ITerminalAddon, IDisposable } from '@xterm/xterm';\nimport type { ImageAddon as IImageApi } from '@xterm/addon-image';\nimport { Emitter, type IEvent } from 'common/Event';\nimport { IIPHandler } from './IIPHandler';\nimport { ImageRenderer } from './ImageRenderer';\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { KittyGraphicsHandler } from './kitty/KittyGraphicsHandler';\nimport { KittyImageStorage } from './kitty/KittyImageStorage';\nimport { SixelHandler } from './SixelHandler';\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { ITerminalExt, IImageAddonOptions, IResetHandler } from './Types';\n\n\n/**\n * Document VT features provided by this addon.\n *\n * @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL \"SIXEL Graphics\" \"DCS Ps ; Ps ; Ps ; q Pt ST\" \"Draw SIXEL image.\"\n *\n * Sixel support is provided by the addon @xterm/addon-image with these limitations:\n * - immediate coloring (no shared palette, allows high color settings of `img2sixel`)\n * - max. palette size of 4096 colors\n * - max. pixel width of 16K\n * - max. 25 MB per sixel sequence\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] OSC 1337 \"iTerm2 Commands\" \"OSC 1337 ; Pt BEL\" \"Custom iTerm2 commands.\"\n *\n * Only the inline image protocol (IIP) is supported by the addon @xterm/addon-image with\n * the following limitations:\n * - sequence:\n * - format: `OSC 1337 ; File=inline=1 ; size= ; ... : BEL`\n * - size param must be set and payload may not exceed CEIL(size * 4 / 3)\n * - strict base64 handling as of RFC4648 §4 (standard alphabet, optional padding,\n * no separator bytes allowed)\n * - supported params: size, name, width, height, preserveAspectRatio\n * - image formats: PNG, JPEG and GIF\n * - no animation support (renders first image of a GIF)\n * - no multipart support\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image)\n * and [iTerm2 IIP docs](https://iterm2.com/documentation-images.html) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] APC KITTY_GRAPHICS \"Kitty Graphics\" \"APC G Pt ST\" \"Kitty Graphics Protocol.\"\n *\n * Kitty graphics support is provided by the addon @xterm/addon-image.\n * Note that while basic image output already works, this is still work in progress.\n */\n\n// default values of addon ctor options\nconst DEFAULT_OPTIONS: IImageAddonOptions = {\n enableSizeReports: true,\n pixelLimit: 16777216, // limit to 4096 * 4096 pixels\n sixelSupport: true,\n sixelScrolling: true,\n sixelPaletteLimit: 4096,\n sixelSizeLimit: 33554432,\n storageLimit: 128,\n showPlaceholder: true,\n iipSupport: true,\n iipSizeLimit: 33554432,\n kittySupport: true,\n kittySizeLimit: 33554432\n};\n\n// max palette size supported by the sixel lib (compile time setting)\nconst MAX_SIXEL_PALETTE_SIZE = 4096;\n\n// definitions for _xtermGraphicsAttributes sequence\nconst enum GaItem {\n COLORS = 1,\n SIXEL_GEO = 2,\n REGIS_GEO = 3\n}\nconst enum GaAction {\n READ = 1,\n SET_DEFAULT = 2,\n SET = 3,\n READ_MAX = 4\n}\nconst enum GaStatus {\n SUCCESS = 0,\n ITEM_ERROR = 1,\n ACTION_ERROR = 2,\n FAILURE = 3\n}\n\n\nexport class ImageAddon implements ITerminalAddon, IImageApi {\n private _opts: IImageAddonOptions;\n private _defaultOpts: IImageAddonOptions;\n private _storage: ImageStorage | undefined;\n private _renderer: ImageRenderer | undefined;\n private _disposables: IDisposable[] = [];\n private _terminal: ITerminalExt | undefined;\n private _handlers: Map = new Map();\n private readonly _onImageAdded = new Emitter();\n public readonly onImageAdded: IEvent = this._onImageAdded.event;\n\n constructor(opts?: Partial) {\n this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);\n this._defaultOpts = Object.assign({}, DEFAULT_OPTIONS, opts);\n }\n\n public dispose(): void {\n for (const obj of this._disposables) {\n obj.dispose();\n }\n this._disposables.length = 0;\n this._handlers.clear();\n this._onImageAdded.dispose();\n }\n\n private _disposeLater(...args: IDisposable[]): void {\n for (const obj of args) {\n this._disposables.push(obj);\n }\n }\n\n public activate(terminal: ITerminalExt): void {\n this._terminal = terminal;\n\n // internal data structures\n this._renderer = new ImageRenderer(terminal);\n this._storage = new ImageStorage(terminal, this._renderer, this._opts);\n this._storage.onImageAdded = () => this._onImageAdded.fire();\n\n // enable size reports\n if (this._opts.enableSizeReports) {\n const windowOps = terminal.options.windowOptions ?? {};\n windowOps.getWinSizePixels = true;\n windowOps.getCellSizePixels = true;\n windowOps.getWinSizeChars = true;\n terminal.options.windowOptions = windowOps;\n }\n\n this._disposeLater(\n this._renderer,\n this._storage,\n\n // DECSET/DECRST/DA1/XTSMGRAPHICS handlers\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'h' }, params => this._decset(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'l' }, params => this._decrst(params)),\n terminal.parser.registerCsiHandler({ final: 'c' }, params => this._da1(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'S' }, params => this._xtermGraphicsAttributes(params)),\n\n // render hook\n terminal.onRender(range => this._storage?.render(range)),\n\n /**\n * reset handlers covered:\n * - DECSTR\n * - RIS\n * - Terminal.reset()\n */\n terminal.parser.registerCsiHandler({ intermediates: '!', final: 'p' }, () => this.reset()),\n terminal.parser.registerEscHandler({ final: 'c' }, () => this.reset()),\n terminal._core._inputHandler.onRequestReset(() => this.reset()),\n\n // wipe canvas and delete alternate images on buffer switch\n terminal.buffer.onBufferChange(() => this._storage?.wipeAlternate()),\n\n // extend images to the right on resize\n terminal.onResize(metrics => this._storage?.viewportResize(metrics))\n );\n\n // SIXEL handler\n if (this._opts.sixelSupport) {\n const sixelStorage = new SixelImageStorage(this._storage!, this._opts, this._renderer!, terminal);\n const sixelHandler = new SixelHandler(this._opts, sixelStorage, terminal);\n this._handlers.set('sixel', sixelHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerDcsHandler({ final: 'q' }, sixelHandler)\n );\n }\n\n // iTerm IIP handler\n if (this._opts.iipSupport) {\n const iipStorage = new IIPImageStorage(this._storage!);\n const iipHandler = new IIPHandler(this._opts, this._renderer!, iipStorage, terminal);\n this._handlers.set('iip', iipHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerOscHandler(1337, iipHandler)\n );\n }\n\n // Kitty graphics handler\n if (this._opts.kittySupport) {\n const kittyStorage = new KittyImageStorage(this._storage!);\n const kittyHandler = new KittyGraphicsHandler(this._opts, this._renderer!, kittyStorage, terminal);\n this._handlers.set('kitty', kittyHandler);\n this._disposeLater(\n kittyStorage,\n kittyHandler,\n terminal._core._inputHandler._parser.registerApcHandler({ final: 'G' }, kittyHandler)\n );\n }\n }\n\n // Note: storageLimit is skipped here to not intoduce a surprising side effect.\n public reset(): boolean {\n // reset options customizable by sequences to defaults\n this._opts.sixelScrolling = this._defaultOpts.sixelScrolling;\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n // also clear image storage\n this._storage?.reset();\n // reset protocol handlers\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return false;\n }\n\n public get storageLimit(): number {\n return this._storage?.getLimit() || -1;\n }\n\n public set storageLimit(limit: number) {\n this._storage?.setLimit(limit);\n this._opts.storageLimit = limit;\n }\n\n public get storageUsage(): number {\n if (this._storage) {\n return this._storage.getUsage();\n }\n return -1;\n }\n\n public get showPlaceholder(): boolean {\n return this._opts.showPlaceholder;\n }\n\n public set showPlaceholder(value: boolean) {\n this._opts.showPlaceholder = value;\n this._renderer?.showPlaceholder(value);\n }\n\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.getImageAtBufferCell(x, y);\n }\n\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.extractTileAtBufferCell(x, y);\n }\n\n private _report(s: string): void {\n this._terminal?._core.input(s, false);\n }\n\n private _decset(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = false;\n break;\n }\n }\n return false;\n }\n\n private _decrst(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = true;\n break;\n }\n }\n return false;\n }\n\n // overload DA to return something more appropriate\n private _da1(params: (number | number[])[]): boolean {\n if (params[0]) {\n return true;\n }\n // reported features:\n // 62 - VT220\n // 4 - SIXEL support\n // 9 - charsets\n // 22 - ANSI colors\n if (this._opts.sixelSupport) {\n this._report(`\\x1b[?62;4;9;22c`);\n return true;\n }\n return false;\n }\n\n /**\n * Implementation of xterm's graphics attribute sequence.\n *\n * Supported features:\n * - read/change palette limits (max 4096 by sixel lib)\n * - read SIXEL canvas geometry (reports current window canvas or\n * squared pixelLimit if canvas > pixel limit)\n *\n * Everything else is deactivated.\n */\n private _xtermGraphicsAttributes(params: (number | number[])[]): boolean {\n if (params.length < 2) {\n return true;\n }\n if (params[0] === GaItem.COLORS) {\n switch (params[1]) {\n case GaAction.READ:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n return true;\n case GaAction.SET_DEFAULT:\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n // also reset protocol handlers for now\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return true;\n case GaAction.SET:\n if (params.length > 2 && !(params[2] instanceof Array) && params[2] <= MAX_SIXEL_PALETTE_SIZE) {\n this._opts.sixelPaletteLimit = params[2];\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n } else {\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n }\n return true;\n case GaAction.READ_MAX:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${MAX_SIXEL_PALETTE_SIZE}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n if (params[0] === GaItem.SIXEL_GEO) {\n switch (params[1]) {\n // we only implement read and read_max here\n case GaAction.READ:\n let width = this._renderer?.dimensions?.css.canvas.width;\n let height = this._renderer?.dimensions?.css.canvas.height;\n if (!width || !height) {\n // for some reason we have no working image renderer\n // --> fallback to default cell size\n const cellSize = CELL_SIZE_DEFAULT;\n width = (this._terminal?.cols || 80) * cellSize.width;\n height = (this._terminal?.rows || 24) * cellSize.height;\n }\n if (width * height < this._opts.pixelLimit) {\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${width.toFixed(0)};${height.toFixed(0)}S`);\n } else {\n // if we overflow pixelLimit report that squared instead\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n }\n return true;\n case GaAction.READ_MAX:\n // read_max returns pixelLimit as square area\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n // exit with error on ReGIS or any other requests\n this._report(`\\x1b[?${params[0]};${GaStatus.ITEM_ERROR}S`);\n return true;\n }\n}\n"],"names":["root","factory","exports","module","define","amd","globalThis","red","n","green","blue","toRGBA8888","r","g","b","a","clamp","low","high","value","Math","max","min","h2c","t1","t2","c","normalizeRGB","round","Object","defineProperty","DEFAULT_FOREGROUND","DEFAULT_BACKGROUND","PALETTE_ANSI_256","PALETTE_VT340_GREY","PALETTE_VT340_COLOR","normalizeHLS","nearestColorIndex","fromRGBA8888","alpha","BIG_ENDIAN","Uint8Array","Uint32Array","buffer","console","warn","color","palette","Number","MAX_SAFE_INTEGER","idx","i","length","dr","dg","db","d","h","l","s","v","HLStoRGB","p","push","decodeAsync","decode","Decoder","DecoderAsync","Colors_1","__webpack_require__","wasm_1","WASM_BYTES","Buffer","from","bytestring","atob","result","charCodeAt","decodeBase64","LIMITS","BYTES","WASM_MODULE","NULL_CANVAS","CallbackProxy","constructor","this","bandHandler","width","modeHandler","mode","handle_band","mode_parsed","DEFAULT_OPTIONS","memoryLimit","sixelColor","fillColor","paletteLimit","PALETTE_SIZE","truncate","opts","cbProxy","importObj","env","bind","WebAssembly","instantiate","then","inst","instance","_instance","_cbProxy","_PIXEL_OFFSET","MAX_WIDTH","_canvas","_bandWidths","_maxWidth","_minWidth","_lastOffset","_currentHeight","_opts","assign","Error","_handle_band","_initCanvas","Module","Instance","_wasm","_chunk","memory","get_chunk_address","CHUNK_SIZE","_states","get_state_address","_palette","get_palette_address","set","_pSrc","get_p0_address","init","_fillColor","_truncate","_rasterWidth","_rasterHeight","_width","_height","_level","_mode","_paletteLimit","pixels","height","release","_realloc","offset","additionalPixels","newCanvas","ceil","adv","remaining","subarray","current_width","current_height","memoryUsage","byteLength","properties","level","memUsage","rasterAttributes","numerator","denominator","data","start","end","decodeString","j","data32","currentWidth","fill","escape","final","finalOffset","bw","currentHeight","data8","Uint8ClampedArray","dec","async","Lifecycle_1","EventUtils","_listeners","_disposed","event","_event","listener","thisArgs","disposables","toDisposable","entry","fn","slice","indexOf","splice","Array","isArray","add","fire","call","listeners","len","dispose","forward","to","e","map","undefined","any","events","store","DisposableStore","runAndSubscribe","handler","initial","arg","_disposables","Set","_isDisposed","isDisposed","o","clear","Disposable","_store","_register","None","freeze","_value","ImageRenderer_1","ImageStorage_1","Base64Decoder_wasm_1","__importDefault","QoiDecoder_wasm_1","IIPHeaderParser_1","IIPMetrics_1","DEFAULT_HEADER","type","name","size","preserveAspectRatio","inline","_renderer","_storage","_coreTerminal","_aborted","_hp","HeaderParser","_header","_isMultipart","_abortMulti","maxEncodedBytes","iipSizeLimit","initialBytes","_dec","default","_qoiDec","reset","put","state","dataPos","parse","fields","success","seqType","w","CELL_SIZE_DEFAULT","dimensions","css","canvas","cols","rows","scale","_c","_a","_core","_coreBrowserService","dpr","report","toFixed","input","cond","blob","metrics","UNSUPPORTED_TYPE","imageType","mime","pixelLimit","_resize","floor","ImageData","byteOffset","ImageRenderer","createCanvas","_b","getContext","putImageData","addImage","Blob","createImageBitmap","resizeWidth","resizeHeight","bm","catch","cw","cell","ch","_d","rw","_dim","rh","wf","hf","f","total","cdim","endsWith","parseInt","toStr","String","fromCharCode","toInt","toSize","match","DECODERS","toString","bs","TextDecoder","FILE_MARKER","MULTIPARTFILE_MARKER","FILEPART_MARKER","FILEEND_MARKER","REPORTCELLSIZE_MARKER","MAX_FIELDCHARS","_buffer","_position","_key","k","_storeValue","pos","_storeKey","_addImageOpts","scrolling","layer","zIndex","cursorPos","img","d32","blockLength","jpgSize","dim","limit","_layers","get","localDocument","document","createElement","createImageData","ctx","imgData","Promise","resolve","_terminal","super","Map","_optionsRefresh","MutableDisposable","_oldOpen","open","parent","_open","screenElement","optionsService","onOptionChange","option","rescaleCanvas","_renderService","refreshRows","removeLayerFromDom","_oldSetRenderer","setRenderer","_placeholderBitmap","close","_placeholder","showPlaceholder","cellSize","_createPlaceHolder","clearLines","y","clearRect","_e","clearAll","draw","imgSpec","tileId","col","row","count","_rescaleImage","actual","sx","sy","dx","dy","finalWidth","finalHeight","drawImage","extractTile","drawPlaceholder","values","spec","actualCellSize","originalWidth","originalHeight","origCellSize","orig","renderer","key","keys","insertLayerToDom","has","classList","style","isolation","insertBefore","firstChild","appendChild","remove","delete","hasLayer","bWidth","blueprint","black","white","shift","x","screen","ctx2","bitmap","window","ExtendedAttrsImage","ext","_urlId","_ext","underlineStyle","underlineColor","underlineVariantOffset","val","urlId","imageId","clone","isEmpty","EMPTY_ATTRS","_images","_lastId","_lowestId","_fullyCleared","_needsFullClear","_pixelLimit","setLimit","storageLimit","error","message","getLimit","_viewportMetrics","marker","RangeError","_evictOldest","getUsage","_getStoredPixels","storedPixels","_delImg","id","ImageBitmap","onImageDeleted","wipeAlternate","zero","entries","bufferType","deleteImage","termCols","termRows","originX","originY","tileCount","_inputHandler","_dirtyRowTracker","markDirty","line","lines","ybase","_writeToCell","lineFeed","endMarker","registerMarker","onDispose","active","_evictOnAlternate","onImageAdded","render","range","hasTopImages","hasBottomImages","drawCalls","placeholderCalls","ydisp","getBg","_extendedAttrs","startTile","startCol","sort","viewportResize","oldCol","tilesPerRow","hasData","rightCol","_data","lastTile","expandCol","getImageAtBufferCell","extractTileAtBufferCell","room","used","current","old","oldSpec","imgId","Decoder_1","DEFAULT_PALETTE","convertLe","_size","sixelPaletteLimit","hook","params","attr","colors","bg","isInverse","isFgDefault","foreground","rgba","isFgRGB","t","toColorRGB","getFgColor","ansi","isBgDefault","background","isBgRGB","getBgColor","extractActiveBg","_curAttrData","_themeService","sixelSizeLimit","unhook","advanceCursor","sixelScrolling","KittyGraphicsTypes_1","_kittyStorage","_decodeError","_activeDecoder","_inControlData","_controlData","_controlLength","_encodedSizeLimit","_totalEncodedSize","_parsedCommand","_pendingTransmissions","_maxEncodedBytes","kittySizeLimit","_initialEncodedBytes","_cleanupAllPending","_removePendingEntry","_lastPendingKey","pending","decoder","controlEnd","copyLength","parseKittyCommand","_parseControlDataString","imageNumber","_sendResponse","quiet","action","payloadStart","_streamPayload","pendingKey","previousEncodedSize","totalEncodedSize","decoderToRelease","_handleNoPayloadCommand","cmd","_handleDelete","isMoreComing","more","decodeError","finalCmd","imageBytes","_handleCommandWithBytesAndCmd","str","fromCodePoint","_handlePlacement","bytes","_handleTransmit","transmission","_handleTransmitDisplay","_handleQuery","image","getImage","_displayImage","placementId","storeImage","format","compression","_f","lastImageId","expectedBytes","deleteSelector","deleteAll","deleteById","isOk","response","coreService","triggerDataEvent","_decodeAndDisplay","_createBitmap","cropX","cropY","cropW","sourceWidth","cropH","sourceHeight","maxCropW","maxCropH","finalCropW","finalCropH","cropped","imgCols","imgRows","columns","savedX","savedY","savedYbase","scaled","xOffset","yOffset","canvasW","canvasH","offsetCanvas","offsetCtx","offsetBitmap","_g","cursorMovement","scrolled","arrayBuffer","_decompressZlib","url","URL","createObjectURL","Image","reject","addEventListener","revokeObjectURL","src","pixelCount","src32","dst32","alignedPixels","srcOffset","dstOffset","b0","b1","b2","srcByte","dstByte","compressed","_decompress","ds","DecompressionStream","writer","writable","getWriter","write","chunks","reader","readable","getReader","done","read","totalLength","reduce","sum","chunk","images","_kittyIdToStorageId","kittyIdToStorageId","pendingTransmissions","parts","split","part","eqIdx","substring","numValue","KittyImageStorage","_nextImageId","_storageIdToKittyId","_handleStorageImageDeleted","storageId","kittyId","_previousOnImageDeleted","_wrappedOnImageDeleted","imageData","oldStorageId","_maxStoredImages","_evictUndisplayedImages","wasmDecode","InWasm","MAP","el","D","EMPTY","keepSize","maxBytes","_inst","_ended","_bytes","_m32","_mem","m","grow","Memory","requested","needed","newSize","addPages","loadedBytes","freeBytes","wasmQoiDecode","ib","dl","chunkP","def","W","z","compile","_wasmCtx","fromBase64","__webpack_module_cache__","moduleId","cachedModule","__webpack_modules__","Event_1","IIPHandler_1","KittyGraphicsHandler_1","KittyImageStorage_1","SixelHandler_1","SixelImageStorage_1","IIPImageStorage_1","enableSizeReports","sixelSupport","iipSupport","kittySupport","_handlers","_onImageAdded","Emitter","_defaultOpts","obj","_disposeLater","args","activate","terminal","ImageStorage","windowOps","options","windowOptions","getWinSizePixels","getCellSizePixels","getWinSizeChars","parser","registerCsiHandler","prefix","_decset","_decrst","_da1","_xtermGraphicsAttributes","onRender","intermediates","registerEscHandler","onRequestReset","onBufferChange","onResize","sixelStorage","SixelImageStorage","sixelHandler","SixelHandler","_parser","registerDcsHandler","iipStorage","IIPImageStorage","iipHandler","IIPHandler","registerOscHandler","kittyStorage","kittyHandler","KittyGraphicsHandler","registerApcHandler","storageUsage","_report","sqrt"],"sourceRoot":""} \ No newline at end of file -+{"version":3,"file":"addon-image.js","mappings":";CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,IACA,mBAAAG,QAAAA,OAAAC,IACAD,OAAA,GAAAH,GACA,iBAAAC,QACAA,QAAA,WAAAD,IAEAD,EAAA,WAAAC,GACC,CATD,CASCK,WAAA,uCCKD,SAAAC,EAAAC,GACA,WAAAA,CACA,CAEA,SAAAC,EAAAD,GACA,OAAAA,IAAA,KACA,CAEA,SAAAE,EAAAF,GACA,OAAAA,IAAA,MACA,CASA,SAAAG,EAAAC,EAAAC,EAAAC,EAAAC,EAAA,KACA,YAAAA,IAAA,QAAAD,IAAA,QA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A2B,OAAA,EAAAA,EAAE1B,IAAIC,OAAO5L,MAC/C8D,EAAmC,QAA1BsK,EAAc,QAAdpC,EAAAlM,KAAKkK,iBAAS,IAAAgC,OAAA,EAAAA,EAAEN,kBAAU,IAAA0C,OAAA,EAAAA,EAAEzC,IAAIC,OAAO9H,OACpD,IAAK9D,IAAU8D,EAAQ,CAGrB,MAAMmP,EAAW7J,EAAAqC,kBACjBzL,IAAuB,QAAdsT,EAAAxT,KAAK6R,iBAAS,IAAA2B,OAAA,EAAAA,EAAEzH,OAAQ,IAAMoH,EAASjT,MAChD8D,IAAwB,QAAdqc,EAAArgB,KAAK6R,iBAAS,IAAAwO,OAAA,EAAAA,EAAErU,OAAQ,IAAMmH,EAASnP,MACnD,CACA,GAAI9D,EAAQ8D,EAAShE,KAAKkC,MAAM8K,WAC9BhN,KAAKquB,QAAQ,MAASzR,EAAO,QAA0B1c,EAAMsM,QAAQ,MAAMxI,EAAOwI,QAAQ,WACrF,CAEL,MAAMiK,EAAI1a,KAAKmR,MAAMnR,KAAKuyB,KAAKtuB,KAAKkC,MAAM8K,aAC1ChN,KAAKquB,QAAQ,MAASzR,EAAO,QAA0BnG,KAAKA,KAC9D,CACA,OAAO,EACT,OAEE,MAAMA,EAAI1a,KAAKmR,MAAMnR,KAAKuyB,KAAKtuB,KAAKkC,MAAM8K,aAE1C,OADAhN,KAAKquB,QAAQ,MAASzR,EAAO,QAA0BnG,KAAKA,OACrD,EACT,QAEE,OADAzW,KAAKquB,QAAQ,MAASzR,EAAO,UACtB,EAKb,OADA5c,KAAKquB,QAAQ,MAASzR,EAAO,UACtB,CACT","sources":["webpack://ImageAddon/webpack/universalModuleDefinition","webpack://ImageAddon/../node_modules/sixel/lib/Colors.js","webpack://ImageAddon/../node_modules/sixel/lib/Decoder.js","webpack://ImageAddon/../node_modules/sixel/lib/wasm.js","webpack://ImageAddon/../src/common/Event.ts","webpack://ImageAddon/../src/common/Lifecycle.ts","webpack://ImageAddon/./src/IIPHandler.ts","webpack://ImageAddon/./src/IIPHeaderParser.ts","webpack://ImageAddon/./src/IIPImageStorage.ts","webpack://ImageAddon/./src/IIPMetrics.ts","webpack://ImageAddon/./src/ImageRenderer.ts","webpack://ImageAddon/./src/ImageStorage.ts","webpack://ImageAddon/./src/SixelHandler.ts","webpack://ImageAddon/./src/SixelImageStorage.ts","webpack://ImageAddon/./src/kitty/KittyGraphicsHandler.ts","webpack://ImageAddon/./src/kitty/KittyGraphicsTypes.ts","webpack://ImageAddon/./src/kitty/KittyImageStorage.ts","webpack://ImageAddon/../node_modules/xterm-wasm-parts/lib/base64/Base64Decoder.wasm.js","webpack://ImageAddon/../node_modules/xterm-wasm-parts/lib/qoi/QoiDecoder.wasm.js","webpack://ImageAddon/javascript/node_modules/inwasm-runtime/lib/index.cjs","webpack://ImageAddon/webpack/bootstrap","webpack://ImageAddon/./src/ImageAddon.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ImageAddon\"] = factory();\n\telse\n\t\troot[\"ImageAddon\"] = factory();\n})(globalThis, () => {\nreturn ","\"use strict\";\n/**\n * Copyright (c) 2019 Joerg Breitbart.\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DEFAULT_FOREGROUND = exports.DEFAULT_BACKGROUND = exports.PALETTE_ANSI_256 = exports.PALETTE_VT340_GREY = exports.PALETTE_VT340_COLOR = exports.normalizeHLS = exports.normalizeRGB = exports.nearestColorIndex = exports.fromRGBA8888 = exports.toRGBA8888 = exports.alpha = exports.blue = exports.green = exports.red = exports.BIG_ENDIAN = void 0;\n// FIXME: cleanup this mess, move things either to decoder/encoder, keep only shared things\n// system endianess\nexports.BIG_ENDIAN = new Uint8Array(new Uint32Array([0xFF000000]).buffer)[0] === 0xFF;\nif (exports.BIG_ENDIAN) {\n console.warn('BE platform detected. This version of node-sixel works only on LE properly.');\n}\n// channel values\nfunction red(n) {\n return n & 0xFF;\n}\nexports.red = red;\nfunction green(n) {\n return (n >>> 8) & 0xFF;\n}\nexports.green = green;\nfunction blue(n) {\n return (n >>> 16) & 0xFF;\n}\nexports.blue = blue;\nfunction alpha(n) {\n return (n >>> 24) & 0xFF;\n}\nexports.alpha = alpha;\n/**\n * Convert RGB channels to native color RGBA8888.\n */\nfunction toRGBA8888(r, g, b, a = 255) {\n return ((a & 0xFF) << 24 | (b & 0xFF) << 16 | (g & 0xFF) << 8 | (r & 0xFF)) >>> 0; // ABGR32\n}\nexports.toRGBA8888 = toRGBA8888;\n/**\n * Convert native color to [r, g, b, a].\n */\nfunction fromRGBA8888(color) {\n return [color & 0xFF, (color >> 8) & 0xFF, (color >> 16) & 0xFF, color >>> 24];\n}\nexports.fromRGBA8888 = fromRGBA8888;\n/**\n * Get index of nearest color in `palette` for `color`.\n * Uses euclidean distance without any luminescence correction.\n */\nfunction nearestColorIndex(color, palette) {\n const r = red(color);\n const g = green(color);\n const b = blue(color);\n let min = Number.MAX_SAFE_INTEGER;\n let idx = -1;\n // use euclidean distance (manhattan gives very poor results)\n for (let i = 0; i < palette.length; ++i) {\n const dr = r - palette[i][0];\n const dg = g - palette[i][1];\n const db = b - palette[i][2];\n const d = dr * dr + dg * dg + db * db;\n if (!d)\n return i;\n if (d < min) {\n min = d;\n idx = i;\n }\n }\n return idx;\n}\nexports.nearestColorIndex = nearestColorIndex;\n// color conversions\n// HLS taken from: http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl\nfunction clamp(low, high, value) {\n return Math.max(low, Math.min(value, high));\n}\nfunction h2c(t1, t2, c) {\n if (c < 0)\n c += 1;\n if (c > 1)\n c -= 1;\n return c * 6 < 1\n ? t2 + (t1 - t2) * 6 * c\n : c * 2 < 1\n ? t1\n : c * 3 < 2\n ? t2 + (t1 - t2) * (4 - c * 6)\n : t2;\n}\nfunction HLStoRGB(h, l, s) {\n if (!s) {\n const v = Math.round(l * 255);\n return toRGBA8888(v, v, v);\n }\n const t1 = l < 0.5 ? l * (1 + s) : l + s - l * s;\n const t2 = 2 * l - t1;\n return toRGBA8888(clamp(0, 255, Math.round(h2c(t1, t2, h + 1 / 3) * 255)), clamp(0, 255, Math.round(h2c(t1, t2, h) * 255)), clamp(0, 255, Math.round(h2c(t1, t2, h - 1 / 3) * 255)));\n}\n/**\n * Normalize SIXEL RGB values (percent based, 0-100) to RGBA8888.\n */\nfunction normalizeRGB(r, g, b) {\n return (0xFF000000 | Math.round(b / 100 * 255) << 16 | Math.round(g / 100 * 255) << 8 | Math.round(r / 100 * 255)) >>> 0; // ABGR32\n}\nexports.normalizeRGB = normalizeRGB;\n/**\n * Normalize SIXEL HLS values to RGBA8888. Applies hue correction of +240°.\n */\nfunction normalizeHLS(h, l, s) {\n // Note: hue value is turned by 240° in VT340, all values given as fractions\n return HLStoRGB((h + 240 % 360) / 360, l / 100, s / 100);\n}\nexports.normalizeHLS = normalizeHLS;\n/**\n * default palettes\n */\n// FIXME: move palettes to Decoder.ts\n/**\n * 16 predefined color registers of VT340 (values in %):\n * ```\n * R G B\n * 0 Black 0 0 0\n * 1 Blue 20 20 80\n * 2 Red 80 13 13\n * 3 Green 20 80 20\n * 4 Magenta 80 20 80\n * 5 Cyan 20 80 80\n * 6 Yellow 80 80 20\n * 7 Gray 50% 53 53 53\n * 8 Gray 25% 26 26 26\n * 9 Blue* 33 33 60\n * 10 Red* 60 26 26\n * 11 Green* 33 60 33\n * 12 Magenta* 60 33 60\n * 13 Cyan* 33 60 60\n * 14 Yellow* 60 60 33\n * 15 Gray 75% 80 80 80\n * ```\n * (*) less saturated\n *\n * @see https://vt100.net/docs/vt3xx-gp/chapter2.html#S2.4\n*/\nexports.PALETTE_VT340_COLOR = new Uint32Array([\n normalizeRGB(0, 0, 0),\n normalizeRGB(20, 20, 80),\n normalizeRGB(80, 13, 13),\n normalizeRGB(20, 80, 20),\n normalizeRGB(80, 20, 80),\n normalizeRGB(20, 80, 80),\n normalizeRGB(80, 80, 20),\n normalizeRGB(53, 53, 53),\n normalizeRGB(26, 26, 26),\n normalizeRGB(33, 33, 60),\n normalizeRGB(60, 26, 26),\n normalizeRGB(33, 60, 33),\n normalizeRGB(60, 33, 60),\n normalizeRGB(33, 60, 60),\n normalizeRGB(60, 60, 33),\n normalizeRGB(80, 80, 80)\n]);\n/**\n * 16 predefined monochrome registers of VT340 (values in %):\n * ```\n * R G B\n * 0 Black 0 0 0\n * 1 Gray-2 13 13 13\n * 2 Gray-4 26 26 26\n * 3 Gray-6 40 40 40\n * 4 Gray-1 6 6 6\n * 5 Gray-3 20 20 20\n * 6 Gray-5 33 33 33\n * 7 White 7 46 46 46\n * 8 Black 0 0 0 0\n * 9 Gray-2 13 13 13\n * 10 Gray-4 26 26 26\n * 11 Gray-6 40 40 40\n * 12 Gray-1 6 6 6\n * 13 Gray-3 20 20 20\n * 14 Gray-5 33 33 33\n * 15 White 7 46 46 46\n * ```\n *\n * @see https://vt100.net/docs/vt3xx-gp/chapter2.html#S2.4\n */\nexports.PALETTE_VT340_GREY = new Uint32Array([\n normalizeRGB(0, 0, 0),\n normalizeRGB(13, 13, 13),\n normalizeRGB(26, 26, 26),\n normalizeRGB(40, 40, 40),\n normalizeRGB(6, 6, 6),\n normalizeRGB(20, 20, 20),\n normalizeRGB(33, 33, 33),\n normalizeRGB(46, 46, 46),\n normalizeRGB(0, 0, 0),\n normalizeRGB(13, 13, 13),\n normalizeRGB(26, 26, 26),\n normalizeRGB(40, 40, 40),\n normalizeRGB(6, 6, 6),\n normalizeRGB(20, 20, 20),\n normalizeRGB(33, 33, 33),\n normalizeRGB(46, 46, 46)\n]);\n/**\n * 256 predefined ANSI colors.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit\n */\nexports.PALETTE_ANSI_256 = (() => {\n // 16 lower colors (taken from xterm)\n const p = [\n toRGBA8888(0, 0, 0),\n toRGBA8888(205, 0, 0),\n toRGBA8888(0, 205, 0),\n toRGBA8888(205, 205, 0),\n toRGBA8888(0, 0, 238),\n toRGBA8888(205, 0, 205),\n toRGBA8888(0, 250, 205),\n toRGBA8888(229, 229, 229),\n toRGBA8888(127, 127, 127),\n toRGBA8888(255, 0, 0),\n toRGBA8888(0, 255, 0),\n toRGBA8888(255, 255, 0),\n toRGBA8888(92, 92, 255),\n toRGBA8888(255, 0, 255),\n toRGBA8888(0, 255, 255),\n toRGBA8888(255, 255, 255),\n ];\n // colors up to 232\n const d = [0, 95, 135, 175, 215, 255];\n for (let r = 0; r < 6; ++r) {\n for (let g = 0; g < 6; ++g) {\n for (let b = 0; b < 6; ++b) {\n p.push(toRGBA8888(d[r], d[g], d[b]));\n }\n }\n }\n // grey scale to up 255\n for (let v = 8; v <= 238; v += 10) {\n p.push(toRGBA8888(v, v, v));\n }\n return new Uint32Array(p);\n})();\n/**\n * Background: Black by default.\n * Foreground: White by default.\n *\n * Background color is used whenever a fill color is needed and not explicitly set.\n * Foreground color is used as default initial sixel color.\n */\nexports.DEFAULT_BACKGROUND = toRGBA8888(0, 0, 0, 255);\nexports.DEFAULT_FOREGROUND = toRGBA8888(255, 255, 255, 255);\n//# sourceMappingURL=Colors.js.map","\"use strict\";\n/**\n * Copyright (c) 2021 Joerg Breitbart.\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.decodeAsync = exports.decode = exports.Decoder = exports.DecoderAsync = void 0;\nconst Colors_1 = require(\"./Colors\");\nconst wasm_1 = require(\"./wasm\");\n/* istanbul ignore next */\nfunction decodeBase64(s) {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(s, 'base64');\n }\n const bytestring = atob(s);\n const result = new Uint8Array(bytestring.length);\n for (let i = 0; i < result.length; ++i) {\n result[i] = bytestring.charCodeAt(i);\n }\n return result;\n}\nconst WASM_BYTES = decodeBase64(wasm_1.LIMITS.BYTES);\nlet WASM_MODULE;\n// empty canvas\nconst NULL_CANVAS = new Uint32Array();\n// proxy for lazy binding of decoder methods to wasm env callbacks\nclass CallbackProxy {\n constructor() {\n this.bandHandler = (width) => 1;\n this.modeHandler = (mode) => 1;\n }\n handle_band(width) {\n return this.bandHandler(width);\n }\n mode_parsed(mode) {\n return this.modeHandler(mode);\n }\n}\n// default decoder options\nconst DEFAULT_OPTIONS = {\n memoryLimit: 2048 * 65536,\n sixelColor: Colors_1.DEFAULT_FOREGROUND,\n fillColor: Colors_1.DEFAULT_BACKGROUND,\n palette: Colors_1.PALETTE_VT340_COLOR,\n paletteLimit: wasm_1.LIMITS.PALETTE_SIZE,\n truncate: true\n};\n/**\n * Create a decoder instance asynchronously.\n * To be used in the browser main thread.\n */\nfunction DecoderAsync(opts) {\n const cbProxy = new CallbackProxy();\n const importObj = {\n env: {\n handle_band: cbProxy.handle_band.bind(cbProxy),\n mode_parsed: cbProxy.mode_parsed.bind(cbProxy)\n }\n };\n return WebAssembly.instantiate(WASM_MODULE || WASM_BYTES, importObj)\n .then((inst) => {\n WASM_MODULE = WASM_MODULE || inst.module;\n return new Decoder(opts, inst.instance || inst, cbProxy);\n });\n}\nexports.DecoderAsync = DecoderAsync;\n/**\n * Decoder - web assembly based sixel stream decoder.\n *\n * Usage pattern:\n * - call `init` to initialize decoder for new image\n * - feed data chunks to `decode` or `decodeString`\n * - grab pixels from `data32`\n * - optional: call `release` to free memory (e.g. after big images)\n * - start over with next image by calling `init`\n *\n * Properties:\n * - max width of 2^14 - 4 pixels (compile time setting in wasm)\n * - no explicit height limit (only limited by memory)\n * - max 4096 colors palette (compile time setting in wasm)\n *\n * Explanation operation modes:\n * - M1 Mode chosen for level 1 images (no raster attributes),\n * or for level 2 images with `truncate=false`.\n * - M2 Mode chosen for level 2 images with `truncate=true` (default).\n * While this mode is not fully spec conform (decoder not expected to truncate),\n * it is what spec conform encoders should create (should not excess raster).\n * This mode has several advantages:\n * - ~15% faster decoding speed\n * - image dimensions can be evaluated early without processing the whole data\n * - faster pixel access in `data32` (precalulated)\n * - image height is not reported as multiple of 6 pixels\n * - M0 Undecided mode state after `init`.\n * The level of an image is determined during early decoding based on the fact,\n * whether the data contains valid raster attributes before any sixel data.\n * Until then the mode of an image is marked as M0, meaning the real operation mode\n * could not be decided yet.\n */\nclass Decoder {\n /**\n * Synchonous ctor. Can be called from nodejs or a webworker context.\n * For instantiation in the browser main thread use `WasmDecoderAsync` instead.\n */\n constructor(opts, _instance, _cbProxy) {\n this._PIXEL_OFFSET = wasm_1.LIMITS.MAX_WIDTH + 4;\n this._canvas = NULL_CANVAS;\n this._bandWidths = [];\n this._maxWidth = 0;\n this._minWidth = wasm_1.LIMITS.MAX_WIDTH;\n this._lastOffset = 0;\n this._currentHeight = 0;\n this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);\n if (this._opts.paletteLimit > wasm_1.LIMITS.PALETTE_SIZE) {\n throw new Error(`DecoderOptions.paletteLimit must not exceed ${wasm_1.LIMITS.PALETTE_SIZE}`);\n }\n if (!_instance) {\n const module = WASM_MODULE || (WASM_MODULE = new WebAssembly.Module(WASM_BYTES));\n _instance = new WebAssembly.Instance(module, {\n env: {\n handle_band: this._handle_band.bind(this),\n mode_parsed: this._initCanvas.bind(this)\n }\n });\n }\n else {\n _cbProxy.bandHandler = this._handle_band.bind(this);\n _cbProxy.modeHandler = this._initCanvas.bind(this);\n }\n this._instance = _instance;\n this._wasm = this._instance.exports;\n this._chunk = new Uint8Array(this._wasm.memory.buffer, this._wasm.get_chunk_address(), wasm_1.LIMITS.CHUNK_SIZE);\n this._states = new Uint32Array(this._wasm.memory.buffer, this._wasm.get_state_address(), 12);\n this._palette = new Uint32Array(this._wasm.memory.buffer, this._wasm.get_palette_address(), wasm_1.LIMITS.PALETTE_SIZE);\n this._palette.set(this._opts.palette);\n this._pSrc = new Uint32Array(this._wasm.memory.buffer, this._wasm.get_p0_address());\n this._wasm.init(Colors_1.DEFAULT_FOREGROUND, 0, this._opts.paletteLimit, 0);\n }\n // some readonly parser states for internal usage\n get _fillColor() { return this._states[0]; }\n get _truncate() { return this._states[8]; }\n get _rasterWidth() { return this._states[6]; }\n get _rasterHeight() { return this._states[7]; }\n get _width() { return this._states[2] ? this._states[2] - 4 : 0; }\n get _height() { return this._states[3]; }\n get _level() { return this._states[9]; }\n get _mode() { return this._states[10]; }\n get _paletteLimit() { return this._states[11]; }\n _initCanvas(mode) {\n if (mode === 2 /* M2 */) {\n const pixels = this.width * this.height;\n if (pixels > this._canvas.length) {\n if (this._opts.memoryLimit && pixels * 4 > this._opts.memoryLimit) {\n this.release();\n throw new Error('image exceeds memory limit');\n }\n this._canvas = new Uint32Array(pixels);\n }\n this._maxWidth = this._width;\n }\n else if (mode === 1 /* M1 */) {\n if (this._level === 2) {\n // got raster attributes, use them as initial size hint\n const pixels = Math.min(this._rasterWidth, wasm_1.LIMITS.MAX_WIDTH) * this._rasterHeight;\n if (pixels > this._canvas.length) {\n if (this._opts.memoryLimit && pixels * 4 > this._opts.memoryLimit) {\n this.release();\n throw new Error('image exceeds memory limit');\n }\n this._canvas = new Uint32Array(pixels);\n }\n }\n else {\n // else fallback to generic resizing, starting with 256*256 pixels\n if (this._canvas.length < 65536) {\n this._canvas = new Uint32Array(65536);\n }\n }\n }\n return 0; // 0 - continue, 1 - abort right away\n }\n _realloc(offset, additionalPixels) {\n const pixels = offset + additionalPixels;\n if (pixels > this._canvas.length) {\n if (this._opts.memoryLimit && pixels * 4 > this._opts.memoryLimit) {\n this.release();\n throw new Error('image exceeds memory limit');\n }\n // extend in 65536 pixel blocks\n const newCanvas = new Uint32Array(Math.ceil(pixels / 65536) * 65536);\n newCanvas.set(this._canvas);\n this._canvas = newCanvas;\n }\n }\n _handle_band(width) {\n const adv = this._PIXEL_OFFSET;\n let offset = this._lastOffset;\n if (this._mode === 2 /* M2 */) {\n let remaining = this.height - this._currentHeight;\n let c = 0;\n while (c < 6 && remaining > 0) {\n this._canvas.set(this._pSrc.subarray(adv * c, adv * c + width), offset + width * c);\n c++;\n remaining--;\n }\n this._lastOffset += width * c;\n this._currentHeight += c;\n }\n else if (this._mode === 1 /* M1 */) {\n this._realloc(offset, width * 6);\n this._maxWidth = Math.max(this._maxWidth, width);\n this._minWidth = Math.min(this._minWidth, width);\n for (let i = 0; i < 6; ++i) {\n this._canvas.set(this._pSrc.subarray(adv * i, adv * i + width), offset + width * i);\n }\n this._bandWidths.push(width);\n this._lastOffset += width * 6;\n this._currentHeight += 6;\n }\n return 0; // 0 - continue, 1 - abort right away\n }\n /**\n * Width of the image data.\n * Returns the rasterWidth in level2/truncating mode,\n * otherwise the max width, that has been seen so far.\n */\n get width() {\n return this._mode !== 1 /* M1 */\n ? this._width\n : Math.max(this._maxWidth, this._wasm.current_width());\n }\n /**\n * Height of the image data.\n * Returns the rasterHeight in level2/truncating mode,\n * otherwise height touched by sixels.\n */\n get height() {\n return this._mode !== 1 /* M1 */\n ? this._height\n : this._wasm.current_width()\n ? this._bandWidths.length * 6 + this._wasm.current_height()\n : this._bandWidths.length * 6;\n }\n /**\n * Get active palette colors as RGBA8888[] (borrowed).\n */\n get palette() {\n return this._palette.subarray(0, this._paletteLimit);\n }\n /**\n * Get the memory used by the decoder.\n *\n * This is a rough estimate accounting the wasm instance memory\n * and pixel buffers held on JS side (real value will be slightly\n * higher due to JS book-keeping).\n * Note that the decoder does not free ressources on its own,\n * call `release` to free excess memory.\n */\n get memoryUsage() {\n return this._canvas.byteLength + this._wasm.memory.buffer.byteLength + 8 * this._bandWidths.length;\n }\n /**\n * Get various properties of the decoder and the current image.\n */\n get properties() {\n return {\n width: this.width,\n height: this.height,\n mode: this._mode,\n level: this._level,\n truncate: !!this._truncate,\n paletteLimit: this._paletteLimit,\n fillColor: this._fillColor,\n memUsage: this.memoryUsage,\n rasterAttributes: {\n numerator: this._states[4],\n denominator: this._states[5],\n width: this._rasterWidth,\n height: this._rasterHeight,\n }\n };\n }\n /**\n * Initialize decoder for next image. Must be called before\n * any calls to `decode` or `decodeString`.\n */\n // FIXME: reorder arguments, better palette handling\n init(fillColor = this._opts.fillColor, palette = this._opts.palette, paletteLimit = this._opts.paletteLimit, truncate = this._opts.truncate) {\n this._wasm.init(this._opts.sixelColor, fillColor, paletteLimit, truncate ? 1 : 0);\n if (palette) {\n this._palette.set(palette.subarray(0, wasm_1.LIMITS.PALETTE_SIZE));\n }\n this._bandWidths.length = 0;\n this._maxWidth = 0;\n this._minWidth = wasm_1.LIMITS.MAX_WIDTH;\n this._lastOffset = 0;\n this._currentHeight = 0;\n }\n /**\n * Decode next chunk of data from start to end index (exclusive).\n * @throws Will throw if the image exceeds the memory limit.\n */\n decode(data, start = 0, end = data.length) {\n let p = start;\n while (p < end) {\n const length = Math.min(end - p, wasm_1.LIMITS.CHUNK_SIZE);\n this._chunk.set(data.subarray(p, p += length));\n this._wasm.decode(0, length);\n }\n }\n /**\n * Decode next chunk of string data from start to end index (exclusive).\n * Note: Decoding from string data is rather slow, use `decode` with byte data instead.\n * @throws Will throw if the image exceeds the memory limit.\n */\n decodeString(data, start = 0, end = data.length) {\n let p = start;\n while (p < end) {\n const length = Math.min(end - p, wasm_1.LIMITS.CHUNK_SIZE);\n for (let i = 0, j = p; i < length; ++i, ++j) {\n this._chunk[i] = data.charCodeAt(j);\n }\n p += length;\n this._wasm.decode(0, length);\n }\n }\n /**\n * Get current pixel data as 32-bit typed array (RGBA8888).\n * Also peeks into pixel data of the current band, that got not pushed yet.\n */\n get data32() {\n if (this._mode === 0 /* M0 */ || !this.width || !this.height) {\n return NULL_CANVAS;\n }\n // get width of pending band to peek into left-over data\n const currentWidth = this._wasm.current_width();\n if (this._mode === 2 /* M2 */) {\n let remaining = this.height - this._currentHeight;\n if (remaining > 0) {\n const adv = this._PIXEL_OFFSET;\n let offset = this._lastOffset;\n let c = 0;\n while (c < 6 && remaining > 0) {\n this._canvas.set(this._pSrc.subarray(adv * c, adv * c + currentWidth), offset + currentWidth * c);\n c++;\n remaining--;\n }\n if (remaining) {\n this._canvas.fill(this._fillColor, offset + currentWidth * c);\n }\n }\n return this._canvas.subarray(0, this.width * this.height);\n }\n if (this._mode === 1 /* M1 */) {\n if (this._minWidth === this._maxWidth) {\n let escape = false;\n if (currentWidth) {\n if (currentWidth !== this._minWidth) {\n escape = true;\n }\n else {\n const adv = this._PIXEL_OFFSET;\n let offset = this._lastOffset;\n this._realloc(offset, currentWidth * 6);\n for (let i = 0; i < 6; ++i) {\n this._canvas.set(this._pSrc.subarray(adv * i, adv * i + currentWidth), offset + currentWidth * i);\n }\n }\n }\n if (!escape) {\n return this._canvas.subarray(0, this.width * this.height);\n }\n }\n // worst case: re-align pixels if we have bands with different width\n // This is somewhat allocation intensive, any way to do that in-place, and just once?\n const final = new Uint32Array(this.width * this.height);\n final.fill(this._fillColor);\n let finalOffset = 0;\n let start = 0;\n for (let i = 0; i < this._bandWidths.length; ++i) {\n const bw = this._bandWidths[i];\n for (let p = 0; p < 6; ++p) {\n final.set(this._canvas.subarray(start, start += bw), finalOffset);\n finalOffset += this.width;\n }\n }\n // also handle left-over pixels of the current band\n if (currentWidth) {\n const adv = this._PIXEL_OFFSET;\n // other than finished bands, this runs only up to currentHeight\n const currentHeight = this._wasm.current_height();\n for (let i = 0; i < currentHeight; ++i) {\n final.set(this._pSrc.subarray(adv * i, adv * i + currentWidth), finalOffset + this.width * i);\n }\n }\n return final;\n }\n // fallthrough for all not handled cases\n return NULL_CANVAS;\n }\n /**\n * Same as `data32`, but returning pixel data as Uint8ClampedArray suitable\n * for direct usage with `ImageData`.\n */\n get data8() {\n return new Uint8ClampedArray(this.data32.buffer, 0, this.width * this.height * 4);\n }\n /**\n * Release image ressources on JS side held by the decoder.\n *\n * The decoder tries to re-use memory ressources of a previous image\n * to lower allocation and GC pressure. Decoding a single big image\n * will grow the memory usage of the decoder permanently.\n * Call `release` to reset the internal buffers and free the memory.\n * Note that this destroys the image data, call it when done processing\n * a rather big image, otherwise it is not needed. Use `memoryUsage`\n * to decide, whether the held memory is still within your limits.\n * This does not affect the wasm module (operates on static memory).\n */\n release() {\n this._canvas = NULL_CANVAS;\n this._bandWidths.length = 0;\n this._maxWidth = 0;\n this._minWidth = wasm_1.LIMITS.MAX_WIDTH;\n // also nullify parser states in wasm to avoid\n // width/height reporting potential out-of-bound values\n this._wasm.init(Colors_1.DEFAULT_FOREGROUND, 0, this._opts.paletteLimit, 0);\n }\n}\nexports.Decoder = Decoder;\n/**\n * Convenient decoding functions for easier usage.\n *\n * These can be used for casual decoding of sixel images,\n * that dont come in as stream chunks.\n * Note that the functions instantiate a stream decoder for every call,\n * which comes with a performance penalty of ~25%.\n */\n/**\n * Decode function with synchronous wasm loading.\n * Can be used in a web worker or in nodejs. Does not work reliable in normal browser context.\n * @throws Will throw if the image exceeds the memory limit.\n */\nfunction decode(data, opts) {\n const dec = new Decoder(opts);\n dec.init();\n typeof data === 'string' ? dec.decodeString(data) : dec.decode(data);\n return {\n width: dec.width,\n height: dec.height,\n data32: dec.data32,\n data8: dec.data8\n };\n}\nexports.decode = decode;\n/**\n * Decode function with asynchronous wasm loading.\n * Use this version in normal browser context.\n * @throws Will throw if the image exceeds the memory limit.\n */\nasync function decodeAsync(data, opts) {\n const dec = await DecoderAsync(opts);\n dec.init();\n typeof data === 'string' ? dec.decodeString(data) : dec.decode(data);\n return {\n width: dec.width,\n height: dec.height,\n data32: dec.data32,\n data8: dec.data8\n };\n}\nexports.decodeAsync = decodeAsync;\n//# sourceMappingURL=Decoder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LIMITS = void 0;\nexports.LIMITS = {\n CHUNK_SIZE: 16384,\n PALETTE_SIZE: 4096,\n MAX_WIDTH: 16384,\n BYTES: 'AGFzbQEAAAABJAdgAAF/YAJ/fwBgA39/fwF/YAF/AX9gAABgBH9/f38AYAF/AAIlAgNlbnYLaGFuZGxlX2JhbmQAAwNlbnYLbW9kZV9wYXJzZWQAAwMTEgQAAAAAAQQBAQUBAAACAgAGAwQFAXABBwcFBAEBBwcGCAF/AUGAihoLB9wBDgZtZW1vcnkCABFnZXRfc3Rhd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sLQeQIIAU2AgBB4AggAzYCAEHoCCAINgIAC9ELAgF+CH9B2AhCBDcDAEGojQJBoAgpAwAiADcDAEGgjQIgADcDAEGYjQIgADcDAEGQjQIgADcDAEGIjQIgADcDAEGAjQIgADcDAEH4jAIgADcDAEHwjAIgADcDAEHojAIgADcDAEHgjAIgADcDAEHYjAIgADcDAEHQjAIgADcDAEHIjAIgADcDAEHAjAIgADcDAEG4jAIgADcDAEGwjAIgADcDAEGojAIgADcDAEGgjAIgADcDAEGYjAIgADcDAEGQjAIgADcDAEGIjAIgADcDAEGAjAIgADcDAEH4iwIgADcDAEHwiwIgADcDAEHoiwIgADcDAEHgiwIgADcDAEHYiwIgADcDAEHQiwIgADcDAEHIiwIgADcDAEHAiwIgADcDAEG4iwIgADcDAEGwiwIgADcDAEGoiwIgADcDAEGgiwIgADcDAEGYiwIgADcDAEGQiwIgADcDAEGIiwIgADcDAEGAiwIgADcDAEH4igIgADcDAEHwigIgADcDAEHoigIgADcDAEHgigIgADcDAEHYigIgADcDAEHQigIgADcDAEHIigIgADcDAEHAigIgADcDAEG4igIgADcDAEGwigIgADcDAEGoigIgADcDAEGgigIgADcDAEGYigIgADcDAEGQigIgADcDAEGIigIgADcDAEGAigIgADcDAEH4iQIgADcDAEHwiQIgADcDAEHoiQIgADcDAEHgiQIgADcDAEHYiQIgADcDAEHQiQIgADcDAEHIiQIgADcDAEHAiQIgADcDAEG4iQIgADcDAEGwiQIgADcDAEGoCCgCACIEQf8AakGAAW0hCAJAIARBgQFIDQBBASEBIAhBAiAIQQJKG0EBayICQQFxIQMgBEGBAk4EQCACQX5xIQIDQCABQQl0IgdBEHJBoIkCakGwiQJBgAT8CgAAIAdBsI0CakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsLIANFDQAgAUEJdEEQckGgiQJqQbCJAkGABPwKAAALAkAgBEEBSA0AIAhBASAIQQFKGyIDQQFxIQUCQCADQQFrIgdFBEBBACEBDAELIANB/v///wdxIQJBACEBA0AgAUEJd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QCACBEAgBUMAAIA/kiEFDAELIAVDAACAP15FDQAgBUMAAIC/kiEFCwJAIAVDq6oqPl0EQCADIAcgA5NDAADAQJQgBZSSIQcMAQsgBUMAAAA/XQ0AIAVDq6oqP11FBEAgAyEHDAELIAMgByADkyAFQwAAwMCUQwAAgECSlJIhBwsgAEEIdAJ/IAdDAAB/Q5RDAAAAP5IiBkMAAIBPXSAGQwAAAABgcQRAIAapDAELQQALQRB0ciABcgtBgICAeHILNwAgAEH/AWxBMmpB5ABtIAFB/wFsQTJqQeQAbUEIdHIgAkH/AWxBMmpB5ABtQRB0ckGAgIB4cgsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwsYAQBBgAgLEQEAAAACAAAAAwAAAAQAAAAF'\n};\n//# sourceMappingURL=wasm.js.map","/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal event utilities for xterm.js core.\n * Simplified from VS Code's event.ts - no leak detection/profiling.\n */\n\nimport { IDisposable, DisposableStore, toDisposable } from './Lifecycle';\n\nexport interface IEvent {\n (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable;\n}\n\nexport class Emitter {\n private _listeners: { fn: (e: T) => any, thisArgs: any }[] = [];\n private _disposed = false;\n private _event: IEvent | undefined;\n\n public get event(): IEvent {\n if (this._event) {\n return this._event;\n }\n this._event = (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n if (this._disposed) {\n return toDisposable(() => {});\n }\n\n const entry = { fn: listener, thisArgs };\n this._listeners = this._listeners.slice();\n this._listeners.push(entry);\n\n const result = toDisposable(() => {\n const idx = this._listeners.indexOf(entry);\n if (idx !== -1) {\n this._listeners = this._listeners.slice();\n this._listeners.splice(idx, 1);\n }\n });\n\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(result);\n } else {\n disposables.add(result);\n }\n }\n\n return result;\n };\n return this._event;\n }\n\n public fire(event: T): void {\n if (this._disposed || !this._listeners.length) {\n return;\n }\n if (this._listeners.length === 1) {\n this._listeners[0].fn.call(this._listeners[0].thisArgs, event);\n return;\n }\n const listeners = this._listeners;\n for (let i = 0, len = listeners.length; i < len; ++i) {\n listeners[i].fn.call(listeners[i].thisArgs, event);\n }\n }\n\n public dispose(): void {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._listeners.length = 0;\n }\n}\n\nexport namespace EventUtils {\n export function forward(from: IEvent, to: Emitter): IDisposable {\n return from(e => to.fire(e));\n }\n\n export function map(event: IEvent, map: (i: I) => O): IEvent {\n return (listener: (e: O) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n return event(i => listener.call(thisArgs, map(i)), undefined, disposables);\n };\n }\n\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent {\n return (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n const store = new DisposableStore();\n for (const event of events) {\n store.add(event(e => listener.call(thisArgs, e)));\n }\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(store);\n } else {\n disposables.add(store);\n }\n }\n return store;\n };\n }\n\n export function runAndSubscribe(event: IEvent, handler: (e: T) => void, initial: T): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void, initial?: T): IDisposable {\n handler(initial);\n return event(e => handler(e));\n }\n}\n","/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal lifecycle utilities for xterm.js core.\n * Simplified from VS Code's lifecycle.ts - no tracking/leak detection.\n */\n\nexport interface IDisposable {\n dispose(): void;\n}\n\nexport function toDisposable(fn: () => void): IDisposable {\n return { dispose: fn };\n}\n\nexport function dispose(disposable: T): T;\nexport function dispose(disposable: T | undefined): T | undefined;\nexport function dispose(disposables: T[]): T[];\nexport function dispose(arg: T | T[] | undefined): T | T[] | undefined {\n if (!arg) {\n return arg;\n }\n if (Array.isArray(arg)) {\n for (const d of arg) {\n d.dispose();\n }\n return [];\n }\n arg.dispose();\n return arg;\n}\n\nexport function combinedDisposable(...disposables: IDisposable[]): IDisposable {\n return toDisposable(() => dispose(disposables));\n}\n\nexport class DisposableStore implements IDisposable {\n private readonly _disposables = new Set();\n private _isDisposed = false;\n\n public get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n public add(o: T): T {\n if (this._isDisposed) {\n o.dispose();\n } else {\n this._disposables.add(o);\n }\n return o;\n }\n\n public dispose(): void {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n\n public clear(): void {\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n}\n\nexport abstract class Disposable implements IDisposable {\n public static readonly None: IDisposable = Object.freeze({ dispose() { } });\n\n protected readonly _store = new DisposableStore();\n\n public dispose(): void {\n this._store.dispose();\n }\n\n protected _register(o: T): T {\n return this._store.add(o);\n }\n}\n\nexport class MutableDisposable implements IDisposable {\n private _value: T | undefined;\n private _isDisposed = false;\n\n public get value(): T | undefined {\n return this._isDisposed ? undefined : this._value;\n }\n\n public set value(value: T | undefined) {\n if (this._isDisposed || value === this._value) {\n return;\n }\n this._value?.dispose();\n this._value = value;\n }\n\n public clear(): void {\n this.value = undefined;\n }\n\n public dispose(): void {\n this._isDisposed = true;\n this._value?.dispose();\n this._value = undefined;\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IImageAddonOptions, IOscHandler, IResetHandler, ITerminalExt } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { CELL_SIZE_DEFAULT } from './ImageStorage';\nimport Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport QoiDecoder from 'xterm-wasm-parts/lib/qoi/QoiDecoder.wasm';\nimport { HeaderParser, IHeaderFields, HeaderState, SequenceType } from './IIPHeaderParser';\nimport { imageType, UNSUPPORTED_TYPE } from './IIPMetrics';\n\n// Local const enum mirror - esbuild can't inline const enums from external packages\nconst enum DecoderConst {\n // Limit held memory in base64 decoder (encoded bytes).\n KEEP_DATA = 4194304,\n // Initial buffer allocation for the decoder.\n INITIAL_DATA = 1048576,\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n OK = 0\n}\n\n// default IIP header values\nconst DEFAULT_HEADER: IHeaderFields = {\n type: SequenceType.INVALID,\n name: 'Unnamed file',\n size: 0,\n width: 'auto',\n height: 'auto',\n preserveAspectRatio: 1,\n inline: 0\n};\n\n\nexport class IIPHandler implements IOscHandler, IResetHandler {\n private _generation = 0;\n private _aborted = false;\n private _hp = new HeaderParser();\n private _header: IHeaderFields = DEFAULT_HEADER;\n private _dec: Base64Decoder;\n private _qoiDec: QoiDecoder;\n private _isMultipart = false;\n private _abortMulti = false;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _storage: IIPImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n const maxEncodedBytes = Math.ceil(this._opts.iipSizeLimit * 4 / 3);\n const initialBytes = Math.min(DecoderConst.INITIAL_DATA, maxEncodedBytes);\n this._dec = new Base64Decoder(DecoderConst.KEEP_DATA, maxEncodedBytes, initialBytes);\n this._qoiDec = new QoiDecoder(DecoderConst.KEEP_DATA);\n }\n\n public reset(): void {\n this._generation++;\n this._hp.reset();\n this._dec.release();\n this._qoiDec.release();\n }\n\n public start(): void {\n this._aborted = false;\n this._hp.reset();\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (this._hp.state === HeaderState.END) {\n if ((this._dec.put(data.subarray(start, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n }\n } else {\n const dataPos = this._hp.parse(data, start, end);\n if (dataPos === -1) {\n this._aborted = true;\n return;\n }\n if (dataPos > 0) {\n const seqType = this._hp.fields.type;\n if (seqType === SequenceType.FILE) {\n if (this._isMultipart) {\n this._isMultipart = false;\n this._abortMulti = false;\n this._dec.release();\n }\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n if (!this._header.inline) {\n this._aborted = true;\n return;\n }\n this._dec.init();\n } else if (this._abortMulti) {\n this._aborted = true;\n return;\n }\n if ((this._dec.put(data.subarray(dataPos, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n if (this._isMultipart) this._abortMulti = true;\n }\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted) return true;\n\n if (this._hp.state !== HeaderState.END) {\n if (this._hp.end()) return true;\n }\n const seqType = this._hp.fields.type;\n\n if (seqType === SequenceType.FILEPART) return true;\n\n if (seqType === SequenceType.REPORTCELLSIZE) {\n // OSC 1337 ; ReportCellSize=[height];[width];[scale] ST\n let w = CELL_SIZE_DEFAULT.width;\n let h = CELL_SIZE_DEFAULT.height;\n if (this._renderer.dimensions) {\n w = this._renderer.dimensions.css.canvas.width / this._coreTerminal.cols;\n h = this._renderer.dimensions.css.canvas.height / this._coreTerminal.rows;\n }\n const scale = this._coreTerminal._core._coreBrowserService?.dpr ?? 1;\n const report = `\\x1b]1337;ReportCellSize=${h.toFixed(3)};${w.toFixed(3)};${scale.toFixed(3)}\\x1b\\\\`;\n this._coreTerminal.input(report, false);\n return true;\n }\n\n if (seqType === SequenceType.MULTIPARTFILE) {\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n this._isMultipart = true;\n this._abortMulti = false;\n this._dec.release();\n this._dec.init();\n return true;\n }\n\n if (seqType === SequenceType.FILEEND) {\n if (!this._isMultipart) return true;\n this._isMultipart = false;\n if (this._abortMulti || this._header.type !== SequenceType.MULTIPARTFILE) return true;\n }\n\n // fallthrough for SequenceType.FILE & SequenceType.FILEEND\n\n let w = 0;\n let h = 0;\n\n // early exit condition chain\n let cond: number | boolean;\n let metrics = UNSUPPORTED_TYPE;\n if (cond = success) {\n if (cond = !this._dec.end()) {\n metrics = imageType(this._dec.data8);\n if (cond = metrics.mime !== 'unsupported') {\n w = metrics.width;\n h = metrics.height;\n if (cond = w && h && w * h < this._opts.pixelLimit) {\n [w, h] = this._resize(w, h).map(Math.floor);\n cond = w && h && w * h < this._opts.pixelLimit;\n } else {\n console.warn(`IIP: image dimension issue ${metrics.width}x${metrics.height}`);\n }\n } else {\n console.warn('IIP: unsupported image type');\n }\n } else {\n console.warn('IIP: error during BASE64 decoding');\n }\n }\n if (!cond) {\n this._dec.release();\n return true;\n }\n\n let blob: Blob | ImageData;\n if (metrics.mime === 'image/qoi') {\n const data = this._qoiDec.decode(this._dec.data8);\n blob = new ImageData(\n new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength),\n this._qoiDec.width,\n this._qoiDec.height\n );\n this._qoiDec.release();\n if (w === this._qoiDec.width && h === this._qoiDec.height) {\n // use fast-path if we don't need to rescale\n this._dec.release();\n const canvas = ImageRenderer.createCanvas(undefined, this._qoiDec.width, this._qoiDec.height);\n canvas.getContext('2d')?.putImageData(blob, 0, 0);\n this._storage.addImage(canvas);\n return true;\n }\n } else {\n blob = new Blob([this._dec.data8], { type: metrics.mime });\n }\n this._dec.release();\n const generation = this._generation;\n return createImageBitmap(blob, { resizeWidth: w, resizeHeight: h })\n .then(bm => {\n if (generation !== this._generation) {\n bm.close();\n return true;\n }\n this._storage.addImage(bm);\n return true;\n })\n .catch(e => {\n console.warn(`IIP: decoding error ${metrics.mime} ${metrics.width}x${metrics.height}`, e);\n return true;\n });\n }\n\n private _resize(w: number, h: number): [number, number] {\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n const width = this._renderer.dimensions?.css.canvas.width || cw * this._coreTerminal.cols;\n const height = this._renderer.dimensions?.css.canvas.height || ch * this._coreTerminal.rows;\n\n const rw = this._dim(this._header.width!, width, cw);\n const rh = this._dim(this._header.height!, height, ch);\n if (!rw && !rh) {\n const wf = width / w; // TODO: should this respect initial cursor offset?\n const hf = (height - ch) / h; // TODO: fix offset issues from float cell height\n const f = Math.min(wf, hf);\n return f < 1 ? [w * f, h * f] : [w, h];\n }\n return !rw\n ? [w * rh / h, rh]\n : this._header.preserveAspectRatio || !rw || !rh\n ? [rw, h * rw / w] : [rw, rh];\n }\n\n private _dim(s: string, total: number, cdim: number): number {\n if (s === 'auto') return 0;\n if (s.endsWith('%')) return parseInt(s.slice(0, -1), 10) * total / 100;\n if (s.endsWith('px')) return parseInt(s.slice(0, -2), 10);\n return parseInt(s, 10) * cdim;\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n// eslint-disable-next-line\ndeclare const Buffer: any;\n\nexport const enum HeaderState {\n START = 0,\n ABORT = 1,\n KEY = 2,\n VALUE = 3,\n END = 4\n}\n\nexport const enum SequenceType {\n INVALID = 0,\n FILE = 1,\n MULTIPARTFILE = 2,\n FILEPART = 3,\n FILEEND = 4,\n REPORTCELLSIZE = 5\n}\n\nexport interface IHeaderFields {\n [key: string]: number | string | Uint32Array | null | undefined;\n // sequence type\n type: SequenceType;\n // base-64 encoded filename. Defaults to \"Unnamed file\".\n name: string;\n // File size in bytes. The file transfer will be canceled if this size is exceeded.\n size: number;\n /**\n * Optional width and height to render:\n * - N: N character cells.\n * - Npx: N pixels.\n * - N%: N percent of the session's width or height.\n * - auto: The image's inherent size will be used to determine an appropriate dimension.\n */\n width?: string;\n height?: string;\n // Optional, defaults to 1 respecting aspect ratio (width takes precedence).\n preserveAspectRatio?: number;\n // Optional, defaults to 0. If set to 1, the file will be displayed inline, else downloaded\n // (download not supported).\n inline?: number;\n}\n\n// field value decoders\n\n// ASCII bytes to string\nfunction toStr(data: Uint32Array): string {\n let s = '';\n for (let i = 0; i < data.length; ++i) {\n s += String.fromCharCode(data[i]);\n }\n return s;\n}\n\n// digits to integer\nfunction toInt(data: Uint32Array): number {\n let v = 0;\n for (let i = 0; i < data.length; ++i) {\n if (data[i] < 48 || data[i] > 57) {\n throw new Error('illegal char');\n }\n v = v * 10 + data[i] - 48;\n }\n return v;\n}\n\n// check for correct size entry\nfunction toSize(data: Uint32Array): string {\n const v = toStr(data);\n if (!v.match(/^((auto)|(\\d+?((px)|(%)){0,1}))$/)) {\n throw new Error('illegal size');\n }\n return v;\n}\n\n// name is base64 encoded utf-8\nfunction toName(data: Uint32Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(toStr(data), 'base64').toString();\n }\n const bs = atob(toStr(data));\n const b = new Uint8Array(bs.length);\n for (let i = 0; i < b.length; ++i) {\n b[i] = bs.charCodeAt(i);\n }\n return new TextDecoder().decode(b);\n}\n\nconst DECODERS: {[key: string]: (v: Uint32Array) => number | string} = {\n inline: toInt,\n size: toInt,\n name: toName,\n width: toSize,\n height: toSize,\n preserveAspectRatio: toInt\n};\n\n\n// sequence type markers\n// File\nconst FILE_MARKER = [70, 105, 108, 101];\n// MultipartFile\nconst MULTIPARTFILE_MARKER = [77, 117, 108, 116, 105, 112, 97, 114, 116, 70, 105, 108, 101];\n// FilePart\nconst FILEPART_MARKER = [70, 105, 108, 101, 80, 97, 114, 116];\n// FileEnd\nconst FILEEND_MARKER = [70, 105, 108, 101, 69, 110, 100];\n// ReportCellSize\nconst REPORTCELLSIZE_MARKER = [82, 101, 112, 111, 114, 116, 67, 101, 108, 108, 83, 105, 122, 101];\n\n// max allowed chars for sequence header\nconst MAX_FIELDCHARS = 1024;\n\n\nexport class HeaderParser {\n public state: HeaderState = HeaderState.START;\n private _buffer = new Uint32Array(MAX_FIELDCHARS);\n private _position = 0;\n private _key = '';\n public fields: {[key: string]: number | string | Uint32Array | null | undefined} = {};\n\n public reset(): void {\n this._buffer.fill(0);\n this.state = HeaderState.START;\n this._position = 0;\n this.fields = {};\n this._key = '';\n }\n\n public end(): number {\n if (this.state === HeaderState.START) {\n if (this._position === FILEEND_MARKER.length) {\n for (let k = 0; k < FILEEND_MARKER.length; ++k) {\n if (this._buffer[k] !== FILEEND_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEEND;\n this.state = HeaderState.END;\n return 0;\n }\n if (this._position === REPORTCELLSIZE_MARKER.length) {\n for (let k = 0; k < REPORTCELLSIZE_MARKER.length; ++k) {\n if (this._buffer[k] !== REPORTCELLSIZE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.REPORTCELLSIZE;\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n if (this.state === HeaderState.END) return 0;\n if (this.state === HeaderState.VALUE\n && this.fields.type === SequenceType.MULTIPARTFILE\n ) {\n if (!this._storeValue(this._position)) return this._a();\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n\n public parse(data: Uint32Array, start: number, end: number): number {\n let state = this.state;\n let pos = this._position;\n const buffer = this._buffer;\n if (state === HeaderState.ABORT || state === HeaderState.END) return -1;\n if (state === HeaderState.START && pos > 14) return -1;\n for (let i = start; i < end; ++i) {\n const c = data[i];\n switch (c) {\n case 59: // ;\n if (!this._storeValue(pos)) return this._a();\n state = HeaderState.KEY;\n pos = 0;\n break;\n case 61: // =\n if (state === HeaderState.START) {\n if (buffer[0] === 70) {\n // 'File' or 'FilePart'\n let k = 0;\n for (; k < FILE_MARKER.length; ++k) {\n if (buffer[k] !== FILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILE;\n if (pos === FILEPART_MARKER.length) {\n for (; k < FILEPART_MARKER.length; ++k) {\n if (buffer[k] !== FILEPART_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEPART;\n this.state = HeaderState.END;\n return i + 1;\n }\n } else if (buffer[0] === 77) {\n // 'MultipartFile'\n for (let k = 0; k < MULTIPARTFILE_MARKER.length; ++k) {\n if (buffer[k] !== MULTIPARTFILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.MULTIPARTFILE;\n } else {\n return this._a();\n }\n state = HeaderState.KEY;\n pos = 0;\n } else if (state === HeaderState.KEY) {\n if (!this._storeKey(pos)) return this._a();\n state = HeaderState.VALUE;\n pos = 0;\n } else if (state === HeaderState.VALUE) {\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n break;\n case 58: // :\n if (state === HeaderState.VALUE) {\n if (!this._storeValue(pos)) return this._a();\n }\n this.state = HeaderState.END;\n return i + 1;\n default:\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n }\n this.state = state;\n this._position = pos;\n return -2;\n }\n\n private _a(): number {\n this.fields.type = SequenceType.INVALID;\n this.state = HeaderState.ABORT;\n return -1;\n }\n\n private _storeKey(pos: number): boolean {\n const k = toStr(this._buffer.subarray(0, pos));\n if (k) {\n this._key = k;\n this.fields[k] = null;\n return true;\n }\n return false;\n }\n\n private _storeValue(pos: number): boolean {\n if (this._key) {\n try {\n const v = this._buffer.slice(0, pos);\n this.fields[this._key] = DECODERS[this._key] ? DECODERS[this._key](v) : v;\n } catch {\n return false;\n }\n return true;\n }\n return false;\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IAddImageOpts } from './Types';\nimport { ImageStorage } from './ImageStorage';\n\n/**\n * IIP (iTerm Image Protocol) specific image storage controller.\n *\n * Wraps the shared ImageStorage with IIP protocol semantics:\n * - Always uses scrolling mode (cursor advances with image)\n */\nexport class IIPImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n constructor(\n private readonly _storage: ImageStorage\n ) {}\n\n /**\n * Add an IIP image to storage.\n * Always uses scrolling mode — cursor advances past the image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._storage.addImage(img, this._addImageOpts);\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n\nexport type ImageType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/qoi' | 'image/webp' | 'image/avif' | 'unsupported' | '';\n\nexport interface IMetrics {\n mime: ImageType;\n width: number;\n height: number;\n}\n\nexport const UNSUPPORTED_TYPE: IMetrics = {\n mime: 'unsupported',\n width: 0,\n height: 0\n};\n\nexport function imageType(d: Uint8Array): IMetrics {\n if (d.length < 32) {\n return UNSUPPORTED_TYPE;\n }\n const d32 = new Uint32Array(d.buffer, d.byteOffset, 8);\n // PNG: 89 50 4E 47 0D 0A 1A 0A (8 first bytes == magic number for PNG)\n // + first chunk must be IHDR\n if (d32[0] === 0x474E5089 && d32[1] === 0x0A1A0A0D && d32[3] === 0x52444849) {\n return {\n mime: 'image/png',\n width: d[16] << 24 | d[17] << 16 | d[18] << 8 | d[19],\n height: d[20] << 24 | d[21] << 16 | d[22] << 8 | d[23]\n };\n }\n // JPEG: FF D8 FF\n if (d[0] === 0xFF && d[1] === 0xD8 && d[2] === 0xFF) {\n const [width, height] = jpgSize(d);\n return { mime: 'image/jpeg', width, height };\n }\n // GIF: GIF87a or GIF89a\n if (d32[0] === 0x38464947 && (d[4] === 0x37 || d[4] === 0x39) && d[5] === 0x61) {\n return {\n mime: 'image/gif',\n width: d[7] << 8 | d[6],\n height: d[9] << 8 | d[8]\n };\n }\n // QOI: qoif\n if (d32[0] === 0x66696F71) {\n return {\n mime: 'image/qoi',\n width: d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7],\n height: d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11]\n };\n }\n // WEBP: RIFF | xxxx | WEBP | VP8x\n if (d32[0] === 0x46464952 && d32[2] === 0x50424557 && (d32[3] & 0xFFFFFF) === 0x385056) {\n switch (d[15]) {\n case 0x58: // Extended WebP VP8X --> \"X\"\n return {\n mime: 'image/webp',\n width: (d[24] | d[25] << 8 | d[26] << 16) + 1,\n height: (d[27] | d[28] << 8 | d[29] << 16) + 1\n };\n case 0x4C: // Lossless WebP VP8L --> \"L\"\n if (d[20] !== 0x2f) return UNSUPPORTED_TYPE;\n const dim = d[21] | d[22] << 8 | d[23] << 16 | d[24] << 24;\n return {\n mime: 'image/webp',\n width: (dim & 0x3FFF) + 1,\n height: (dim >>> 14 & 0x3FFF) + 1\n };\n case 0x20: // Lossy WebP VP8 --> \" \"\n if (d[23] !== 0x9d || d[24] !== 0x01 || d[25] !== 0x2a) return UNSUPPORTED_TYPE;\n return {\n mime: 'image/webp',\n width: (d[26] | d[27] << 8) & 0x3FFF,\n height: (d[28] | d[29] << 8) & 0x3FFF\n };\n }\n return UNSUPPORTED_TYPE;\n }\n // AVIF: Box size | ftyp | avif/avis\n if (d32[1] === 0x70797466 && (d32[2] === 0x66697661 || d32[2] === 0x73697661)) {\n let pos = -1;\n // search for ispe box within first 1024 bytes\n const limit = Math.min(d.length - 16, 1024);\n for (let i = 8; i < limit; i++) {\n // scan for ispe\n if (d[i] === 0x69 && d[i + 1] === 0x73 && d[i + 2] === 0x70 && d[i + 3] === 0x65) {\n pos = i;\n break;\n }\n }\n if (pos !== -1) {\n // dimensions are in BE at +8 (width) at +12 (height)\n const width =\n d[pos + 8] << 24 |\n d[pos + 9] << 16 |\n d[pos + 10] << 8 |\n d[pos + 11];\n const height =\n d[pos + 12] << 24 |\n d[pos + 13] << 16 |\n d[pos + 14] << 8 |\n d[pos + 15];\n if (width > 0 && height > 0) {\n return { mime: 'image/avif', width, height };\n }\n }\n return UNSUPPORTED_TYPE;\n }\n return UNSUPPORTED_TYPE;\n}\n\n\nfunction jpgSize(d: Uint8Array): [number, number] {\n const len = d.length;\n let i = 4;\n let blockLength = d[i] << 8 | d[i + 1];\n while (true) {\n i += blockLength;\n if (i >= len) {\n // exhausted without size info\n return [0, 0];\n }\n if (d[i] !== 0xFF) {\n return [0, 0];\n }\n if (d[i + 1] === 0xC0 || d[i + 1] === 0xC2) {\n if (i + 8 < len) {\n return [\n d[i + 7] << 8 | d[i + 8],\n d[i + 5] << 8 | d[i + 6]\n ];\n }\n return [0, 0];\n }\n i += 2;\n blockLength = d[i] << 8 | d[i + 1];\n }\n}\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { toRGBA8888 } from 'sixel/lib/Colors';\nimport { IDisposable } from '@xterm/xterm';\nimport { ICellSize, ImageLayer, ITerminalExt, IImageSpec, IRenderDimensions, IRenderService } from './Types';\nimport { Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';\n\nconst enum Constants {\n PLACEHOLDER_LENGTH = 4096,\n PLACEHOLDER_HEIGHT = 24\n}\n\n/**\n * ImageRenderer - terminal frontend extension:\n * - provide primitives for canvas, ImageData, Bitmap (static)\n * - add canvas layer to DOM (browser only for now)\n * - draw image tiles onRender\n */\nexport class ImageRenderer extends Disposable implements IDisposable {\n /** @deprecated Kept for backward compat — points to top layer canvas. */\n public get canvas(): HTMLCanvasElement | undefined { return this._layers.get('top')?.canvas; }\n private _layers = new Map();\n private _placeholder: HTMLCanvasElement | undefined;\n private _placeholderBitmap: ImageBitmap | undefined;\n private _optionsRefresh = this._register(new MutableDisposable());\n private _oldOpen: ((parent: HTMLElement) => void) | undefined;\n private _renderService: IRenderService | undefined;\n private _oldSetRenderer: ((renderer: any) => void) | undefined;\n\n // drawing primitive - canvas\n public static createCanvas(localDocument: Document | undefined, width: number, height: number): HTMLCanvasElement {\n /**\n * NOTE: We normally dont care, from which document the canvas\n * gets created, so we can fall back to global document,\n * if the terminal has no document associated yet.\n * This way early image loads before calling .open keep working\n * (still discouraged though, as the metrics will be screwed up).\n * Only the DOM output canvas should be on the terminal's document,\n * which gets explicitly checked in `insertLayerToDom`.\n */\n const canvas = (localDocument ?? document).createElement('canvas');\n canvas.width = width | 0;\n canvas.height = height | 0;\n return canvas;\n }\n\n // drawing primitive - ImageData with optional buffer\n public static createImageData(ctx: CanvasRenderingContext2D, width: number, height: number, buffer?: ArrayBuffer): ImageData {\n if (typeof ImageData !== 'function') {\n const imgData = ctx.createImageData(width, height);\n if (buffer) {\n imgData.data.set(new Uint8ClampedArray(buffer, 0, width * height * 4));\n }\n return imgData;\n }\n return buffer\n ? new ImageData(new Uint8ClampedArray(buffer, 0, width * height * 4), width, height)\n : new ImageData(width, height);\n }\n\n // drawing primitive - ImageBitmap\n public static createImageBitmap(img: ImageBitmapSource): Promise {\n if (typeof createImageBitmap !== 'function') {\n return Promise.resolve(undefined);\n }\n return createImageBitmap(img);\n }\n\n\n constructor(private _terminal: ITerminalExt) {\n super();\n this._oldOpen = this._terminal._core.open;\n this._terminal._core.open = (parent: HTMLElement): void => {\n this._oldOpen?.call(this._terminal._core, parent);\n this._open();\n };\n if (this._terminal._core.screenElement) {\n this._open();\n }\n // hack to spot fontSize changes\n this._optionsRefresh.value = this._terminal._core.optionsService.onOptionChange(option => {\n if (option === 'fontSize') {\n this.rescaleCanvas();\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n });\n this._register(toDisposable(() => {\n this.removeLayerFromDom();\n this.removeLayerFromDom('bottom');\n if (this._terminal._core && this._oldOpen) {\n this._terminal._core.open = this._oldOpen;\n this._oldOpen = undefined;\n }\n if (this._renderService && this._oldSetRenderer) {\n this._renderService.setRenderer = this._oldSetRenderer;\n this._oldSetRenderer = undefined;\n }\n this._renderService = undefined;\n this._layers.clear();\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }));\n }\n\n /**\n * Enable the placeholder.\n */\n public showPlaceholder(value: boolean): void {\n if (value) {\n if (!this._placeholder && this.cellSize.height !== -1) {\n this._createPlaceHolder(Math.max(this.cellSize.height + 1, Constants.PLACEHOLDER_HEIGHT));\n }\n } else {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n\n /**\n * Dimensions of the terminal.\n * Forwarded from internal render service.\n */\n public get dimensions(): IRenderDimensions | undefined {\n return this._terminal.dimensions;\n }\n\n /**\n * Current cell size (float).\n */\n public get cellSize(): ICellSize {\n return {\n width: this.dimensions?.css.cell.width || -1,\n height: this.dimensions?.css.cell.height || -1\n };\n }\n\n /**\n * Clear a region of the image layer canvas.\n */\n public clearLines(start: number, end: number, layer?: ImageLayer): void {\n const y = start * (this.dimensions?.css.cell.height || 0);\n const w = this.dimensions?.css.canvas.width || 0;\n const h = (end + 1 - start) * (this.dimensions?.css.cell.height || 0);\n if (!layer || layer === 'top') {\n this._layers.get('top')?.clearRect(0, y, w, h);\n }\n if (!layer || layer === 'bottom') {\n this._layers.get('bottom')?.clearRect(0, y, w, h);\n }\n }\n\n /**\n * Clear whole image canvas.\n */\n public clearAll(layer?: ImageLayer): void {\n if (!layer || layer === 'top') {\n const ctx = this._layers.get('top');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n if (!layer || layer === 'bottom') {\n const ctx = this._layers.get('bottom');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n }\n\n /**\n * Draw neighboring tiles on the image layer canvas.\n */\n public draw(imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get(imgSpec.layer);\n if (!ctx) {\n return;\n }\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const { width: sourceWidth, height: sourceHeight } = imgSpec.actualCellSize;\n const cols = Math.ceil(img.width / sourceWidth);\n\n const sx = (tileId % cols) * sourceWidth;\n const sy = Math.floor(tileId / cols) * sourceHeight;\n const dx = col * width;\n const dy = row * height;\n\n // safari bug: never access image source out of bounds\n const finalWidth = count * sourceWidth + sx > img.width ? img.width - sx : count * sourceWidth;\n const finalHeight = sy + sourceHeight > img.height ? img.height - sy : sourceHeight;\n\n // Floor all pixel offsets to get stable tile mapping without any overflows.\n // Note: For not pixel perfect aligned cells like in the DOM renderer\n // this will move a tile slightly to the top/left (subpixel range, thus ignore it).\n // FIX #34: avoid striping on displays with pixelDeviceRatio != 1 by ceiling height and width\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.ceil(finalWidth), Math.ceil(finalHeight),\n Math.floor(dx), Math.floor(dy), Math.ceil(finalWidth * width / sourceWidth), Math.ceil(finalHeight * height / sourceHeight)\n );\n }\n\n /**\n * Extract a single tile from an image.\n */\n public extractTile(imgSpec: IImageSpec, tileId: number): HTMLCanvasElement | undefined {\n const { width, height } = this.cellSize;\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const { width: sourceWidth, height: sourceHeight } = imgSpec.actualCellSize;\n const cols = Math.ceil(img.width / sourceWidth);\n const sx = (tileId % cols) * sourceWidth;\n const sy = Math.floor(tileId / cols) * sourceHeight;\n const finalWidth = sourceWidth + sx > img.width ? img.width - sx : sourceWidth;\n const finalHeight = sy + sourceHeight > img.height ? img.height - sy : sourceHeight;\n\n const canvas = ImageRenderer.createCanvas(this.document, Math.ceil(finalWidth * width / sourceWidth), Math.ceil(finalHeight * height / sourceHeight));\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.floor(finalWidth), Math.floor(finalHeight),\n 0, 0, canvas.width, canvas.height\n );\n return canvas;\n }\n }\n\n /**\n * Draw a line with placeholder on the image layer canvas.\n */\n public drawPlaceholder(col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get('top');\n if (ctx) {\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n if (!this._placeholder) {\n this._createPlaceHolder(Math.max(height + 1, Constants.PLACEHOLDER_HEIGHT));\n } else if (height >= this._placeholder!.height) {\n this._createPlaceHolder(height + 1);\n }\n if (!this._placeholder) return;\n ctx.drawImage(\n this._placeholderBitmap ?? this._placeholder!,\n col * width,\n (row * height) % 2 ? 0 : 1, // needs %2 offset correction\n width * count,\n height,\n col * width,\n row * height,\n width * count,\n height\n );\n }\n }\n\n /**\n * Rescale image layer canvas if needed.\n * Checked once from `ImageStorage.render`.\n */\n public rescaleCanvas(): void {\n const w = this.dimensions?.css.canvas.width || 0;\n const h = this.dimensions?.css.canvas.height || 0;\n for (const ctx of this._layers.values()) {\n if (ctx.canvas.width !== w || ctx.canvas.height !== h) {\n ctx.canvas.width = w;\n ctx.canvas.height = h;\n }\n }\n }\n\n /**\n * Rescale image in storage if needed.\n */\n private _rescaleImage(spec: IImageSpec, currentWidth: number, currentHeight: number): void {\n if (currentWidth === spec.actualCellSize.width && currentHeight === spec.actualCellSize.height) {\n return;\n }\n const { width: originalWidth, height: originalHeight } = spec.origCellSize;\n if (currentWidth === originalWidth && currentHeight === originalHeight) {\n spec.actual = spec.orig;\n spec.actualCellSize.width = originalWidth;\n spec.actualCellSize.height = originalHeight;\n return;\n }\n const scaledWidth = Math.ceil(spec.orig!.width * currentWidth / originalWidth);\n const scaledHeight = Math.ceil(spec.orig!.height * currentHeight / originalHeight);\n // Upscale visible tiles directly; a full zoomed copy can dwarf the image budget.\n if (scaledWidth * scaledHeight > spec.orig!.width * spec.orig!.height) {\n spec.actual = spec.orig;\n spec.actualCellSize.width = originalWidth;\n spec.actualCellSize.height = originalHeight;\n return;\n }\n const canvas = ImageRenderer.createCanvas(this.document, scaledWidth, scaledHeight);\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(spec.orig!, 0, 0, canvas.width, canvas.height);\n spec.actual = canvas;\n spec.actualCellSize.width = currentWidth;\n spec.actualCellSize.height = currentHeight;\n }\n }\n\n /**\n * Lazy init for the renderer.\n */\n private _open(): void {\n this._renderService = this._terminal._core._renderService;\n this._oldSetRenderer = this._renderService.setRenderer.bind(this._renderService);\n this._renderService.setRenderer = (renderer: any) => {\n for (const key of [...this._layers.keys()]) {\n this.removeLayerFromDom(key);\n }\n this._oldSetRenderer?.call(this._renderService, renderer);\n };\n }\n\n public insertLayerToDom(layer: ImageLayer = 'top'): void {\n // make sure that the terminal is attached to a document and to DOM\n if (!this.document || !this._terminal._core.screenElement) {\n console.warn('image addon: cannot insert output canvas to DOM, missing document or screenElement');\n return;\n }\n if (this._layers.has(layer)) {\n return;\n }\n const canvas = ImageRenderer.createCanvas(\n this.document, this.dimensions?.css.canvas.width || 0,\n this.dimensions?.css.canvas.height || 0\n );\n canvas.classList.add(`xterm-image-layer-${layer}`);\n const screenElement = this._terminal._core.screenElement;\n // Use isolation to create a stacking context without overriding z-index,\n // which would conflict with integrators (e.g. VS Code) that set their\n // own z-index on the screen element.\n screenElement.style.isolation = 'isolate';\n if (layer === 'bottom') {\n // Use z-index:-1 so it paints behind non-positioned text elements.\n // The screen element needs to be a stacking context (via isolation)\n // to contain the negative z-index, otherwise it would go behind the\n // entire terminal.\n canvas.style.zIndex = '-1';\n screenElement.insertBefore(canvas, screenElement.firstChild);\n } else {\n // Explicit z-index ensures the image canvas reliably stacks above\n // the text layer (DOM renderer rows). z-index: 0 is below the\n // selection overlay (z-index: 1).\n canvas.style.zIndex = '0';\n screenElement.appendChild(canvas);\n }\n const ctx = canvas.getContext('2d', { alpha: true });\n if (!ctx) {\n canvas.remove();\n return;\n }\n this._layers.set(layer, ctx);\n this.clearAll(layer);\n }\n\n public removeLayerFromDom(layer: ImageLayer = 'top'): void {\n const ctx = this._layers.get(layer);\n if (ctx) {\n ctx.canvas.remove();\n this._layers.delete(layer);\n }\n }\n\n public hasLayer(layer: ImageLayer): boolean {\n return this._layers.has(layer);\n }\n\n private _createPlaceHolder(height: number = Constants.PLACEHOLDER_HEIGHT): void {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n\n // create blueprint to fill placeholder with\n const bWidth = 32; // must be 2^n\n const blueprint = ImageRenderer.createCanvas(this.document, bWidth, height);\n const ctx = blueprint.getContext('2d', { alpha: false });\n if (!ctx) return;\n const imgData = ImageRenderer.createImageData(ctx, bWidth, height);\n const d32 = new Uint32Array(imgData.data.buffer);\n const black = toRGBA8888(0, 0, 0);\n const white = toRGBA8888(255, 255, 255);\n d32.fill(black);\n for (let y = 0; y < height; ++y) {\n const shift = y % 2;\n const offset = y * bWidth;\n for (let x = 0; x < bWidth; x += 2) {\n d32[offset + x + shift] = white;\n }\n }\n ctx.putImageData(imgData, 0, 0);\n\n // create placeholder line, width aligned to blueprint width\n const width = (screen.width + bWidth - 1) & ~(bWidth - 1) || Constants.PLACEHOLDER_LENGTH;\n this._placeholder = ImageRenderer.createCanvas(this.document, width, height);\n const ctx2 = this._placeholder.getContext('2d', { alpha: false });\n if (!ctx2) {\n this._placeholder = undefined;\n return;\n }\n for (let i = 0; i < width; i += bWidth) {\n ctx2.drawImage(blueprint, i, 0);\n }\n const placeholder = this._placeholder;\n ImageRenderer.createImageBitmap(placeholder).then(bitmap => {\n if (this._placeholder !== placeholder) bitmap?.close();\n else this._placeholderBitmap = bitmap;\n }).catch(() => {});\n }\n\n public get document(): Document | undefined {\n return this._terminal._core._coreBrowserService?.window.document;\n }\n}\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageRenderer } from './ImageRenderer';\nimport {\n ITerminalExt, IExtendedAttrsImage, IImageAddonOptions, IImageSpec,\n IBufferLineExt, BgFlags, Cell, Content, ICellSize, ExtFlags, Attributes,\n UnderlineStyle, IAddImageOpts\n} from './Types';\n\n\n// fallback default cell size\nexport const CELL_SIZE_DEFAULT: ICellSize = {\n width: 7,\n height: 14\n};\n\n/**\n * Extend extended attribute to also hold image tile information.\n *\n * Object definition is copied from base repo to fully mimick its behavior.\n * Image data is added as additional public properties `imageId` and `tileId`.\n */\nclass ExtendedAttrsImage implements IExtendedAttrsImage {\n private _ext: number = 0;\n public get ext(): number {\n if (this._urlId) {\n return (\n (this._ext & ~ExtFlags.UNDERLINE_STYLE) |\n (this.underlineStyle << 26)\n );\n }\n return this._ext;\n }\n public set ext(value: number) { this._ext = value; }\n\n public get underlineStyle(): UnderlineStyle {\n // Always return the URL style if it has one\n if (this._urlId) {\n return UnderlineStyle.DASHED;\n }\n return (this._ext & ExtFlags.UNDERLINE_STYLE) >> 26;\n }\n public set underlineStyle(value: UnderlineStyle) {\n this._ext &= ~ExtFlags.UNDERLINE_STYLE;\n this._ext |= (value << 26) & ExtFlags.UNDERLINE_STYLE;\n }\n\n public get underlineColor(): number {\n return this._ext & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n public set underlineColor(value: number) {\n this._ext &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n this._ext |= value & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n\n public get underlineVariantOffset(): number {\n const val = (this._ext & ExtFlags.VARIANT_OFFSET) >> 29;\n if (val < 0) {\n return val ^ 0xFFFFFFF8;\n }\n return val;\n }\n public set underlineVariantOffset(value: number) {\n this._ext &= ~ExtFlags.VARIANT_OFFSET;\n this._ext |= (value << 29) & ExtFlags.VARIANT_OFFSET;\n }\n\n private _urlId: number = 0;\n public get urlId(): number {\n return this._urlId;\n }\n public set urlId(value: number) {\n this._urlId = value;\n }\n\n constructor(\n ext: number = 0,\n urlId: number = 0,\n public imageId = -1,\n public tileId = -1\n ) {\n this._ext = ext;\n this._urlId = urlId;\n }\n\n public clone(): IExtendedAttrsImage {\n /**\n * Technically we dont need a clone variant of ExtendedAttrsImage,\n * as we never clone a cell holding image data.\n * Note: Clone is only meant to be used by the InputHandler for\n * sticky attributes, which is never the case for image data.\n * We still provide a proper clone method to reflect the full ext attr\n * state in case there are future use cases for clone.\n */\n return new ExtendedAttrsImage(this._ext, this._urlId, this.imageId, this.tileId);\n }\n\n public isEmpty(): boolean {\n return this.underlineStyle === UnderlineStyle.NONE && this._urlId === 0 && this.imageId === -1;\n }\n}\nconst EMPTY_ATTRS = new ExtendedAttrsImage();\n\n\n/**\n * ImageStorage - extension of CoreTerminal:\n * - hold image data\n * - write/read image data to/from buffer\n *\n * TODO: image composition for overwrites\n */\nexport class ImageStorage implements IDisposable {\n // storage\n private _images: Map = new Map();\n // last used id\n private _lastId = 0;\n // last evicted id\n private _lowestId = 0;\n // whether a full clear happened before\n private _fullyCleared = false;\n // whether render should do a full clear\n private _needsFullClear = false;\n // hard limit of stored pixels (fallback limit of 10 MB)\n private _pixelLimit: number = 2500000;\n\n private _viewportMetrics: { cols: number, rows: number };\n public onImageAdded: (() => void) | undefined;\n public onImageDeleted: ((storageId: number) => void) | undefined;\n\n constructor(\n private _terminal: ITerminalExt,\n private _renderer: ImageRenderer,\n private _opts: IImageAddonOptions\n ) {\n try {\n this.setLimit(this._opts.storageLimit);\n } catch (e: unknown) {\n if (e instanceof Error) {\n console.error(e.message);\n }\n console.warn(`storageLimit is set to ${this.getLimit()} MB`);\n }\n this._viewportMetrics = {\n cols: this._terminal.cols,\n rows: this._terminal.rows\n };\n }\n\n public dispose(): void {\n this.reset();\n }\n\n public reset(): void {\n for (const spec of this._images.values()) {\n spec.marker?.dispose();\n }\n // NOTE: marker.dispose above already calls ImageBitmap.close\n // therefore we can just wipe the map here\n this._images.clear();\n this._renderer.clearAll();\n }\n\n public getLimit(): number {\n return this._pixelLimit * 4 / 1000000;\n }\n\n public setLimit(value: number): void {\n if (value < 0.5 || value > 1000) {\n throw RangeError('invalid storageLimit, should be at least 0.5 MB and not exceed 1G');\n }\n this._pixelLimit = (value / 4 * 1000000) >>> 0;\n this._evictOldest(0);\n }\n\n public getUsage(): number {\n return this._getStoredPixels() * 4 / 1000000;\n }\n\n private _getStoredPixels(): number {\n let storedPixels = 0;\n for (const spec of this._images.values()) {\n if (spec.orig) {\n storedPixels += spec.orig.width * spec.orig.height;\n if (spec.actual && spec.actual !== spec.orig) {\n storedPixels += spec.actual.width * spec.actual.height;\n }\n }\n }\n return storedPixels;\n }\n\n private _delImg(id: number): void {\n const spec = this._images.get(id);\n if (!spec) return;\n this._images.delete(id);\n // FIXME: really ugly workaround to get bitmaps deallocated :(\n if (window.ImageBitmap && spec.orig instanceof ImageBitmap) {\n spec.orig.close();\n }\n this.onImageDeleted?.(id);\n }\n\n /**\n * Wipe canvas and images on alternate buffer.\n */\n public wipeAlternate(): void {\n // remove all alternate tagged images\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate') {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n // mark canvas to be wiped on next render\n this._needsFullClear = true;\n this._fullyCleared = false;\n }\n\n /**\n * Delete an image by its internal storage ID.\n * Used by protocols that support explicit deletion (e.g. Kitty a=d).\n */\n public deleteImage(id: number): void {\n const spec = this._images.get(id);\n if (spec) {\n spec.marker?.dispose();\n this._delImg(id);\n }\n }\n\n /**\n * Method to add an image to the storage.\n * @param img - The image to add (canvas or bitmap).\n * @param opts - Options for addImage:\n * - scrolling: When true, cursor advances with the image.\n * When false, image is placed at ORIGIN and cursor does not move.\n * - layer: Which canvas layer to render on ('top' or 'bottom').\n * - zIndex: Z-index for image layering within the same layer.\n * - cursorPos: 'vt340' for bottom-left, 'iip' for bottom.right.\n * @returns The internal image ID assigned to the stored image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap, opts: IAddImageOpts): number {\n // never allow storage to exceed memory limit\n this._evictOldest(img.width * img.height);\n\n // calc rows x cols needed to display the image\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const cols = Math.ceil(img.width / cellSize.width);\n const rows = Math.ceil(img.height / cellSize.height);\n\n const imageId = ++this._lastId;\n\n const buffer = this._terminal._core.buffer;\n const termCols = this._terminal.cols;\n const termRows = this._terminal.rows;\n const originX = buffer.x;\n const originY = buffer.y;\n let offset = originX;\n let tileCount = 0;\n\n if (!opts.scrolling) {\n buffer.x = 0;\n buffer.y = 0;\n offset = 0;\n }\n\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(buffer.y + buffer.ybase);\n for (let col = 0; col < cols; ++col) {\n if (offset + col >= termCols) break;\n this._writeToCell(line as IBufferLineExt, offset + col, imageId, row * cols + col);\n tileCount++;\n }\n if (opts.scrolling) {\n if (row < rows - 1) this._terminal._core._inputHandler.lineFeed();\n } else {\n if (++buffer.y >= termRows) break;\n }\n buffer.x = offset;\n }\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n\n // cursor positioning modes\n if (opts.scrolling) {\n if (opts.cursorPos === 'iip') {\n buffer.x = Math.min(offset + cols, termCols);\n } else {\n buffer.x = offset;\n }\n } else {\n buffer.x = originX;\n buffer.y = originY;\n }\n\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.tileCount < 1) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n\n // eviction marker:\n // delete the image when the marker gets disposed\n const endMarker = this._terminal.registerMarker(0);\n endMarker?.onDispose(() => {\n const spec = this._images.get(imageId);\n if (spec) {\n this._delImg(imageId);\n }\n });\n\n // since markers do not work on alternate for some reason,\n // we evict images here manually\n if (this._terminal.buffer.active.type === 'alternate') {\n this._evictOnAlternate();\n }\n\n // create storage entry\n const imgSpec: IImageSpec = {\n orig: img,\n origCellSize: cellSize,\n actual: img,\n actualCellSize: { ...cellSize }, // clone needed, since later modified\n marker: endMarker || undefined,\n tileCount,\n bufferType: this._terminal.buffer.active.type,\n layer: opts.layer,\n zIndex: opts.zIndex\n };\n\n // finally add the image\n this._images.set(imageId, imgSpec);\n this.onImageAdded?.();\n return imageId;\n }\n\n\n /**\n * Render method. Collects buffer information and triggers\n * canvas updates.\n */\n // TODO: Should we move this to the ImageRenderer?\n public render(range: { start: number, end: number }): void {\n // Determine which layers have images\n let hasTopImages = false;\n let hasBottomImages = false;\n for (const spec of this._images.values()) {\n if (spec.layer === 'bottom') {\n hasBottomImages = true;\n } else {\n hasTopImages = true;\n }\n if (hasTopImages && hasBottomImages) break;\n }\n\n // Lazily insert layers that are needed\n if (hasTopImages && !this._renderer.hasLayer('top')) {\n this._renderer.insertLayerToDom('top');\n if (!this._renderer.hasLayer('top')) return;\n }\n if (hasBottomImages && !this._renderer.hasLayer('bottom')) {\n this._renderer.insertLayerToDom('bottom');\n }\n\n // rescale if needed\n this._renderer.rescaleCanvas();\n\n // exit early if we dont have any images to test for\n if (!this._images.size) {\n if (!this._fullyCleared) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n if (this._renderer.hasLayer('top')) {\n this._renderer.removeLayerFromDom('top');\n }\n if (this._renderer.hasLayer('bottom')) {\n this._renderer.removeLayerFromDom('bottom');\n }\n return;\n }\n\n // Remove layers no longer needed\n if (!hasTopImages && this._renderer.hasLayer('top')) {\n this._renderer.clearAll('top');\n this._renderer.removeLayerFromDom('top');\n }\n if (!hasBottomImages && this._renderer.hasLayer('bottom')) {\n this._renderer.clearAll('bottom');\n this._renderer.removeLayerFromDom('bottom');\n }\n\n // buffer switches force a full clear\n if (this._needsFullClear) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n\n const { start, end } = range;\n const buffer = this._terminal._core.buffer;\n const cols = this._terminal._core.cols;\n\n // clear drawing area\n this._renderer.clearLines(start, end);\n\n // Collect draw calls so we can sort by z-index (lower z drawn first).\n const drawCalls: { imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number }[] = [];\n const placeholderCalls: { col: number, row: number, count: number }[] = [];\n\n // walk all cells in viewport and collect tiles found\n for (let row = start; row <= end; ++row) {\n const line = buffer.lines.get(row + buffer.ydisp) as IBufferLineExt;\n if (!line) return;\n for (let col = 0; col < cols; ++col) {\n if (line.getBg(col) & BgFlags.HAS_EXTENDED) {\n let e: IExtendedAttrsImage = line._extendedAttrs[col] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (e.tileId !== -1) {\n const startTile = e.tileId;\n const startCol = col;\n let count = 1;\n /**\n * merge tiles to the right into a single draw call, if:\n * - not at end of line\n * - cell has same image id\n * - cell has consecutive tile id\n */\n while (\n ++col < cols\n && (line.getBg(col) & BgFlags.HAS_EXTENDED)\n && (e = line._extendedAttrs[col] ?? EMPTY_ATTRS)\n && (e.imageId === imageId)\n && (e.tileId === startTile + count)\n ) {\n count++;\n }\n col--;\n if (imgSpec) {\n if (imgSpec.actual) {\n drawCalls.push({ imgSpec, tileId: startTile, col: startCol, row, count });\n }\n } else if (this._opts.showPlaceholder) {\n placeholderCalls.push({ col: startCol, row, count });\n }\n this._fullyCleared = false;\n }\n }\n }\n }\n\n // Sort by z-index so lower z draws first (higher z renders on top)\n drawCalls.sort((a, b) => a.imgSpec.zIndex - b.imgSpec.zIndex);\n\n // Draw placeholders first (lowest priority)\n for (const call of placeholderCalls) {\n this._renderer.drawPlaceholder(call.col, call.row, call.count);\n }\n\n // Draw images in z-index order\n for (const call of drawCalls) {\n this._renderer.draw(call.imgSpec, call.tileId, call.col, call.row, call.count);\n }\n }\n\n public viewportResize(metrics: { cols: number, rows: number }): void {\n // exit early if we have nothing in storage\n if (!this._images.size) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // handle only viewport width enlargements, exit all other cases\n // TODO: needs patch for tile counter\n if (this._viewportMetrics.cols >= metrics.cols) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // walk scrollbuffer at old col width to find all possible expansion matches\n const buffer = this._terminal._core.buffer;\n const rows = buffer.lines.length;\n const oldCol = this._viewportMetrics.cols - 1;\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(row) as IBufferLineExt;\n if (line.getBg(oldCol) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[oldCol] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (!imgSpec) {\n continue;\n }\n // found an image tile at oldCol, check if it qualifies for right exapansion\n const tilesPerRow = Math.ceil((imgSpec.actual?.width || 0) / imgSpec.actualCellSize.width);\n if ((e.tileId % tilesPerRow) + 1 >= tilesPerRow) {\n continue;\n }\n // expand only if right side is empty (nothing got wrapped from below)\n let hasData = false;\n for (let rightCol = oldCol + 1; rightCol > metrics.cols; ++rightCol) {\n if (line._data[rightCol * Cell.SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK) {\n hasData = true;\n break;\n }\n }\n if (hasData) {\n continue;\n }\n // do right expansion on terminal buffer\n const end = Math.min(metrics.cols, tilesPerRow - (e.tileId % tilesPerRow) + oldCol);\n let lastTile = e.tileId;\n for (let expandCol = oldCol + 1; expandCol < end; ++expandCol) {\n this._writeToCell(line as IBufferLineExt, expandCol, imageId, ++lastTile);\n imgSpec.tileCount++;\n }\n }\n }\n // store new viewport metrics\n this._viewportMetrics = metrics;\n }\n\n /**\n * Retrieve original canvas at buffer position.\n */\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1) {\n const orig = this._images.get(e.imageId)?.orig;\n if (window.ImageBitmap && orig instanceof ImageBitmap) {\n const canvas = ImageRenderer.createCanvas(window.document, orig.width, orig.height);\n canvas.getContext('2d')?.drawImage(orig, 0, 0, orig.width, orig.height);\n return canvas;\n }\n return orig as HTMLCanvasElement;\n }\n }\n }\n\n /**\n * Extract active single tile at buffer position.\n */\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1 && e.tileId !== -1) {\n const spec = this._images.get(e.imageId);\n if (spec) {\n return this._renderer.extractTile(spec, e.tileId);\n }\n }\n }\n }\n\n // TODO: Do we need some blob offloading tricks here to avoid early eviction?\n // also see https://stackoverflow.com/questions/28307789/is-there-any-limitation-on-javascript-max-blob-size\n private _evictOldest(room: number): number {\n const used = this._getStoredPixels();\n let current = used;\n while (this._pixelLimit < current + room && this._images.size) {\n const spec = this._images.get(++this._lowestId);\n if (spec && spec.orig) {\n current -= spec.orig.width * spec.orig.height;\n if (spec.actual && spec.orig !== spec.actual) {\n current -= spec.actual.width * spec.actual.height;\n }\n spec.marker?.dispose();\n this._delImg(this._lowestId);\n }\n }\n return used - current;\n }\n\n private _writeToCell(line: IBufferLineExt, x: number, imageId: number, tileId: number): void {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const old = line._extendedAttrs[x];\n if (old) {\n if (old.imageId !== undefined) {\n // found an old ExtendedAttrsImage, since we know that\n // they are always isolated instances (single cell usage),\n // we can re-use it and just update their id entries\n const oldSpec = this._images.get(old.imageId);\n if (oldSpec) {\n // early eviction for in-viewport overwrites\n oldSpec.tileCount--;\n }\n old.imageId = imageId;\n old.tileId = tileId;\n return;\n }\n // found a plain ExtendedAttrs instance, clone it to new entry\n line._extendedAttrs[x] = new ExtendedAttrsImage(old.ext, old.urlId, imageId, tileId);\n return;\n }\n }\n // fall-through: always create new ExtendedAttrsImage entry\n line._data[x * Cell.SIZE + Cell.BG] |= BgFlags.HAS_EXTENDED;\n line._extendedAttrs[x] = new ExtendedAttrsImage(0, 0, imageId, tileId);\n }\n\n private _evictOnAlternate(): void {\n // nullify tile count of all images on alternate buffer\n for (const spec of this._images.values()) {\n if (spec.bufferType === 'alternate') {\n spec.tileCount = 0;\n }\n }\n // re-count tiles on whole buffer\n const buffer = this._terminal._core.buffer;\n for (let y = 0; y < this._terminal.rows; ++y) {\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (!line) {\n continue;\n }\n for (let x = 0; x < this._terminal.cols; ++x) {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const imgId = line._extendedAttrs[x]?.imageId;\n if (imgId) {\n const spec = this._images.get(imgId);\n if (spec) {\n spec.tileCount++;\n }\n }\n }\n }\n }\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate' && !spec.tileCount) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n }\n}\n","/**\n * Copyright (c) 2020, 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IDcsHandler, IParams, IImageAddonOptions, ITerminalExt, AttributeData, IResetHandler, ReadonlyColorSet } from './Types';\nimport { toRGBA8888, BIG_ENDIAN, PALETTE_ANSI_256, PALETTE_VT340_COLOR } from 'sixel/lib/Colors';\nimport { RGBA8888 } from 'sixel/lib/Types';\nimport { ImageRenderer } from './ImageRenderer';\n\nimport { DecoderAsync, Decoder } from 'sixel/lib/Decoder';\n\n// always free decoder ressources after decoding if it exceeds this limit\nconst MEM_PERMA_LIMIT = 4194304; // 1024 pixels * 1024 pixels * 4 channels = 4MB\n\n// custom default palette: VT340 (lower 16 colors) + ANSI256 (up to 256) + zeroed (up to 4096)\nconst DEFAULT_PALETTE = PALETTE_ANSI_256;\nDEFAULT_PALETTE.set(PALETTE_VT340_COLOR);\n\n\nexport class SixelHandler implements IDcsHandler, IResetHandler {\n private _size = 0;\n private _aborted = false;\n private _dec: Decoder | undefined;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _storage: SixelImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n DecoderAsync({\n memoryLimit: this._opts.pixelLimit * 4,\n palette: DEFAULT_PALETTE,\n paletteLimit: this._opts.sixelPaletteLimit\n }).then(d => this._dec = d);\n }\n\n public reset(): void {\n /**\n * reset sixel decoder to defaults:\n * - release all memory\n * - nullify palette (4096)\n * - apply default palette (256)\n */\n if (this._dec) {\n this._dec.release();\n // FIXME: missing interface on decoder to nullify full palette\n (this._dec as any)._palette.fill(0);\n this._dec.init(0, DEFAULT_PALETTE, this._opts.sixelPaletteLimit);\n }\n }\n\n public hook(params: IParams): void {\n this._size = 0;\n this._aborted = false;\n if (this._dec) {\n const fillColor = params.params[1] === 1 ? 0 : extractActiveBg(\n this._coreTerminal._core._inputHandler._curAttrData,\n this._coreTerminal._core._themeService?.colors);\n this._dec.init(fillColor, null, this._opts.sixelPaletteLimit);\n }\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted || !this._dec) {\n return;\n }\n this._size += end - start;\n if (this._size > this._opts.sixelSizeLimit) {\n console.warn(`SIXEL: too much data, aborting`);\n this._aborted = true;\n this._dec.release();\n return;\n }\n try {\n this._dec.decode(data, start, end);\n } catch (e) {\n console.warn(`SIXEL: error while decoding image - ${e}`);\n this._aborted = true;\n this._dec.release();\n }\n }\n\n public unhook(success: boolean): boolean | Promise {\n if (this._aborted || !success || !this._dec) {\n return true;\n }\n\n const width = this._dec.width;\n const height = this._dec.height;\n\n // partial fix for https://github.com/jerch/xterm-addon-image/issues/37\n if (!width || !height) {\n if (height) {\n this._storage.advanceCursor(height);\n }\n return true;\n }\n\n const canvas = ImageRenderer.createCanvas(undefined, width, height);\n canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8 as Uint8ClampedArray, width, height), 0, 0);\n if (this._dec.memoryUsage > MEM_PERMA_LIMIT) {\n this._dec.release();\n }\n this._storage.addImage(canvas);\n return true;\n }\n}\n\n\n/**\n * Some helpers to extract current terminal colors.\n */\n\n// get currently active background color from terminal\n// also respect INVERSE setting\nfunction extractActiveBg(attr: AttributeData, colors: ReadonlyColorSet | undefined): RGBA8888 {\n let bg = 0;\n if (!colors) {\n // FIXME: theme service is prolly not available yet,\n // happens if .open() was not called yet (bug in core?)\n return bg;\n }\n if (attr.isInverse()) {\n if (attr.isFgDefault()) {\n bg = convertLe(colors.foreground.rgba);\n } else if (attr.isFgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getFgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getFgColor()].rgba);\n }\n } else {\n if (attr.isBgDefault()) {\n bg = convertLe(colors.background.rgba);\n } else if (attr.isBgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getBgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getBgColor()].rgba);\n }\n }\n return bg;\n}\n\n// rgba values on the color managers are always in BE, thus convert to LE\nfunction convertLe(color: number): RGBA8888 {\n if (BIG_ENDIAN) return color;\n return (color & 0xFF) << 24 | (color >>> 8 & 0xFF) << 16 | (color >>> 16 & 0xFF) << 8 | color >>> 24 & 0xFF;\n}\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { IImageAddonOptions, ITerminalExt, IAddImageOpts } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\n\n/**\n * Sixel-specific image storage controller.\n *\n * Wraps the shared ImageStorage with sixel protocol semantics:\n * - Cursor behavior governed by DECSET 80 (sixelScrolling option)\n * - advanceCursor for empty sixels carrying only height\n */\nexport class SixelImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'vt340' };\n constructor(\n private readonly _storage: ImageStorage,\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _terminal: ITerminalExt\n ) {}\n\n /**\n * Add a sixel image to storage.\n * Cursor behavior depends on the sixelScrolling option (DECSET 80).\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._addImageOpts.scrolling = this._opts.sixelScrolling;\n this._storage.addImage(img, this._addImageOpts);\n }\n\n /**\n * Only advance text cursor.\n * This is an edge case from empty sixels carrying only a height but no pixels.\n * Partially fixes https://github.com/jerch/xterm-addon-image/issues/37.\n */\n public advanceCursor(height: number): void {\n if (this._opts.sixelScrolling) {\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const rows = Math.ceil(height / cellSize.height);\n for (let i = 1; i < rows; ++i) {\n this._terminal._core._inputHandler.lineFeed();\n }\n }\n }\n}\n","/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { IApcHandler, IImageAddonOptions, IResetHandler, ITerminalExt, ImageLayer } from '../Types';\nimport { ImageRenderer } from '../ImageRenderer';\nimport { CELL_SIZE_DEFAULT } from '../ImageStorage';\nimport { imageType } from '../IIPMetrics';\nimport { KittyImageStorage } from './KittyImageStorage';\nimport Base64Decoder, { type DecodeStatus } from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport {\n KittyAction,\n KittyFormat,\n KittyCompression,\n IKittyCommand,\n IPendingTransmission,\n IKittyImageData,\n KittyPixelConstants,\n parseKittyCommand\n} from './KittyGraphicsTypes';\n\nconst enum Constants {\n // Memory limit for base64 decoder (4MB, same as IIPHandler)\n DECODER_KEEP_DATA = 4194304,\n DECODER_INITIAL_DATA = 4194304, // 4MB\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n DECODER_OK = 0,\n // Maximum control data size\n MAX_CONTROL_DATA_SIZE = 512,\n // Semicolon codepoint\n SEMICOLON = 0x3B\n}\n\nconst DECODER_OK = Constants.DECODER_OK as unknown as DecodeStatus.OK;\n\n// Kitty graphics protocol handler with streaming base64 decoding.\nexport class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDisposable {\n private _aborted = false;\n private _generation = 0;\n private _decodeError = false;\n\n private _activeDecoder: Base64Decoder | null = null;\n private readonly _maxEncodedBytes: number;\n private readonly _initialEncodedBytes: number;\n\n // Streaming related states\n\n // True while receiving control data (before semicolon).\n private _inControlData = true;\n\n // Buffer for control data.\n private _controlData = new Uint32Array(Constants.MAX_CONTROL_DATA_SIZE);\n private _controlLength = 0;\n\n // Pre-calculated encoded size limit\n private _encodedSizeLimit = 0;\n private _totalEncodedSize = 0;\n\n // Parsed command. These are the control data before semicolon.\n private _parsedCommand: IKittyCommand | null = null;\n\n // Storage related states\n\n private _pendingTransmissions: Map = new Map();\n // Tracks the pending key of the most recently started chunked upload.\n // Per spec, subsequent chunks only need m= (and optionally q=), without i=.\n // When a chunk arrives with no i=, this key is used to find the pending upload.\n private _lastPendingKey: number | undefined;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _kittyStorage: KittyImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n // Convert decoded size limit -> max encoded bytes.\n this._maxEncodedBytes = Math.ceil(this._opts.kittySizeLimit * 4 / 3);\n // ensure we preallocate more than configured limit while using 4mb initial size.\n this._initialEncodedBytes = Math.min(Constants.DECODER_INITIAL_DATA, this._maxEncodedBytes);\n }\n\n public reset(): void {\n this._generation++;\n this._cleanupAllPending();\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n this._kittyStorage.reset();\n }\n\n public dispose(): void {\n this.reset();\n }\n\n private _removePendingEntry(key: number): void {\n this._pendingTransmissions.delete(key);\n if (this._lastPendingKey === key) {\n this._lastPendingKey = undefined;\n }\n }\n\n private _cleanupAllPending(): void {\n for (const pending of this._pendingTransmissions.values()) {\n pending.decoder.release();\n }\n this._pendingTransmissions.clear();\n this._lastPendingKey = undefined;\n }\n\n public start(): void {\n this._aborted = false;\n this._decodeError = false;\n this._inControlData = true;\n this._controlLength = 0;\n this._parsedCommand = null;\n // Pre-calculate encoded limit once: base64 is 4 bytes encoded → 3 bytes decoded\n this._encodedSizeLimit = this._maxEncodedBytes;\n this._totalEncodedSize = 0;\n this._activeDecoder = null;\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (!this._inControlData) {\n this._streamPayload(data, start, end);\n } else {\n // Scan for semicolon\n let controlEnd = end;\n for (let i = start; i < end; i++) {\n if (data[i] === Constants.SEMICOLON) {\n this._inControlData = false;\n controlEnd = i;\n break;\n }\n }\n\n // Copy control data\n const copyLength = controlEnd - start;\n if (this._controlLength + copyLength > Constants.MAX_CONTROL_DATA_SIZE) {\n this._aborted = true;\n return;\n }\n this._controlData.set(data.subarray(start, controlEnd), this._controlLength);\n this._controlLength += copyLength;\n\n if (!this._inControlData) {\n // Found semicolon - parse control data early for validation\n this._parsedCommand = parseKittyCommand(this._parseControlDataString());\n\n // Early validation: i+I conflict\n if (this._parsedCommand.id !== undefined && this._parsedCommand.imageNumber !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'EINVAL:cannot specify both i and I keys', this._parsedCommand.quiet ?? 0);\n this._aborted = true;\n return;\n }\n\n // Delete action doesn't need payload - skip streaming\n if (this._parsedCommand.action === KittyAction.DELETE) {\n return;\n }\n\n // Stream remaining as payload\n const payloadStart = controlEnd + 1;\n if (payloadStart < end) {\n this._streamPayload(data, payloadStart, end);\n }\n }\n }\n }\n\n // Stream payload bytes into the base64 decoder.\n private _streamPayload(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n // Check size limit (compare encoded bytes against pre-calculated limit)\n // Include cumulative size from pending transmission for multi-chunk images.\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = this._parsedCommand?.id ?? this._lastPendingKey ?? 0;\n const pending = this._pendingTransmissions.get(pendingKey);\n const previousEncodedSize = pending?.totalEncodedSize ?? 0;\n this._totalEncodedSize += end - start;\n const cumulativeEncodedSize = previousEncodedSize + this._totalEncodedSize;\n if (cumulativeEncodedSize > this._encodedSizeLimit) {\n const decoderToRelease = this._activeDecoder ?? pending?.decoder;\n if (decoderToRelease) {\n decoderToRelease.release();\n }\n this._activeDecoder = null;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n this._aborted = true;\n return;\n }\n\n if (this._decodeError) return;\n\n if (pending?.decoder && !this._activeDecoder) {\n this._activeDecoder = pending.decoder;\n }\n if (!this._activeDecoder) {\n // Budget WASM capacity, including one page of decoder state and rounding.\n const decoderCapacity = this._maxEncodedBytes + 131072;\n if (decoderCapacity > this._opts.storageLimit * 1000000) {\n this._aborted = true;\n if (this._parsedCommand?.id !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'ENOMEM:pending image budget exceeded', this._parsedCommand.quiet ?? 0);\n }\n return;\n }\n const maxPending = Math.max(1, Math.floor(this._opts.storageLimit * 1000000 / decoderCapacity));\n while (this._pendingTransmissions.size >= maxPending) {\n const oldest = this._pendingTransmissions.entries().next().value;\n if (!oldest) break;\n oldest[1].decoder.release();\n this._removePendingEntry(oldest[0]);\n if (oldest[1].cmd.id !== undefined) {\n this._sendResponse(oldest[1].cmd.id, 'ENOMEM:pending image budget exceeded', oldest[1].cmd.quiet ?? 0);\n }\n }\n this._activeDecoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes);\n this._activeDecoder.init();\n }\n\n if (this._activeDecoder.put(data.subarray(start, end)) !== DECODER_OK) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n this._decodeError = true;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted || !success) {\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n return true;\n }\n\n // No semicolon = no payload (delete, capability query)\n if (this._inControlData) {\n return this._handleNoPayloadCommand();\n }\n\n // Use command parsed early in put() - i+I already validated there\n const cmd = this._parsedCommand!;\n\n // Delete action was handled by skipping payload - just execute\n if (cmd.action === KittyAction.DELETE) {\n return this._handleDelete(cmd);\n }\n\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = cmd.id ?? this._lastPendingKey ?? 0;\n const isMoreComing = cmd.more === 1;\n const pending = this._pendingTransmissions.get(pendingKey);\n\n if (isMoreComing) {\n if (this._activeDecoder) {\n if (pending) {\n pending.totalEncodedSize += this._totalEncodedSize;\n pending.decodeError = pending.decodeError || this._decodeError;\n } else {\n this._pendingTransmissions.set(pendingKey, {\n cmd: { ...cmd },\n decoder: this._activeDecoder,\n totalEncodedSize: this._totalEncodedSize,\n decodeError: this._decodeError\n });\n }\n this._lastPendingKey = pendingKey;\n this._activeDecoder = null;\n }\n return true;\n }\n\n // Final chunk received — clear the last pending key\n if (pending) {\n this._lastPendingKey = undefined;\n }\n\n let decodeError = this._decodeError;\n let finalCmd = cmd;\n let decoder = this._activeDecoder;\n\n if (pending) {\n finalCmd = pending.cmd;\n decoder = pending.decoder;\n decodeError = decodeError || pending.decodeError;\n this._pendingTransmissions.delete(pendingKey);\n }\n\n let imageBytes = new Uint8Array(0);\n if (decoder) {\n if (decoder.end() !== DECODER_OK) {\n decodeError = true;\n }\n imageBytes = decoder.data8;\n }\n this._activeDecoder = null;\n\n // Handle command first — handlers create Blob/ImageData from imageBytes,\n // which copies the data. Only then is it safe to release the decoder's\n // wasm memory that imageBytes points into.\n const result = this._handleCommandWithBytesAndCmd(finalCmd, imageBytes, decodeError);\n if (decoder) {\n decoder.release();\n }\n return result;\n }\n\n // Command handling\n\n private _parseControlDataString(): string {\n let str = '';\n for (let i = 0; i < this._controlLength; i++) {\n str += String.fromCodePoint(this._controlData[i]);\n }\n return str;\n }\n\n private _handleNoPayloadCommand(): boolean | Promise {\n const cmd = parseKittyCommand(this._parseControlDataString());\n\n // Per spec: specifying both i and I is an error\n if (cmd.id !== undefined && cmd.imageNumber !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:cannot specify both i and I keys', cmd.quiet ?? 0);\n return true;\n }\n\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.DELETE:\n return this._handleDelete(cmd);\n case KittyAction.QUERY:\n this._sendResponse(cmd.id ?? 0, 'OK', cmd.quiet ?? 0);\n return true;\n case KittyAction.PLACEMENT:\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handleCommandWithBytesAndCmd(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.TRANSMIT: {\n const result = this._handleTransmit(cmd, bytes, decodeError);\n // Only send response when _handleTransmit didn't already respond\n // (it handles unsupported transmission medium responses internally)\n if ((cmd.transmission ?? 'd') === 'd' && cmd.id !== undefined) {\n if (decodeError) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n } else if (bytes.length > 0) {\n this._sendResponse(cmd.id, 'OK', cmd.quiet ?? 0);\n }\n }\n return result;\n }\n case KittyAction.TRANSMIT_DISPLAY:\n return this._handleTransmitDisplay(cmd, bytes, decodeError);\n case KittyAction.QUERY:\n return this._handleQuery(cmd, bytes, decodeError);\n case KittyAction.PLACEMENT:\n // a=p ignores any payload — image data was already transmitted\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handlePlacement(cmd: IKittyCommand): boolean | Promise {\n if (cmd.id === undefined) {\n return true;\n }\n const id = cmd.id;\n const image = this._kittyStorage.getImage(id);\n if (!image) {\n this._sendResponse(id, 'ENOENT:image not found', cmd.quiet ?? 0, cmd.placementId);\n return true;\n }\n const result = this._displayImage(image, cmd);\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0, cmd.placementId);\n return true;\n });\n }\n\n private _handleTransmit(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n // TODO: Support file-based transmission modes (t=f, t=t, t=s)\n // Currently only supports direct transmission (t=d, the default).\n // - t=f (file): Payload is base64-encoded file path. Terminal reads image from that path.\n // - t=t (temp file): Payload is base64-encoded path in temp directory. Terminal reads, deletes.\n // - t=s: Payload is base64-encoded POSIX shm name. Terminal reads from shared memory.\n // These modes require filesystem/IPC access not available in browsers. For Node.js/Electron:\n // 1. Check cmd.transmission (t key) before treating bytes as image data\n // 2. For t=f/t/s: decode bytes as UTF-8 string (the path/name), then read file contents\n // 3. For t=d: treat bytes as image data (current behavior)\n // When implementing, also update _handleQuery to accept these transmission mediums.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported transmission medium', cmd.quiet ?? 0);\n }\n return true;\n }\n\n if (decodeError || bytes.length === 0) return true;\n\n this._kittyStorage.storeImage(cmd.id, {\n data: new Blob([bytes as BlobPart]),\n width: cmd.width ?? 0,\n height: cmd.height ?? 0,\n format: (cmd.format ?? KittyFormat.RGBA) as 24 | 32 | 100,\n compression: cmd.compression ?? ''\n });\n return true;\n }\n\n private _handleTransmitDisplay(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n if (decodeError) {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n }\n return true;\n }\n\n this._handleTransmit(cmd, bytes, decodeError);\n\n const id = cmd.id ?? this._kittyStorage.lastImageId;\n const image = this._kittyStorage.getImage(id);\n if (image) {\n const result = this._displayImage(image, cmd);\n if (cmd.id !== undefined) {\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0);\n return true;\n });\n }\n return result.then(() => true);\n }\n return true;\n }\n\n private _handleQuery(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n const id = cmd.id ?? 0;\n const quiet = cmd.quiet ?? 0;\n\n // Per spec: reject unsupported transmission mediums (only t=d is supported atm)\n // TODO: When filesystem support is added (Node.js/Electron), update this to accept\n // t=f (file), t=t (temp file), and t=s (shared memory) and respond OK for queries.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n this._sendResponse(id, 'EINVAL:unsupported transmission medium', quiet);\n return true;\n }\n\n // Check decode error first (invalid base64)\n if (decodeError) {\n this._sendResponse(id, 'EINVAL:invalid base64 data', quiet);\n return true;\n }\n\n // Capability query (no payload) - just respond OK\n if (bytes.length === 0) {\n this._sendResponse(id, 'OK', quiet);\n return true;\n }\n\n const format = cmd.format ?? KittyFormat.RGBA;\n\n if (format === KittyFormat.PNG) {\n this._sendResponse(id, 'OK', quiet);\n } else {\n const width = cmd.width ?? 0;\n const height = cmd.height ?? 0;\n\n if (!width || !height) {\n this._sendResponse(id, 'EINVAL:width and height required for raw pixel data', quiet);\n return true;\n }\n\n const bytesPerPixel = format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n this._sendResponse(id, `EINVAL:insufficient pixel data`, quiet);\n return true;\n }\n\n this._sendResponse(id, 'OK', quiet);\n }\n return true;\n }\n\n private _handleDelete(cmd: IKittyCommand): boolean {\n // Per spec: default delete selector is 'a' (delete all visible placements)\n const selector = cmd.deleteSelector ?? 'a';\n\n // TODO: Distinguish lowercase (delete placements only) from uppercase\n // (delete placements + free stored image data). Currently both variants\n // free everything since we don't separate stored data from placements.\n switch (selector) {\n case 'a':\n case 'A':\n this._cleanupAllPending();\n this._kittyStorage.deleteAll();\n break;\n case 'i':\n case 'I':\n // TODO: When placement id tracking is implemented (see TODO in\n // KittyImageStorage), d=i with p= should delete only that\n // specific placement, while d=i without p should delete all\n // placements for the image.\n if (cmd.id !== undefined) {\n const pending = this._pendingTransmissions.get(cmd.id);\n if (pending) {\n pending.decoder.release();\n }\n this._removePendingEntry(cmd.id);\n this._kittyStorage.deleteById(cmd.id);\n }\n break;\n default:\n // Unsupported selectors (c, n, p, q, r, x, y, z, f) — ignore for now\n break;\n }\n return true;\n }\n\n private _sendResponse(id: number, message: string, quiet: number, placementId?: number): void {\n const isOk = message === 'OK';\n if (isOk && quiet >= 1) return;\n if (!isOk && quiet >= 2) return;\n\n const pPart = placementId ? `,p=${placementId}` : '';\n const response = `\\x1b_Gi=${id}${pPart};${message}\\x1b\\\\`;\n this._coreTerminal._core.coreService.triggerDataEvent(response);\n }\n\n // Image display\n\n private _displayImage(image: IKittyImageData, cmd: IKittyCommand): Promise {\n return this._decodeAndDisplay(image, cmd)\n .then(() => true)\n .catch(() => false);\n }\n\n private async _decodeAndDisplay(image: IKittyImageData, cmd: IKittyCommand): Promise {\n const generation = this._generation;\n let bitmap: ImageBitmap | undefined = await this._createBitmap(image);\n\n try {\n if (generation !== this._generation) throw new Error('image decode canceled');\n const cropX = Math.max(0, cmd.x ?? 0);\n const cropY = Math.max(0, cmd.y ?? 0);\n const cropW = cmd.sourceWidth || (bitmap.width - cropX);\n const cropH = cmd.sourceHeight || (bitmap.height - cropY);\n\n const maxCropW = Math.max(0, bitmap.width - cropX);\n const maxCropH = Math.max(0, bitmap.height - cropY);\n const finalCropW = Math.max(0, Math.min(cropW, maxCropW));\n const finalCropH = Math.max(0, Math.min(cropH, maxCropH));\n\n if (finalCropW === 0 || finalCropH === 0) {\n throw new Error('invalid source rectangle');\n }\n\n if (cropX !== 0 || cropY !== 0 || finalCropW !== bitmap.width || finalCropH !== bitmap.height) {\n const cropped = await createImageBitmap(bitmap, cropX, cropY, finalCropW, finalCropH);\n bitmap.close();\n bitmap = cropped;\n }\n\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n\n // Per spec: c/r default to image's natural cell dimensions.\n // If only one of c/r is specified, compute the other from image aspect ratio.\n let imgCols: number;\n let imgRows: number;\n if (cmd.columns !== undefined && cmd.rows !== undefined) {\n imgCols = cmd.columns;\n imgRows = cmd.rows;\n } else if (cmd.columns !== undefined) {\n imgCols = cmd.columns;\n imgRows = Math.max(1, Math.ceil((bitmap.height / bitmap.width) * (imgCols * cw) / ch));\n } else if (cmd.rows !== undefined) {\n imgRows = cmd.rows;\n imgCols = Math.max(1, Math.ceil((bitmap.width / bitmap.height) * (imgRows * ch) / cw));\n } else {\n imgCols = Math.ceil(bitmap.width / cw);\n imgRows = Math.ceil(bitmap.height / ch);\n }\n\n let w = bitmap.width;\n let h = bitmap.height;\n\n // Scale bitmap to fit placement rectangle when c/r are specified\n if (cmd.columns !== undefined || cmd.rows !== undefined) {\n w = Math.round(imgCols * cw);\n h = Math.round(imgRows * ch);\n }\n\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n\n // Save cursor position before addImage modifies it\n const buffer = this._coreTerminal._core.buffer;\n const savedX = buffer.x;\n const savedY = buffer.y;\n const savedYbase = buffer.ybase;\n\n // Determine layer based on z-index: negative = behind text, 0+ = on top.\n // When z<0 we always use the bottom layer even without allowTransparency —\n // the image will simply be hidden behind the opaque text background, which\n // is the correct behavior (client asked for \"behind text\").\n const wantsBottom = cmd.zIndex !== undefined && cmd.zIndex < 0;\n const layer: ImageLayer = wantsBottom ? 'bottom' : 'top';\n\n if (w !== bitmap.width || h !== bitmap.height) {\n const scaled = await createImageBitmap(bitmap, { resizeWidth: w, resizeHeight: h });\n bitmap.close();\n bitmap = scaled;\n }\n\n // Per spec: X/Y are pixel offsets within the first cell, so clamp to cell dimensions\n const xOffset = Math.min(Math.max(0, cmd.xOffset ?? 0), cw - 1);\n const yOffset = Math.min(Math.max(0, cmd.yOffset ?? 0), ch - 1);\n if (xOffset !== 0 || yOffset !== 0) {\n // Per spec: X/Y is not added to c/r area. When c/r are explicit, the\n // total placement area remains c*cw × r*ch pixels and the offset image\n // is clipped to fit. When c/r are unset, the padded canvas determines\n // the natural cell dimensions.\n const canvasW = (cmd.columns !== undefined) ? Math.round(imgCols * cw) : bitmap.width + xOffset;\n const canvasH = (cmd.rows !== undefined) ? Math.round(imgRows * ch) : bitmap.height + yOffset;\n const offsetCanvas = ImageRenderer.createCanvas(window.document, canvasW, canvasH);\n const offsetCtx = offsetCanvas.getContext('2d');\n if (!offsetCtx) {\n throw new Error('Failed to create offset canvas context');\n }\n offsetCtx.drawImage(bitmap, xOffset, yOffset);\n\n const offsetBitmap = await createImageBitmap(offsetCanvas);\n offsetCanvas.width = offsetCanvas.height = 0;\n bitmap.close();\n bitmap = offsetBitmap;\n w = bitmap.width;\n h = bitmap.height;\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n if (cmd.columns === undefined) {\n imgCols = Math.ceil(bitmap.width / cw);\n }\n if (cmd.rows === undefined) {\n imgRows = Math.ceil(bitmap.height / ch);\n }\n }\n\n if (generation !== this._generation) throw new Error('image decode canceled');\n const zIndex = cmd.zIndex ?? 0;\n this._kittyStorage.addImage(image.id, bitmap, true, layer, zIndex);\n bitmap = undefined; // ownership transferred to storage\n\n // Kitty cursor movement\n // Per spec: cursor placed at first column after last image column,\n // on the last row of the image. C=1 means don't move cursor.\n if (cmd.cursorMovement === 1) {\n // C=1: restore cursor to position before image was placed\n const scrolled = buffer.ybase - savedYbase;\n buffer.x = savedX;\n // Can't restore cursor to scrollback?\n buffer.y = Math.max(savedY - scrolled, 0);\n } else {\n // Default (C=0): advance cursor horizontally past the image\n // addImage already positioned cursor on the last row via lineFeeds\n buffer.x = Math.min(savedX + imgCols, this._coreTerminal.cols);\n }\n } catch (e) {\n bitmap?.close();\n throw e;\n }\n }\n\n // Create ImageBitmap from already-decoded image data.\n private async _createBitmap(image: IKittyImageData): Promise {\n let bytes: Uint8Array = new Uint8Array(await image.data.arrayBuffer());\n\n if (image.compression === KittyCompression.ZLIB) {\n bytes = await this._decompressZlib(bytes);\n }\n\n if (image.format === KittyFormat.PNG) {\n const metrics = imageType(bytes);\n // IHDR dimensions are parsed with signed shifts, so a value >= 0x80000000 comes\n // back negative and a bare `>` pixel-limit test passes it; require positive.\n if (metrics.mime !== 'image/png' || !(metrics.width > 0) || !(metrics.height > 0) || metrics.width * metrics.height > this._opts.pixelLimit) {\n throw new RangeError('PNG exceeds pixel limit or has invalid dimensions');\n }\n const blob = new Blob([bytes as BlobPart], { type: 'image/png' });\n if (!window.createImageBitmap) {\n const url = URL.createObjectURL(blob);\n const img = new Image();\n return new Promise((resolve, reject) => {\n img.addEventListener('load', () => {\n URL.revokeObjectURL(url);\n const canvas = ImageRenderer.createCanvas(window.document, img.width, img.height);\n canvas.getContext('2d')?.drawImage(img, 0, 0);\n createImageBitmap(canvas).then(resolve).catch(reject);\n });\n img.addEventListener('error', () => {\n URL.revokeObjectURL(url);\n reject(new Error('Failed to load image'));\n });\n img.src = url;\n });\n }\n return createImageBitmap(blob);\n }\n\n // Raw pixel data\n const width = image.width;\n const height = image.height;\n\n if (!width || !height) {\n throw new Error('Width and height required for raw pixel data');\n }\n\n const bytesPerPixel = image.format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n throw new Error('Insufficient pixel data');\n }\n\n const pixelCount = width * height;\n\n if (image.format === KittyFormat.RGBA) {\n // RGBA: use bytes directly — no copy needed\n return createImageBitmap(new ImageData(new Uint8ClampedArray(bytes.buffer as ArrayBuffer, bytes.byteOffset, pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA), width, height));\n }\n\n // RGB→RGBA: interleave alpha using uint32 block processing (4 pixels per iteration).\n // 3 uint32 reads + 4 uint32 writes per 4 pixels vs 28 byte reads/writes — ~6x faster.\n // Assumes little-endian (all modern browsers/Node.js).\n const data = new Uint8ClampedArray(pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA);\n const src32 = new Uint32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4));\n const dst32 = new Uint32Array(data.buffer);\n const alignedPixels = pixelCount & ~3; // round down to multiple of 4\n\n let srcOffset = 0;\n let dstOffset = 0;\n for (let i = 0; i < alignedPixels; i += 4) {\n const b0 = src32[srcOffset++];\n const b1 = src32[srcOffset++];\n const b2 = src32[srcOffset++];\n // Little-endian: pixel bytes are [R,G,B] → uint32 ABGR layout\n dst32[dstOffset++] = 0xFF000000 | b0;\n dst32[dstOffset++] = 0xFF000000 | (b0 >>> 24) | (b1 << 8);\n dst32[dstOffset++] = 0xFF000000 | (b1 >>> 16) | (b2 << 16);\n dst32[dstOffset++] = 0xFF000000 | (b2 >>> 8);\n }\n\n // Handle remaining 1–3 pixels\n let srcByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n let dstByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n for (let i = alignedPixels; i < pixelCount; i++) {\n data[dstByte] = bytes[srcByte];\n data[dstByte + 1] = bytes[srcByte + 1];\n data[dstByte + 2] = bytes[srcByte + 2];\n data[dstByte + 3] = KittyPixelConstants.ALPHA_OPAQUE;\n srcByte += KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n dstByte += KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n }\n\n return createImageBitmap(new ImageData(data, width, height));\n }\n\n private async _decompressZlib(compressed: Uint8Array): Promise {\n try {\n return await this._decompress(compressed, 'deflate');\n } catch (error) {\n if (error instanceof RangeError) throw error;\n return await this._decompress(compressed, 'deflate-raw');\n }\n }\n\n private async _decompress(compressed: Uint8Array, format: 'deflate' | 'deflate-raw'): Promise {\n const limit = Math.min(this._opts.kittySizeLimit, this._opts.pixelLimit * 4, this._opts.storageLimit * 1000000);\n let offsetIn = 0;\n // Bound inflation within one native transform before its output is budgeted.\n const source = new ReadableStream({\n pull(controller) {\n if (offsetIn >= compressed.length) {\n controller.close();\n return;\n }\n const end = Math.min(offsetIn + 4096, compressed.length);\n controller.enqueue(new Uint8Array(compressed.subarray(offsetIn, end)));\n offsetIn = end;\n }\n });\n const reader = source.pipeThrough(new DecompressionStream(format)).getReader();\n const chunks: Uint8Array[] = [];\n let totalLength = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n totalLength += value.byteLength;\n if (totalLength > limit) {\n await reader.cancel().catch(() => {});\n throw new RangeError('decompressed image exceeds byte limit');\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n }\n\n public get images(): ReadonlyMap {\n return this._kittyStorage.images;\n }\n\n public get _kittyIdToStorageId(): ReadonlyMap {\n return this._kittyStorage.kittyIdToStorageId;\n }\n\n public get pendingTransmissions(): ReadonlyMap {\n return this._pendingTransmissions;\n }\n}\n","/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Kitty graphics protocol types, constants, and parsing utilities.\n */\n\nimport type Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\n\n// Kitty graphics protocol action types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'a'.\nexport const enum KittyAction {\n TRANSMIT = 't',\n TRANSMIT_DISPLAY = 'T',\n QUERY = 'q',\n PLACEMENT = 'p',\n DELETE = 'd'\n}\n\n// Kitty graphics protocol format types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyFormat {\n RGB = 24,\n RGBA = 32,\n PNG = 100\n}\n\n// Kitty graphics protocol compression types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'o'.\nexport const enum KittyCompression {\n NONE = '',\n ZLIB = 'z'\n}\n\n// Kitty graphics protocol control data keys.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyKey {\n // Action to perform (t=transmit, T=transmit+display, q=query, p=placement, d=delete)\n ACTION = 'a',\n // Image format (24=RGB, 32=RGBA, 100=PNG)\n FORMAT = 'f',\n // Image ID for referencing stored images\n ID = 'i',\n // Image number (alternative to ID, terminal assigns ID)\n IMAGE_NUMBER = 'I',\n // Source image width in pixels\n WIDTH = 's',\n // Source image height in pixels\n HEIGHT = 'v',\n // The left edge (in pixels) of the image area to display\n X_OFFSET = 'x',\n // The top edge (in pixels) of the image area to display\n Y_OFFSET = 'y',\n // Width (in pixels) of the source rectangle to display\n SOURCE_WIDTH = 'w',\n // Height (in pixels) of the source rectangle to display\n SOURCE_HEIGHT = 'h',\n // Horizontal offset (in pixels) within the first cell\n X_PLACEMENT_OFFSET = 'X',\n // Vertical offset (in pixels) within the first cell\n Y_PLACEMENT_OFFSET = 'Y',\n // Number of terminal columns to display the image over\n COLUMNS = 'c',\n // Number of terminal rows to display the image over\n ROWS = 'r',\n // More data flag (1=more chunks coming, 0=final chunk)\n MORE = 'm',\n // Compression type (z=zlib). This is essential for chunking larger images.\n COMPRESSION = 'o',\n // Quiet mode (1=suppress OK responses, 2=suppress error responses)\n QUIET = 'q',\n // Cursor movement policy (0=move cursor after image, 1=don't move cursor)\n CURSOR_MOVEMENT = 'C',\n // Z-index for image layering (negative = behind text, 0+ = on top)\n Z_INDEX = 'z',\n // Transmission medium (d=direct, f=file, t=temp file, s=shared memory)\n TRANSMISSION = 't',\n // Delete selector (a/A=all, i/I=by id, c/C=at cursor, etc.) — only used when a=d\n DELETE_SELECTOR = 'd',\n // Placement ID for targeting specific placements\n PLACEMENT_ID = 'p'\n}\n\n// Pixel format constants\nexport const enum KittyPixelConstants {\n BYTES_PER_PIXEL_RGB = 3,\n BYTES_PER_PIXEL_RGBA = 4,\n ALPHA_OPAQUE = 255\n}\n\n// Parsed Kitty graphics command.\nexport interface IKittyCommand {\n action?: string;\n format?: number;\n id?: number;\n imageNumber?: number;\n width?: number;\n height?: number;\n x?: number;\n y?: number;\n sourceWidth?: number;\n sourceHeight?: number;\n xOffset?: number;\n yOffset?: number;\n columns?: number;\n rows?: number;\n more?: number;\n quiet?: number;\n cursorMovement?: number;\n zIndex?: number;\n transmission?: string;\n deleteSelector?: string;\n placementId?: number;\n compression?: string;\n payload?: string;\n}\n\n// Pending chunked transmission state.\n// Stores metadata from the first chunk while accumulating decoded payload data.\nexport interface IPendingTransmission {\n // The parsed command from the first chunk (contains action, format, dimensions, etc.)\n cmd: IKittyCommand;\n // Decoder used across chunked payloads\n decoder: Base64Decoder;\n // Total encoded (base64) bytes received across all chunks - for size limit enforcement\n totalEncodedSize: number;\n // Whether any chunk has failed to decode\n decodeError: boolean;\n}\n\n// Stored Kitty image data.\nexport interface IKittyImageData {\n id: number;\n // Decoded image data stored as Blob (off JS heap) to avoid 2GB heap limit\n data: Blob;\n width: number;\n height: number;\n format: 24 | 32 | 100;\n compression?: string;\n}\n\n// Parses Kitty graphics control data into a command object.\nexport function parseKittyCommand(data: string): IKittyCommand {\n const cmd: IKittyCommand = {};\n const parts = data.split(',');\n\n for (const part of parts) {\n const eqIdx = part.indexOf('=');\n if (eqIdx === -1) continue;\n\n const key = part.substring(0, eqIdx);\n const value = part.substring(eqIdx + 1);\n\n // Handle string keys first\n if (key === KittyKey.ACTION) {\n cmd.action = value;\n continue;\n }\n if (key === KittyKey.COMPRESSION) {\n cmd.compression = value;\n continue;\n }\n if (key === KittyKey.TRANSMISSION) {\n cmd.transmission = value;\n continue;\n }\n if (key === KittyKey.DELETE_SELECTOR) {\n cmd.deleteSelector = value;\n continue;\n }\n const numValue = parseInt(value, 10);\n switch (key) {\n case KittyKey.FORMAT: cmd.format = numValue; break;\n case KittyKey.ID: cmd.id = numValue; break;\n case KittyKey.IMAGE_NUMBER: cmd.imageNumber = numValue; break;\n case KittyKey.WIDTH: cmd.width = numValue; break;\n case KittyKey.HEIGHT: cmd.height = numValue; break;\n case KittyKey.X_OFFSET: cmd.x = numValue; break;\n case KittyKey.Y_OFFSET: cmd.y = numValue; break;\n case KittyKey.SOURCE_WIDTH: cmd.sourceWidth = numValue; break;\n case KittyKey.SOURCE_HEIGHT: cmd.sourceHeight = numValue; break;\n case KittyKey.X_PLACEMENT_OFFSET: cmd.xOffset = numValue; break;\n case KittyKey.Y_PLACEMENT_OFFSET: cmd.yOffset = numValue; break;\n case KittyKey.COLUMNS: cmd.columns = numValue; break;\n case KittyKey.ROWS: cmd.rows = numValue; break;\n case KittyKey.MORE: cmd.more = numValue; break;\n case KittyKey.QUIET: cmd.quiet = numValue; break;\n case KittyKey.CURSOR_MOVEMENT: cmd.cursorMovement = numValue; break;\n case KittyKey.Z_INDEX: cmd.zIndex = numValue; break;\n case KittyKey.PLACEMENT_ID: cmd.placementId = numValue; break;\n }\n }\n\n return cmd;\n}\n","/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageStorage } from '../ImageStorage';\nimport { ImageLayer, IAddImageOpts } from '../Types';\nimport { IKittyImageData } from './KittyGraphicsTypes';\n\n// Kitty-specific image storage controller.\n//\n// Wraps shared ImageStorage with kitty protocol semantics:\n// - tracks transmitted image payloads by kitty image id\n// - tracks kitty image id -> shared ImageStorage id mapping for displayed images\n// - mirrors shared-storage evictions into kitty maps\n// - applies protocol-level undisplayed-image eviction policy\nexport class KittyImageStorage implements IDisposable {\n private static readonly _maxStoredImages = 256;\n\n private _nextImageId = 1;\n private readonly _images: Map = new Map();\n // TODO: Support multiple placements per image. The kitty spec identifies\n // placements by an (image id, placement id) pair — same i + different p\n // values should coexist, and same i + same p should replace the prior\n // placement. Currently we track only one storage entry per kitty image id,\n // so multiple placements of the same image overwrite each other. Fixing\n // this requires changing these maps to Map>\n // (kittyId → placementId → storageId) and updating addImage/deleteById\n // accordingly. The underlying shared ImageStorage would also need to\n // support multiple entries per logical image.\n private readonly _kittyIdToStorageId: Map = new Map();\n private readonly _storageIdToKittyId: Map = new Map();\n\n private readonly _previousOnImageDeleted: ((storageId: number) => void) | undefined;\n private readonly _wrappedOnImageDeleted: (storageId: number) => void;\n private readonly _handleStorageImageDeleted = (storageId: number): void => {\n const kittyId = this._storageIdToKittyId.get(storageId);\n if (kittyId !== undefined) {\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n this._images.delete(kittyId);\n }\n };\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n\n constructor(\n private readonly _storage: ImageStorage\n ) {\n this._previousOnImageDeleted = this._storage.onImageDeleted;\n this._wrappedOnImageDeleted = (storageId: number) => {\n this._previousOnImageDeleted?.(storageId);\n this._handleStorageImageDeleted(storageId);\n };\n this._storage.onImageDeleted = this._wrappedOnImageDeleted;\n }\n\n public reset(): void {\n this._nextImageId = 1;\n this._images.clear();\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public dispose(): void {\n this.reset();\n if (this._storage.onImageDeleted === this._wrappedOnImageDeleted) {\n this._storage.onImageDeleted = this._previousOnImageDeleted;\n }\n }\n\n public storeImage(id: number | undefined, imageData: Omit): number {\n const imageId = id ?? this._nextImageId++;\n\n const oldStorageId = this._kittyIdToStorageId.get(imageId);\n if (oldStorageId !== undefined) {\n this._storage.deleteImage(oldStorageId);\n this._kittyIdToStorageId.delete(imageId);\n this._storageIdToKittyId.delete(oldStorageId);\n }\n\n if (!this._images.has(imageId) && this._images.size >= KittyImageStorage._maxStoredImages) {\n this._evictUndisplayedImages();\n }\n\n // Encoded images awaiting placement are outside ImageStorage's pixel budget.\n // Unplaced payloads are evicted first so a new upload cannot erase a visible\n // image while abandoned blobs still hold budget; placed ones go only when\n // that is not enough, because the byte cap is a hard bound. The new image is\n // always stored, so an oversized one overshoots by at most one payload\n // (itself bounded by kittySizeLimit) rather than being dropped after an OK ack.\n const byteLimit = this._storage.getLimit() * 1000000;\n this._images.delete(imageId);\n let retainedBytes = 0;\n for (const image of this._images.values()) retainedBytes += image.data.size;\n for (const evictPlaced of [false, true]) {\n for (const [oldestId, image] of this._images) {\n if (retainedBytes + imageData.data.size <= byteLimit) break;\n if (this._kittyIdToStorageId.has(oldestId) !== evictPlaced) continue;\n retainedBytes -= image.data.size;\n this.deleteById(oldestId);\n }\n }\n\n this._images.set(imageId, {\n ...imageData,\n id: imageId\n });\n return imageId;\n }\n\n public addImage(kittyId: number, image: HTMLCanvasElement | ImageBitmap, scrolling: boolean, layer: ImageLayer, zIndex: number): void {\n // Clean up stale reverse-mapping from a previous placement of the same\n // kitty image. The old shared-storage entry is kept (it may still be\n // visible on screen) but its reverse mapping is removed so that eviction\n // of the old entry won't incorrectly delete the kitty image data.\n const oldStorageId = this._kittyIdToStorageId.get(kittyId);\n if (oldStorageId !== undefined) {\n this._storageIdToKittyId.delete(oldStorageId);\n }\n this._addImageOpts.scrolling = scrolling;\n this._addImageOpts.layer = layer;\n this._addImageOpts.zIndex = zIndex;\n const storageId = this._storage.addImage(image, this._addImageOpts);\n this._kittyIdToStorageId.set(kittyId, storageId);\n this._storageIdToKittyId.set(storageId, kittyId);\n }\n\n public getImage(kittyId: number): IKittyImageData | undefined {\n return this._images.get(kittyId);\n }\n\n public deleteById(kittyId: number): void {\n this._images.delete(kittyId);\n const storageId = this._kittyIdToStorageId.get(kittyId);\n if (storageId !== undefined) {\n this._storage.deleteImage(storageId);\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n }\n }\n\n public deleteAll(): void {\n this._images.clear();\n for (const storageId of this._kittyIdToStorageId.values()) {\n this._storage.deleteImage(storageId);\n }\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public get images(): ReadonlyMap {\n return this._images;\n }\n\n public get kittyIdToStorageId(): ReadonlyMap {\n return this._kittyIdToStorageId;\n }\n\n public get lastImageId(): number {\n return this._nextImageId - 1;\n }\n\n private _evictUndisplayedImages(): void {\n for (const [kittyId] of this._images) {\n if (this._images.size <= KittyImageStorage._maxStoredImages / 2) {\n break;\n }\n if (!this._kittyIdToStorageId.has(kittyId)) {\n this._images.delete(kittyId);\n }\n }\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023, 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\n/**\n * wasm base64 decoder.\n */\nconst wasmDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#828e69684093b2c6:rdef-start:\"decode\"*/{s:1,t:0,d:'AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML'}/*inwasm#828e69684093b2c6:rdef-end:\"decode\"*/);\n// SIMD version (speedup ~1.4x, not covered by tests yet)\n/*\nconst wasmDecode = InWasm({\n name: 'decode',\n type: OutputType.INSTANCE,\n mode: OutputMode.SYNC,\n srctype: 'Clang-C',\n imports: {\n env: { memory: new WebAssembly.Memory({ initial: 1 }) }\n },\n exports: {\n dec: () => 0,\n end: () => 0\n },\n compile: {\n switches: ['-msimd128', '-Wl,-z,stack-size=0', '-Wl,--stack-first']\n },\n code: `\n #include \n typedef struct {\n unsigned int wp;\n unsigned int sp;\n unsigned int dp;\n unsigned int e_size;\n unsigned int dummy[4];\n unsigned char data[0];\n } State;\n\n unsigned int *D0 = (unsigned int *) ${P32.D0 * 4};\n unsigned int *D1 = (unsigned int *) ${P32.D1 * 4};\n unsigned int *D2 = (unsigned int *) ${P32.D2 * 4};\n unsigned int *D3 = (unsigned int *) ${P32.D3 * 4};\n State *state = (State *) ${P32.STATE * 4};\n\n #define packed_byte(x) wasm_i8x16_splat((char) x)\n #define packed_dword(x) wasm_i32x4_splat(x)\n #define masked(x, mask) wasm_v128_and(x, wasm_i32x4_splat(mask))\n\n __attribute__((noinline)) int dec() {\n unsigned int nsp = (state->wp - 1) & ~3;\n unsigned char *src = state->data + state->sp;\n unsigned char *end = state->data + nsp;\n unsigned char *dst = state->data + state->dp;\n unsigned int error = 0;\n\n v128_t err = wasm_i8x16_splat(0);\n unsigned char *end16 = state->data + (nsp & ~15);\n while (src < end16) {\n v128_t data = wasm_v128_load((v128_t *) src);\n\n // wasm-simd rewrite of http://0x80.pl/notesen/2016-01-17-sse-base64-decoding.html#vector-lookup-pshufb\n const v128_t higher_nibble = wasm_u32x4_shr(data, 4) & packed_byte(0x0f);\n const char linv = 1;\n const char hinv = 0;\n\n const v128_t lower_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n linv, linv, 0x2b, 0x30,\n 0x41, 0x50, 0x61, 0x70,\n linv, linv, linv, linv,\n linv, linv, linv, linv\n );\n const v128_t upper_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n hinv, hinv, 0x2b, 0x39,\n 0x4f, 0x5a, 0x6f, 0x7a,\n hinv, hinv, hinv, hinv,\n hinv, hinv, hinv, hinv\n );\n // the difference between the shift and lower bound\n const v128_t shift_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n 0x00, 0x00, 0x3e - 0x2b, 0x34 - 0x30,\n 0x00 - 0x41, 0x0f - 0x50, 0x1a - 0x61, 0x29 - 0x70,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00\n );\n\n const v128_t upper_bound = wasm_i8x16_swizzle(upper_bound_LUT, higher_nibble);\n const v128_t lower_bound = wasm_i8x16_swizzle(lower_bound_LUT, higher_nibble);\n\n const v128_t below = wasm_i8x16_lt(data, lower_bound);\n const v128_t above = wasm_i8x16_gt(data, upper_bound);\n const v128_t eq_2f = wasm_i8x16_eq(data, packed_byte(0x2f));\n\n // in_range = not (below or above) or eq_2f\n // outside = not in_range = below or above and not eq_2f (from deMorgan law)\n const v128_t outside = wasm_v128_andnot(eq_2f, above | below);\n err = wasm_v128_or(err, outside);\n\n const v128_t shift = wasm_i8x16_swizzle(shift_LUT, higher_nibble);\n const v128_t t0 = wasm_i8x16_add(data, shift);\n v128_t v = wasm_i8x16_add(t0, wasm_v128_and(eq_2f, packed_byte(-3)));\n\n // pack bytes\n const v128_t ca = masked(v, 0x003f003f);\n const v128_t db = masked(v, 0x3f003f00);\n const v128_t t00 = wasm_v128_or(wasm_u32x4_shr(db, 8), wasm_i32x4_shl(ca, 6));\n v128_t res = wasm_v128_or(wasm_u32x4_shr(t00, 16), wasm_i32x4_shl(t00, 12));\n res = wasm_i8x16_swizzle(res, wasm_i8x16_const(2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, 16, 16, 16, 16));\n\n wasm_v128_store((v128_t *) dst, res);\n dst += 12;\n src += 16;\n }\n //if (wasm_i8x16_bitmask(err) != 0) return -1;\n if (wasm_v128_any_true(err)) return -1;\n\n // operate on 4-byte blocks\n while (src < end) {\n error |= *((unsigned int *) dst) = D0[src[0]] | D1[src[1]] | D2[src[2]] | D3[src[3]];\n dst += 3;\n src += 4;\n }\n if (error >> 24) return -1;\n state->sp = nsp;\n state->dp = dst - state->data;\n return 0;\n }\n\n int end() {\n int rem = state->wp - state->sp;\n if (rem > 4 && dec()) return -1;\n rem = state->wp - state->sp;\n if (rem < 2) return -1;\n\n unsigned char *src = state->data + state->sp;\n if (rem == 4) {\n if (src[3] == 61) rem--;\n if (src[2] == 61) rem--;\n }\n unsigned int accu = D0[src[0]] | D1[src[1]];\n int dp = 1;\n if (rem > 2) {\n accu |= D2[src[2]];\n dp++;\n if (rem == 4) {\n accu |= D3[src[3]];\n dp++;\n }\n }\n if (accu >> 24) return -1;\n *((unsigned int *) (state->data + state->dp)) = accu;\n state->dp += dp;\n return 0;\n }\n `\n});\n*/\n// base64 map\nconst MAP = new Uint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n .split('')\n .map(el => el.charCodeAt(0)));\n// init decoder maps in LE order\nconst D = new Uint32Array(1024);\nD.fill(0xFF000000);\nfor (let i = 0; i < MAP.length; ++i)\n D[MAP[i]] = i << 2;\nfor (let i = 0; i < MAP.length; ++i)\n D[256 + MAP[i]] = i >> 4 | ((i << 4) & 0xFF) << 8;\nfor (let i = 0; i < MAP.length; ++i)\n D[512 + MAP[i]] = (i >> 2) << 8 | ((i << 6) & 0xFF) << 16;\nfor (let i = 0; i < MAP.length; ++i)\n D[768 + MAP[i]] = i << 16;\nconst EMPTY = new Uint8Array(0);\n/**\n * base64 stream decoder.\n *\n * Features / assumptions:\n * - lazy chunkwise decoding\n * - errors out on any non base64 chars (no support for NL formatted base64)\n * - decodes in wasm\n * - inplace decoding to save memory\n * - supports a keepSize for lazy memory release\n */\nclass Base64Decoder {\n /**\n * @param keepSize Keep the wasm instance below this limit when calling `release()`.\n * @param maxBytes Max allowed bytes to allocate.\n * @param initialBytes Initial bytes to allocate.\n */\n constructor(keepSize, maxBytes, initialBytes) {\n this._inst = null;\n this._ended = true;\n this._bytes = 0;\n this.keepSize = keepSize !== null && keepSize !== void 0 ? keepSize : 1048576 /* Bytes.KEEP */;\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : 4294901760 /* Bytes.MAX */;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : 32768 /* Bytes.INITIAL */;\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw new Error('invalid byte settings');\n }\n }\n /**\n * Currently decoded bytes (borrowed).\n * Must be accessed before calling `release` or `init`.\n */\n get data8() {\n return this._inst ? this._d.subarray(0, this._m32[1282 /* P32.STATE_DP */]) : EMPTY;\n }\n /**\n * Release memory conditionally based on `keepSize`.\n * If memory gets released, also the wasm instance will be freed and recreated on next `init`,\n * otherwise the instance will be reused.\n */\n release() {\n if (!this._inst)\n return;\n if (this._bytes > this.keepSize) {\n this._inst = this._m32 = this._d = this._mem = null;\n }\n else {\n this._m32[1280 /* P32.STATE_WP */] = 0;\n this._m32[1281 /* P32.STATE_SP */] = 0;\n this._m32[1282 /* P32.STATE_DP */] = 0;\n }\n }\n /**\n * Initializes the decoder for new base64 data.\n * Must be called before doing any decoding attempts.\n * The method will either spawn a new wasm instance or grow\n * the needed memory of an existing instance.\n * @param maxBytes Max allowed bytes to allocate (overwrites ctor value).\n * @param initialBytes Initial bytes to allocate (overwrites ctor value).\n */\n init(maxBytes, initialBytes) {\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : this.maxBytes;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : Math.min(this._bytes, this.maxBytes);\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw Error('invalid byte settings');\n }\n let m = this._m32;\n const bytes = this._bytes + 5152 /* Bytes._DATA_OFFSET */;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmDecode({ env: { memory: this._mem } });\n m = new Uint32Array(this._mem.buffer, 0);\n m.set(D, 256 /* P32.D0 */);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n m = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n m[1280 /* P32.STATE_WP */] = 0;\n m[1281 /* P32.STATE_SP */] = 0;\n m[1282 /* P32.STATE_DP */] = 0;\n this._m32 = m;\n this._ended = false;\n }\n /**\n * Realloc memory. Realloc only happens, if the requested\n * size doesn't fit in the current memory.\n * The new size will be capped by `maxBytes`.\n * @param requested Bytes to be stored.\n */\n _realloc(requested) {\n const needed = this._m32[1280 /* P32.STATE_WP */] + requested;\n if (this._bytes < needed) {\n if (needed > this.maxBytes) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n let newSize = this._bytes;\n while ((newSize *= 2) < needed) { }\n newSize = Math.min(newSize, this.maxBytes);\n if (newSize < needed) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n if (newSize + 5152 /* Bytes._DATA_OFFSET */ > this._mem.buffer.byteLength) {\n const addPages = Math.ceil((newSize + 5152 /* Bytes._DATA_OFFSET */ - this._mem.buffer.byteLength) / 65536);\n this._mem.grow(addPages);\n this._m32 = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n this._bytes = newSize;\n }\n return 0 /* DecodeStatus.OK */;\n }\n /**\n * Put bytes in `data` into the decoder.\n * Additionally decodes the payload, if it reached 2^17 bytes.\n * The return value indicates the type of issue.\n * @param data Bytes to be loaded.\n */\n put(data) {\n if (!this._inst || this._ended) {\n return -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n if (this._realloc(data.length)) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n const m = this._m32;\n this._d.set(data, m[1280 /* P32.STATE_WP */]);\n m[1280 /* P32.STATE_WP */] += data.length;\n // max chunk in input handler is 2^17, try to run in \"tandem mode\"\n return m[1280 /* P32.STATE_WP */] - m[1281 /* P32.STATE_SP */] >= 131072\n ? this._inst.exports.dec()\n : 0 /* DecodeStatus.OK */;\n }\n /**\n * End the current decoding.\n * Also decodes leftover payload from previous put calls.\n */\n end() {\n this._ended = true;\n return this._inst\n ? this._inst.exports.end()\n : -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n /**\n * Bytes loaded into the decoder.\n */\n get loadedBytes() {\n return this._inst\n ? this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n /**\n * Free bytes to feed to the decoder.\n */\n get freeBytes() {\n return this._inst\n ? this.maxBytes - this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n}\nexports.default = Base64Decoder;\n//# sourceMappingURL=Base64Decoder.wasm.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\nconst wasmQoiDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#459f9e1bfb80b1a8:rdef-start:\"qoi_decode\"*/{s:1,t:0,d:'AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=='}/*inwasm#459f9e1bfb80b1a8:rdef-end:\"qoi_decode\"*/);\nclass QoiDecoder {\n constructor(keepSize) {\n this.keepSize = keepSize;\n this.width = 0;\n this.height = 0;\n }\n decode(d) {\n this.width = d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7];\n this.height = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];\n const pixels = this.width * this.height;\n const ib = pixels * 4;\n const dl = d.length;\n /**\n * byte/offset calculation:\n * To save some memory we dont reserve full memory for decoded + encoded,\n * but place encoded at the end of decoded plus 50% security distance\n * to avoid reads before writes positions:\n *\n * encoded < decoded (good compression)\n * enc ####################\n * dec #######################################\n * ^ ^\n * DST_P CHUNK_P\n *\n * encoded > decoded (degenerated compression, should not happen)\n * enc ##############################\n * dec ####################\n * ^ ^\n * DST_P CHUNK_P\n *\n * There is still a chance for overlapping r/w positions in case the compressed\n * data has very different pixel progression, yet the 50% security distance\n * should deal with that, as QOI will bloat data by 25% at max (RGB -> OP byte + RGB).\n * Since we always assume RGBA at decoding stage, the possible bloat reduces to 20% at max.\n */\n const bytes = Math.max(ib, dl) + (Math.min(ib, dl) >> 1) + 4096;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmQoiDecode({ env: { memory: this._mem } });\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n this._d = null;\n }\n if (!this._d) {\n this._d = new Uint8Array(this._mem.buffer);\n }\n // put src data at the end of memory, also align to 256\n const chunkP = (this._mem.buffer.byteLength - dl) & ~0xFF;\n this._d.set(d, chunkP);\n this._inst.exports.dec(chunkP, dl, pixels);\n return this._d.subarray(1024 /* P8.DST_P */, 1024 /* P8.DST_P */ + ib);\n }\n release() {\n if (!this._inst)\n return;\n if (this._mem.buffer.byteLength > this.keepSize) {\n this._inst = this._d = this._mem = null;\n }\n }\n}\nexports.default = QoiDecoder;\n//# sourceMappingURL=QoiDecoder.wasm.js.map","\"use strict\";\n/**\n * Copyright (c) 2022, 2026 Joerg Breitbart\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InWasm = InWasm;\nlet z = (s) => {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(s);\n if (typeof Buffer !== 'undefined')\n return Buffer.from(s, 'base64');\n const b = atob(s);\n const r = new Uint8Array(b.length);\n for (let i = 0; i < r.length; ++i)\n r[i] = b.charCodeAt(i);\n return r;\n};\nfunction InWasm(def) {\n if (def.d) {\n const { t, s, d } = def;\n let b;\n let m;\n const W = WebAssembly;\n if (t === 0 /* OutputType.INSTANCE */) {\n if (s)\n return (e) => new W.Instance(m || (m = new W.Module(b || (b = z(d)))), e);\n return (e) => m\n ? W.instantiate(m, e)\n : W.instantiate(b || (b = z(d)), e).then(r => (m = r.module) && r.instance);\n }\n if (t === 1 /* OutputType.MODULE */) {\n if (s)\n return () => m || (m = new W.Module(b || (b = z(d))));\n return () => m\n ? Promise.resolve(m)\n : W.compile(b || (b = z(d))).then(r => m = r);\n }\n if (s)\n return () => b || (b = z(d));\n return () => Promise.resolve(b || (b = z(d)));\n }\n if (typeof _wasmCtx === 'undefined')\n throw new Error('must run \"inwasm\"');\n _wasmCtx.add(def);\n}\n//# sourceMappingURL=index.js.map","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport type { ITerminalAddon, IDisposable } from '@xterm/xterm';\nimport type { ImageAddon as IImageApi } from '@xterm/addon-image';\nimport { Emitter, type IEvent } from 'common/Event';\nimport { IIPHandler } from './IIPHandler';\nimport { ImageRenderer } from './ImageRenderer';\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { KittyGraphicsHandler } from './kitty/KittyGraphicsHandler';\nimport { KittyImageStorage } from './kitty/KittyImageStorage';\nimport { SixelHandler } from './SixelHandler';\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { ITerminalExt, IImageAddonOptions, IResetHandler } from './Types';\n\n\n/**\n * Document VT features provided by this addon.\n *\n * @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL \"SIXEL Graphics\" \"DCS Ps ; Ps ; Ps ; q Pt ST\" \"Draw SIXEL image.\"\n *\n * Sixel support is provided by the addon @xterm/addon-image with these limitations:\n * - immediate coloring (no shared palette, allows high color settings of `img2sixel`)\n * - max. palette size of 4096 colors\n * - max. pixel width of 16K\n * - max. 25 MB per sixel sequence\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] OSC 1337 \"iTerm2 Commands\" \"OSC 1337 ; Pt BEL\" \"Custom iTerm2 commands.\"\n *\n * Only the inline image protocol (IIP) is supported by the addon @xterm/addon-image with\n * the following limitations:\n * - sequence:\n * - format: `OSC 1337 ; File=inline=1 ; size= ; ... : BEL`\n * - size param must be set and payload may not exceed CEIL(size * 4 / 3)\n * - strict base64 handling as of RFC4648 §4 (standard alphabet, optional padding,\n * no separator bytes allowed)\n * - supported params: size, name, width, height, preserveAspectRatio\n * - image formats: PNG, JPEG and GIF\n * - no animation support (renders first image of a GIF)\n * - no multipart support\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image)\n * and [iTerm2 IIP docs](https://iterm2.com/documentation-images.html) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] APC KITTY_GRAPHICS \"Kitty Graphics\" \"APC G Pt ST\" \"Kitty Graphics Protocol.\"\n *\n * Kitty graphics support is provided by the addon @xterm/addon-image.\n * Note that while basic image output already works, this is still work in progress.\n */\n\n// default values of addon ctor options\nconst DEFAULT_OPTIONS: IImageAddonOptions = {\n enableSizeReports: true,\n pixelLimit: 16777216, // limit to 4096 * 4096 pixels\n sixelSupport: true,\n sixelScrolling: true,\n sixelPaletteLimit: 4096,\n sixelSizeLimit: 33554432,\n storageLimit: 128,\n showPlaceholder: true,\n iipSupport: true,\n iipSizeLimit: 33554432,\n kittySupport: true,\n kittySizeLimit: 33554432\n};\n\n// max palette size supported by the sixel lib (compile time setting)\nconst MAX_SIXEL_PALETTE_SIZE = 4096;\n\n// definitions for _xtermGraphicsAttributes sequence\nconst enum GaItem {\n COLORS = 1,\n SIXEL_GEO = 2,\n REGIS_GEO = 3\n}\nconst enum GaAction {\n READ = 1,\n SET_DEFAULT = 2,\n SET = 3,\n READ_MAX = 4\n}\nconst enum GaStatus {\n SUCCESS = 0,\n ITEM_ERROR = 1,\n ACTION_ERROR = 2,\n FAILURE = 3\n}\n\n\nexport class ImageAddon implements ITerminalAddon, IImageApi {\n private _opts: IImageAddonOptions;\n private _defaultOpts: IImageAddonOptions;\n private _storage: ImageStorage | undefined;\n private _renderer: ImageRenderer | undefined;\n private _disposables: IDisposable[] = [];\n private _terminal: ITerminalExt | undefined;\n private _handlers: Map = new Map();\n private readonly _onImageAdded = new Emitter();\n public readonly onImageAdded: IEvent = this._onImageAdded.event;\n\n constructor(opts?: Partial) {\n this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);\n this._defaultOpts = Object.assign({}, DEFAULT_OPTIONS, opts);\n }\n\n public dispose(): void {\n for (const handler of this._handlers.values()) handler.reset();\n for (const obj of this._disposables) {\n obj.dispose();\n }\n this._disposables.length = 0;\n this._handlers.clear();\n this._onImageAdded.dispose();\n }\n\n private _disposeLater(...args: IDisposable[]): void {\n for (const obj of args) {\n this._disposables.push(obj);\n }\n }\n\n public activate(terminal: ITerminalExt): void {\n this._terminal = terminal;\n\n // internal data structures\n this._renderer = new ImageRenderer(terminal);\n this._storage = new ImageStorage(terminal, this._renderer, this._opts);\n this._storage.onImageAdded = () => this._onImageAdded.fire();\n\n // enable size reports\n if (this._opts.enableSizeReports) {\n const windowOps = terminal.options.windowOptions ?? {};\n windowOps.getWinSizePixels = true;\n windowOps.getCellSizePixels = true;\n windowOps.getWinSizeChars = true;\n terminal.options.windowOptions = windowOps;\n }\n\n this._disposeLater(\n this._renderer,\n this._storage,\n\n // DECSET/DECRST/DA1/XTSMGRAPHICS handlers\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'h' }, params => this._decset(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'l' }, params => this._decrst(params)),\n terminal.parser.registerCsiHandler({ final: 'c' }, params => this._da1(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'S' }, params => this._xtermGraphicsAttributes(params)),\n\n // render hook\n terminal.onRender(range => this._storage?.render(range)),\n\n /**\n * reset handlers covered:\n * - DECSTR\n * - RIS\n * - Terminal.reset()\n */\n terminal.parser.registerCsiHandler({ intermediates: '!', final: 'p' }, () => this.reset()),\n terminal.parser.registerEscHandler({ final: 'c' }, () => this.reset()),\n terminal._core._inputHandler.onRequestReset(() => this.reset()),\n\n // wipe canvas and delete alternate images on buffer switch\n terminal.buffer.onBufferChange(() => this._storage?.wipeAlternate()),\n\n // extend images to the right on resize\n terminal.onResize(metrics => this._storage?.viewportResize(metrics))\n );\n\n // SIXEL handler\n if (this._opts.sixelSupport) {\n const sixelStorage = new SixelImageStorage(this._storage!, this._opts, this._renderer!, terminal);\n const sixelHandler = new SixelHandler(this._opts, sixelStorage, terminal);\n this._handlers.set('sixel', sixelHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerDcsHandler({ final: 'q' }, sixelHandler)\n );\n }\n\n // iTerm IIP handler\n if (this._opts.iipSupport) {\n const iipStorage = new IIPImageStorage(this._storage!);\n const iipHandler = new IIPHandler(this._opts, this._renderer!, iipStorage, terminal);\n this._handlers.set('iip', iipHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerOscHandler(1337, iipHandler)\n );\n }\n\n // Kitty graphics handler\n if (this._opts.kittySupport) {\n const kittyStorage = new KittyImageStorage(this._storage!);\n const kittyHandler = new KittyGraphicsHandler(this._opts, this._renderer!, kittyStorage, terminal);\n this._handlers.set('kitty', kittyHandler);\n this._disposeLater(\n kittyStorage,\n kittyHandler,\n terminal._core._inputHandler._parser.registerApcHandler({ final: 'G' }, kittyHandler)\n );\n }\n }\n\n // Note: storageLimit is skipped here to not intoduce a surprising side effect.\n public reset(): boolean {\n // reset options customizable by sequences to defaults\n this._opts.sixelScrolling = this._defaultOpts.sixelScrolling;\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n // also clear image storage\n this._storage?.reset();\n // reset protocol handlers\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return false;\n }\n\n public get storageLimit(): number {\n return this._storage?.getLimit() || -1;\n }\n\n public set storageLimit(limit: number) {\n this._storage?.setLimit(limit);\n this._opts.storageLimit = limit;\n }\n\n public get storageUsage(): number {\n if (this._storage) {\n return this._storage.getUsage();\n }\n return -1;\n }\n\n public get showPlaceholder(): boolean {\n return this._opts.showPlaceholder;\n }\n\n public set showPlaceholder(value: boolean) {\n this._opts.showPlaceholder = value;\n this._renderer?.showPlaceholder(value);\n }\n\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.getImageAtBufferCell(x, y);\n }\n\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.extractTileAtBufferCell(x, y);\n }\n\n private _report(s: string): void {\n this._terminal?._core.input(s, false);\n }\n\n private _decset(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = false;\n break;\n }\n }\n return false;\n }\n\n private _decrst(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = true;\n break;\n }\n }\n return false;\n }\n\n // overload DA to return something more appropriate\n private _da1(params: (number | number[])[]): boolean {\n if (params[0]) {\n return true;\n }\n // reported features:\n // 62 - VT220\n // 4 - SIXEL support\n // 9 - charsets\n // 22 - ANSI colors\n if (this._opts.sixelSupport) {\n this._report(`\\x1b[?62;4;9;22c`);\n return true;\n }\n return false;\n }\n\n /**\n * Implementation of xterm's graphics attribute sequence.\n *\n * Supported features:\n * - read/change palette limits (max 4096 by sixel lib)\n * - read SIXEL canvas geometry (reports current window canvas or\n * squared pixelLimit if canvas > pixel limit)\n *\n * Everything else is deactivated.\n */\n private _xtermGraphicsAttributes(params: (number | number[])[]): boolean {\n if (params.length < 2) {\n return true;\n }\n if (params[0] === GaItem.COLORS) {\n switch (params[1]) {\n case GaAction.READ:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n return true;\n case GaAction.SET_DEFAULT:\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n // also reset protocol handlers for now\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return true;\n case GaAction.SET:\n if (params.length > 2 && !(params[2] instanceof Array) && params[2] <= MAX_SIXEL_PALETTE_SIZE) {\n this._opts.sixelPaletteLimit = params[2];\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n } else {\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n }\n return true;\n case GaAction.READ_MAX:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${MAX_SIXEL_PALETTE_SIZE}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n if (params[0] === GaItem.SIXEL_GEO) {\n switch (params[1]) {\n // we only implement read and read_max here\n case GaAction.READ:\n let width = this._renderer?.dimensions?.css.canvas.width;\n let height = this._renderer?.dimensions?.css.canvas.height;\n if (!width || !height) {\n // for some reason we have no working image renderer\n // --> fallback to default cell size\n const cellSize = CELL_SIZE_DEFAULT;\n width = (this._terminal?.cols || 80) * cellSize.width;\n height = (this._terminal?.rows || 24) * cellSize.height;\n }\n if (width * height < this._opts.pixelLimit) {\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${width.toFixed(0)};${height.toFixed(0)}S`);\n } else {\n // if we overflow pixelLimit report that squared instead\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n }\n return true;\n case GaAction.READ_MAX:\n // read_max returns pixelLimit as square area\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n // exit with error on ReGIS or any other requests\n this._report(`\\x1b[?${params[0]};${GaStatus.ITEM_ERROR}S`);\n return true;\n }\n}\n"],"names":["root","factory","exports","module","define","amd","globalThis","red","n","green","blue","toRGBA8888","r","g","b","a","clamp","low","high","value","Math","max","min","h2c","t1","t2","c","normalizeRGB","round","Object","defineProperty","DEFAULT_FOREGROUND","DEFAULT_BACKGROUND","PALETTE_ANSI_256","PALETTE_VT340_GREY","PALETTE_VT340_COLOR","normalizeHLS","nearestColorIndex","fromRGBA8888","alpha","BIG_ENDIAN","Uint8Array","Uint32Array","buffer","console","warn","color","palette","Number","MAX_SAFE_INTEGER","idx","i","length","dr","dg","db","d","h","l","s","v","HLStoRGB","p","push","decodeAsync","decode","Decoder","DecoderAsync","Colors_1","__webpack_require__","wasm_1","WASM_BYTES","Buffer","from","bytestring","atob","result","charCodeAt","decodeBase64","LIMITS","BYTES","WASM_MODULE","NULL_CANVAS","CallbackProxy","constructor","this","bandHandler","width","modeHandler","mode","handle_band","mode_parsed","DEFAULT_OPTIONS","memoryLimit","sixelColor","fillColor","paletteLimit","PALETTE_SIZE","truncate","opts","cbProxy","importObj","env","bind","WebAssembly","instantiate","then","inst","instance","_instance","_cbProxy","_PIXEL_OFFSET","MAX_WIDTH","_canvas","_bandWidths","_maxWidth","_minWidth","_lastOffset","_currentHeight","_opts","assign","Error","_handle_band","_initCanvas","Module","Instance","_wasm","_chunk","memory","get_chunk_address","CHUNK_SIZE","_states","get_state_address","_palette","get_palette_address","set","_pSrc","get_p0_address","init","_fillColor","_truncate","_rasterWidth","_rasterHeight","_width","_height","_level","_mode","_paletteLimit","pixels","height","release","_realloc","offset","additionalPixels","newCanvas","ceil","adv","remaining","subarray","current_width","current_height","memoryUsage","byteLength","properties","level","memUsage","rasterAttributes","numerator","denominator","data","start","end","decodeString","j","data32","currentWidth","fill","escape","final","finalOffset","bw","currentHeight","data8","Uint8ClampedArray","dec","async","Lifecycle_1","EventUtils","_listeners","_disposed","event","_event","listener","thisArgs","disposables","toDisposable","entry","fn","slice","indexOf","splice","Array","isArray","add","fire","call","listeners","len","dispose","forward","to","e","map","undefined","any","events","store","DisposableStore","runAndSubscribe","handler","initial","arg","_disposables","Set","_isDisposed","isDisposed","o","clear","Disposable","_store","_register","None","freeze","_value","ImageRenderer_1","ImageStorage_1","Base64Decoder_wasm_1","__importDefault","QoiDecoder_wasm_1","IIPHeaderParser_1","IIPMetrics_1","DEFAULT_HEADER","type","name","size","preserveAspectRatio","inline","_renderer","_storage","_coreTerminal","_generation","_aborted","_hp","HeaderParser","_header","_isMultipart","_abortMulti","maxEncodedBytes","iipSizeLimit","initialBytes","_dec","default","_qoiDec","reset","put","state","dataPos","parse","fields","success","seqType","w","CELL_SIZE_DEFAULT","dimensions","css","canvas","cols","rows","scale","_c","_a","_core","_coreBrowserService","dpr","report","toFixed","input","cond","blob","metrics","UNSUPPORTED_TYPE","imageType","mime","pixelLimit","_resize","floor","ImageData","byteOffset","ImageRenderer","createCanvas","_b","getContext","putImageData","addImage","Blob","generation","createImageBitmap","resizeWidth","resizeHeight","bm","close","catch","cw","cell","ch","_d","rw","_dim","rh","wf","hf","f","total","cdim","endsWith","parseInt","toStr","String","fromCharCode","toInt","toSize","match","DECODERS","toString","bs","TextDecoder","FILE_MARKER","MULTIPARTFILE_MARKER","FILEPART_MARKER","FILEEND_MARKER","REPORTCELLSIZE_MARKER","MAX_FIELDCHARS","_buffer","_position","_key","k","_storeValue","pos","_storeKey","_addImageOpts","scrolling","layer","zIndex","cursorPos","img","d32","blockLength","jpgSize","dim","limit","_layers","get","localDocument","document","createElement","createImageData","ctx","imgData","Promise","resolve","_terminal","super","Map","_optionsRefresh","MutableDisposable","_oldOpen","open","parent","_open","screenElement","optionsService","onOptionChange","option","rescaleCanvas","_renderService","refreshRows","removeLayerFromDom","_oldSetRenderer","setRenderer","_placeholderBitmap","_placeholder","showPlaceholder","cellSize","_createPlaceHolder","clearLines","y","clearRect","_e","clearAll","draw","imgSpec","tileId","col","row","count","_rescaleImage","actual","sourceWidth","sourceHeight","actualCellSize","sx","sy","dx","dy","finalWidth","finalHeight","drawImage","extractTile","drawPlaceholder","values","spec","originalWidth","originalHeight","origCellSize","orig","scaledWidth","scaledHeight","renderer","key","keys","insertLayerToDom","has","classList","style","isolation","insertBefore","firstChild","appendChild","remove","delete","hasLayer","bWidth","blueprint","black","white","shift","x","screen","ctx2","placeholder","bitmap","window","ExtendedAttrsImage","ext","_urlId","_ext","underlineStyle","underlineColor","underlineVariantOffset","val","urlId","imageId","clone","isEmpty","EMPTY_ATTRS","_images","_lastId","_lowestId","_fullyCleared","_needsFullClear","_pixelLimit","setLimit","storageLimit","error","message","getLimit","_viewportMetrics","marker","RangeError","_evictOldest","getUsage","_getStoredPixels","storedPixels","_delImg","id","ImageBitmap","onImageDeleted","wipeAlternate","zero","entries","bufferType","deleteImage","termCols","termRows","originX","originY","tileCount","_inputHandler","_dirtyRowTracker","markDirty","line","lines","ybase","_writeToCell","lineFeed","endMarker","registerMarker","onDispose","active","_evictOnAlternate","onImageAdded","render","range","hasTopImages","hasBottomImages","drawCalls","placeholderCalls","ydisp","getBg","_extendedAttrs","startTile","startCol","sort","viewportResize","oldCol","tilesPerRow","hasData","rightCol","_data","lastTile","expandCol","getImageAtBufferCell","extractTileAtBufferCell","room","used","current","old","oldSpec","imgId","Decoder_1","DEFAULT_PALETTE","convertLe","_size","sixelPaletteLimit","hook","params","attr","colors","bg","isInverse","isFgDefault","foreground","rgba","isFgRGB","t","toColorRGB","getFgColor","ansi","isBgDefault","background","isBgRGB","getBgColor","extractActiveBg","_curAttrData","_themeService","sixelSizeLimit","unhook","advanceCursor","sixelScrolling","KittyGraphicsTypes_1","_kittyStorage","_decodeError","_activeDecoder","_inControlData","_controlData","_controlLength","_encodedSizeLimit","_totalEncodedSize","_parsedCommand","_pendingTransmissions","_maxEncodedBytes","kittySizeLimit","_initialEncodedBytes","_cleanupAllPending","_removePendingEntry","_lastPendingKey","pending","decoder","controlEnd","copyLength","parseKittyCommand","_parseControlDataString","imageNumber","_sendResponse","quiet","action","payloadStart","_streamPayload","pendingKey","previousEncodedSize","totalEncodedSize","decoderToRelease","_f","decoderCapacity","_g","maxPending","oldest","next","cmd","_h","_handleNoPayloadCommand","_handleDelete","isMoreComing","more","decodeError","finalCmd","imageBytes","_handleCommandWithBytesAndCmd","str","fromCodePoint","_handlePlacement","bytes","_handleTransmit","transmission","_handleTransmitDisplay","_handleQuery","image","getImage","_displayImage","placementId","storeImage","format","compression","lastImageId","expectedBytes","deleteSelector","deleteAll","deleteById","isOk","response","coreService","triggerDataEvent","_decodeAndDisplay","_createBitmap","cropX","cropY","cropW","cropH","maxCropW","maxCropH","finalCropW","finalCropH","cropped","imgCols","imgRows","columns","savedX","savedY","savedYbase","scaled","xOffset","yOffset","canvasW","canvasH","offsetCanvas","offsetCtx","offsetBitmap","cursorMovement","scrolled","arrayBuffer","_decompressZlib","url","URL","createObjectURL","Image","reject","addEventListener","revokeObjectURL","src","pixelCount","src32","dst32","alignedPixels","srcOffset","dstOffset","b0","b1","b2","srcByte","dstByte","compressed","_decompress","offsetIn","reader","ReadableStream","pull","controller","enqueue","pipeThrough","DecompressionStream","getReader","chunks","totalLength","done","read","cancel","releaseLock","chunk","images","_kittyIdToStorageId","kittyIdToStorageId","pendingTransmissions","parts","split","part","eqIdx","substring","numValue","KittyImageStorage","_nextImageId","_storageIdToKittyId","_handleStorageImageDeleted","storageId","kittyId","_previousOnImageDeleted","_wrappedOnImageDeleted","imageData","oldStorageId","_maxStoredImages","_evictUndisplayedImages","byteLimit","retainedBytes","evictPlaced","oldestId","wasmDecode","InWasm","MAP","el","D","EMPTY","keepSize","maxBytes","_inst","_ended","_bytes","_m32","_mem","m","grow","Memory","requested","needed","newSize","addPages","loadedBytes","freeBytes","wasmQoiDecode","ib","dl","chunkP","def","W","z","compile","_wasmCtx","fromBase64","__webpack_module_cache__","moduleId","cachedModule","__webpack_modules__","Event_1","IIPHandler_1","KittyGraphicsHandler_1","KittyImageStorage_1","SixelHandler_1","SixelImageStorage_1","IIPImageStorage_1","enableSizeReports","sixelSupport","iipSupport","kittySupport","_handlers","_onImageAdded","Emitter","_defaultOpts","obj","_disposeLater","args","activate","terminal","ImageStorage","windowOps","options","windowOptions","getWinSizePixels","getCellSizePixels","getWinSizeChars","parser","registerCsiHandler","prefix","_decset","_decrst","_da1","_xtermGraphicsAttributes","onRender","intermediates","registerEscHandler","onRequestReset","onBufferChange","onResize","sixelStorage","SixelImageStorage","sixelHandler","SixelHandler","_parser","registerDcsHandler","iipStorage","IIPImageStorage","iipHandler","IIPHandler","registerOscHandler","kittyStorage","kittyHandler","KittyGraphicsHandler","registerApcHandler","storageUsage","_report","sqrt"],"sourceRoot":""} ++{"version":3,"file":"addon-image.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AK8R,iBAAS,IAAA+O,OAAA,EAAAA,EAAE5U,OAAQ,IAAMmH,EAASpP,MACnD,CACA,GAAI9D,EAAQ8D,EAAShE,KAAKkC,MAAM+K,WAC9BjN,KAAKivB,QAAQ,MAAS/R,EAAO,QAA0Bhd,EAAMuM,QAAQ,MAAMzI,EAAOyI,QAAQ,WACrF,CAEL,MAAMiK,EAAI3a,KAAKoR,MAAMpR,KAAKmzB,KAAKlvB,KAAKkC,MAAM+K,aAC1CjN,KAAKivB,QAAQ,MAAS/R,EAAO,QAA0BxG,KAAKA,KAC9D,CACA,OAAO,EACT,OAEE,MAAMA,EAAI3a,KAAKoR,MAAMpR,KAAKmzB,KAAKlvB,KAAKkC,MAAM+K,aAE1C,OADAjN,KAAKivB,QAAQ,MAAS/R,EAAO,QAA0BxG,KAAKA,OACrD,EACT,QAEE,OADA1W,KAAKivB,QAAQ,MAAS/R,EAAO,UACtB,EAKb,OADAld,KAAKivB,QAAQ,MAAS/R,EAAO,UACtB,CACT","sources":["webpack://ImageAddon/webpack/universalModuleDefinition","webpack://ImageAddon/../node_modules/sixel/lib/Colors.js","webpack://ImageAddon/../node_modules/sixel/lib/Decoder.js","webpack://ImageAddon/../node_modules/sixel/lib/wasm.js","webpack://ImageAddon/../src/common/Event.ts","webpack://ImageAddon/../src/common/Lifecycle.ts","webpack://ImageAddon/./src/IIPHandler.ts","webpack://ImageAddon/./src/IIPHeaderParser.ts","webpack://ImageAddon/./src/IIPImageStorage.ts","webpack://ImageAddon/./src/IIPMetrics.ts","webpack://ImageAddon/./src/ImageRenderer.ts","webpack://ImageAddon/./src/ImageStorage.ts","webpack://ImageAddon/./src/SixelHandler.ts","webpack://ImageAddon/./src/SixelImageStorage.ts","webpack://ImageAddon/./src/kitty/KittyGraphicsHandler.ts","webpack://ImageAddon/./src/kitty/KittyGraphicsTypes.ts","webpack://ImageAddon/./src/kitty/KittyImageStorage.ts","webpack://ImageAddon/../node_modules/xterm-wasm-parts/lib/base64/Base64Decoder.wasm.js","webpack://ImageAddon/../node_modules/xterm-wasm-parts/lib/qoi/QoiDecoder.wasm.js","webpack://ImageAddon/javascript/node_modules/inwasm-runtime/lib/index.cjs","webpack://ImageAddon/webpack/bootstrap","webpack://ImageAddon/./src/ImageAddon.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ImageAddon\"] = factory();\n\telse\n\t\troot[\"ImageAddon\"] = factory();\n})(globalThis, () => {\nreturn ","\"use strict\";\n/**\n * Copyright (c) 2019 Joerg Breitbart.\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DEFAULT_FOREGROUND = exports.DEFAULT_BACKGROUND = exports.PALETTE_ANSI_256 = exports.PALETTE_VT340_GREY = exports.PALETTE_VT340_COLOR = exports.normalizeHLS = exports.normalizeRGB = exports.nearestColorIndex = exports.fromRGBA8888 = exports.toRGBA8888 = exports.alpha = exports.blue = exports.green = exports.red = exports.BIG_ENDIAN = void 0;\n// FIXME: cleanup this mess, move things either to decoder/encoder, keep only shared things\n// system endianess\nexports.BIG_ENDIAN = new Uint8Array(new Uint32Array([0xFF000000]).buffer)[0] === 0xFF;\nif (exports.BIG_ENDIAN) {\n console.warn('BE platform detected. This version of node-sixel works only on LE properly.');\n}\n// channel values\nfunction red(n) {\n return n & 0xFF;\n}\nexports.red = red;\nfunction green(n) {\n return (n >>> 8) & 0xFF;\n}\nexports.green = green;\nfunction blue(n) {\n return (n >>> 16) & 0xFF;\n}\nexports.blue = blue;\nfunction alpha(n) {\n return (n >>> 24) & 0xFF;\n}\nexports.alpha = alpha;\n/**\n * Convert RGB channels to native color RGBA8888.\n */\nfunction toRGBA8888(r, g, b, a = 255) {\n return ((a & 0xFF) << 24 | (b & 0xFF) << 16 | (g & 0xFF) << 8 | (r & 0xFF)) >>> 0; // ABGR32\n}\nexports.toRGBA8888 = toRGBA8888;\n/**\n * Convert native color to [r, g, b, a].\n */\nfunction fromRGBA8888(color) {\n return [color & 0xFF, (color >> 8) & 0xFF, (color >> 16) & 0xFF, color >>> 24];\n}\nexports.fromRGBA8888 = fromRGBA8888;\n/**\n * Get index of nearest color in `palette` for `color`.\n * Uses euclidean distance without any luminescence correction.\n */\nfunction nearestColorIndex(color, palette) {\n const r = red(color);\n const g = green(color);\n const b = blue(color);\n let min = Number.MAX_SAFE_INTEGER;\n let idx = -1;\n // use euclidean distance (manhattan gives very poor results)\n for (let i = 0; i < palette.length; ++i) {\n const dr = r - palette[i][0];\n const dg = g - palette[i][1];\n const db = b - palette[i][2];\n const d = dr * dr + dg * dg + db * db;\n if (!d)\n return i;\n if (d < min) {\n min = d;\n idx = i;\n }\n }\n return idx;\n}\nexports.nearestColorIndex = nearestColorIndex;\n// color conversions\n// HLS taken from: http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl\nfunction clamp(low, high, value) {\n return Math.max(low, Math.min(value, high));\n}\nfunction h2c(t1, t2, c) {\n if (c < 0)\n c += 1;\n if (c > 1)\n c -= 1;\n return c * 6 < 1\n ? t2 + (t1 - t2) * 6 * c\n : c * 2 < 1\n ? t1\n : c * 3 < 2\n ? t2 + (t1 - t2) * (4 - c * 6)\n : t2;\n}\nfunction HLStoRGB(h, l, s) {\n if (!s) {\n const v = Math.round(l * 255);\n return toRGBA8888(v, v, v);\n }\n const t1 = l < 0.5 ? l * (1 + s) : l + s - l * s;\n const t2 = 2 * l - t1;\n return toRGBA8888(clamp(0, 255, Math.round(h2c(t1, t2, h + 1 / 3) * 255)), clamp(0, 255, Math.round(h2c(t1, t2, h) * 255)), clamp(0, 255, Math.round(h2c(t1, t2, h - 1 / 3) * 255)));\n}\n/**\n * Normalize SIXEL RGB values (percent based, 0-100) to RGBA8888.\n */\nfunction normalizeRGB(r, g, b) {\n return (0xFF000000 | Math.round(b / 100 * 255) << 16 | Math.round(g / 100 * 255) << 8 | Math.round(r / 100 * 255)) >>> 0; // ABGR32\n}\nexports.normalizeRGB = normalizeRGB;\n/**\n * Normalize SIXEL HLS values to RGBA8888. Applies hue correction of +240°.\n */\nfunction normalizeHLS(h, l, s) {\n // Note: hue value is turned by 240° in VT340, all values given as fractions\n return HLStoRGB((h + 240 % 360) / 360, l / 100, s / 100);\n}\nexports.normalizeHLS = normalizeHLS;\n/**\n * default palettes\n */\n// FIXME: move palettes to Decoder.ts\n/**\n * 16 predefined color registers of VT340 (values in %):\n * ```\n * R G B\n * 0 Black 0 0 0\n * 1 Blue 20 20 80\n * 2 Red 80 13 13\n * 3 Green 20 80 20\n * 4 Magenta 80 20 80\n * 5 Cyan 20 80 80\n * 6 Yellow 80 80 20\n * 7 Gray 50% 53 53 53\n * 8 Gray 25% 26 26 26\n * 9 Blue* 33 33 60\n * 10 Red* 60 26 26\n * 11 Green* 33 60 33\n * 12 Magenta* 60 33 60\n * 13 Cyan* 33 60 60\n * 14 Yellow* 60 60 33\n * 15 Gray 75% 80 80 80\n * ```\n * (*) less saturated\n *\n * @see https://vt100.net/docs/vt3xx-gp/chapter2.html#S2.4\n*/\nexports.PALETTE_VT340_COLOR = new Uint32Array([\n normalizeRGB(0, 0, 0),\n normalizeRGB(20, 20, 80),\n normalizeRGB(80, 13, 13),\n normalizeRGB(20, 80, 20),\n normalizeRGB(80, 20, 80),\n normalizeRGB(20, 80, 80),\n normalizeRGB(80, 80, 20),\n normalizeRGB(53, 53, 53),\n normalizeRGB(26, 26, 26),\n normalizeRGB(33, 33, 60),\n normalizeRGB(60, 26, 26),\n normalizeRGB(33, 60, 33),\n normalizeRGB(60, 33, 60),\n normalizeRGB(33, 60, 60),\n normalizeRGB(60, 60, 33),\n normalizeRGB(80, 80, 80)\n]);\n/**\n * 16 predefined monochrome registers of VT340 (values in %):\n * ```\n * R G B\n * 0 Black 0 0 0\n * 1 Gray-2 13 13 13\n * 2 Gray-4 26 26 26\n * 3 Gray-6 40 40 40\n * 4 Gray-1 6 6 6\n * 5 Gray-3 20 20 20\n * 6 Gray-5 33 33 33\n * 7 White 7 46 46 46\n * 8 Black 0 0 0 0\n * 9 Gray-2 13 13 13\n * 10 Gray-4 26 26 26\n * 11 Gray-6 40 40 40\n * 12 Gray-1 6 6 6\n * 13 Gray-3 20 20 20\n * 14 Gray-5 33 33 33\n * 15 White 7 46 46 46\n * ```\n *\n * @see https://vt100.net/docs/vt3xx-gp/chapter2.html#S2.4\n */\nexports.PALETTE_VT340_GREY = new Uint32Array([\n normalizeRGB(0, 0, 0),\n normalizeRGB(13, 13, 13),\n normalizeRGB(26, 26, 26),\n normalizeRGB(40, 40, 40),\n normalizeRGB(6, 6, 6),\n normalizeRGB(20, 20, 20),\n normalizeRGB(33, 33, 33),\n normalizeRGB(46, 46, 46),\n normalizeRGB(0, 0, 0),\n normalizeRGB(13, 13, 13),\n normalizeRGB(26, 26, 26),\n normalizeRGB(40, 40, 40),\n normalizeRGB(6, 6, 6),\n normalizeRGB(20, 20, 20),\n normalizeRGB(33, 33, 33),\n normalizeRGB(46, 46, 46)\n]);\n/**\n * 256 predefined ANSI colors.\n *\n * @see https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit\n */\nexports.PALETTE_ANSI_256 = (() => {\n // 16 lower colors (taken from xterm)\n const p = [\n toRGBA8888(0, 0, 0),\n toRGBA8888(205, 0, 0),\n toRGBA8888(0, 205, 0),\n toRGBA8888(205, 205, 0),\n toRGBA8888(0, 0, 238),\n toRGBA8888(205, 0, 205),\n toRGBA8888(0, 250, 205),\n toRGBA8888(229, 229, 229),\n toRGBA8888(127, 127, 127),\n toRGBA8888(255, 0, 0),\n toRGBA8888(0, 255, 0),\n toRGBA8888(255, 255, 0),\n toRGBA8888(92, 92, 255),\n toRGBA8888(255, 0, 255),\n toRGBA8888(0, 255, 255),\n toRGBA8888(255, 255, 255),\n ];\n // colors up to 232\n const d = [0, 95, 135, 175, 215, 255];\n for (let r = 0; r < 6; ++r) {\n for (let g = 0; g < 6; ++g) {\n for (let b = 0; b < 6; ++b) {\n p.push(toRGBA8888(d[r], d[g], d[b]));\n }\n }\n }\n // grey scale to up 255\n for (let v = 8; v <= 238; v += 10) {\n p.push(toRGBA8888(v, v, v));\n }\n return new Uint32Array(p);\n})();\n/**\n * Background: Black by default.\n * Foreground: White by default.\n *\n * Background color is used whenever a fill color is needed and not explicitly set.\n * Foreground color is used as default initial sixel color.\n */\nexports.DEFAULT_BACKGROUND = toRGBA8888(0, 0, 0, 255);\nexports.DEFAULT_FOREGROUND = toRGBA8888(255, 255, 255, 255);\n//# sourceMappingURL=Colors.js.map","\"use strict\";\n/**\n * Copyright (c) 2021 Joerg Breitbart.\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.decodeAsync = exports.decode = exports.Decoder = exports.DecoderAsync = void 0;\nconst Colors_1 = require(\"./Colors\");\nconst wasm_1 = require(\"./wasm\");\n/* istanbul ignore next */\nfunction decodeBase64(s) {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(s, 'base64');\n }\n const bytestring = atob(s);\n const result = new Uint8Array(bytestring.length);\n for (let i = 0; i < result.length; ++i) {\n result[i] = bytestring.charCodeAt(i);\n }\n return result;\n}\nconst WASM_BYTES = decodeBase64(wasm_1.LIMITS.BYTES);\nlet WASM_MODULE;\n// empty canvas\nconst NULL_CANVAS = new Uint32Array();\n// proxy for lazy binding of decoder methods to wasm env callbacks\nclass CallbackProxy {\n constructor() {\n this.bandHandler = (width) => 1;\n this.modeHandler = (mode) => 1;\n }\n handle_band(width) {\n return this.bandHandler(width);\n }\n mode_parsed(mode) {\n return this.modeHandler(mode);\n }\n}\n// default decoder options\nconst DEFAULT_OPTIONS = {\n memoryLimit: 2048 * 65536,\n sixelColor: Colors_1.DEFAULT_FOREGROUND,\n fillColor: Colors_1.DEFAULT_BACKGROUND,\n palette: Colors_1.PALETTE_VT340_COLOR,\n paletteLimit: wasm_1.LIMITS.PALETTE_SIZE,\n truncate: true\n};\n/**\n * Create a decoder instance asynchronously.\n * To be used in the browser main thread.\n */\nfunction DecoderAsync(opts) {\n const cbProxy = new CallbackProxy();\n const importObj = {\n env: {\n handle_band: cbProxy.handle_band.bind(cbProxy),\n mode_parsed: cbProxy.mode_parsed.bind(cbProxy)\n }\n };\n return WebAssembly.instantiate(WASM_MODULE || WASM_BYTES, importObj)\n .then((inst) => {\n WASM_MODULE = WASM_MODULE || inst.module;\n return new Decoder(opts, inst.instance || inst, cbProxy);\n });\n}\nexports.DecoderAsync = DecoderAsync;\n/**\n * Decoder - web assembly based sixel stream decoder.\n *\n * Usage pattern:\n * - call `init` to initialize decoder for new image\n * - feed data chunks to `decode` or `decodeString`\n * - grab pixels from `data32`\n * - optional: call `release` to free memory (e.g. after big images)\n * - start over with next image by calling `init`\n *\n * Properties:\n * - max width of 2^14 - 4 pixels (compile time setting in wasm)\n * - no explicit height limit (only limited by memory)\n * - max 4096 colors palette (compile time setting in wasm)\n *\n * Explanation operation modes:\n * - M1 Mode chosen for level 1 images (no raster attributes),\n * or for level 2 images with `truncate=false`.\n * - M2 Mode chosen for level 2 images with `truncate=true` (default).\n * While this mode is not fully spec conform (decoder not expected to truncate),\n * it is what spec conform encoders should create (should not excess raster).\n * This mode has several advantages:\n * - ~15% faster decoding speed\n * - image dimensions can be evaluated early without processing the whole data\n * - faster pixel access in `data32` (precalulated)\n * - image height is not reported as multiple of 6 pixels\n * - M0 Undecided mode state after `init`.\n * The level of an image is determined during early decoding based on the fact,\n * whether the data contains valid raster attributes before any sixel data.\n * Until then the mode of an image is marked as M0, meaning the real operation mode\n * could not be decided yet.\n */\nclass Decoder {\n /**\n * Synchonous ctor. Can be called from nodejs or a webworker context.\n * For instantiation in the browser main thread use `WasmDecoderAsync` instead.\n */\n constructor(opts, _instance, _cbProxy) {\n this._PIXEL_OFFSET = wasm_1.LIMITS.MAX_WIDTH + 4;\n this._canvas = NULL_CANVAS;\n this._bandWidths = [];\n this._maxWidth = 0;\n this._minWidth = wasm_1.LIMITS.MAX_WIDTH;\n this._lastOffset = 0;\n this._currentHeight = 0;\n this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);\n if (this._opts.paletteLimit > wasm_1.LIMITS.PALETTE_SIZE) {\n throw new Error(`DecoderOptions.paletteLimit must not exceed ${wasm_1.LIMITS.PALETTE_SIZE}`);\n }\n if (!_instance) {\n const module = WASM_MODULE || (WASM_MODULE = new WebAssembly.Module(WASM_BYTES));\n _instance = new WebAssembly.Instance(module, {\n env: {\n handle_band: this._handle_band.bind(this),\n mode_parsed: this._initCanvas.bind(this)\n }\n });\n }\n else {\n _cbProxy.bandHandler = this._handle_band.bind(this);\n _cbProxy.modeHandler = this._initCanvas.bind(this);\n }\n this._instance = _instance;\n this._wasm = this._instance.exports;\n this._chunk = new Uint8Array(this._wasm.memory.buffer, this._wasm.get_chunk_address(), wasm_1.LIMITS.CHUNK_SIZE);\n this._states = new Uint32Array(this._wasm.memory.buffer, this._wasm.get_state_address(), 12);\n this._palette = new Uint32Array(this._wasm.memory.buffer, this._wasm.get_palette_address(), wasm_1.LIMITS.PALETTE_SIZE);\n this._palette.set(this._opts.palette);\n this._pSrc = new Uint32Array(this._wasm.memory.buffer, this._wasm.get_p0_address());\n this._wasm.init(Colors_1.DEFAULT_FOREGROUND, 0, this._opts.paletteLimit, 0);\n }\n // some readonly parser states for internal usage\n get _fillColor() { return this._states[0]; }\n get _truncate() { return this._states[8]; }\n get _rasterWidth() { return this._states[6]; }\n get _rasterHeight() { return this._states[7]; }\n get _width() { return this._states[2] ? this._states[2] - 4 : 0; }\n get _height() { return this._states[3]; }\n get _level() { return this._states[9]; }\n get _mode() { return this._states[10]; }\n get _paletteLimit() { return this._states[11]; }\n _initCanvas(mode) {\n if (mode === 2 /* M2 */) {\n const pixels = this.width * this.height;\n if (pixels > this._canvas.length) {\n if (this._opts.memoryLimit && pixels * 4 > this._opts.memoryLimit) {\n this.release();\n throw new Error('image exceeds memory limit');\n }\n this._canvas = new Uint32Array(pixels);\n }\n this._maxWidth = this._width;\n }\n else if (mode === 1 /* M1 */) {\n if (this._level === 2) {\n // got raster attributes, use them as initial size hint\n const pixels = Math.min(this._rasterWidth, wasm_1.LIMITS.MAX_WIDTH) * this._rasterHeight;\n if (pixels > this._canvas.length) {\n if (this._opts.memoryLimit && pixels * 4 > this._opts.memoryLimit) {\n this.release();\n throw new Error('image exceeds memory limit');\n }\n this._canvas = new Uint32Array(pixels);\n }\n }\n else {\n // else fallback to generic resizing, starting with 256*256 pixels\n if (this._canvas.length < 65536) {\n this._canvas = new Uint32Array(65536);\n }\n }\n }\n return 0; // 0 - continue, 1 - abort right away\n }\n _realloc(offset, additionalPixels) {\n const pixels = offset + additionalPixels;\n if (pixels > this._canvas.length) {\n if (this._opts.memoryLimit && pixels * 4 > this._opts.memoryLimit) {\n this.release();\n throw new Error('image exceeds memory limit');\n }\n // extend in 65536 pixel blocks\n const newCanvas = new Uint32Array(Math.ceil(pixels / 65536) * 65536);\n newCanvas.set(this._canvas);\n this._canvas = newCanvas;\n }\n }\n _handle_band(width) {\n const adv = this._PIXEL_OFFSET;\n let offset = this._lastOffset;\n if (this._mode === 2 /* M2 */) {\n let remaining = this.height - this._currentHeight;\n let c = 0;\n while (c < 6 && remaining > 0) {\n this._canvas.set(this._pSrc.subarray(adv * c, adv * c + width), offset + width * c);\n c++;\n remaining--;\n }\n this._lastOffset += width * c;\n this._currentHeight += c;\n }\n else if (this._mode === 1 /* M1 */) {\n this._realloc(offset, width * 6);\n this._maxWidth = Math.max(this._maxWidth, width);\n this._minWidth = Math.min(this._minWidth, width);\n for (let i = 0; i < 6; ++i) {\n this._canvas.set(this._pSrc.subarray(adv * i, adv * i + width), offset + width * i);\n }\n this._bandWidths.push(width);\n this._lastOffset += width * 6;\n this._currentHeight += 6;\n }\n return 0; // 0 - continue, 1 - abort right away\n }\n /**\n * Width of the image data.\n * Returns the rasterWidth in level2/truncating mode,\n * otherwise the max width, that has been seen so far.\n */\n get width() {\n return this._mode !== 1 /* M1 */\n ? this._width\n : Math.max(this._maxWidth, this._wasm.current_width());\n }\n /**\n * Height of the image data.\n * Returns the rasterHeight in level2/truncating mode,\n * otherwise height touched by sixels.\n */\n get height() {\n return this._mode !== 1 /* M1 */\n ? this._height\n : this._wasm.current_width()\n ? this._bandWidths.length * 6 + this._wasm.current_height()\n : this._bandWidths.length * 6;\n }\n /**\n * Get active palette colors as RGBA8888[] (borrowed).\n */\n get palette() {\n return this._palette.subarray(0, this._paletteLimit);\n }\n /**\n * Get the memory used by the decoder.\n *\n * This is a rough estimate accounting the wasm instance memory\n * and pixel buffers held on JS side (real value will be slightly\n * higher due to JS book-keeping).\n * Note that the decoder does not free ressources on its own,\n * call `release` to free excess memory.\n */\n get memoryUsage() {\n return this._canvas.byteLength + this._wasm.memory.buffer.byteLength + 8 * this._bandWidths.length;\n }\n /**\n * Get various properties of the decoder and the current image.\n */\n get properties() {\n return {\n width: this.width,\n height: this.height,\n mode: this._mode,\n level: this._level,\n truncate: !!this._truncate,\n paletteLimit: this._paletteLimit,\n fillColor: this._fillColor,\n memUsage: this.memoryUsage,\n rasterAttributes: {\n numerator: this._states[4],\n denominator: this._states[5],\n width: this._rasterWidth,\n height: this._rasterHeight,\n }\n };\n }\n /**\n * Initialize decoder for next image. Must be called before\n * any calls to `decode` or `decodeString`.\n */\n // FIXME: reorder arguments, better palette handling\n init(fillColor = this._opts.fillColor, palette = this._opts.palette, paletteLimit = this._opts.paletteLimit, truncate = this._opts.truncate) {\n this._wasm.init(this._opts.sixelColor, fillColor, paletteLimit, truncate ? 1 : 0);\n if (palette) {\n this._palette.set(palette.subarray(0, wasm_1.LIMITS.PALETTE_SIZE));\n }\n this._bandWidths.length = 0;\n this._maxWidth = 0;\n this._minWidth = wasm_1.LIMITS.MAX_WIDTH;\n this._lastOffset = 0;\n this._currentHeight = 0;\n }\n /**\n * Decode next chunk of data from start to end index (exclusive).\n * @throws Will throw if the image exceeds the memory limit.\n */\n decode(data, start = 0, end = data.length) {\n let p = start;\n while (p < end) {\n const length = Math.min(end - p, wasm_1.LIMITS.CHUNK_SIZE);\n this._chunk.set(data.subarray(p, p += length));\n this._wasm.decode(0, length);\n }\n }\n /**\n * Decode next chunk of string data from start to end index (exclusive).\n * Note: Decoding from string data is rather slow, use `decode` with byte data instead.\n * @throws Will throw if the image exceeds the memory limit.\n */\n decodeString(data, start = 0, end = data.length) {\n let p = start;\n while (p < end) {\n const length = Math.min(end - p, wasm_1.LIMITS.CHUNK_SIZE);\n for (let i = 0, j = p; i < length; ++i, ++j) {\n this._chunk[i] = data.charCodeAt(j);\n }\n p += length;\n this._wasm.decode(0, length);\n }\n }\n /**\n * Get current pixel data as 32-bit typed array (RGBA8888).\n * Also peeks into pixel data of the current band, that got not pushed yet.\n */\n get data32() {\n if (this._mode === 0 /* M0 */ || !this.width || !this.height) {\n return NULL_CANVAS;\n }\n // get width of pending band to peek into left-over data\n const currentWidth = this._wasm.current_width();\n if (this._mode === 2 /* M2 */) {\n let remaining = this.height - this._currentHeight;\n if (remaining > 0) {\n const adv = this._PIXEL_OFFSET;\n let offset = this._lastOffset;\n let c = 0;\n while (c < 6 && remaining > 0) {\n this._canvas.set(this._pSrc.subarray(adv * c, adv * c + currentWidth), offset + currentWidth * c);\n c++;\n remaining--;\n }\n if (remaining) {\n this._canvas.fill(this._fillColor, offset + currentWidth * c);\n }\n }\n return this._canvas.subarray(0, this.width * this.height);\n }\n if (this._mode === 1 /* M1 */) {\n if (this._minWidth === this._maxWidth) {\n let escape = false;\n if (currentWidth) {\n if (currentWidth !== this._minWidth) {\n escape = true;\n }\n else {\n const adv = this._PIXEL_OFFSET;\n let offset = this._lastOffset;\n this._realloc(offset, currentWidth * 6);\n for (let i = 0; i < 6; ++i) {\n this._canvas.set(this._pSrc.subarray(adv * i, adv * i + currentWidth), offset + currentWidth * i);\n }\n }\n }\n if (!escape) {\n return this._canvas.subarray(0, this.width * this.height);\n }\n }\n // worst case: re-align pixels if we have bands with different width\n // This is somewhat allocation intensive, any way to do that in-place, and just once?\n const final = new Uint32Array(this.width * this.height);\n final.fill(this._fillColor);\n let finalOffset = 0;\n let start = 0;\n for (let i = 0; i < this._bandWidths.length; ++i) {\n const bw = this._bandWidths[i];\n for (let p = 0; p < 6; ++p) {\n final.set(this._canvas.subarray(start, start += bw), finalOffset);\n finalOffset += this.width;\n }\n }\n // also handle left-over pixels of the current band\n if (currentWidth) {\n const adv = this._PIXEL_OFFSET;\n // other than finished bands, this runs only up to currentHeight\n const currentHeight = this._wasm.current_height();\n for (let i = 0; i < currentHeight; ++i) {\n final.set(this._pSrc.subarray(adv * i, adv * i + currentWidth), finalOffset + this.width * i);\n }\n }\n return final;\n }\n // fallthrough for all not handled cases\n return NULL_CANVAS;\n }\n /**\n * Same as `data32`, but returning pixel data as Uint8ClampedArray suitable\n * for direct usage with `ImageData`.\n */\n get data8() {\n return new Uint8ClampedArray(this.data32.buffer, 0, this.width * this.height * 4);\n }\n /**\n * Release image ressources on JS side held by the decoder.\n *\n * The decoder tries to re-use memory ressources of a previous image\n * to lower allocation and GC pressure. Decoding a single big image\n * will grow the memory usage of the decoder permanently.\n * Call `release` to reset the internal buffers and free the memory.\n * Note that this destroys the image data, call it when done processing\n * a rather big image, otherwise it is not needed. Use `memoryUsage`\n * to decide, whether the held memory is still within your limits.\n * This does not affect the wasm module (operates on static memory).\n */\n release() {\n this._canvas = NULL_CANVAS;\n this._bandWidths.length = 0;\n this._maxWidth = 0;\n this._minWidth = wasm_1.LIMITS.MAX_WIDTH;\n // also nullify parser states in wasm to avoid\n // width/height reporting potential out-of-bound values\n this._wasm.init(Colors_1.DEFAULT_FOREGROUND, 0, this._opts.paletteLimit, 0);\n }\n}\nexports.Decoder = Decoder;\n/**\n * Convenient decoding functions for easier usage.\n *\n * These can be used for casual decoding of sixel images,\n * that dont come in as stream chunks.\n * Note that the functions instantiate a stream decoder for every call,\n * which comes with a performance penalty of ~25%.\n */\n/**\n * Decode function with synchronous wasm loading.\n * Can be used in a web worker or in nodejs. Does not work reliable in normal browser context.\n * @throws Will throw if the image exceeds the memory limit.\n */\nfunction decode(data, opts) {\n const dec = new Decoder(opts);\n dec.init();\n typeof data === 'string' ? dec.decodeString(data) : dec.decode(data);\n return {\n width: dec.width,\n height: dec.height,\n data32: dec.data32,\n data8: dec.data8\n };\n}\nexports.decode = decode;\n/**\n * Decode function with asynchronous wasm loading.\n * Use this version in normal browser context.\n * @throws Will throw if the image exceeds the memory limit.\n */\nasync function decodeAsync(data, opts) {\n const dec = await DecoderAsync(opts);\n dec.init();\n typeof data === 'string' ? dec.decodeString(data) : dec.decode(data);\n return {\n width: dec.width,\n height: dec.height,\n data32: dec.data32,\n data8: dec.data8\n };\n}\nexports.decodeAsync = decodeAsync;\n//# sourceMappingURL=Decoder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LIMITS = void 0;\nexports.LIMITS = {\n CHUNK_SIZE: 16384,\n PALETTE_SIZE: 4096,\n MAX_WIDTH: 16384,\n BYTES: 'AGFzbQEAAAABJAdgAAF/YAJ/fwBgA39/fwF/YAF/AX9gAABgBH9/f38AYAF/AAIlAgNlbnYLaGFuZGxlX2JhbmQAAwNlbnYLbW9kZV9wYXJzZWQAAwMTEgQAAAAAAQQBAQUBAAACAgAGAwQFAXABBwcFBAEBBwcGCAF/AUGAihoLB9wBDgZtZW1vcnkCABFnZXRfc3RhdGVfYWRkcmVzcwADEWdldF9jaHVua19hZGRyZXNzAAQOZ2V0X3AwX2FkZHJlc3MABRNnZXRfcGFsZXR0ZV9hZGRyZXNzAAYEaW5pdAALBmRlY29kZQAMDWN1cnJlbnRfd2lkdGgADQ5jdXJyZW50X2hlaWdodAAOGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtfaW5pdGlhbGl6ZQACCXN0YWNrU2F2ZQARDHN0YWNrUmVzdG9yZQASCnN0YWNrQWxsb2MAEwkMAQBBAQsGCgcJDxACDAEBCq5UEgMAAQsFAEGgCAsGAEGQiQELBgBBsIkCCw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gADcDAEHoiwIgADcDAEHgiwIgADcDAEHYiwIgADcDAEHQiwIgADcDAEHIiwIgADcDAEHAiwIgADcDAEG4iwIgADcDAEGwiwIgADcDAEGoiwIgADcDAEGgiwIgADcDAEGYiwIgADcDAEGQiwIgADcDAEGIiwIgADcDAEGAiwIgADcDAEH4igIgADcDAEHwigIgADcDAEHoigIgADcDAEHgigIgADcDAEHYigIgADcDAEHQigIgADcDAEHIigIgADcDAEHAigIgADcDAEG4igIgADcDAEGwigIgADcDAEGoigIgADcDAEGgigIgADcDAEGYigIgADcDAEGQigIgADcDAEGIigIgADcDAEGAigIgADcDAEH4iQIgADcDAEHwiQIgADcDAEHoiQIgADcDAEHgiQIgADcDAEHYiQIgADcDAEHQiQIgADcDAEHIiQIgADcDAEHAiQIgADcDAEG4iQIgADcDAEGwiQIgADcDAEGoCCgCACIEQf8AakGAAW0hCAJAIARBgQFIDQBBASEBIAhBAiAIQQJKG0EBayICQQFxIQMgBEGBAk4EQCACQX5xIQIDQCABQQl0IgdBEHJBoIkCakGwiQJBgAT8CgAAIAdBsI0CakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsLIANFDQAgAUEJdEEQckGgiQJqQbCJAkGABPwKAAALAkAgBEEBSA0AIAhBASAIQQFKGyIDQQFxIQUCQCADQQFrIgdFBEBBACEBDAELIANB/v///wdxIQJBACEBA0AgAUEJdCIGQRByQbCJBmpBsIkCQYAE/AoAACAGQZAEckGwiQZqQbCJAkGABPwKAAAgAUECaiEBIAJBAmsiAg0ACwsgBQRAIAFBCXRBEHJBsIkGakGwiQJBgAT8CgAACyAEQQFIDQAgA0EBcSEFIAcEfyADQf7///8HcSECQQAhAQNAIAFBCXQiBkEQckHAiQpqQbCJAkGABPwKAAAgBkGQBHJBwIkKakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsgAUEHdEEEcgVBBAshASAFBEAgAUECdEHAiQpqQbCJAkGABPwKAAALIARBAUgNACADQQFxIQUgBwR/IANB/v///wdxIQJ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ACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwsYAQBBgAgLEQEAAAACAAAAAwAAAAQAAAAF'\n};\n//# sourceMappingURL=wasm.js.map","/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal event utilities for xterm.js core.\n * Simplified from VS Code's event.ts - no leak detection/profiling.\n */\n\nimport { IDisposable, DisposableStore, toDisposable } from './Lifecycle';\n\nexport interface IEvent {\n (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable;\n}\n\nexport class Emitter {\n private _listeners: { fn: (e: T) => any, thisArgs: any }[] = [];\n private _disposed = false;\n private _event: IEvent | undefined;\n\n public get event(): IEvent {\n if (this._event) {\n return this._event;\n }\n this._event = (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n if (this._disposed) {\n return toDisposable(() => {});\n }\n\n const entry = { fn: listener, thisArgs };\n this._listeners = this._listeners.slice();\n this._listeners.push(entry);\n\n const result = toDisposable(() => {\n const idx = this._listeners.indexOf(entry);\n if (idx !== -1) {\n this._listeners = this._listeners.slice();\n this._listeners.splice(idx, 1);\n }\n });\n\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(result);\n } else {\n disposables.add(result);\n }\n }\n\n return result;\n };\n return this._event;\n }\n\n public fire(event: T): void {\n if (this._disposed || !this._listeners.length) {\n return;\n }\n if (this._listeners.length === 1) {\n this._listeners[0].fn.call(this._listeners[0].thisArgs, event);\n return;\n }\n const listeners = this._listeners;\n for (let i = 0, len = listeners.length; i < len; ++i) {\n listeners[i].fn.call(listeners[i].thisArgs, event);\n }\n }\n\n public dispose(): void {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._listeners.length = 0;\n }\n}\n\nexport namespace EventUtils {\n export function forward(from: IEvent, to: Emitter): IDisposable {\n return from(e => to.fire(e));\n }\n\n export function map(event: IEvent, map: (i: I) => O): IEvent {\n return (listener: (e: O) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n return event(i => listener.call(thisArgs, map(i)), undefined, disposables);\n };\n }\n\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent {\n return (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n const store = new DisposableStore();\n for (const event of events) {\n store.add(event(e => listener.call(thisArgs, e)));\n }\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(store);\n } else {\n disposables.add(store);\n }\n }\n return store;\n };\n }\n\n export function runAndSubscribe(event: IEvent, handler: (e: T) => void, initial: T): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void, initial?: T): IDisposable {\n handler(initial);\n return event(e => handler(e));\n }\n}\n","/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal lifecycle utilities for xterm.js core.\n * Simplified from VS Code's lifecycle.ts - no tracking/leak detection.\n */\n\nexport interface IDisposable {\n dispose(): void;\n}\n\nexport function toDisposable(fn: () => void): IDisposable {\n return { dispose: fn };\n}\n\nexport function dispose(disposable: T): T;\nexport function dispose(disposable: T | undefined): T | undefined;\nexport function dispose(disposables: T[]): T[];\nexport function dispose(arg: T | T[] | undefined): T | T[] | undefined {\n if (!arg) {\n return arg;\n }\n if (Array.isArray(arg)) {\n for (const d of arg) {\n d.dispose();\n }\n return [];\n }\n arg.dispose();\n return arg;\n}\n\nexport function combinedDisposable(...disposables: IDisposable[]): IDisposable {\n return toDisposable(() => dispose(disposables));\n}\n\nexport class DisposableStore implements IDisposable {\n private readonly _disposables = new Set();\n private _isDisposed = false;\n\n public get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n public add(o: T): T {\n if (this._isDisposed) {\n o.dispose();\n } else {\n this._disposables.add(o);\n }\n return o;\n }\n\n public dispose(): void {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n\n public clear(): void {\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n}\n\nexport abstract class Disposable implements IDisposable {\n public static readonly None: IDisposable = Object.freeze({ dispose() { } });\n\n protected readonly _store = new DisposableStore();\n\n public dispose(): void {\n this._store.dispose();\n }\n\n protected _register(o: T): T {\n return this._store.add(o);\n }\n}\n\nexport class MutableDisposable implements IDisposable {\n private _value: T | undefined;\n private _isDisposed = false;\n\n public get value(): T | undefined {\n return this._isDisposed ? undefined : this._value;\n }\n\n public set value(value: T | undefined) {\n if (this._isDisposed || value === this._value) {\n return;\n }\n this._value?.dispose();\n this._value = value;\n }\n\n public clear(): void {\n this.value = undefined;\n }\n\n public dispose(): void {\n this._isDisposed = true;\n this._value?.dispose();\n this._value = undefined;\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IImageAddonOptions, IOscHandler, IResetHandler, ITerminalExt } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { CELL_SIZE_DEFAULT } from './ImageStorage';\nimport Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport QoiDecoder from 'xterm-wasm-parts/lib/qoi/QoiDecoder.wasm';\nimport { HeaderParser, IHeaderFields, HeaderState, SequenceType } from './IIPHeaderParser';\nimport { imageType, UNSUPPORTED_TYPE } from './IIPMetrics';\n\n// Local const enum mirror - esbuild can't inline const enums from external packages\nconst enum DecoderConst {\n // Held memory in base64/QOI decoders between images. Zero because each kept\n // decoder pins a wasm memory, and V8 caps those per process (~124 in a\n // sandboxed renderer), so idle terminals must not hold one.\n KEEP_DATA = 0,\n // Initial buffer allocation for the decoder.\n INITIAL_DATA = 1048576,\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n OK = 0\n}\n\n// default IIP header values\nconst DEFAULT_HEADER: IHeaderFields = {\n type: SequenceType.INVALID,\n name: 'Unnamed file',\n size: 0,\n width: 'auto',\n height: 'auto',\n preserveAspectRatio: 1,\n inline: 0\n};\n\n\nexport class IIPHandler implements IOscHandler, IResetHandler {\n private _generation = 0;\n private _aborted = false;\n private _hp = new HeaderParser();\n private _header: IHeaderFields = DEFAULT_HEADER;\n private _dec: Base64Decoder;\n private _qoiDec: QoiDecoder;\n private _isMultipart = false;\n private _abortMulti = false;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _storage: IIPImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n const maxEncodedBytes = Math.ceil(this._opts.iipSizeLimit * 4 / 3);\n const initialBytes = Math.min(DecoderConst.INITIAL_DATA, maxEncodedBytes);\n this._dec = new Base64Decoder(DecoderConst.KEEP_DATA, maxEncodedBytes, initialBytes);\n this._qoiDec = new QoiDecoder(DecoderConst.KEEP_DATA);\n }\n\n public reset(): void {\n this._generation++;\n this._hp.reset();\n this._dec.release();\n this._qoiDec.release();\n }\n\n public start(): void {\n this._aborted = false;\n this._hp.reset();\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (this._hp.state === HeaderState.END) {\n if ((this._dec.put(data.subarray(start, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n }\n } else {\n const dataPos = this._hp.parse(data, start, end);\n if (dataPos === -1) {\n this._aborted = true;\n return;\n }\n if (dataPos > 0) {\n const seqType = this._hp.fields.type;\n if (seqType === SequenceType.FILE) {\n if (this._isMultipart) {\n this._isMultipart = false;\n this._abortMulti = false;\n this._dec.release();\n }\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n if (!this._header.inline) {\n this._aborted = true;\n return;\n }\n if (!this._initDecoder()) {\n this._aborted = true;\n return;\n }\n } else if (this._abortMulti) {\n this._aborted = true;\n return;\n }\n if ((this._dec.put(data.subarray(dataPos, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n if (this._isMultipart) this._abortMulti = true;\n }\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted) return true;\n\n if (this._hp.state !== HeaderState.END) {\n if (this._hp.end()) return true;\n }\n const seqType = this._hp.fields.type;\n\n if (seqType === SequenceType.FILEPART) return true;\n\n if (seqType === SequenceType.REPORTCELLSIZE) {\n // OSC 1337 ; ReportCellSize=[height];[width];[scale] ST\n let w = CELL_SIZE_DEFAULT.width;\n let h = CELL_SIZE_DEFAULT.height;\n if (this._renderer.dimensions) {\n w = this._renderer.dimensions.css.canvas.width / this._coreTerminal.cols;\n h = this._renderer.dimensions.css.canvas.height / this._coreTerminal.rows;\n }\n const scale = this._coreTerminal._core._coreBrowserService?.dpr ?? 1;\n const report = `\\x1b]1337;ReportCellSize=${h.toFixed(3)};${w.toFixed(3)};${scale.toFixed(3)}\\x1b\\\\`;\n this._coreTerminal.input(report, false);\n return true;\n }\n\n if (seqType === SequenceType.MULTIPARTFILE) {\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n this._isMultipart = true;\n this._abortMulti = false;\n this._dec.release();\n if (!this._initDecoder()) {\n this._abortMulti = true;\n }\n return true;\n }\n\n if (seqType === SequenceType.FILEEND) {\n if (!this._isMultipart) return true;\n this._isMultipart = false;\n if (this._abortMulti || this._header.type !== SequenceType.MULTIPARTFILE) return true;\n }\n\n // fallthrough for SequenceType.FILE & SequenceType.FILEEND\n\n let w = 0;\n let h = 0;\n\n // early exit condition chain\n let cond: number | boolean;\n let metrics = UNSUPPORTED_TYPE;\n if (cond = success) {\n if (cond = !this._dec.end()) {\n metrics = imageType(this._dec.data8);\n if (cond = metrics.mime !== 'unsupported') {\n w = metrics.width;\n h = metrics.height;\n if (cond = w && h && w * h < this._opts.pixelLimit) {\n [w, h] = this._resize(w, h).map(Math.floor);\n cond = w && h && w * h < this._opts.pixelLimit;\n } else {\n console.warn(`IIP: image dimension issue ${metrics.width}x${metrics.height}`);\n }\n } else {\n console.warn('IIP: unsupported image type');\n }\n } else {\n console.warn('IIP: error during BASE64 decoding');\n }\n }\n if (!cond) {\n this._dec.release();\n return true;\n }\n\n let blob: Blob | ImageData;\n if (metrics.mime === 'image/qoi') {\n let data: Uint8Array;\n try {\n data = this._qoiDec.decode(this._dec.data8);\n } catch (e) {\n console.warn('IIP: could not decode QOI image', e);\n this._dec.release();\n this._qoiDec.release();\n return true;\n }\n blob = new ImageData(\n new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength),\n this._qoiDec.width,\n this._qoiDec.height\n );\n this._qoiDec.release();\n if (w === this._qoiDec.width && h === this._qoiDec.height) {\n // use fast-path if we don't need to rescale\n this._dec.release();\n const canvas = ImageRenderer.createCanvas(undefined, this._qoiDec.width, this._qoiDec.height);\n canvas.getContext('2d')?.putImageData(blob, 0, 0);\n this._storage.addImage(canvas);\n return true;\n }\n } else {\n blob = new Blob([this._dec.data8], { type: metrics.mime });\n }\n this._dec.release();\n const generation = this._generation;\n return createImageBitmap(blob, { resizeWidth: w, resizeHeight: h })\n .then(bm => {\n if (generation !== this._generation) {\n bm.close();\n return true;\n }\n this._storage.addImage(bm);\n return true;\n })\n .catch(e => {\n console.warn(`IIP: decoding error ${metrics.mime} ${metrics.width}x${metrics.height}`, e);\n return true;\n });\n }\n\n // Why: wasm memory exhaustion must drop this image, not throw out of the parser and wedge the write queue.\n private _initDecoder(): boolean {\n try {\n this._dec.init();\n return true;\n } catch (e) {\n console.warn('IIP: could not allocate decoder', e);\n this._dec.release();\n return false;\n }\n }\n\n private _resize(w: number, h: number): [number, number] {\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n const width = this._renderer.dimensions?.css.canvas.width || cw * this._coreTerminal.cols;\n const height = this._renderer.dimensions?.css.canvas.height || ch * this._coreTerminal.rows;\n\n const rw = this._dim(this._header.width!, width, cw);\n const rh = this._dim(this._header.height!, height, ch);\n if (!rw && !rh) {\n const wf = width / w; // TODO: should this respect initial cursor offset?\n const hf = (height - ch) / h; // TODO: fix offset issues from float cell height\n const f = Math.min(wf, hf);\n return f < 1 ? [w * f, h * f] : [w, h];\n }\n return !rw\n ? [w * rh / h, rh]\n : this._header.preserveAspectRatio || !rw || !rh\n ? [rw, h * rw / w] : [rw, rh];\n }\n\n private _dim(s: string, total: number, cdim: number): number {\n if (s === 'auto') return 0;\n if (s.endsWith('%')) return parseInt(s.slice(0, -1), 10) * total / 100;\n if (s.endsWith('px')) return parseInt(s.slice(0, -2), 10);\n return parseInt(s, 10) * cdim;\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n// eslint-disable-next-line\ndeclare const Buffer: any;\n\nexport const enum HeaderState {\n START = 0,\n ABORT = 1,\n KEY = 2,\n VALUE = 3,\n END = 4\n}\n\nexport const enum SequenceType {\n INVALID = 0,\n FILE = 1,\n MULTIPARTFILE = 2,\n FILEPART = 3,\n FILEEND = 4,\n REPORTCELLSIZE = 5\n}\n\nexport interface IHeaderFields {\n [key: string]: number | string | Uint32Array | null | undefined;\n // sequence type\n type: SequenceType;\n // base-64 encoded filename. Defaults to \"Unnamed file\".\n name: string;\n // File size in bytes. The file transfer will be canceled if this size is exceeded.\n size: number;\n /**\n * Optional width and height to render:\n * - N: N character cells.\n * - Npx: N pixels.\n * - N%: N percent of the session's width or height.\n * - auto: The image's inherent size will be used to determine an appropriate dimension.\n */\n width?: string;\n height?: string;\n // Optional, defaults to 1 respecting aspect ratio (width takes precedence).\n preserveAspectRatio?: number;\n // Optional, defaults to 0. If set to 1, the file will be displayed inline, else downloaded\n // (download not supported).\n inline?: number;\n}\n\n// field value decoders\n\n// ASCII bytes to string\nfunction toStr(data: Uint32Array): string {\n let s = '';\n for (let i = 0; i < data.length; ++i) {\n s += String.fromCharCode(data[i]);\n }\n return s;\n}\n\n// digits to integer\nfunction toInt(data: Uint32Array): number {\n let v = 0;\n for (let i = 0; i < data.length; ++i) {\n if (data[i] < 48 || data[i] > 57) {\n throw new Error('illegal char');\n }\n v = v * 10 + data[i] - 48;\n }\n return v;\n}\n\n// check for correct size entry\nfunction toSize(data: Uint32Array): string {\n const v = toStr(data);\n if (!v.match(/^((auto)|(\\d+?((px)|(%)){0,1}))$/)) {\n throw new Error('illegal size');\n }\n return v;\n}\n\n// name is base64 encoded utf-8\nfunction toName(data: Uint32Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(toStr(data), 'base64').toString();\n }\n const bs = atob(toStr(data));\n const b = new Uint8Array(bs.length);\n for (let i = 0; i < b.length; ++i) {\n b[i] = bs.charCodeAt(i);\n }\n return new TextDecoder().decode(b);\n}\n\nconst DECODERS: {[key: string]: (v: Uint32Array) => number | string} = {\n inline: toInt,\n size: toInt,\n name: toName,\n width: toSize,\n height: toSize,\n preserveAspectRatio: toInt\n};\n\n\n// sequence type markers\n// File\nconst FILE_MARKER = [70, 105, 108, 101];\n// MultipartFile\nconst MULTIPARTFILE_MARKER = [77, 117, 108, 116, 105, 112, 97, 114, 116, 70, 105, 108, 101];\n// FilePart\nconst FILEPART_MARKER = [70, 105, 108, 101, 80, 97, 114, 116];\n// FileEnd\nconst FILEEND_MARKER = [70, 105, 108, 101, 69, 110, 100];\n// ReportCellSize\nconst REPORTCELLSIZE_MARKER = [82, 101, 112, 111, 114, 116, 67, 101, 108, 108, 83, 105, 122, 101];\n\n// max allowed chars for sequence header\nconst MAX_FIELDCHARS = 1024;\n\n\nexport class HeaderParser {\n public state: HeaderState = HeaderState.START;\n private _buffer = new Uint32Array(MAX_FIELDCHARS);\n private _position = 0;\n private _key = '';\n public fields: {[key: string]: number | string | Uint32Array | null | undefined} = {};\n\n public reset(): void {\n this._buffer.fill(0);\n this.state = HeaderState.START;\n this._position = 0;\n this.fields = {};\n this._key = '';\n }\n\n public end(): number {\n if (this.state === HeaderState.START) {\n if (this._position === FILEEND_MARKER.length) {\n for (let k = 0; k < FILEEND_MARKER.length; ++k) {\n if (this._buffer[k] !== FILEEND_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEEND;\n this.state = HeaderState.END;\n return 0;\n }\n if (this._position === REPORTCELLSIZE_MARKER.length) {\n for (let k = 0; k < REPORTCELLSIZE_MARKER.length; ++k) {\n if (this._buffer[k] !== REPORTCELLSIZE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.REPORTCELLSIZE;\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n if (this.state === HeaderState.END) return 0;\n if (this.state === HeaderState.VALUE\n && this.fields.type === SequenceType.MULTIPARTFILE\n ) {\n if (!this._storeValue(this._position)) return this._a();\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n\n public parse(data: Uint32Array, start: number, end: number): number {\n let state = this.state;\n let pos = this._position;\n const buffer = this._buffer;\n if (state === HeaderState.ABORT || state === HeaderState.END) return -1;\n if (state === HeaderState.START && pos > 14) return -1;\n for (let i = start; i < end; ++i) {\n const c = data[i];\n switch (c) {\n case 59: // ;\n if (!this._storeValue(pos)) return this._a();\n state = HeaderState.KEY;\n pos = 0;\n break;\n case 61: // =\n if (state === HeaderState.START) {\n if (buffer[0] === 70) {\n // 'File' or 'FilePart'\n let k = 0;\n for (; k < FILE_MARKER.length; ++k) {\n if (buffer[k] !== FILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILE;\n if (pos === FILEPART_MARKER.length) {\n for (; k < FILEPART_MARKER.length; ++k) {\n if (buffer[k] !== FILEPART_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEPART;\n this.state = HeaderState.END;\n return i + 1;\n }\n } else if (buffer[0] === 77) {\n // 'MultipartFile'\n for (let k = 0; k < MULTIPARTFILE_MARKER.length; ++k) {\n if (buffer[k] !== MULTIPARTFILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.MULTIPARTFILE;\n } else {\n return this._a();\n }\n state = HeaderState.KEY;\n pos = 0;\n } else if (state === HeaderState.KEY) {\n if (!this._storeKey(pos)) return this._a();\n state = HeaderState.VALUE;\n pos = 0;\n } else if (state === HeaderState.VALUE) {\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n break;\n case 58: // :\n if (state === HeaderState.VALUE) {\n if (!this._storeValue(pos)) return this._a();\n }\n this.state = HeaderState.END;\n return i + 1;\n default:\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n }\n this.state = state;\n this._position = pos;\n return -2;\n }\n\n private _a(): number {\n this.fields.type = SequenceType.INVALID;\n this.state = HeaderState.ABORT;\n return -1;\n }\n\n private _storeKey(pos: number): boolean {\n const k = toStr(this._buffer.subarray(0, pos));\n if (k) {\n this._key = k;\n this.fields[k] = null;\n return true;\n }\n return false;\n }\n\n private _storeValue(pos: number): boolean {\n if (this._key) {\n try {\n const v = this._buffer.slice(0, pos);\n this.fields[this._key] = DECODERS[this._key] ? DECODERS[this._key](v) : v;\n } catch {\n return false;\n }\n return true;\n }\n return false;\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IAddImageOpts } from './Types';\nimport { ImageStorage } from './ImageStorage';\n\n/**\n * IIP (iTerm Image Protocol) specific image storage controller.\n *\n * Wraps the shared ImageStorage with IIP protocol semantics:\n * - Always uses scrolling mode (cursor advances with image)\n */\nexport class IIPImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n constructor(\n private readonly _storage: ImageStorage\n ) {}\n\n /**\n * Add an IIP image to storage.\n * Always uses scrolling mode — cursor advances past the image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._storage.addImage(img, this._addImageOpts);\n }\n}\n","/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n\nexport type ImageType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/qoi' | 'image/webp' | 'image/avif' | 'unsupported' | '';\n\nexport interface IMetrics {\n mime: ImageType;\n width: number;\n height: number;\n}\n\nexport const UNSUPPORTED_TYPE: IMetrics = {\n mime: 'unsupported',\n width: 0,\n height: 0\n};\n\nexport function imageType(d: Uint8Array): IMetrics {\n if (d.length < 32) {\n return UNSUPPORTED_TYPE;\n }\n const d32 = new Uint32Array(d.buffer, d.byteOffset, 8);\n // PNG: 89 50 4E 47 0D 0A 1A 0A (8 first bytes == magic number for PNG)\n // + first chunk must be IHDR\n if (d32[0] === 0x474E5089 && d32[1] === 0x0A1A0A0D && d32[3] === 0x52444849) {\n return {\n mime: 'image/png',\n width: d[16] << 24 | d[17] << 16 | d[18] << 8 | d[19],\n height: d[20] << 24 | d[21] << 16 | d[22] << 8 | d[23]\n };\n }\n // JPEG: FF D8 FF\n if (d[0] === 0xFF && d[1] === 0xD8 && d[2] === 0xFF) {\n const [width, height] = jpgSize(d);\n return { mime: 'image/jpeg', width, height };\n }\n // GIF: GIF87a or GIF89a\n if (d32[0] === 0x38464947 && (d[4] === 0x37 || d[4] === 0x39) && d[5] === 0x61) {\n return {\n mime: 'image/gif',\n width: d[7] << 8 | d[6],\n height: d[9] << 8 | d[8]\n };\n }\n // QOI: qoif\n if (d32[0] === 0x66696F71) {\n return {\n mime: 'image/qoi',\n width: d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7],\n height: d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11]\n };\n }\n // WEBP: RIFF | xxxx | WEBP | VP8x\n if (d32[0] === 0x46464952 && d32[2] === 0x50424557 && (d32[3] & 0xFFFFFF) === 0x385056) {\n switch (d[15]) {\n case 0x58: // Extended WebP VP8X --> \"X\"\n return {\n mime: 'image/webp',\n width: (d[24] | d[25] << 8 | d[26] << 16) + 1,\n height: (d[27] | d[28] << 8 | d[29] << 16) + 1\n };\n case 0x4C: // Lossless WebP VP8L --> \"L\"\n if (d[20] !== 0x2f) return UNSUPPORTED_TYPE;\n const dim = d[21] | d[22] << 8 | d[23] << 16 | d[24] << 24;\n return {\n mime: 'image/webp',\n width: (dim & 0x3FFF) + 1,\n height: (dim >>> 14 & 0x3FFF) + 1\n };\n case 0x20: // Lossy WebP VP8 --> \" \"\n if (d[23] !== 0x9d || d[24] !== 0x01 || d[25] !== 0x2a) return UNSUPPORTED_TYPE;\n return {\n mime: 'image/webp',\n width: (d[26] | d[27] << 8) & 0x3FFF,\n height: (d[28] | d[29] << 8) & 0x3FFF\n };\n }\n return UNSUPPORTED_TYPE;\n }\n // AVIF: Box size | ftyp | avif/avis\n if (d32[1] === 0x70797466 && (d32[2] === 0x66697661 || d32[2] === 0x73697661)) {\n let pos = -1;\n // search for ispe box within first 1024 bytes\n const limit = Math.min(d.length - 16, 1024);\n for (let i = 8; i < limit; i++) {\n // scan for ispe\n if (d[i] === 0x69 && d[i + 1] === 0x73 && d[i + 2] === 0x70 && d[i + 3] === 0x65) {\n pos = i;\n break;\n }\n }\n if (pos !== -1) {\n // dimensions are in BE at +8 (width) at +12 (height)\n const width =\n d[pos + 8] << 24 |\n d[pos + 9] << 16 |\n d[pos + 10] << 8 |\n d[pos + 11];\n const height =\n d[pos + 12] << 24 |\n d[pos + 13] << 16 |\n d[pos + 14] << 8 |\n d[pos + 15];\n if (width > 0 && height > 0) {\n return { mime: 'image/avif', width, height };\n }\n }\n return UNSUPPORTED_TYPE;\n }\n return UNSUPPORTED_TYPE;\n}\n\n\nfunction jpgSize(d: Uint8Array): [number, number] {\n const len = d.length;\n let i = 4;\n let blockLength = d[i] << 8 | d[i + 1];\n while (true) {\n i += blockLength;\n if (i >= len) {\n // exhausted without size info\n return [0, 0];\n }\n if (d[i] !== 0xFF) {\n return [0, 0];\n }\n if (d[i + 1] === 0xC0 || d[i + 1] === 0xC2) {\n if (i + 8 < len) {\n return [\n d[i + 7] << 8 | d[i + 8],\n d[i + 5] << 8 | d[i + 6]\n ];\n }\n return [0, 0];\n }\n i += 2;\n blockLength = d[i] << 8 | d[i + 1];\n }\n}\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { toRGBA8888 } from 'sixel/lib/Colors';\nimport { IDisposable } from '@xterm/xterm';\nimport { ICellSize, ImageLayer, ITerminalExt, IImageSpec, IRenderDimensions, IRenderService } from './Types';\nimport { Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';\n\nconst enum Constants {\n PLACEHOLDER_LENGTH = 4096,\n PLACEHOLDER_HEIGHT = 24\n}\n\n/**\n * ImageRenderer - terminal frontend extension:\n * - provide primitives for canvas, ImageData, Bitmap (static)\n * - add canvas layer to DOM (browser only for now)\n * - draw image tiles onRender\n */\nexport class ImageRenderer extends Disposable implements IDisposable {\n /** @deprecated Kept for backward compat — points to top layer canvas. */\n public get canvas(): HTMLCanvasElement | undefined { return this._layers.get('top')?.canvas; }\n private _layers = new Map();\n private _placeholder: HTMLCanvasElement | undefined;\n private _placeholderBitmap: ImageBitmap | undefined;\n private _optionsRefresh = this._register(new MutableDisposable());\n private _oldOpen: ((parent: HTMLElement) => void) | undefined;\n private _renderService: IRenderService | undefined;\n private _oldSetRenderer: ((renderer: any) => void) | undefined;\n\n // drawing primitive - canvas\n public static createCanvas(localDocument: Document | undefined, width: number, height: number): HTMLCanvasElement {\n /**\n * NOTE: We normally dont care, from which document the canvas\n * gets created, so we can fall back to global document,\n * if the terminal has no document associated yet.\n * This way early image loads before calling .open keep working\n * (still discouraged though, as the metrics will be screwed up).\n * Only the DOM output canvas should be on the terminal's document,\n * which gets explicitly checked in `insertLayerToDom`.\n */\n const canvas = (localDocument ?? document).createElement('canvas');\n canvas.width = width | 0;\n canvas.height = height | 0;\n return canvas;\n }\n\n // drawing primitive - ImageData with optional buffer\n public static createImageData(ctx: CanvasRenderingContext2D, width: number, height: number, buffer?: ArrayBuffer): ImageData {\n if (typeof ImageData !== 'function') {\n const imgData = ctx.createImageData(width, height);\n if (buffer) {\n imgData.data.set(new Uint8ClampedArray(buffer, 0, width * height * 4));\n }\n return imgData;\n }\n return buffer\n ? new ImageData(new Uint8ClampedArray(buffer, 0, width * height * 4), width, height)\n : new ImageData(width, height);\n }\n\n // drawing primitive - ImageBitmap\n public static createImageBitmap(img: ImageBitmapSource): Promise {\n if (typeof createImageBitmap !== 'function') {\n return Promise.resolve(undefined);\n }\n return createImageBitmap(img);\n }\n\n\n constructor(private _terminal: ITerminalExt) {\n super();\n this._oldOpen = this._terminal._core.open;\n this._terminal._core.open = (parent: HTMLElement): void => {\n this._oldOpen?.call(this._terminal._core, parent);\n this._open();\n };\n if (this._terminal._core.screenElement) {\n this._open();\n }\n // hack to spot fontSize changes\n this._optionsRefresh.value = this._terminal._core.optionsService.onOptionChange(option => {\n if (option === 'fontSize') {\n this.rescaleCanvas();\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n });\n this._register(toDisposable(() => {\n this.removeLayerFromDom();\n this.removeLayerFromDom('bottom');\n if (this._terminal._core && this._oldOpen) {\n this._terminal._core.open = this._oldOpen;\n this._oldOpen = undefined;\n }\n if (this._renderService && this._oldSetRenderer) {\n this._renderService.setRenderer = this._oldSetRenderer;\n this._oldSetRenderer = undefined;\n }\n this._renderService = undefined;\n this._layers.clear();\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }));\n }\n\n /**\n * Enable the placeholder.\n */\n public showPlaceholder(value: boolean): void {\n if (value) {\n if (!this._placeholder && this.cellSize.height !== -1) {\n this._createPlaceHolder(Math.max(this.cellSize.height + 1, Constants.PLACEHOLDER_HEIGHT));\n }\n } else {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n\n /**\n * Dimensions of the terminal.\n * Forwarded from internal render service.\n */\n public get dimensions(): IRenderDimensions | undefined {\n return this._terminal.dimensions;\n }\n\n /**\n * Current cell size (float).\n */\n public get cellSize(): ICellSize {\n return {\n width: this.dimensions?.css.cell.width || -1,\n height: this.dimensions?.css.cell.height || -1\n };\n }\n\n /**\n * Clear a region of the image layer canvas.\n */\n public clearLines(start: number, end: number, layer?: ImageLayer): void {\n const y = start * (this.dimensions?.css.cell.height || 0);\n const w = this.dimensions?.css.canvas.width || 0;\n const h = (end + 1 - start) * (this.dimensions?.css.cell.height || 0);\n if (!layer || layer === 'top') {\n this._layers.get('top')?.clearRect(0, y, w, h);\n }\n if (!layer || layer === 'bottom') {\n this._layers.get('bottom')?.clearRect(0, y, w, h);\n }\n }\n\n /**\n * Clear whole image canvas.\n */\n public clearAll(layer?: ImageLayer): void {\n if (!layer || layer === 'top') {\n const ctx = this._layers.get('top');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n if (!layer || layer === 'bottom') {\n const ctx = this._layers.get('bottom');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n }\n\n /**\n * Draw neighboring tiles on the image layer canvas.\n */\n public draw(imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get(imgSpec.layer);\n if (!ctx) {\n return;\n }\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const { width: sourceWidth, height: sourceHeight } = imgSpec.actualCellSize;\n const cols = Math.ceil(img.width / sourceWidth);\n\n const sx = (tileId % cols) * sourceWidth;\n const sy = Math.floor(tileId / cols) * sourceHeight;\n const dx = col * width;\n const dy = row * height;\n\n // safari bug: never access image source out of bounds\n const finalWidth = count * sourceWidth + sx > img.width ? img.width - sx : count * sourceWidth;\n const finalHeight = sy + sourceHeight > img.height ? img.height - sy : sourceHeight;\n\n // Floor all pixel offsets to get stable tile mapping without any overflows.\n // Note: For not pixel perfect aligned cells like in the DOM renderer\n // this will move a tile slightly to the top/left (subpixel range, thus ignore it).\n // FIX #34: avoid striping on displays with pixelDeviceRatio != 1 by ceiling height and width\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.ceil(finalWidth), Math.ceil(finalHeight),\n Math.floor(dx), Math.floor(dy), Math.ceil(finalWidth * width / sourceWidth), Math.ceil(finalHeight * height / sourceHeight)\n );\n }\n\n /**\n * Extract a single tile from an image.\n */\n public extractTile(imgSpec: IImageSpec, tileId: number): HTMLCanvasElement | undefined {\n const { width, height } = this.cellSize;\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const { width: sourceWidth, height: sourceHeight } = imgSpec.actualCellSize;\n const cols = Math.ceil(img.width / sourceWidth);\n const sx = (tileId % cols) * sourceWidth;\n const sy = Math.floor(tileId / cols) * sourceHeight;\n const finalWidth = sourceWidth + sx > img.width ? img.width - sx : sourceWidth;\n const finalHeight = sy + sourceHeight > img.height ? img.height - sy : sourceHeight;\n\n const canvas = ImageRenderer.createCanvas(this.document, Math.ceil(finalWidth * width / sourceWidth), Math.ceil(finalHeight * height / sourceHeight));\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.floor(finalWidth), Math.floor(finalHeight),\n 0, 0, canvas.width, canvas.height\n );\n return canvas;\n }\n }\n\n /**\n * Draw a line with placeholder on the image layer canvas.\n */\n public drawPlaceholder(col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get('top');\n if (ctx) {\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n if (!this._placeholder) {\n this._createPlaceHolder(Math.max(height + 1, Constants.PLACEHOLDER_HEIGHT));\n } else if (height >= this._placeholder!.height) {\n this._createPlaceHolder(height + 1);\n }\n if (!this._placeholder) return;\n ctx.drawImage(\n this._placeholderBitmap ?? this._placeholder!,\n col * width,\n (row * height) % 2 ? 0 : 1, // needs %2 offset correction\n width * count,\n height,\n col * width,\n row * height,\n width * count,\n height\n );\n }\n }\n\n /**\n * Rescale image layer canvas if needed.\n * Checked once from `ImageStorage.render`.\n */\n public rescaleCanvas(): void {\n const w = this.dimensions?.css.canvas.width || 0;\n const h = this.dimensions?.css.canvas.height || 0;\n for (const ctx of this._layers.values()) {\n if (ctx.canvas.width !== w || ctx.canvas.height !== h) {\n ctx.canvas.width = w;\n ctx.canvas.height = h;\n }\n }\n }\n\n /**\n * Rescale image in storage if needed.\n */\n private _rescaleImage(spec: IImageSpec, currentWidth: number, currentHeight: number): void {\n if (currentWidth === spec.actualCellSize.width && currentHeight === spec.actualCellSize.height) {\n return;\n }\n const { width: originalWidth, height: originalHeight } = spec.origCellSize;\n if (currentWidth === originalWidth && currentHeight === originalHeight) {\n spec.actual = spec.orig;\n spec.actualCellSize.width = originalWidth;\n spec.actualCellSize.height = originalHeight;\n return;\n }\n const scaledWidth = Math.ceil(spec.orig!.width * currentWidth / originalWidth);\n const scaledHeight = Math.ceil(spec.orig!.height * currentHeight / originalHeight);\n // Upscale visible tiles directly; a full zoomed copy can dwarf the image budget.\n if (scaledWidth * scaledHeight > spec.orig!.width * spec.orig!.height) {\n spec.actual = spec.orig;\n spec.actualCellSize.width = originalWidth;\n spec.actualCellSize.height = originalHeight;\n return;\n }\n const canvas = ImageRenderer.createCanvas(this.document, scaledWidth, scaledHeight);\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(spec.orig!, 0, 0, canvas.width, canvas.height);\n spec.actual = canvas;\n spec.actualCellSize.width = currentWidth;\n spec.actualCellSize.height = currentHeight;\n }\n }\n\n /**\n * Lazy init for the renderer.\n */\n private _open(): void {\n this._renderService = this._terminal._core._renderService;\n this._oldSetRenderer = this._renderService.setRenderer.bind(this._renderService);\n this._renderService.setRenderer = (renderer: any) => {\n for (const key of [...this._layers.keys()]) {\n this.removeLayerFromDom(key);\n }\n this._oldSetRenderer?.call(this._renderService, renderer);\n };\n }\n\n public insertLayerToDom(layer: ImageLayer = 'top'): void {\n // make sure that the terminal is attached to a document and to DOM\n if (!this.document || !this._terminal._core.screenElement) {\n console.warn('image addon: cannot insert output canvas to DOM, missing document or screenElement');\n return;\n }\n if (this._layers.has(layer)) {\n return;\n }\n const canvas = ImageRenderer.createCanvas(\n this.document, this.dimensions?.css.canvas.width || 0,\n this.dimensions?.css.canvas.height || 0\n );\n canvas.classList.add(`xterm-image-layer-${layer}`);\n const screenElement = this._terminal._core.screenElement;\n // Use isolation to create a stacking context without overriding z-index,\n // which would conflict with integrators (e.g. VS Code) that set their\n // own z-index on the screen element.\n screenElement.style.isolation = 'isolate';\n if (layer === 'bottom') {\n // Use z-index:-1 so it paints behind non-positioned text elements.\n // The screen element needs to be a stacking context (via isolation)\n // to contain the negative z-index, otherwise it would go behind the\n // entire terminal.\n canvas.style.zIndex = '-1';\n screenElement.insertBefore(canvas, screenElement.firstChild);\n } else {\n // Explicit z-index ensures the image canvas reliably stacks above\n // the text layer (DOM renderer rows). z-index: 0 is below the\n // selection overlay (z-index: 1).\n canvas.style.zIndex = '0';\n screenElement.appendChild(canvas);\n }\n const ctx = canvas.getContext('2d', { alpha: true });\n if (!ctx) {\n canvas.remove();\n return;\n }\n this._layers.set(layer, ctx);\n this.clearAll(layer);\n }\n\n public removeLayerFromDom(layer: ImageLayer = 'top'): void {\n const ctx = this._layers.get(layer);\n if (ctx) {\n ctx.canvas.remove();\n this._layers.delete(layer);\n }\n }\n\n public hasLayer(layer: ImageLayer): boolean {\n return this._layers.has(layer);\n }\n\n private _createPlaceHolder(height: number = Constants.PLACEHOLDER_HEIGHT): void {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n\n // create blueprint to fill placeholder with\n const bWidth = 32; // must be 2^n\n const blueprint = ImageRenderer.createCanvas(this.document, bWidth, height);\n const ctx = blueprint.getContext('2d', { alpha: false });\n if (!ctx) return;\n const imgData = ImageRenderer.createImageData(ctx, bWidth, height);\n const d32 = new Uint32Array(imgData.data.buffer);\n const black = toRGBA8888(0, 0, 0);\n const white = toRGBA8888(255, 255, 255);\n d32.fill(black);\n for (let y = 0; y < height; ++y) {\n const shift = y % 2;\n const offset = y * bWidth;\n for (let x = 0; x < bWidth; x += 2) {\n d32[offset + x + shift] = white;\n }\n }\n ctx.putImageData(imgData, 0, 0);\n\n // create placeholder line, width aligned to blueprint width\n const width = (screen.width + bWidth - 1) & ~(bWidth - 1) || Constants.PLACEHOLDER_LENGTH;\n this._placeholder = ImageRenderer.createCanvas(this.document, width, height);\n const ctx2 = this._placeholder.getContext('2d', { alpha: false });\n if (!ctx2) {\n this._placeholder = undefined;\n return;\n }\n for (let i = 0; i < width; i += bWidth) {\n ctx2.drawImage(blueprint, i, 0);\n }\n const placeholder = this._placeholder;\n ImageRenderer.createImageBitmap(placeholder).then(bitmap => {\n if (this._placeholder !== placeholder) bitmap?.close();\n else this._placeholderBitmap = bitmap;\n }).catch(() => {});\n }\n\n public get document(): Document | undefined {\n return this._terminal._core._coreBrowserService?.window.document;\n }\n}\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageRenderer } from './ImageRenderer';\nimport {\n ITerminalExt, IExtendedAttrsImage, IImageAddonOptions, IImageSpec,\n IBufferLineExt, BgFlags, Cell, Content, ICellSize, ExtFlags, Attributes,\n UnderlineStyle, IAddImageOpts\n} from './Types';\n\n\n// fallback default cell size\nexport const CELL_SIZE_DEFAULT: ICellSize = {\n width: 7,\n height: 14\n};\n\n/**\n * Extend extended attribute to also hold image tile information.\n *\n * Object definition is copied from base repo to fully mimick its behavior.\n * Image data is added as additional public properties `imageId` and `tileId`.\n */\nclass ExtendedAttrsImage implements IExtendedAttrsImage {\n private _ext: number = 0;\n public get ext(): number {\n if (this._urlId) {\n return (\n (this._ext & ~ExtFlags.UNDERLINE_STYLE) |\n (this.underlineStyle << 26)\n );\n }\n return this._ext;\n }\n public set ext(value: number) { this._ext = value; }\n\n public get underlineStyle(): UnderlineStyle {\n // Always return the URL style if it has one\n if (this._urlId) {\n return UnderlineStyle.DASHED;\n }\n return (this._ext & ExtFlags.UNDERLINE_STYLE) >> 26;\n }\n public set underlineStyle(value: UnderlineStyle) {\n this._ext &= ~ExtFlags.UNDERLINE_STYLE;\n this._ext |= (value << 26) & ExtFlags.UNDERLINE_STYLE;\n }\n\n public get underlineColor(): number {\n return this._ext & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n public set underlineColor(value: number) {\n this._ext &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n this._ext |= value & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n\n public get underlineVariantOffset(): number {\n const val = (this._ext & ExtFlags.VARIANT_OFFSET) >> 29;\n if (val < 0) {\n return val ^ 0xFFFFFFF8;\n }\n return val;\n }\n public set underlineVariantOffset(value: number) {\n this._ext &= ~ExtFlags.VARIANT_OFFSET;\n this._ext |= (value << 29) & ExtFlags.VARIANT_OFFSET;\n }\n\n private _urlId: number = 0;\n public get urlId(): number {\n return this._urlId;\n }\n public set urlId(value: number) {\n this._urlId = value;\n }\n\n constructor(\n ext: number = 0,\n urlId: number = 0,\n public imageId = -1,\n public tileId = -1\n ) {\n this._ext = ext;\n this._urlId = urlId;\n }\n\n public clone(): IExtendedAttrsImage {\n /**\n * Technically we dont need a clone variant of ExtendedAttrsImage,\n * as we never clone a cell holding image data.\n * Note: Clone is only meant to be used by the InputHandler for\n * sticky attributes, which is never the case for image data.\n * We still provide a proper clone method to reflect the full ext attr\n * state in case there are future use cases for clone.\n */\n return new ExtendedAttrsImage(this._ext, this._urlId, this.imageId, this.tileId);\n }\n\n public isEmpty(): boolean {\n return this.underlineStyle === UnderlineStyle.NONE && this._urlId === 0 && this.imageId === -1;\n }\n}\nconst EMPTY_ATTRS = new ExtendedAttrsImage();\n\n\n/**\n * ImageStorage - extension of CoreTerminal:\n * - hold image data\n * - write/read image data to/from buffer\n *\n * TODO: image composition for overwrites\n */\nexport class ImageStorage implements IDisposable {\n // storage\n private _images: Map = new Map();\n // last used id\n private _lastId = 0;\n // last evicted id\n private _lowestId = 0;\n // whether a full clear happened before\n private _fullyCleared = false;\n // whether render should do a full clear\n private _needsFullClear = false;\n // hard limit of stored pixels (fallback limit of 10 MB)\n private _pixelLimit: number = 2500000;\n\n private _viewportMetrics: { cols: number, rows: number };\n public onImageAdded: (() => void) | undefined;\n public onImageDeleted: ((storageId: number) => void) | undefined;\n\n constructor(\n private _terminal: ITerminalExt,\n private _renderer: ImageRenderer,\n private _opts: IImageAddonOptions\n ) {\n try {\n this.setLimit(this._opts.storageLimit);\n } catch (e: unknown) {\n if (e instanceof Error) {\n console.error(e.message);\n }\n console.warn(`storageLimit is set to ${this.getLimit()} MB`);\n }\n this._viewportMetrics = {\n cols: this._terminal.cols,\n rows: this._terminal.rows\n };\n }\n\n public dispose(): void {\n this.reset();\n }\n\n public reset(): void {\n for (const spec of this._images.values()) {\n spec.marker?.dispose();\n }\n // NOTE: marker.dispose above already calls ImageBitmap.close\n // therefore we can just wipe the map here\n this._images.clear();\n this._renderer.clearAll();\n }\n\n public getLimit(): number {\n return this._pixelLimit * 4 / 1000000;\n }\n\n public setLimit(value: number): void {\n if (value < 0.5 || value > 1000) {\n throw RangeError('invalid storageLimit, should be at least 0.5 MB and not exceed 1G');\n }\n this._pixelLimit = (value / 4 * 1000000) >>> 0;\n this._evictOldest(0);\n }\n\n public getUsage(): number {\n return this._getStoredPixels() * 4 / 1000000;\n }\n\n private _getStoredPixels(): number {\n let storedPixels = 0;\n for (const spec of this._images.values()) {\n if (spec.orig) {\n storedPixels += spec.orig.width * spec.orig.height;\n if (spec.actual && spec.actual !== spec.orig) {\n storedPixels += spec.actual.width * spec.actual.height;\n }\n }\n }\n return storedPixels;\n }\n\n private _delImg(id: number): void {\n const spec = this._images.get(id);\n if (!spec) return;\n this._images.delete(id);\n // FIXME: really ugly workaround to get bitmaps deallocated :(\n if (window.ImageBitmap && spec.orig instanceof ImageBitmap) {\n spec.orig.close();\n }\n this.onImageDeleted?.(id);\n }\n\n /**\n * Wipe canvas and images on alternate buffer.\n */\n public wipeAlternate(): void {\n // remove all alternate tagged images\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate') {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n // mark canvas to be wiped on next render\n this._needsFullClear = true;\n this._fullyCleared = false;\n }\n\n /**\n * Delete an image by its internal storage ID.\n * Used by protocols that support explicit deletion (e.g. Kitty a=d).\n */\n public deleteImage(id: number): void {\n const spec = this._images.get(id);\n if (spec) {\n spec.marker?.dispose();\n this._delImg(id);\n }\n }\n\n /**\n * Method to add an image to the storage.\n * @param img - The image to add (canvas or bitmap).\n * @param opts - Options for addImage:\n * - scrolling: When true, cursor advances with the image.\n * When false, image is placed at ORIGIN and cursor does not move.\n * - layer: Which canvas layer to render on ('top' or 'bottom').\n * - zIndex: Z-index for image layering within the same layer.\n * - cursorPos: 'vt340' for bottom-left, 'iip' for bottom.right.\n * @returns The internal image ID assigned to the stored image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap, opts: IAddImageOpts): number {\n // never allow storage to exceed memory limit\n this._evictOldest(img.width * img.height);\n\n // calc rows x cols needed to display the image\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const cols = Math.ceil(img.width / cellSize.width);\n const rows = Math.ceil(img.height / cellSize.height);\n\n const imageId = ++this._lastId;\n\n const buffer = this._terminal._core.buffer;\n const termCols = this._terminal.cols;\n const termRows = this._terminal.rows;\n const originX = buffer.x;\n const originY = buffer.y;\n let offset = originX;\n let tileCount = 0;\n\n if (!opts.scrolling) {\n buffer.x = 0;\n buffer.y = 0;\n offset = 0;\n }\n\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(buffer.y + buffer.ybase);\n for (let col = 0; col < cols; ++col) {\n if (offset + col >= termCols) break;\n this._writeToCell(line as IBufferLineExt, offset + col, imageId, row * cols + col);\n tileCount++;\n }\n if (opts.scrolling) {\n if (row < rows - 1) this._terminal._core._inputHandler.lineFeed();\n } else {\n if (++buffer.y >= termRows) break;\n }\n buffer.x = offset;\n }\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n\n // cursor positioning modes\n if (opts.scrolling) {\n if (opts.cursorPos === 'iip') {\n buffer.x = Math.min(offset + cols, termCols);\n } else {\n buffer.x = offset;\n }\n } else {\n buffer.x = originX;\n buffer.y = originY;\n }\n\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.tileCount < 1) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n\n // eviction marker:\n // delete the image when the marker gets disposed\n const endMarker = this._terminal.registerMarker(0);\n endMarker?.onDispose(() => {\n const spec = this._images.get(imageId);\n if (spec) {\n this._delImg(imageId);\n }\n });\n\n // since markers do not work on alternate for some reason,\n // we evict images here manually\n if (this._terminal.buffer.active.type === 'alternate') {\n this._evictOnAlternate();\n }\n\n // create storage entry\n const imgSpec: IImageSpec = {\n orig: img,\n origCellSize: cellSize,\n actual: img,\n actualCellSize: { ...cellSize }, // clone needed, since later modified\n marker: endMarker || undefined,\n tileCount,\n bufferType: this._terminal.buffer.active.type,\n layer: opts.layer,\n zIndex: opts.zIndex\n };\n\n // finally add the image\n this._images.set(imageId, imgSpec);\n this.onImageAdded?.();\n return imageId;\n }\n\n\n /**\n * Render method. Collects buffer information and triggers\n * canvas updates.\n */\n // TODO: Should we move this to the ImageRenderer?\n public render(range: { start: number, end: number }): void {\n // Determine which layers have images\n let hasTopImages = false;\n let hasBottomImages = false;\n for (const spec of this._images.values()) {\n if (spec.layer === 'bottom') {\n hasBottomImages = true;\n } else {\n hasTopImages = true;\n }\n if (hasTopImages && hasBottomImages) break;\n }\n\n // Lazily insert layers that are needed\n if (hasTopImages && !this._renderer.hasLayer('top')) {\n this._renderer.insertLayerToDom('top');\n if (!this._renderer.hasLayer('top')) return;\n }\n if (hasBottomImages && !this._renderer.hasLayer('bottom')) {\n this._renderer.insertLayerToDom('bottom');\n }\n\n // rescale if needed\n this._renderer.rescaleCanvas();\n\n // exit early if we dont have any images to test for\n if (!this._images.size) {\n if (!this._fullyCleared) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n if (this._renderer.hasLayer('top')) {\n this._renderer.removeLayerFromDom('top');\n }\n if (this._renderer.hasLayer('bottom')) {\n this._renderer.removeLayerFromDom('bottom');\n }\n return;\n }\n\n // Remove layers no longer needed\n if (!hasTopImages && this._renderer.hasLayer('top')) {\n this._renderer.clearAll('top');\n this._renderer.removeLayerFromDom('top');\n }\n if (!hasBottomImages && this._renderer.hasLayer('bottom')) {\n this._renderer.clearAll('bottom');\n this._renderer.removeLayerFromDom('bottom');\n }\n\n // buffer switches force a full clear\n if (this._needsFullClear) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n\n const { start, end } = range;\n const buffer = this._terminal._core.buffer;\n const cols = this._terminal._core.cols;\n\n // clear drawing area\n this._renderer.clearLines(start, end);\n\n // Collect draw calls so we can sort by z-index (lower z drawn first).\n const drawCalls: { imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number }[] = [];\n const placeholderCalls: { col: number, row: number, count: number }[] = [];\n\n // walk all cells in viewport and collect tiles found\n for (let row = start; row <= end; ++row) {\n const line = buffer.lines.get(row + buffer.ydisp) as IBufferLineExt;\n if (!line) return;\n for (let col = 0; col < cols; ++col) {\n if (line.getBg(col) & BgFlags.HAS_EXTENDED) {\n let e: IExtendedAttrsImage = line._extendedAttrs[col] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (e.tileId !== -1) {\n const startTile = e.tileId;\n const startCol = col;\n let count = 1;\n /**\n * merge tiles to the right into a single draw call, if:\n * - not at end of line\n * - cell has same image id\n * - cell has consecutive tile id\n */\n while (\n ++col < cols\n && (line.getBg(col) & BgFlags.HAS_EXTENDED)\n && (e = line._extendedAttrs[col] ?? EMPTY_ATTRS)\n && (e.imageId === imageId)\n && (e.tileId === startTile + count)\n ) {\n count++;\n }\n col--;\n if (imgSpec) {\n if (imgSpec.actual) {\n drawCalls.push({ imgSpec, tileId: startTile, col: startCol, row, count });\n }\n } else if (this._opts.showPlaceholder) {\n placeholderCalls.push({ col: startCol, row, count });\n }\n this._fullyCleared = false;\n }\n }\n }\n }\n\n // Sort by z-index so lower z draws first (higher z renders on top)\n drawCalls.sort((a, b) => a.imgSpec.zIndex - b.imgSpec.zIndex);\n\n // Draw placeholders first (lowest priority)\n for (const call of placeholderCalls) {\n this._renderer.drawPlaceholder(call.col, call.row, call.count);\n }\n\n // Draw images in z-index order\n for (const call of drawCalls) {\n this._renderer.draw(call.imgSpec, call.tileId, call.col, call.row, call.count);\n }\n }\n\n public viewportResize(metrics: { cols: number, rows: number }): void {\n // exit early if we have nothing in storage\n if (!this._images.size) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // handle only viewport width enlargements, exit all other cases\n // TODO: needs patch for tile counter\n if (this._viewportMetrics.cols >= metrics.cols) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // walk scrollbuffer at old col width to find all possible expansion matches\n const buffer = this._terminal._core.buffer;\n const rows = buffer.lines.length;\n const oldCol = this._viewportMetrics.cols - 1;\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(row) as IBufferLineExt;\n if (line.getBg(oldCol) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[oldCol] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (!imgSpec) {\n continue;\n }\n // found an image tile at oldCol, check if it qualifies for right exapansion\n const tilesPerRow = Math.ceil((imgSpec.actual?.width || 0) / imgSpec.actualCellSize.width);\n if ((e.tileId % tilesPerRow) + 1 >= tilesPerRow) {\n continue;\n }\n // expand only if right side is empty (nothing got wrapped from below)\n let hasData = false;\n for (let rightCol = oldCol + 1; rightCol > metrics.cols; ++rightCol) {\n if (line._data[rightCol * Cell.SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK) {\n hasData = true;\n break;\n }\n }\n if (hasData) {\n continue;\n }\n // do right expansion on terminal buffer\n const end = Math.min(metrics.cols, tilesPerRow - (e.tileId % tilesPerRow) + oldCol);\n let lastTile = e.tileId;\n for (let expandCol = oldCol + 1; expandCol < end; ++expandCol) {\n this._writeToCell(line as IBufferLineExt, expandCol, imageId, ++lastTile);\n imgSpec.tileCount++;\n }\n }\n }\n // store new viewport metrics\n this._viewportMetrics = metrics;\n }\n\n /**\n * Retrieve original canvas at buffer position.\n */\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1) {\n const orig = this._images.get(e.imageId)?.orig;\n if (window.ImageBitmap && orig instanceof ImageBitmap) {\n const canvas = ImageRenderer.createCanvas(window.document, orig.width, orig.height);\n canvas.getContext('2d')?.drawImage(orig, 0, 0, orig.width, orig.height);\n return canvas;\n }\n return orig as HTMLCanvasElement;\n }\n }\n }\n\n /**\n * Extract active single tile at buffer position.\n */\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1 && e.tileId !== -1) {\n const spec = this._images.get(e.imageId);\n if (spec) {\n return this._renderer.extractTile(spec, e.tileId);\n }\n }\n }\n }\n\n // TODO: Do we need some blob offloading tricks here to avoid early eviction?\n // also see https://stackoverflow.com/questions/28307789/is-there-any-limitation-on-javascript-max-blob-size\n private _evictOldest(room: number): number {\n const used = this._getStoredPixels();\n let current = used;\n while (this._pixelLimit < current + room && this._images.size) {\n const spec = this._images.get(++this._lowestId);\n if (spec && spec.orig) {\n current -= spec.orig.width * spec.orig.height;\n if (spec.actual && spec.orig !== spec.actual) {\n current -= spec.actual.width * spec.actual.height;\n }\n spec.marker?.dispose();\n this._delImg(this._lowestId);\n }\n }\n return used - current;\n }\n\n private _writeToCell(line: IBufferLineExt, x: number, imageId: number, tileId: number): void {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const old = line._extendedAttrs[x];\n if (old) {\n if (old.imageId !== undefined) {\n // found an old ExtendedAttrsImage, since we know that\n // they are always isolated instances (single cell usage),\n // we can re-use it and just update their id entries\n const oldSpec = this._images.get(old.imageId);\n if (oldSpec) {\n // early eviction for in-viewport overwrites\n oldSpec.tileCount--;\n }\n old.imageId = imageId;\n old.tileId = tileId;\n return;\n }\n // found a plain ExtendedAttrs instance, clone it to new entry\n line._extendedAttrs[x] = new ExtendedAttrsImage(old.ext, old.urlId, imageId, tileId);\n return;\n }\n }\n // fall-through: always create new ExtendedAttrsImage entry\n line._data[x * Cell.SIZE + Cell.BG] |= BgFlags.HAS_EXTENDED;\n line._extendedAttrs[x] = new ExtendedAttrsImage(0, 0, imageId, tileId);\n }\n\n private _evictOnAlternate(): void {\n // nullify tile count of all images on alternate buffer\n for (const spec of this._images.values()) {\n if (spec.bufferType === 'alternate') {\n spec.tileCount = 0;\n }\n }\n // re-count tiles on whole buffer\n const buffer = this._terminal._core.buffer;\n for (let y = 0; y < this._terminal.rows; ++y) {\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (!line) {\n continue;\n }\n for (let x = 0; x < this._terminal.cols; ++x) {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const imgId = line._extendedAttrs[x]?.imageId;\n if (imgId) {\n const spec = this._images.get(imgId);\n if (spec) {\n spec.tileCount++;\n }\n }\n }\n }\n }\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate' && !spec.tileCount) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n }\n}\n","/**\n * Copyright (c) 2020, 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IDcsHandler, IParams, IImageAddonOptions, ITerminalExt, AttributeData, IResetHandler, ReadonlyColorSet } from './Types';\nimport { toRGBA8888, BIG_ENDIAN, PALETTE_ANSI_256, PALETTE_VT340_COLOR } from 'sixel/lib/Colors';\nimport { RGBA8888 } from 'sixel/lib/Types';\nimport { ImageRenderer } from './ImageRenderer';\n\nimport { DecoderAsync, Decoder } from 'sixel/lib/Decoder';\nimport { LIMITS } from 'sixel/lib/wasm';\n\n// always free decoder ressources after decoding if it exceeds this limit\nconst MEM_PERMA_LIMIT = 4194304; // 1024 pixels * 1024 pixels * 4 channels = 4MB\n\n// custom default palette: VT340 (lower 16 colors) + ANSI256 (up to 256) + zeroed (up to 4096)\nconst DEFAULT_PALETTE = PALETTE_ANSI_256;\nDEFAULT_PALETTE.set(PALETTE_VT340_COLOR);\n\n// Why pooled: every decoder owns a wasm memory, and V8 caps live wasm memories\n// per process (~124 in a sandboxed renderer). Terminals borrow a decoder only\n// while a SIXEL sequence is open, so idle terminals hold none.\nconst MAX_IDLE_DECODERS = 2;\nconst idleDecoders = new Map();\nlet poolPrimed = false;\n\nfunction primeDecoderPool(memoryLimit: number): void {\n if (poolPrimed) return;\n poolPrimed = true;\n // Async compile once, off the parser's hot path; later decoders reuse the cached module.\n DecoderAsync({ memoryLimit, palette: DEFAULT_PALETTE }).then(\n d => releaseDecoder(d, memoryLimit),\n () => { poolPrimed = false; }\n );\n}\n\nfunction acquireDecoder(memoryLimit: number): Decoder {\n return idleDecoders.get(memoryLimit)?.pop() ?? new Decoder({ memoryLimit, palette: DEFAULT_PALETTE });\n}\n\nfunction releaseDecoder(dec: Decoder, memoryLimit: number): void {\n if (dec.memoryUsage > MEM_PERMA_LIMIT) {\n dec.release();\n }\n const idle = idleDecoders.get(memoryLimit) ?? [];\n if (idle.length < MAX_IDLE_DECODERS) {\n idle.push(dec);\n idleDecoders.set(memoryLimit, idle);\n }\n}\n\n\nexport class SixelHandler implements IDcsHandler, IResetHandler {\n private _size = 0;\n private _aborted = false;\n private _dec: Decoder | undefined;\n private _decMemoryLimit = 0;\n // Color registers outlive a single image, so they live here rather than in a pooled decoder.\n private readonly _palette = new Uint32Array(LIMITS.PALETTE_SIZE);\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _storage: SixelImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n this._palette.set(DEFAULT_PALETTE);\n primeDecoderPool(this._opts.pixelLimit * 4);\n }\n\n public reset(): void {\n this._returnDecoder();\n this._palette.fill(0);\n this._palette.set(DEFAULT_PALETTE);\n }\n\n public hook(params: IParams): void {\n this._size = 0;\n this._aborted = false;\n this._returnDecoder();\n const memoryLimit = this._opts.pixelLimit * 4;\n try {\n this._dec = acquireDecoder(memoryLimit);\n } catch (e) {\n // Why: exhausting wasm memory must drop this image, not throw out of the parser and wedge the write queue.\n console.warn(`SIXEL: could not allocate decoder - ${e}`);\n this._aborted = true;\n return;\n }\n this._decMemoryLimit = memoryLimit;\n const fillColor = params.params[1] === 1 ? 0 : extractActiveBg(\n this._coreTerminal._core._inputHandler._curAttrData,\n this._coreTerminal._core._themeService?.colors);\n this._dec.init(fillColor, this._palette, this._opts.sixelPaletteLimit);\n }\n\n private _returnDecoder(): void {\n const dec = this._dec;\n if (!dec) return;\n this._dec = undefined;\n this._palette.set(dec.palette);\n releaseDecoder(dec, this._decMemoryLimit);\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted || !this._dec) {\n return;\n }\n this._size += end - start;\n if (this._size > this._opts.sixelSizeLimit) {\n console.warn(`SIXEL: too much data, aborting`);\n this._aborted = true;\n this._dec.release();\n return;\n }\n try {\n this._dec.decode(data, start, end);\n } catch (e) {\n console.warn(`SIXEL: error while decoding image - ${e}`);\n this._aborted = true;\n this._dec.release();\n }\n }\n\n public unhook(success: boolean): boolean | Promise {\n try {\n return this._unhook(success);\n } finally {\n this._returnDecoder();\n }\n }\n\n private _unhook(success: boolean): boolean {\n if (this._aborted || !success || !this._dec) {\n return true;\n }\n\n const width = this._dec.width;\n const height = this._dec.height;\n\n // partial fix for https://github.com/jerch/xterm-addon-image/issues/37\n if (!width || !height) {\n if (height) {\n this._storage.advanceCursor(height);\n }\n return true;\n }\n\n const canvas = ImageRenderer.createCanvas(undefined, width, height);\n canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8 as Uint8ClampedArray, width, height), 0, 0);\n this._storage.addImage(canvas);\n return true;\n }\n}\n\n\n/**\n * Some helpers to extract current terminal colors.\n */\n\n// get currently active background color from terminal\n// also respect INVERSE setting\nfunction extractActiveBg(attr: AttributeData, colors: ReadonlyColorSet | undefined): RGBA8888 {\n let bg = 0;\n if (!colors) {\n // FIXME: theme service is prolly not available yet,\n // happens if .open() was not called yet (bug in core?)\n return bg;\n }\n if (attr.isInverse()) {\n if (attr.isFgDefault()) {\n bg = convertLe(colors.foreground.rgba);\n } else if (attr.isFgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getFgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getFgColor()].rgba);\n }\n } else {\n if (attr.isBgDefault()) {\n bg = convertLe(colors.background.rgba);\n } else if (attr.isBgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getBgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getBgColor()].rgba);\n }\n }\n return bg;\n}\n\n// rgba values on the color managers are always in BE, thus convert to LE\nfunction convertLe(color: number): RGBA8888 {\n if (BIG_ENDIAN) return color;\n return (color & 0xFF) << 24 | (color >>> 8 & 0xFF) << 16 | (color >>> 16 & 0xFF) << 8 | color >>> 24 & 0xFF;\n}\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { IImageAddonOptions, ITerminalExt, IAddImageOpts } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\n\n/**\n * Sixel-specific image storage controller.\n *\n * Wraps the shared ImageStorage with sixel protocol semantics:\n * - Cursor behavior governed by DECSET 80 (sixelScrolling option)\n * - advanceCursor for empty sixels carrying only height\n */\nexport class SixelImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'vt340' };\n constructor(\n private readonly _storage: ImageStorage,\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _terminal: ITerminalExt\n ) {}\n\n /**\n * Add a sixel image to storage.\n * Cursor behavior depends on the sixelScrolling option (DECSET 80).\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._addImageOpts.scrolling = this._opts.sixelScrolling;\n this._storage.addImage(img, this._addImageOpts);\n }\n\n /**\n * Only advance text cursor.\n * This is an edge case from empty sixels carrying only a height but no pixels.\n * Partially fixes https://github.com/jerch/xterm-addon-image/issues/37.\n */\n public advanceCursor(height: number): void {\n if (this._opts.sixelScrolling) {\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const rows = Math.ceil(height / cellSize.height);\n for (let i = 1; i < rows; ++i) {\n this._terminal._core._inputHandler.lineFeed();\n }\n }\n }\n}\n","/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { IApcHandler, IImageAddonOptions, IResetHandler, ITerminalExt, ImageLayer } from '../Types';\nimport { ImageRenderer } from '../ImageRenderer';\nimport { CELL_SIZE_DEFAULT } from '../ImageStorage';\nimport { imageType } from '../IIPMetrics';\nimport { KittyImageStorage } from './KittyImageStorage';\nimport Base64Decoder, { type DecodeStatus } from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport {\n KittyAction,\n KittyFormat,\n KittyCompression,\n IKittyCommand,\n IPendingTransmission,\n IKittyImageData,\n KittyPixelConstants,\n parseKittyCommand\n} from './KittyGraphicsTypes';\n\nconst enum Constants {\n // Memory limit for base64 decoder (4MB, same as IIPHandler)\n DECODER_KEEP_DATA = 4194304,\n DECODER_INITIAL_DATA = 4194304, // 4MB\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n DECODER_OK = 0,\n // Maximum control data size\n MAX_CONTROL_DATA_SIZE = 512,\n // Semicolon codepoint\n SEMICOLON = 0x3B\n}\n\nconst DECODER_OK = Constants.DECODER_OK as unknown as DecodeStatus.OK;\n\n// Kitty graphics protocol handler with streaming base64 decoding.\nexport class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDisposable {\n private _aborted = false;\n private _generation = 0;\n private _decodeError = false;\n\n private _activeDecoder: Base64Decoder | null = null;\n private readonly _maxEncodedBytes: number;\n private readonly _initialEncodedBytes: number;\n\n // Streaming related states\n\n // True while receiving control data (before semicolon).\n private _inControlData = true;\n\n // Buffer for control data.\n private _controlData = new Uint32Array(Constants.MAX_CONTROL_DATA_SIZE);\n private _controlLength = 0;\n\n // Pre-calculated encoded size limit\n private _encodedSizeLimit = 0;\n private _totalEncodedSize = 0;\n\n // Parsed command. These are the control data before semicolon.\n private _parsedCommand: IKittyCommand | null = null;\n\n // Storage related states\n\n private _pendingTransmissions: Map = new Map();\n // Tracks the pending key of the most recently started chunked upload.\n // Per spec, subsequent chunks only need m= (and optionally q=), without i=.\n // When a chunk arrives with no i=, this key is used to find the pending upload.\n private _lastPendingKey: number | undefined;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _kittyStorage: KittyImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n // Convert decoded size limit -> max encoded bytes.\n this._maxEncodedBytes = Math.ceil(this._opts.kittySizeLimit * 4 / 3);\n // ensure we preallocate more than configured limit while using 4mb initial size.\n this._initialEncodedBytes = Math.min(Constants.DECODER_INITIAL_DATA, this._maxEncodedBytes);\n }\n\n public reset(): void {\n this._generation++;\n this._cleanupAllPending();\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n this._kittyStorage.reset();\n }\n\n public dispose(): void {\n this.reset();\n }\n\n private _removePendingEntry(key: number): void {\n this._pendingTransmissions.delete(key);\n if (this._lastPendingKey === key) {\n this._lastPendingKey = undefined;\n }\n }\n\n private _cleanupAllPending(): void {\n for (const pending of this._pendingTransmissions.values()) {\n pending.decoder.release();\n }\n this._pendingTransmissions.clear();\n this._lastPendingKey = undefined;\n }\n\n public start(): void {\n this._aborted = false;\n this._decodeError = false;\n this._inControlData = true;\n this._controlLength = 0;\n this._parsedCommand = null;\n // Pre-calculate encoded limit once: base64 is 4 bytes encoded → 3 bytes decoded\n this._encodedSizeLimit = this._maxEncodedBytes;\n this._totalEncodedSize = 0;\n this._activeDecoder = null;\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (!this._inControlData) {\n this._streamPayload(data, start, end);\n } else {\n // Scan for semicolon\n let controlEnd = end;\n for (let i = start; i < end; i++) {\n if (data[i] === Constants.SEMICOLON) {\n this._inControlData = false;\n controlEnd = i;\n break;\n }\n }\n\n // Copy control data\n const copyLength = controlEnd - start;\n if (this._controlLength + copyLength > Constants.MAX_CONTROL_DATA_SIZE) {\n this._aborted = true;\n return;\n }\n this._controlData.set(data.subarray(start, controlEnd), this._controlLength);\n this._controlLength += copyLength;\n\n if (!this._inControlData) {\n // Found semicolon - parse control data early for validation\n this._parsedCommand = parseKittyCommand(this._parseControlDataString());\n\n // Early validation: i+I conflict\n if (this._parsedCommand.id !== undefined && this._parsedCommand.imageNumber !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'EINVAL:cannot specify both i and I keys', this._parsedCommand.quiet ?? 0);\n this._aborted = true;\n return;\n }\n\n // Delete action doesn't need payload - skip streaming\n if (this._parsedCommand.action === KittyAction.DELETE) {\n return;\n }\n\n // Stream remaining as payload\n const payloadStart = controlEnd + 1;\n if (payloadStart < end) {\n this._streamPayload(data, payloadStart, end);\n }\n }\n }\n }\n\n // Stream payload bytes into the base64 decoder.\n private _streamPayload(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n // Check size limit (compare encoded bytes against pre-calculated limit)\n // Include cumulative size from pending transmission for multi-chunk images.\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = this._parsedCommand?.id ?? this._lastPendingKey ?? 0;\n const pending = this._pendingTransmissions.get(pendingKey);\n const previousEncodedSize = pending?.totalEncodedSize ?? 0;\n this._totalEncodedSize += end - start;\n const cumulativeEncodedSize = previousEncodedSize + this._totalEncodedSize;\n if (cumulativeEncodedSize > this._encodedSizeLimit) {\n const decoderToRelease = this._activeDecoder ?? pending?.decoder;\n if (decoderToRelease) {\n decoderToRelease.release();\n }\n this._activeDecoder = null;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n this._aborted = true;\n return;\n }\n\n if (this._decodeError) return;\n\n if (pending?.decoder && !this._activeDecoder) {\n this._activeDecoder = pending.decoder;\n }\n if (!this._activeDecoder) {\n // Budget WASM capacity, including one page of decoder state and rounding.\n const decoderCapacity = this._maxEncodedBytes + 131072;\n if (decoderCapacity > this._opts.storageLimit * 1000000) {\n this._aborted = true;\n if (this._parsedCommand?.id !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'ENOMEM:pending image budget exceeded', this._parsedCommand.quiet ?? 0);\n }\n return;\n }\n const maxPending = Math.max(1, Math.floor(this._opts.storageLimit * 1000000 / decoderCapacity));\n while (this._pendingTransmissions.size >= maxPending) {\n const oldest = this._pendingTransmissions.entries().next().value;\n if (!oldest) break;\n oldest[1].decoder.release();\n this._removePendingEntry(oldest[0]);\n if (oldest[1].cmd.id !== undefined) {\n this._sendResponse(oldest[1].cmd.id, 'ENOMEM:pending image budget exceeded', oldest[1].cmd.quiet ?? 0);\n }\n }\n const decoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes);\n try {\n decoder.init();\n } catch (e) {\n // Why: wasm memory exhaustion must drop this image, not throw out of the parser and wedge the write queue.\n console.warn('KITTY: could not allocate decoder', e);\n this._aborted = true;\n if (this._parsedCommand?.id !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'ENOMEM:could not allocate decoder', this._parsedCommand.quiet ?? 0);\n }\n return;\n }\n this._activeDecoder = decoder;\n }\n\n if (this._activeDecoder.put(data.subarray(start, end)) !== DECODER_OK) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n this._decodeError = true;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted || !success) {\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n return true;\n }\n\n // No semicolon = no payload (delete, capability query)\n if (this._inControlData) {\n return this._handleNoPayloadCommand();\n }\n\n // Use command parsed early in put() - i+I already validated there\n const cmd = this._parsedCommand!;\n\n // Delete action was handled by skipping payload - just execute\n if (cmd.action === KittyAction.DELETE) {\n return this._handleDelete(cmd);\n }\n\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = cmd.id ?? this._lastPendingKey ?? 0;\n const isMoreComing = cmd.more === 1;\n const pending = this._pendingTransmissions.get(pendingKey);\n\n if (isMoreComing) {\n if (this._activeDecoder) {\n if (pending) {\n pending.totalEncodedSize += this._totalEncodedSize;\n pending.decodeError = pending.decodeError || this._decodeError;\n } else {\n this._pendingTransmissions.set(pendingKey, {\n cmd: { ...cmd },\n decoder: this._activeDecoder,\n totalEncodedSize: this._totalEncodedSize,\n decodeError: this._decodeError\n });\n }\n this._lastPendingKey = pendingKey;\n this._activeDecoder = null;\n }\n return true;\n }\n\n // Final chunk received — clear the last pending key\n if (pending) {\n this._lastPendingKey = undefined;\n }\n\n let decodeError = this._decodeError;\n let finalCmd = cmd;\n let decoder = this._activeDecoder;\n\n if (pending) {\n finalCmd = pending.cmd;\n decoder = pending.decoder;\n decodeError = decodeError || pending.decodeError;\n this._pendingTransmissions.delete(pendingKey);\n }\n\n let imageBytes = new Uint8Array(0);\n if (decoder) {\n if (decoder.end() !== DECODER_OK) {\n decodeError = true;\n }\n imageBytes = decoder.data8;\n }\n this._activeDecoder = null;\n\n // Handle command first — handlers create Blob/ImageData from imageBytes,\n // which copies the data. Only then is it safe to release the decoder's\n // wasm memory that imageBytes points into.\n const result = this._handleCommandWithBytesAndCmd(finalCmd, imageBytes, decodeError);\n if (decoder) {\n decoder.release();\n }\n return result;\n }\n\n // Command handling\n\n private _parseControlDataString(): string {\n let str = '';\n for (let i = 0; i < this._controlLength; i++) {\n str += String.fromCodePoint(this._controlData[i]);\n }\n return str;\n }\n\n private _handleNoPayloadCommand(): boolean | Promise {\n const cmd = parseKittyCommand(this._parseControlDataString());\n\n // Per spec: specifying both i and I is an error\n if (cmd.id !== undefined && cmd.imageNumber !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:cannot specify both i and I keys', cmd.quiet ?? 0);\n return true;\n }\n\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.DELETE:\n return this._handleDelete(cmd);\n case KittyAction.QUERY:\n this._sendResponse(cmd.id ?? 0, 'OK', cmd.quiet ?? 0);\n return true;\n case KittyAction.PLACEMENT:\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handleCommandWithBytesAndCmd(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.TRANSMIT: {\n const result = this._handleTransmit(cmd, bytes, decodeError);\n // Only send response when _handleTransmit didn't already respond\n // (it handles unsupported transmission medium responses internally)\n if ((cmd.transmission ?? 'd') === 'd' && cmd.id !== undefined) {\n if (decodeError) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n } else if (bytes.length > 0) {\n this._sendResponse(cmd.id, 'OK', cmd.quiet ?? 0);\n }\n }\n return result;\n }\n case KittyAction.TRANSMIT_DISPLAY:\n return this._handleTransmitDisplay(cmd, bytes, decodeError);\n case KittyAction.QUERY:\n return this._handleQuery(cmd, bytes, decodeError);\n case KittyAction.PLACEMENT:\n // a=p ignores any payload — image data was already transmitted\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handlePlacement(cmd: IKittyCommand): boolean | Promise {\n if (cmd.id === undefined) {\n return true;\n }\n const id = cmd.id;\n const image = this._kittyStorage.getImage(id);\n if (!image) {\n this._sendResponse(id, 'ENOENT:image not found', cmd.quiet ?? 0, cmd.placementId);\n return true;\n }\n const result = this._displayImage(image, cmd);\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0, cmd.placementId);\n return true;\n });\n }\n\n private _handleTransmit(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n // TODO: Support file-based transmission modes (t=f, t=t, t=s)\n // Currently only supports direct transmission (t=d, the default).\n // - t=f (file): Payload is base64-encoded file path. Terminal reads image from that path.\n // - t=t (temp file): Payload is base64-encoded path in temp directory. Terminal reads, deletes.\n // - t=s: Payload is base64-encoded POSIX shm name. Terminal reads from shared memory.\n // These modes require filesystem/IPC access not available in browsers. For Node.js/Electron:\n // 1. Check cmd.transmission (t key) before treating bytes as image data\n // 2. For t=f/t/s: decode bytes as UTF-8 string (the path/name), then read file contents\n // 3. For t=d: treat bytes as image data (current behavior)\n // When implementing, also update _handleQuery to accept these transmission mediums.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported transmission medium', cmd.quiet ?? 0);\n }\n return true;\n }\n\n if (decodeError || bytes.length === 0) return true;\n\n this._kittyStorage.storeImage(cmd.id, {\n data: new Blob([bytes as BlobPart]),\n width: cmd.width ?? 0,\n height: cmd.height ?? 0,\n format: (cmd.format ?? KittyFormat.RGBA) as 24 | 32 | 100,\n compression: cmd.compression ?? ''\n });\n return true;\n }\n\n private _handleTransmitDisplay(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n if (decodeError) {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n }\n return true;\n }\n\n this._handleTransmit(cmd, bytes, decodeError);\n\n const id = cmd.id ?? this._kittyStorage.lastImageId;\n const image = this._kittyStorage.getImage(id);\n if (image) {\n const result = this._displayImage(image, cmd);\n if (cmd.id !== undefined) {\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0);\n return true;\n });\n }\n return result.then(() => true);\n }\n return true;\n }\n\n private _handleQuery(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n const id = cmd.id ?? 0;\n const quiet = cmd.quiet ?? 0;\n\n // Per spec: reject unsupported transmission mediums (only t=d is supported atm)\n // TODO: When filesystem support is added (Node.js/Electron), update this to accept\n // t=f (file), t=t (temp file), and t=s (shared memory) and respond OK for queries.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n this._sendResponse(id, 'EINVAL:unsupported transmission medium', quiet);\n return true;\n }\n\n // Check decode error first (invalid base64)\n if (decodeError) {\n this._sendResponse(id, 'EINVAL:invalid base64 data', quiet);\n return true;\n }\n\n // Capability query (no payload) - just respond OK\n if (bytes.length === 0) {\n this._sendResponse(id, 'OK', quiet);\n return true;\n }\n\n const format = cmd.format ?? KittyFormat.RGBA;\n\n if (format === KittyFormat.PNG) {\n this._sendResponse(id, 'OK', quiet);\n } else {\n const width = cmd.width ?? 0;\n const height = cmd.height ?? 0;\n\n if (!width || !height) {\n this._sendResponse(id, 'EINVAL:width and height required for raw pixel data', quiet);\n return true;\n }\n\n const bytesPerPixel = format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n this._sendResponse(id, `EINVAL:insufficient pixel data`, quiet);\n return true;\n }\n\n this._sendResponse(id, 'OK', quiet);\n }\n return true;\n }\n\n private _handleDelete(cmd: IKittyCommand): boolean {\n // Per spec: default delete selector is 'a' (delete all visible placements)\n const selector = cmd.deleteSelector ?? 'a';\n\n // TODO: Distinguish lowercase (delete placements only) from uppercase\n // (delete placements + free stored image data). Currently both variants\n // free everything since we don't separate stored data from placements.\n switch (selector) {\n case 'a':\n case 'A':\n this._cleanupAllPending();\n this._kittyStorage.deleteAll();\n break;\n case 'i':\n case 'I':\n // TODO: When placement id tracking is implemented (see TODO in\n // KittyImageStorage), d=i with p= should delete only that\n // specific placement, while d=i without p should delete all\n // placements for the image.\n if (cmd.id !== undefined) {\n const pending = this._pendingTransmissions.get(cmd.id);\n if (pending) {\n pending.decoder.release();\n }\n this._removePendingEntry(cmd.id);\n this._kittyStorage.deleteById(cmd.id);\n }\n break;\n default:\n // Unsupported selectors (c, n, p, q, r, x, y, z, f) — ignore for now\n break;\n }\n return true;\n }\n\n private _sendResponse(id: number, message: string, quiet: number, placementId?: number): void {\n const isOk = message === 'OK';\n if (isOk && quiet >= 1) return;\n if (!isOk && quiet >= 2) return;\n\n const pPart = placementId ? `,p=${placementId}` : '';\n const response = `\\x1b_Gi=${id}${pPart};${message}\\x1b\\\\`;\n this._coreTerminal._core.coreService.triggerDataEvent(response);\n }\n\n // Image display\n\n private _displayImage(image: IKittyImageData, cmd: IKittyCommand): Promise {\n return this._decodeAndDisplay(image, cmd)\n .then(() => true)\n .catch(() => false);\n }\n\n private async _decodeAndDisplay(image: IKittyImageData, cmd: IKittyCommand): Promise {\n const generation = this._generation;\n let bitmap: ImageBitmap | undefined = await this._createBitmap(image);\n\n try {\n if (generation !== this._generation) throw new Error('image decode canceled');\n const cropX = Math.max(0, cmd.x ?? 0);\n const cropY = Math.max(0, cmd.y ?? 0);\n const cropW = cmd.sourceWidth || (bitmap.width - cropX);\n const cropH = cmd.sourceHeight || (bitmap.height - cropY);\n\n const maxCropW = Math.max(0, bitmap.width - cropX);\n const maxCropH = Math.max(0, bitmap.height - cropY);\n const finalCropW = Math.max(0, Math.min(cropW, maxCropW));\n const finalCropH = Math.max(0, Math.min(cropH, maxCropH));\n\n if (finalCropW === 0 || finalCropH === 0) {\n throw new Error('invalid source rectangle');\n }\n\n if (cropX !== 0 || cropY !== 0 || finalCropW !== bitmap.width || finalCropH !== bitmap.height) {\n const cropped = await createImageBitmap(bitmap, cropX, cropY, finalCropW, finalCropH);\n bitmap.close();\n bitmap = cropped;\n }\n\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n\n // Per spec: c/r default to image's natural cell dimensions.\n // If only one of c/r is specified, compute the other from image aspect ratio.\n let imgCols: number;\n let imgRows: number;\n if (cmd.columns !== undefined && cmd.rows !== undefined) {\n imgCols = cmd.columns;\n imgRows = cmd.rows;\n } else if (cmd.columns !== undefined) {\n imgCols = cmd.columns;\n imgRows = Math.max(1, Math.ceil((bitmap.height / bitmap.width) * (imgCols * cw) / ch));\n } else if (cmd.rows !== undefined) {\n imgRows = cmd.rows;\n imgCols = Math.max(1, Math.ceil((bitmap.width / bitmap.height) * (imgRows * ch) / cw));\n } else {\n imgCols = Math.ceil(bitmap.width / cw);\n imgRows = Math.ceil(bitmap.height / ch);\n }\n\n let w = bitmap.width;\n let h = bitmap.height;\n\n // Scale bitmap to fit placement rectangle when c/r are specified\n if (cmd.columns !== undefined || cmd.rows !== undefined) {\n w = Math.round(imgCols * cw);\n h = Math.round(imgRows * ch);\n }\n\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n\n // Save cursor position before addImage modifies it\n const buffer = this._coreTerminal._core.buffer;\n const savedX = buffer.x;\n const savedY = buffer.y;\n const savedYbase = buffer.ybase;\n\n // Determine layer based on z-index: negative = behind text, 0+ = on top.\n // When z<0 we always use the bottom layer even without allowTransparency —\n // the image will simply be hidden behind the opaque text background, which\n // is the correct behavior (client asked for \"behind text\").\n const wantsBottom = cmd.zIndex !== undefined && cmd.zIndex < 0;\n const layer: ImageLayer = wantsBottom ? 'bottom' : 'top';\n\n if (w !== bitmap.width || h !== bitmap.height) {\n const scaled = await createImageBitmap(bitmap, { resizeWidth: w, resizeHeight: h });\n bitmap.close();\n bitmap = scaled;\n }\n\n // Per spec: X/Y are pixel offsets within the first cell, so clamp to cell dimensions\n const xOffset = Math.min(Math.max(0, cmd.xOffset ?? 0), cw - 1);\n const yOffset = Math.min(Math.max(0, cmd.yOffset ?? 0), ch - 1);\n if (xOffset !== 0 || yOffset !== 0) {\n // Per spec: X/Y is not added to c/r area. When c/r are explicit, the\n // total placement area remains c*cw × r*ch pixels and the offset image\n // is clipped to fit. When c/r are unset, the padded canvas determines\n // the natural cell dimensions.\n const canvasW = (cmd.columns !== undefined) ? Math.round(imgCols * cw) : bitmap.width + xOffset;\n const canvasH = (cmd.rows !== undefined) ? Math.round(imgRows * ch) : bitmap.height + yOffset;\n const offsetCanvas = ImageRenderer.createCanvas(window.document, canvasW, canvasH);\n const offsetCtx = offsetCanvas.getContext('2d');\n if (!offsetCtx) {\n throw new Error('Failed to create offset canvas context');\n }\n offsetCtx.drawImage(bitmap, xOffset, yOffset);\n\n const offsetBitmap = await createImageBitmap(offsetCanvas);\n offsetCanvas.width = offsetCanvas.height = 0;\n bitmap.close();\n bitmap = offsetBitmap;\n w = bitmap.width;\n h = bitmap.height;\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n if (cmd.columns === undefined) {\n imgCols = Math.ceil(bitmap.width / cw);\n }\n if (cmd.rows === undefined) {\n imgRows = Math.ceil(bitmap.height / ch);\n }\n }\n\n if (generation !== this._generation) throw new Error('image decode canceled');\n const zIndex = cmd.zIndex ?? 0;\n this._kittyStorage.addImage(image.id, bitmap, true, layer, zIndex);\n bitmap = undefined; // ownership transferred to storage\n\n // Kitty cursor movement\n // Per spec: cursor placed at first column after last image column,\n // on the last row of the image. C=1 means don't move cursor.\n if (cmd.cursorMovement === 1) {\n // C=1: restore cursor to position before image was placed\n const scrolled = buffer.ybase - savedYbase;\n buffer.x = savedX;\n // Can't restore cursor to scrollback?\n buffer.y = Math.max(savedY - scrolled, 0);\n } else {\n // Default (C=0): advance cursor horizontally past the image\n // addImage already positioned cursor on the last row via lineFeeds\n buffer.x = Math.min(savedX + imgCols, this._coreTerminal.cols);\n }\n } catch (e) {\n bitmap?.close();\n throw e;\n }\n }\n\n // Create ImageBitmap from already-decoded image data.\n private async _createBitmap(image: IKittyImageData): Promise {\n let bytes: Uint8Array = new Uint8Array(await image.data.arrayBuffer());\n\n if (image.compression === KittyCompression.ZLIB) {\n bytes = await this._decompressZlib(bytes);\n }\n\n if (image.format === KittyFormat.PNG) {\n const metrics = imageType(bytes);\n // IHDR dimensions are parsed with signed shifts, so a value >= 0x80000000 comes\n // back negative and a bare `>` pixel-limit test passes it; require positive.\n if (metrics.mime !== 'image/png' || !(metrics.width > 0) || !(metrics.height > 0) || metrics.width * metrics.height > this._opts.pixelLimit) {\n throw new RangeError('PNG exceeds pixel limit or has invalid dimensions');\n }\n const blob = new Blob([bytes as BlobPart], { type: 'image/png' });\n if (!window.createImageBitmap) {\n const url = URL.createObjectURL(blob);\n const img = new Image();\n return new Promise((resolve, reject) => {\n img.addEventListener('load', () => {\n URL.revokeObjectURL(url);\n const canvas = ImageRenderer.createCanvas(window.document, img.width, img.height);\n canvas.getContext('2d')?.drawImage(img, 0, 0);\n createImageBitmap(canvas).then(resolve).catch(reject);\n });\n img.addEventListener('error', () => {\n URL.revokeObjectURL(url);\n reject(new Error('Failed to load image'));\n });\n img.src = url;\n });\n }\n return createImageBitmap(blob);\n }\n\n // Raw pixel data\n const width = image.width;\n const height = image.height;\n\n if (!width || !height) {\n throw new Error('Width and height required for raw pixel data');\n }\n\n const bytesPerPixel = image.format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n throw new Error('Insufficient pixel data');\n }\n\n const pixelCount = width * height;\n\n if (image.format === KittyFormat.RGBA) {\n // RGBA: use bytes directly — no copy needed\n return createImageBitmap(new ImageData(new Uint8ClampedArray(bytes.buffer as ArrayBuffer, bytes.byteOffset, pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA), width, height));\n }\n\n // RGB→RGBA: interleave alpha using uint32 block processing (4 pixels per iteration).\n // 3 uint32 reads + 4 uint32 writes per 4 pixels vs 28 byte reads/writes — ~6x faster.\n // Assumes little-endian (all modern browsers/Node.js).\n const data = new Uint8ClampedArray(pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA);\n const src32 = new Uint32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4));\n const dst32 = new Uint32Array(data.buffer);\n const alignedPixels = pixelCount & ~3; // round down to multiple of 4\n\n let srcOffset = 0;\n let dstOffset = 0;\n for (let i = 0; i < alignedPixels; i += 4) {\n const b0 = src32[srcOffset++];\n const b1 = src32[srcOffset++];\n const b2 = src32[srcOffset++];\n // Little-endian: pixel bytes are [R,G,B] → uint32 ABGR layout\n dst32[dstOffset++] = 0xFF000000 | b0;\n dst32[dstOffset++] = 0xFF000000 | (b0 >>> 24) | (b1 << 8);\n dst32[dstOffset++] = 0xFF000000 | (b1 >>> 16) | (b2 << 16);\n dst32[dstOffset++] = 0xFF000000 | (b2 >>> 8);\n }\n\n // Handle remaining 1–3 pixels\n let srcByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n let dstByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n for (let i = alignedPixels; i < pixelCount; i++) {\n data[dstByte] = bytes[srcByte];\n data[dstByte + 1] = bytes[srcByte + 1];\n data[dstByte + 2] = bytes[srcByte + 2];\n data[dstByte + 3] = KittyPixelConstants.ALPHA_OPAQUE;\n srcByte += KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n dstByte += KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n }\n\n return createImageBitmap(new ImageData(data, width, height));\n }\n\n private async _decompressZlib(compressed: Uint8Array): Promise {\n try {\n return await this._decompress(compressed, 'deflate');\n } catch (error) {\n if (error instanceof RangeError) throw error;\n return await this._decompress(compressed, 'deflate-raw');\n }\n }\n\n private async _decompress(compressed: Uint8Array, format: 'deflate' | 'deflate-raw'): Promise {\n const limit = Math.min(this._opts.kittySizeLimit, this._opts.pixelLimit * 4, this._opts.storageLimit * 1000000);\n let offsetIn = 0;\n // Bound inflation within one native transform before its output is budgeted.\n const source = new ReadableStream({\n pull(controller) {\n if (offsetIn >= compressed.length) {\n controller.close();\n return;\n }\n const end = Math.min(offsetIn + 4096, compressed.length);\n controller.enqueue(new Uint8Array(compressed.subarray(offsetIn, end)));\n offsetIn = end;\n }\n });\n const reader = source.pipeThrough(new DecompressionStream(format)).getReader();\n const chunks: Uint8Array[] = [];\n let totalLength = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n totalLength += value.byteLength;\n if (totalLength > limit) {\n await reader.cancel().catch(() => {});\n throw new RangeError('decompressed image exceeds byte limit');\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n }\n\n public get images(): ReadonlyMap {\n return this._kittyStorage.images;\n }\n\n public get _kittyIdToStorageId(): ReadonlyMap {\n return this._kittyStorage.kittyIdToStorageId;\n }\n\n public get pendingTransmissions(): ReadonlyMap {\n return this._pendingTransmissions;\n }\n}\n","/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Kitty graphics protocol types, constants, and parsing utilities.\n */\n\nimport type Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\n\n// Kitty graphics protocol action types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'a'.\nexport const enum KittyAction {\n TRANSMIT = 't',\n TRANSMIT_DISPLAY = 'T',\n QUERY = 'q',\n PLACEMENT = 'p',\n DELETE = 'd'\n}\n\n// Kitty graphics protocol format types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyFormat {\n RGB = 24,\n RGBA = 32,\n PNG = 100\n}\n\n// Kitty graphics protocol compression types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'o'.\nexport const enum KittyCompression {\n NONE = '',\n ZLIB = 'z'\n}\n\n// Kitty graphics protocol control data keys.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyKey {\n // Action to perform (t=transmit, T=transmit+display, q=query, p=placement, d=delete)\n ACTION = 'a',\n // Image format (24=RGB, 32=RGBA, 100=PNG)\n FORMAT = 'f',\n // Image ID for referencing stored images\n ID = 'i',\n // Image number (alternative to ID, terminal assigns ID)\n IMAGE_NUMBER = 'I',\n // Source image width in pixels\n WIDTH = 's',\n // Source image height in pixels\n HEIGHT = 'v',\n // The left edge (in pixels) of the image area to display\n X_OFFSET = 'x',\n // The top edge (in pixels) of the image area to display\n Y_OFFSET = 'y',\n // Width (in pixels) of the source rectangle to display\n SOURCE_WIDTH = 'w',\n // Height (in pixels) of the source rectangle to display\n SOURCE_HEIGHT = 'h',\n // Horizontal offset (in pixels) within the first cell\n X_PLACEMENT_OFFSET = 'X',\n // Vertical offset (in pixels) within the first cell\n Y_PLACEMENT_OFFSET = 'Y',\n // Number of terminal columns to display the image over\n COLUMNS = 'c',\n // Number of terminal rows to display the image over\n ROWS = 'r',\n // More data flag (1=more chunks coming, 0=final chunk)\n MORE = 'm',\n // Compression type (z=zlib). This is essential for chunking larger images.\n COMPRESSION = 'o',\n // Quiet mode (1=suppress OK responses, 2=suppress error responses)\n QUIET = 'q',\n // Cursor movement policy (0=move cursor after image, 1=don't move cursor)\n CURSOR_MOVEMENT = 'C',\n // Z-index for image layering (negative = behind text, 0+ = on top)\n Z_INDEX = 'z',\n // Transmission medium (d=direct, f=file, t=temp file, s=shared memory)\n TRANSMISSION = 't',\n // Delete selector (a/A=all, i/I=by id, c/C=at cursor, etc.) — only used when a=d\n DELETE_SELECTOR = 'd',\n // Placement ID for targeting specific placements\n PLACEMENT_ID = 'p'\n}\n\n// Pixel format constants\nexport const enum KittyPixelConstants {\n BYTES_PER_PIXEL_RGB = 3,\n BYTES_PER_PIXEL_RGBA = 4,\n ALPHA_OPAQUE = 255\n}\n\n// Parsed Kitty graphics command.\nexport interface IKittyCommand {\n action?: string;\n format?: number;\n id?: number;\n imageNumber?: number;\n width?: number;\n height?: number;\n x?: number;\n y?: number;\n sourceWidth?: number;\n sourceHeight?: number;\n xOffset?: number;\n yOffset?: number;\n columns?: number;\n rows?: number;\n more?: number;\n quiet?: number;\n cursorMovement?: number;\n zIndex?: number;\n transmission?: string;\n deleteSelector?: string;\n placementId?: number;\n compression?: string;\n payload?: string;\n}\n\n// Pending chunked transmission state.\n// Stores metadata from the first chunk while accumulating decoded payload data.\nexport interface IPendingTransmission {\n // The parsed command from the first chunk (contains action, format, dimensions, etc.)\n cmd: IKittyCommand;\n // Decoder used across chunked payloads\n decoder: Base64Decoder;\n // Total encoded (base64) bytes received across all chunks - for size limit enforcement\n totalEncodedSize: number;\n // Whether any chunk has failed to decode\n decodeError: boolean;\n}\n\n// Stored Kitty image data.\nexport interface IKittyImageData {\n id: number;\n // Decoded image data stored as Blob (off JS heap) to avoid 2GB heap limit\n data: Blob;\n width: number;\n height: number;\n format: 24 | 32 | 100;\n compression?: string;\n}\n\n// Parses Kitty graphics control data into a command object.\nexport function parseKittyCommand(data: string): IKittyCommand {\n const cmd: IKittyCommand = {};\n const parts = data.split(',');\n\n for (const part of parts) {\n const eqIdx = part.indexOf('=');\n if (eqIdx === -1) continue;\n\n const key = part.substring(0, eqIdx);\n const value = part.substring(eqIdx + 1);\n\n // Handle string keys first\n if (key === KittyKey.ACTION) {\n cmd.action = value;\n continue;\n }\n if (key === KittyKey.COMPRESSION) {\n cmd.compression = value;\n continue;\n }\n if (key === KittyKey.TRANSMISSION) {\n cmd.transmission = value;\n continue;\n }\n if (key === KittyKey.DELETE_SELECTOR) {\n cmd.deleteSelector = value;\n continue;\n }\n const numValue = parseInt(value, 10);\n switch (key) {\n case KittyKey.FORMAT: cmd.format = numValue; break;\n case KittyKey.ID: cmd.id = numValue; break;\n case KittyKey.IMAGE_NUMBER: cmd.imageNumber = numValue; break;\n case KittyKey.WIDTH: cmd.width = numValue; break;\n case KittyKey.HEIGHT: cmd.height = numValue; break;\n case KittyKey.X_OFFSET: cmd.x = numValue; break;\n case KittyKey.Y_OFFSET: cmd.y = numValue; break;\n case KittyKey.SOURCE_WIDTH: cmd.sourceWidth = numValue; break;\n case KittyKey.SOURCE_HEIGHT: cmd.sourceHeight = numValue; break;\n case KittyKey.X_PLACEMENT_OFFSET: cmd.xOffset = numValue; break;\n case KittyKey.Y_PLACEMENT_OFFSET: cmd.yOffset = numValue; break;\n case KittyKey.COLUMNS: cmd.columns = numValue; break;\n case KittyKey.ROWS: cmd.rows = numValue; break;\n case KittyKey.MORE: cmd.more = numValue; break;\n case KittyKey.QUIET: cmd.quiet = numValue; break;\n case KittyKey.CURSOR_MOVEMENT: cmd.cursorMovement = numValue; break;\n case KittyKey.Z_INDEX: cmd.zIndex = numValue; break;\n case KittyKey.PLACEMENT_ID: cmd.placementId = numValue; break;\n }\n }\n\n return cmd;\n}\n","/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageStorage } from '../ImageStorage';\nimport { ImageLayer, IAddImageOpts } from '../Types';\nimport { IKittyImageData } from './KittyGraphicsTypes';\n\n// Kitty-specific image storage controller.\n//\n// Wraps shared ImageStorage with kitty protocol semantics:\n// - tracks transmitted image payloads by kitty image id\n// - tracks kitty image id -> shared ImageStorage id mapping for displayed images\n// - mirrors shared-storage evictions into kitty maps\n// - applies protocol-level undisplayed-image eviction policy\nexport class KittyImageStorage implements IDisposable {\n private static readonly _maxStoredImages = 256;\n\n private _nextImageId = 1;\n private readonly _images: Map = new Map();\n // TODO: Support multiple placements per image. The kitty spec identifies\n // placements by an (image id, placement id) pair — same i + different p\n // values should coexist, and same i + same p should replace the prior\n // placement. Currently we track only one storage entry per kitty image id,\n // so multiple placements of the same image overwrite each other. Fixing\n // this requires changing these maps to Map>\n // (kittyId → placementId → storageId) and updating addImage/deleteById\n // accordingly. The underlying shared ImageStorage would also need to\n // support multiple entries per logical image.\n private readonly _kittyIdToStorageId: Map = new Map();\n private readonly _storageIdToKittyId: Map = new Map();\n\n private readonly _previousOnImageDeleted: ((storageId: number) => void) | undefined;\n private readonly _wrappedOnImageDeleted: (storageId: number) => void;\n private readonly _handleStorageImageDeleted = (storageId: number): void => {\n const kittyId = this._storageIdToKittyId.get(storageId);\n if (kittyId !== undefined) {\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n this._images.delete(kittyId);\n }\n };\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n\n constructor(\n private readonly _storage: ImageStorage\n ) {\n this._previousOnImageDeleted = this._storage.onImageDeleted;\n this._wrappedOnImageDeleted = (storageId: number) => {\n this._previousOnImageDeleted?.(storageId);\n this._handleStorageImageDeleted(storageId);\n };\n this._storage.onImageDeleted = this._wrappedOnImageDeleted;\n }\n\n public reset(): void {\n this._nextImageId = 1;\n this._images.clear();\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public dispose(): void {\n this.reset();\n if (this._storage.onImageDeleted === this._wrappedOnImageDeleted) {\n this._storage.onImageDeleted = this._previousOnImageDeleted;\n }\n }\n\n public storeImage(id: number | undefined, imageData: Omit): number {\n const imageId = id ?? this._nextImageId++;\n\n const oldStorageId = this._kittyIdToStorageId.get(imageId);\n if (oldStorageId !== undefined) {\n this._storage.deleteImage(oldStorageId);\n this._kittyIdToStorageId.delete(imageId);\n this._storageIdToKittyId.delete(oldStorageId);\n }\n\n if (!this._images.has(imageId) && this._images.size >= KittyImageStorage._maxStoredImages) {\n this._evictUndisplayedImages();\n }\n\n // Encoded images awaiting placement are outside ImageStorage's pixel budget.\n // Unplaced payloads are evicted first so a new upload cannot erase a visible\n // image while abandoned blobs still hold budget; placed ones go only when\n // that is not enough, because the byte cap is a hard bound. The new image is\n // always stored, so an oversized one overshoots by at most one payload\n // (itself bounded by kittySizeLimit) rather than being dropped after an OK ack.\n const byteLimit = this._storage.getLimit() * 1000000;\n this._images.delete(imageId);\n let retainedBytes = 0;\n for (const image of this._images.values()) retainedBytes += image.data.size;\n for (const evictPlaced of [false, true]) {\n for (const [oldestId, image] of this._images) {\n if (retainedBytes + imageData.data.size <= byteLimit) break;\n if (this._kittyIdToStorageId.has(oldestId) !== evictPlaced) continue;\n retainedBytes -= image.data.size;\n this.deleteById(oldestId);\n }\n }\n\n this._images.set(imageId, {\n ...imageData,\n id: imageId\n });\n return imageId;\n }\n\n public addImage(kittyId: number, image: HTMLCanvasElement | ImageBitmap, scrolling: boolean, layer: ImageLayer, zIndex: number): void {\n // Clean up stale reverse-mapping from a previous placement of the same\n // kitty image. The old shared-storage entry is kept (it may still be\n // visible on screen) but its reverse mapping is removed so that eviction\n // of the old entry won't incorrectly delete the kitty image data.\n const oldStorageId = this._kittyIdToStorageId.get(kittyId);\n if (oldStorageId !== undefined) {\n this._storageIdToKittyId.delete(oldStorageId);\n }\n this._addImageOpts.scrolling = scrolling;\n this._addImageOpts.layer = layer;\n this._addImageOpts.zIndex = zIndex;\n const storageId = this._storage.addImage(image, this._addImageOpts);\n this._kittyIdToStorageId.set(kittyId, storageId);\n this._storageIdToKittyId.set(storageId, kittyId);\n }\n\n public getImage(kittyId: number): IKittyImageData | undefined {\n return this._images.get(kittyId);\n }\n\n public deleteById(kittyId: number): void {\n this._images.delete(kittyId);\n const storageId = this._kittyIdToStorageId.get(kittyId);\n if (storageId !== undefined) {\n this._storage.deleteImage(storageId);\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n }\n }\n\n public deleteAll(): void {\n this._images.clear();\n for (const storageId of this._kittyIdToStorageId.values()) {\n this._storage.deleteImage(storageId);\n }\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public get images(): ReadonlyMap {\n return this._images;\n }\n\n public get kittyIdToStorageId(): ReadonlyMap {\n return this._kittyIdToStorageId;\n }\n\n public get lastImageId(): number {\n return this._nextImageId - 1;\n }\n\n private _evictUndisplayedImages(): void {\n for (const [kittyId] of this._images) {\n if (this._images.size <= KittyImageStorage._maxStoredImages / 2) {\n break;\n }\n if (!this._kittyIdToStorageId.has(kittyId)) {\n this._images.delete(kittyId);\n }\n }\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023, 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\n/**\n * wasm base64 decoder.\n */\nconst wasmDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#828e69684093b2c6:rdef-start:\"decode\"*/{s:1,t:0,d:'AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML'}/*inwasm#828e69684093b2c6:rdef-end:\"decode\"*/);\n// SIMD version (speedup ~1.4x, not covered by tests yet)\n/*\nconst wasmDecode = InWasm({\n name: 'decode',\n type: OutputType.INSTANCE,\n mode: OutputMode.SYNC,\n srctype: 'Clang-C',\n imports: {\n env: { memory: new WebAssembly.Memory({ initial: 1 }) }\n },\n exports: {\n dec: () => 0,\n end: () => 0\n },\n compile: {\n switches: ['-msimd128', '-Wl,-z,stack-size=0', '-Wl,--stack-first']\n },\n code: `\n #include \n typedef struct {\n unsigned int wp;\n unsigned int sp;\n unsigned int dp;\n unsigned int e_size;\n unsigned int dummy[4];\n unsigned char data[0];\n } State;\n\n unsigned int *D0 = (unsigned int *) ${P32.D0 * 4};\n unsigned int *D1 = (unsigned int *) ${P32.D1 * 4};\n unsigned int *D2 = (unsigned int *) ${P32.D2 * 4};\n unsigned int *D3 = (unsigned int *) ${P32.D3 * 4};\n State *state = (State *) ${P32.STATE * 4};\n\n #define packed_byte(x) wasm_i8x16_splat((char) x)\n #define packed_dword(x) wasm_i32x4_splat(x)\n #define masked(x, mask) wasm_v128_and(x, wasm_i32x4_splat(mask))\n\n __attribute__((noinline)) int dec() {\n unsigned int nsp = (state->wp - 1) & ~3;\n unsigned char *src = state->data + state->sp;\n unsigned char *end = state->data + nsp;\n unsigned char *dst = state->data + state->dp;\n unsigned int error = 0;\n\n v128_t err = wasm_i8x16_splat(0);\n unsigned char *end16 = state->data + (nsp & ~15);\n while (src < end16) {\n v128_t data = wasm_v128_load((v128_t *) src);\n\n // wasm-simd rewrite of http://0x80.pl/notesen/2016-01-17-sse-base64-decoding.html#vector-lookup-pshufb\n const v128_t higher_nibble = wasm_u32x4_shr(data, 4) & packed_byte(0x0f);\n const char linv = 1;\n const char hinv = 0;\n\n const v128_t lower_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n linv, linv, 0x2b, 0x30,\n 0x41, 0x50, 0x61, 0x70,\n linv, linv, linv, linv,\n linv, linv, linv, linv\n );\n const v128_t upper_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n hinv, hinv, 0x2b, 0x39,\n 0x4f, 0x5a, 0x6f, 0x7a,\n hinv, hinv, hinv, hinv,\n hinv, hinv, hinv, hinv\n );\n // the difference between the shift and lower bound\n const v128_t shift_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n 0x00, 0x00, 0x3e - 0x2b, 0x34 - 0x30,\n 0x00 - 0x41, 0x0f - 0x50, 0x1a - 0x61, 0x29 - 0x70,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00\n );\n\n const v128_t upper_bound = wasm_i8x16_swizzle(upper_bound_LUT, higher_nibble);\n const v128_t lower_bound = wasm_i8x16_swizzle(lower_bound_LUT, higher_nibble);\n\n const v128_t below = wasm_i8x16_lt(data, lower_bound);\n const v128_t above = wasm_i8x16_gt(data, upper_bound);\n const v128_t eq_2f = wasm_i8x16_eq(data, packed_byte(0x2f));\n\n // in_range = not (below or above) or eq_2f\n // outside = not in_range = below or above and not eq_2f (from deMorgan law)\n const v128_t outside = wasm_v128_andnot(eq_2f, above | below);\n err = wasm_v128_or(err, outside);\n\n const v128_t shift = wasm_i8x16_swizzle(shift_LUT, higher_nibble);\n const v128_t t0 = wasm_i8x16_add(data, shift);\n v128_t v = wasm_i8x16_add(t0, wasm_v128_and(eq_2f, packed_byte(-3)));\n\n // pack bytes\n const v128_t ca = masked(v, 0x003f003f);\n const v128_t db = masked(v, 0x3f003f00);\n const v128_t t00 = wasm_v128_or(wasm_u32x4_shr(db, 8), wasm_i32x4_shl(ca, 6));\n v128_t res = wasm_v128_or(wasm_u32x4_shr(t00, 16), wasm_i32x4_shl(t00, 12));\n res = wasm_i8x16_swizzle(res, wasm_i8x16_const(2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, 16, 16, 16, 16));\n\n wasm_v128_store((v128_t *) dst, res);\n dst += 12;\n src += 16;\n }\n //if (wasm_i8x16_bitmask(err) != 0) return -1;\n if (wasm_v128_any_true(err)) return -1;\n\n // operate on 4-byte blocks\n while (src < end) {\n error |= *((unsigned int *) dst) = D0[src[0]] | D1[src[1]] | D2[src[2]] | D3[src[3]];\n dst += 3;\n src += 4;\n }\n if (error >> 24) return -1;\n state->sp = nsp;\n state->dp = dst - state->data;\n return 0;\n }\n\n int end() {\n int rem = state->wp - state->sp;\n if (rem > 4 && dec()) return -1;\n rem = state->wp - state->sp;\n if (rem < 2) return -1;\n\n unsigned char *src = state->data + state->sp;\n if (rem == 4) {\n if (src[3] == 61) rem--;\n if (src[2] == 61) rem--;\n }\n unsigned int accu = D0[src[0]] | D1[src[1]];\n int dp = 1;\n if (rem > 2) {\n accu |= D2[src[2]];\n dp++;\n if (rem == 4) {\n accu |= D3[src[3]];\n dp++;\n }\n }\n if (accu >> 24) return -1;\n *((unsigned int *) (state->data + state->dp)) = accu;\n state->dp += dp;\n return 0;\n }\n `\n});\n*/\n// base64 map\nconst MAP = new Uint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n .split('')\n .map(el => el.charCodeAt(0)));\n// init decoder maps in LE order\nconst D = new Uint32Array(1024);\nD.fill(0xFF000000);\nfor (let i = 0; i < MAP.length; ++i)\n D[MAP[i]] = i << 2;\nfor (let i = 0; i < MAP.length; ++i)\n D[256 + MAP[i]] = i >> 4 | ((i << 4) & 0xFF) << 8;\nfor (let i = 0; i < MAP.length; ++i)\n D[512 + MAP[i]] = (i >> 2) << 8 | ((i << 6) & 0xFF) << 16;\nfor (let i = 0; i < MAP.length; ++i)\n D[768 + MAP[i]] = i << 16;\nconst EMPTY = new Uint8Array(0);\n/**\n * base64 stream decoder.\n *\n * Features / assumptions:\n * - lazy chunkwise decoding\n * - errors out on any non base64 chars (no support for NL formatted base64)\n * - decodes in wasm\n * - inplace decoding to save memory\n * - supports a keepSize for lazy memory release\n */\nclass Base64Decoder {\n /**\n * @param keepSize Keep the wasm instance below this limit when calling `release()`.\n * @param maxBytes Max allowed bytes to allocate.\n * @param initialBytes Initial bytes to allocate.\n */\n constructor(keepSize, maxBytes, initialBytes) {\n this._inst = null;\n this._ended = true;\n this._bytes = 0;\n this.keepSize = keepSize !== null && keepSize !== void 0 ? keepSize : 1048576 /* Bytes.KEEP */;\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : 4294901760 /* Bytes.MAX */;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : 32768 /* Bytes.INITIAL */;\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw new Error('invalid byte settings');\n }\n }\n /**\n * Currently decoded bytes (borrowed).\n * Must be accessed before calling `release` or `init`.\n */\n get data8() {\n return this._inst ? this._d.subarray(0, this._m32[1282 /* P32.STATE_DP */]) : EMPTY;\n }\n /**\n * Release memory conditionally based on `keepSize`.\n * If memory gets released, also the wasm instance will be freed and recreated on next `init`,\n * otherwise the instance will be reused.\n */\n release() {\n if (!this._inst)\n return;\n if (this._bytes > this.keepSize) {\n this._inst = this._m32 = this._d = this._mem = null;\n }\n else {\n this._m32[1280 /* P32.STATE_WP */] = 0;\n this._m32[1281 /* P32.STATE_SP */] = 0;\n this._m32[1282 /* P32.STATE_DP */] = 0;\n }\n }\n /**\n * Initializes the decoder for new base64 data.\n * Must be called before doing any decoding attempts.\n * The method will either spawn a new wasm instance or grow\n * the needed memory of an existing instance.\n * @param maxBytes Max allowed bytes to allocate (overwrites ctor value).\n * @param initialBytes Initial bytes to allocate (overwrites ctor value).\n */\n init(maxBytes, initialBytes) {\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : this.maxBytes;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : Math.min(this._bytes, this.maxBytes);\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw Error('invalid byte settings');\n }\n let m = this._m32;\n const bytes = this._bytes + 5152 /* Bytes._DATA_OFFSET */;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmDecode({ env: { memory: this._mem } });\n m = new Uint32Array(this._mem.buffer, 0);\n m.set(D, 256 /* P32.D0 */);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n m = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n m[1280 /* P32.STATE_WP */] = 0;\n m[1281 /* P32.STATE_SP */] = 0;\n m[1282 /* P32.STATE_DP */] = 0;\n this._m32 = m;\n this._ended = false;\n }\n /**\n * Realloc memory. Realloc only happens, if the requested\n * size doesn't fit in the current memory.\n * The new size will be capped by `maxBytes`.\n * @param requested Bytes to be stored.\n */\n _realloc(requested) {\n const needed = this._m32[1280 /* P32.STATE_WP */] + requested;\n if (this._bytes < needed) {\n if (needed > this.maxBytes) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n let newSize = this._bytes;\n while ((newSize *= 2) < needed) { }\n newSize = Math.min(newSize, this.maxBytes);\n if (newSize < needed) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n if (newSize + 5152 /* Bytes._DATA_OFFSET */ > this._mem.buffer.byteLength) {\n const addPages = Math.ceil((newSize + 5152 /* Bytes._DATA_OFFSET */ - this._mem.buffer.byteLength) / 65536);\n this._mem.grow(addPages);\n this._m32 = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n this._bytes = newSize;\n }\n return 0 /* DecodeStatus.OK */;\n }\n /**\n * Put bytes in `data` into the decoder.\n * Additionally decodes the payload, if it reached 2^17 bytes.\n * The return value indicates the type of issue.\n * @param data Bytes to be loaded.\n */\n put(data) {\n if (!this._inst || this._ended) {\n return -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n if (this._realloc(data.length)) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n const m = this._m32;\n this._d.set(data, m[1280 /* P32.STATE_WP */]);\n m[1280 /* P32.STATE_WP */] += data.length;\n // max chunk in input handler is 2^17, try to run in \"tandem mode\"\n return m[1280 /* P32.STATE_WP */] - m[1281 /* P32.STATE_SP */] >= 131072\n ? this._inst.exports.dec()\n : 0 /* DecodeStatus.OK */;\n }\n /**\n * End the current decoding.\n * Also decodes leftover payload from previous put calls.\n */\n end() {\n this._ended = true;\n return this._inst\n ? this._inst.exports.end()\n : -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n /**\n * Bytes loaded into the decoder.\n */\n get loadedBytes() {\n return this._inst\n ? this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n /**\n * Free bytes to feed to the decoder.\n */\n get freeBytes() {\n return this._inst\n ? this.maxBytes - this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n}\nexports.default = Base64Decoder;\n//# sourceMappingURL=Base64Decoder.wasm.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\nconst wasmQoiDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#459f9e1bfb80b1a8:rdef-start:\"qoi_decode\"*/{s:1,t:0,d:'AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=='}/*inwasm#459f9e1bfb80b1a8:rdef-end:\"qoi_decode\"*/);\nclass QoiDecoder {\n constructor(keepSize) {\n this.keepSize = keepSize;\n this.width = 0;\n this.height = 0;\n }\n decode(d) {\n this.width = d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7];\n this.height = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];\n const pixels = this.width * this.height;\n const ib = pixels * 4;\n const dl = d.length;\n /**\n * byte/offset calculation:\n * To save some memory we dont reserve full memory for decoded + encoded,\n * but place encoded at the end of decoded plus 50% security distance\n * to avoid reads before writes positions:\n *\n * encoded < decoded (good compression)\n * enc ####################\n * dec #######################################\n * ^ ^\n * DST_P CHUNK_P\n *\n * encoded > decoded (degenerated compression, should not happen)\n * enc ##############################\n * dec ####################\n * ^ ^\n * DST_P CHUNK_P\n *\n * There is still a chance for overlapping r/w positions in case the compressed\n * data has very different pixel progression, yet the 50% security distance\n * should deal with that, as QOI will bloat data by 25% at max (RGB -> OP byte + RGB).\n * Since we always assume RGBA at decoding stage, the possible bloat reduces to 20% at max.\n */\n const bytes = Math.max(ib, dl) + (Math.min(ib, dl) >> 1) + 4096;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmQoiDecode({ env: { memory: this._mem } });\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n this._d = null;\n }\n if (!this._d) {\n this._d = new Uint8Array(this._mem.buffer);\n }\n // put src data at the end of memory, also align to 256\n const chunkP = (this._mem.buffer.byteLength - dl) & ~0xFF;\n this._d.set(d, chunkP);\n this._inst.exports.dec(chunkP, dl, pixels);\n return this._d.subarray(1024 /* P8.DST_P */, 1024 /* P8.DST_P */ + ib);\n }\n release() {\n if (!this._inst)\n return;\n if (this._mem.buffer.byteLength > this.keepSize) {\n this._inst = this._d = this._mem = null;\n }\n }\n}\nexports.default = QoiDecoder;\n//# sourceMappingURL=QoiDecoder.wasm.js.map","\"use strict\";\n/**\n * Copyright (c) 2022, 2026 Joerg Breitbart\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InWasm = InWasm;\nlet z = (s) => {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(s);\n if (typeof Buffer !== 'undefined')\n return Buffer.from(s, 'base64');\n const b = atob(s);\n const r = new Uint8Array(b.length);\n for (let i = 0; i < r.length; ++i)\n r[i] = b.charCodeAt(i);\n return r;\n};\nfunction InWasm(def) {\n if (def.d) {\n const { t, s, d } = def;\n let b;\n let m;\n const W = WebAssembly;\n if (t === 0 /* OutputType.INSTANCE */) {\n if (s)\n return (e) => new W.Instance(m || (m = new W.Module(b || (b = z(d)))), e);\n return (e) => m\n ? W.instantiate(m, e)\n : W.instantiate(b || (b = z(d)), e).then(r => (m = r.module) && r.instance);\n }\n if (t === 1 /* OutputType.MODULE */) {\n if (s)\n return () => m || (m = new W.Module(b || (b = z(d))));\n return () => m\n ? Promise.resolve(m)\n : W.compile(b || (b = z(d))).then(r => m = r);\n }\n if (s)\n return () => b || (b = z(d));\n return () => Promise.resolve(b || (b = z(d)));\n }\n if (typeof _wasmCtx === 'undefined')\n throw new Error('must run \"inwasm\"');\n _wasmCtx.add(def);\n}\n//# sourceMappingURL=index.js.map","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport type { ITerminalAddon, IDisposable } from '@xterm/xterm';\nimport type { ImageAddon as IImageApi } from '@xterm/addon-image';\nimport { Emitter, type IEvent } from 'common/Event';\nimport { IIPHandler } from './IIPHandler';\nimport { ImageRenderer } from './ImageRenderer';\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { KittyGraphicsHandler } from './kitty/KittyGraphicsHandler';\nimport { KittyImageStorage } from './kitty/KittyImageStorage';\nimport { SixelHandler } from './SixelHandler';\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { ITerminalExt, IImageAddonOptions, IResetHandler } from './Types';\n\n\n/**\n * Document VT features provided by this addon.\n *\n * @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL \"SIXEL Graphics\" \"DCS Ps ; Ps ; Ps ; q Pt ST\" \"Draw SIXEL image.\"\n *\n * Sixel support is provided by the addon @xterm/addon-image with these limitations:\n * - immediate coloring (no shared palette, allows high color settings of `img2sixel`)\n * - max. palette size of 4096 colors\n * - max. pixel width of 16K\n * - max. 25 MB per sixel sequence\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] OSC 1337 \"iTerm2 Commands\" \"OSC 1337 ; Pt BEL\" \"Custom iTerm2 commands.\"\n *\n * Only the inline image protocol (IIP) is supported by the addon @xterm/addon-image with\n * the following limitations:\n * - sequence:\n * - format: `OSC 1337 ; File=inline=1 ; size= ; ... : BEL`\n * - size param must be set and payload may not exceed CEIL(size * 4 / 3)\n * - strict base64 handling as of RFC4648 §4 (standard alphabet, optional padding,\n * no separator bytes allowed)\n * - supported params: size, name, width, height, preserveAspectRatio\n * - image formats: PNG, JPEG and GIF\n * - no animation support (renders first image of a GIF)\n * - no multipart support\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image)\n * and [iTerm2 IIP docs](https://iterm2.com/documentation-images.html) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] APC KITTY_GRAPHICS \"Kitty Graphics\" \"APC G Pt ST\" \"Kitty Graphics Protocol.\"\n *\n * Kitty graphics support is provided by the addon @xterm/addon-image.\n * Note that while basic image output already works, this is still work in progress.\n */\n\n// default values of addon ctor options\nconst DEFAULT_OPTIONS: IImageAddonOptions = {\n enableSizeReports: true,\n pixelLimit: 16777216, // limit to 4096 * 4096 pixels\n sixelSupport: true,\n sixelScrolling: true,\n sixelPaletteLimit: 4096,\n sixelSizeLimit: 33554432,\n storageLimit: 128,\n showPlaceholder: true,\n iipSupport: true,\n iipSizeLimit: 33554432,\n kittySupport: true,\n kittySizeLimit: 33554432\n};\n\n// max palette size supported by the sixel lib (compile time setting)\nconst MAX_SIXEL_PALETTE_SIZE = 4096;\n\n// definitions for _xtermGraphicsAttributes sequence\nconst enum GaItem {\n COLORS = 1,\n SIXEL_GEO = 2,\n REGIS_GEO = 3\n}\nconst enum GaAction {\n READ = 1,\n SET_DEFAULT = 2,\n SET = 3,\n READ_MAX = 4\n}\nconst enum GaStatus {\n SUCCESS = 0,\n ITEM_ERROR = 1,\n ACTION_ERROR = 2,\n FAILURE = 3\n}\n\n\nexport class ImageAddon implements ITerminalAddon, IImageApi {\n private _opts: IImageAddonOptions;\n private _defaultOpts: IImageAddonOptions;\n private _storage: ImageStorage | undefined;\n private _renderer: ImageRenderer | undefined;\n private _disposables: IDisposable[] = [];\n private _terminal: ITerminalExt | undefined;\n private _handlers: Map = new Map();\n private readonly _onImageAdded = new Emitter();\n public readonly onImageAdded: IEvent = this._onImageAdded.event;\n\n constructor(opts?: Partial) {\n this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);\n this._defaultOpts = Object.assign({}, DEFAULT_OPTIONS, opts);\n }\n\n public dispose(): void {\n for (const handler of this._handlers.values()) handler.reset();\n for (const obj of this._disposables) {\n obj.dispose();\n }\n this._disposables.length = 0;\n this._handlers.clear();\n this._onImageAdded.dispose();\n }\n\n private _disposeLater(...args: IDisposable[]): void {\n for (const obj of args) {\n this._disposables.push(obj);\n }\n }\n\n public activate(terminal: ITerminalExt): void {\n this._terminal = terminal;\n\n // internal data structures\n this._renderer = new ImageRenderer(terminal);\n this._storage = new ImageStorage(terminal, this._renderer, this._opts);\n this._storage.onImageAdded = () => this._onImageAdded.fire();\n\n // enable size reports\n if (this._opts.enableSizeReports) {\n const windowOps = terminal.options.windowOptions ?? {};\n windowOps.getWinSizePixels = true;\n windowOps.getCellSizePixels = true;\n windowOps.getWinSizeChars = true;\n terminal.options.windowOptions = windowOps;\n }\n\n this._disposeLater(\n this._renderer,\n this._storage,\n\n // DECSET/DECRST/DA1/XTSMGRAPHICS handlers\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'h' }, params => this._decset(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'l' }, params => this._decrst(params)),\n terminal.parser.registerCsiHandler({ final: 'c' }, params => this._da1(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'S' }, params => this._xtermGraphicsAttributes(params)),\n\n // render hook\n terminal.onRender(range => this._storage?.render(range)),\n\n /**\n * reset handlers covered:\n * - DECSTR\n * - RIS\n * - Terminal.reset()\n */\n terminal.parser.registerCsiHandler({ intermediates: '!', final: 'p' }, () => this.reset()),\n terminal.parser.registerEscHandler({ final: 'c' }, () => this.reset()),\n terminal._core._inputHandler.onRequestReset(() => this.reset()),\n\n // wipe canvas and delete alternate images on buffer switch\n terminal.buffer.onBufferChange(() => this._storage?.wipeAlternate()),\n\n // extend images to the right on resize\n terminal.onResize(metrics => this._storage?.viewportResize(metrics))\n );\n\n // SIXEL handler\n if (this._opts.sixelSupport) {\n const sixelStorage = new SixelImageStorage(this._storage!, this._opts, this._renderer!, terminal);\n const sixelHandler = new SixelHandler(this._opts, sixelStorage, terminal);\n this._handlers.set('sixel', sixelHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerDcsHandler({ final: 'q' }, sixelHandler)\n );\n }\n\n // iTerm IIP handler\n if (this._opts.iipSupport) {\n const iipStorage = new IIPImageStorage(this._storage!);\n const iipHandler = new IIPHandler(this._opts, this._renderer!, iipStorage, terminal);\n this._handlers.set('iip', iipHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerOscHandler(1337, iipHandler)\n );\n }\n\n // Kitty graphics handler\n if (this._opts.kittySupport) {\n const kittyStorage = new KittyImageStorage(this._storage!);\n const kittyHandler = new KittyGraphicsHandler(this._opts, this._renderer!, kittyStorage, terminal);\n this._handlers.set('kitty', kittyHandler);\n this._disposeLater(\n kittyStorage,\n kittyHandler,\n terminal._core._inputHandler._parser.registerApcHandler({ final: 'G' }, kittyHandler)\n );\n }\n }\n\n // Note: storageLimit is skipped here to not intoduce a surprising side effect.\n public reset(): boolean {\n // reset options customizable by sequences to defaults\n this._opts.sixelScrolling = this._defaultOpts.sixelScrolling;\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n // also clear image storage\n this._storage?.reset();\n // reset protocol handlers\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return false;\n }\n\n public get storageLimit(): number {\n return this._storage?.getLimit() || -1;\n }\n\n public set storageLimit(limit: number) {\n this._storage?.setLimit(limit);\n this._opts.storageLimit = limit;\n }\n\n public get storageUsage(): number {\n if (this._storage) {\n return this._storage.getUsage();\n }\n return -1;\n }\n\n public get showPlaceholder(): boolean {\n return this._opts.showPlaceholder;\n }\n\n public set showPlaceholder(value: boolean) {\n this._opts.showPlaceholder = value;\n this._renderer?.showPlaceholder(value);\n }\n\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.getImageAtBufferCell(x, y);\n }\n\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.extractTileAtBufferCell(x, y);\n }\n\n private _report(s: string): void {\n this._terminal?._core.input(s, false);\n }\n\n private _decset(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = false;\n break;\n }\n }\n return false;\n }\n\n private _decrst(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = true;\n break;\n }\n }\n return false;\n }\n\n // overload DA to return something more appropriate\n private _da1(params: (number | number[])[]): boolean {\n if (params[0]) {\n return true;\n }\n // reported features:\n // 62 - VT220\n // 4 - SIXEL support\n // 9 - charsets\n // 22 - ANSI colors\n if (this._opts.sixelSupport) {\n this._report(`\\x1b[?62;4;9;22c`);\n return true;\n }\n return false;\n }\n\n /**\n * Implementation of xterm's graphics attribute sequence.\n *\n * Supported features:\n * - read/change palette limits (max 4096 by sixel lib)\n * - read SIXEL canvas geometry (reports current window canvas or\n * squared pixelLimit if canvas > pixel limit)\n *\n * Everything else is deactivated.\n */\n private _xtermGraphicsAttributes(params: (number | number[])[]): boolean {\n if (params.length < 2) {\n return true;\n }\n if (params[0] === GaItem.COLORS) {\n switch (params[1]) {\n case GaAction.READ:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n return true;\n case GaAction.SET_DEFAULT:\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n // also reset protocol handlers for now\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return true;\n case GaAction.SET:\n if (params.length > 2 && !(params[2] instanceof Array) && params[2] <= MAX_SIXEL_PALETTE_SIZE) {\n this._opts.sixelPaletteLimit = params[2];\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n } else {\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n }\n return true;\n case GaAction.READ_MAX:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${MAX_SIXEL_PALETTE_SIZE}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n if (params[0] === GaItem.SIXEL_GEO) {\n switch (params[1]) {\n // we only implement read and read_max here\n case GaAction.READ:\n let width = this._renderer?.dimensions?.css.canvas.width;\n let height = this._renderer?.dimensions?.css.canvas.height;\n if (!width || !height) {\n // for some reason we have no working image renderer\n // --> fallback to default cell size\n const cellSize = CELL_SIZE_DEFAULT;\n width = (this._terminal?.cols || 80) * cellSize.width;\n height = (this._terminal?.rows || 24) * cellSize.height;\n }\n if (width * height < this._opts.pixelLimit) {\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${width.toFixed(0)};${height.toFixed(0)}S`);\n } else {\n // if we overflow pixelLimit report that squared instead\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n }\n return true;\n case GaAction.READ_MAX:\n // read_max returns pixelLimit as square area\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n // exit with error on ReGIS or any other requests\n this._report(`\\x1b[?${params[0]};${GaStatus.ITEM_ERROR}S`);\n return true;\n }\n}\n"],"names":["root","factory","exports","module","define","amd","globalThis","red","n","green","blue","toRGBA8888","r","g","b","a","clamp","low","high","value","Math","max","min","h2c","t1","t2","c","normalizeRGB","round","Object","defineProperty","DEFAULT_FOREGROUND","DEFAULT_BACKGROUND","PALETTE_ANSI_256","PALETTE_VT340_GREY","PALETTE_VT340_COLOR","normalizeHLS","nearestColorIndex","fromRGBA8888","alpha","BIG_ENDIAN","Uint8Array","Uint32Array","buffer","console","warn","color","palette","Number","MAX_SAFE_INTEGER","idx","i","length","dr","dg","db","d","h","l","s","v","HLStoRGB","p","push","decodeAsync","decode","Decoder","DecoderAsync","Colors_1","__webpack_require__","wasm_1","WASM_BYTES","Buffer","from","bytestring","atob","result","charCodeAt","decodeBase64","LIMITS","BYTES","WASM_MODULE","NULL_CANVAS","CallbackProxy","constructor","this","bandHandler","width","modeHandler","mode","handle_band","mode_parsed","DEFAULT_OPTIONS","memoryLimit","sixelColor","fillColor","paletteLimit","PALETTE_SIZE","truncate","opts","cbProxy","importObj","env","bind","WebAssembly","instantiate","then","inst","instance","_instance","_cbProxy","_PIXEL_OFFSET","MAX_WIDTH","_canvas","_bandWidths","_maxWidth","_minWidth","_lastOffset","_currentHeight","_opts","assign","Error","_handle_band","_initCanvas","Module","Instance","_wasm","_chunk","memory","get_chunk_address","CHUNK_SIZE","_states","get_state_address","_palette","get_palette_address","set","_pSrc","get_p0_address","init","_fillColor","_truncate","_rasterWidth","_rasterHeight","_width","_height","_level","_mode","_paletteLimit","pixels","height","release","_realloc","offset","additionalPixels","newCanvas","ceil","adv","remaining","subarray","current_width","current_height","memoryUsage","byteLength","properties","level","memUsage","rasterAttributes","numerator","denominator","data","start","end","decodeString","j","data32","currentWidth","fill","escape","final","finalOffset","bw","currentHeight","data8","Uint8ClampedArray","dec","async","Lifecycle_1","EventUtils","_listeners","_disposed","event","_event","listener","thisArgs","disposables","toDisposable","entry","fn","slice","indexOf","splice","Array","isArray","add","fire","call","listeners","len","dispose","forward","to","e","map","undefined","any","events","store","DisposableStore","runAndSubscribe","handler","initial","arg","_disposables","Set","_isDisposed","isDisposed","o","clear","Disposable","_store","_register","None","freeze","_value","ImageRenderer_1","ImageStorage_1","Base64Decoder_wasm_1","__importDefault","QoiDecoder_wasm_1","IIPHeaderParser_1","IIPMetrics_1","DEFAULT_HEADER","type","name","size","preserveAspectRatio","inline","_renderer","_storage","_coreTerminal","_generation","_aborted","_hp","HeaderParser","_header","_isMultipart","_abortMulti","maxEncodedBytes","iipSizeLimit","initialBytes","_dec","default","_qoiDec","reset","put","state","dataPos","parse","fields","_initDecoder","success","seqType","w","CELL_SIZE_DEFAULT","dimensions","css","canvas","cols","rows","scale","_c","_a","_core","_coreBrowserService","dpr","report","toFixed","input","cond","blob","metrics","UNSUPPORTED_TYPE","imageType","mime","pixelLimit","_resize","floor","ImageData","byteOffset","ImageRenderer","createCanvas","_b","getContext","putImageData","addImage","Blob","generation","createImageBitmap","resizeWidth","resizeHeight","bm","close","catch","cw","cell","ch","_d","rw","_dim","rh","wf","hf","f","total","cdim","endsWith","parseInt","toStr","String","fromCharCode","toInt","toSize","match","DECODERS","toString","bs","TextDecoder","FILE_MARKER","MULTIPARTFILE_MARKER","FILEPART_MARKER","FILEEND_MARKER","REPORTCELLSIZE_MARKER","MAX_FIELDCHARS","_buffer","_position","_key","k","_storeValue","pos","_storeKey","_addImageOpts","scrolling","layer","zIndex","cursorPos","img","d32","blockLength","jpgSize","dim","limit","_layers","get","localDocument","document","createElement","createImageData","ctx","imgData","Promise","resolve","_terminal","super","Map","_optionsRefresh","MutableDisposable","_oldOpen","open","parent","_open","screenElement","optionsService","onOptionChange","option","rescaleCanvas","_renderService","refreshRows","removeLayerFromDom","_oldSetRenderer","setRenderer","_placeholderBitmap","_placeholder","showPlaceholder","cellSize","_createPlaceHolder","clearLines","y","clearRect","_e","clearAll","draw","imgSpec","tileId","col","row","count","_rescaleImage","actual","sourceWidth","sourceHeight","actualCellSize","sx","sy","dx","dy","finalWidth","finalHeight","drawImage","extractTile","drawPlaceholder","values","spec","originalWidth","originalHeight","origCellSize","orig","scaledWidth","scaledHeight","renderer","key","keys","insertLayerToDom","has","classList","style","isolation","insertBefore","firstChild","appendChild","remove","delete","hasLayer","bWidth","blueprint","black","white","shift","x","screen","ctx2","placeholder","bitmap","window","ExtendedAttrsImage","ext","_urlId","_ext","underlineStyle","underlineColor","underlineVariantOffset","val","urlId","imageId","clone","isEmpty","EMPTY_ATTRS","_images","_lastId","_lowestId","_fullyCleared","_needsFullClear","_pixelLimit","setLimit","storageLimit","error","message","getLimit","_viewportMetrics","marker","RangeError","_evictOldest","getUsage","_getStoredPixels","storedPixels","_delImg","id","ImageBitmap","onImageDeleted","wipeAlternate","zero","entries","bufferType","deleteImage","termCols","termRows","originX","originY","tileCount","_inputHandler","_dirtyRowTracker","markDirty","line","lines","ybase","_writeToCell","lineFeed","endMarker","registerMarker","onDispose","active","_evictOnAlternate","onImageAdded","render","range","hasTopImages","hasBottomImages","drawCalls","placeholderCalls","ydisp","getBg","_extendedAttrs","startTile","startCol","sort","viewportResize","oldCol","tilesPerRow","hasData","rightCol","_data","lastTile","expandCol","getImageAtBufferCell","extractTileAtBufferCell","room","used","current","old","oldSpec","imgId","Decoder_1","DEFAULT_PALETTE","idleDecoders","poolPrimed","releaseDecoder","idle","convertLe","_size","_decMemoryLimit","_returnDecoder","hook","params","pop","acquireDecoder","attr","colors","bg","isInverse","isFgDefault","foreground","rgba","isFgRGB","t","toColorRGB","getFgColor","ansi","isBgDefault","background","isBgRGB","getBgColor","extractActiveBg","_curAttrData","_themeService","sixelPaletteLimit","sixelSizeLimit","unhook","_unhook","advanceCursor","sixelScrolling","KittyGraphicsTypes_1","_kittyStorage","_decodeError","_activeDecoder","_inControlData","_controlData","_controlLength","_encodedSizeLimit","_totalEncodedSize","_parsedCommand","_pendingTransmissions","_maxEncodedBytes","kittySizeLimit","_initialEncodedBytes","_cleanupAllPending","_removePendingEntry","_lastPendingKey","pending","decoder","controlEnd","copyLength","parseKittyCommand","_parseControlDataString","imageNumber","_sendResponse","quiet","action","payloadStart","_streamPayload","pendingKey","previousEncodedSize","_f","totalEncodedSize","decoderToRelease","_g","decoderCapacity","_h","maxPending","oldest","next","cmd","_j","_k","_handleNoPayloadCommand","_handleDelete","isMoreComing","more","decodeError","finalCmd","imageBytes","_handleCommandWithBytesAndCmd","str","fromCodePoint","_handlePlacement","bytes","_handleTransmit","transmission","_handleTransmitDisplay","_handleQuery","image","getImage","_displayImage","placementId","storeImage","format","compression","lastImageId","expectedBytes","deleteSelector","deleteAll","deleteById","isOk","response","coreService","triggerDataEvent","_decodeAndDisplay","_createBitmap","cropX","cropY","cropW","cropH","maxCropW","maxCropH","finalCropW","finalCropH","cropped","imgCols","imgRows","columns","savedX","savedY","savedYbase","scaled","xOffset","yOffset","canvasW","canvasH","offsetCanvas","offsetCtx","offsetBitmap","cursorMovement","scrolled","arrayBuffer","_decompressZlib","url","URL","createObjectURL","Image","reject","addEventListener","revokeObjectURL","src","pixelCount","src32","dst32","alignedPixels","srcOffset","dstOffset","b0","b1","b2","srcByte","dstByte","compressed","_decompress","offsetIn","reader","ReadableStream","pull","controller","enqueue","pipeThrough","DecompressionStream","getReader","chunks","totalLength","done","read","cancel","releaseLock","chunk","images","_kittyIdToStorageId","kittyIdToStorageId","pendingTransmissions","parts","split","part","eqIdx","substring","numValue","KittyImageStorage","_nextImageId","_storageIdToKittyId","_handleStorageImageDeleted","storageId","kittyId","_previousOnImageDeleted","_wrappedOnImageDeleted","imageData","oldStorageId","_maxStoredImages","_evictUndisplayedImages","byteLimit","retainedBytes","evictPlaced","oldestId","wasmDecode","InWasm","MAP","el","D","EMPTY","keepSize","maxBytes","_inst","_ended","_bytes","_m32","_mem","m","grow","Memory","requested","needed","newSize","addPages","loadedBytes","freeBytes","wasmQoiDecode","ib","dl","chunkP","def","W","z","compile","_wasmCtx","fromBase64","__webpack_module_cache__","moduleId","cachedModule","__webpack_modules__","Event_1","IIPHandler_1","KittyGraphicsHandler_1","KittyImageStorage_1","SixelHandler_1","SixelImageStorage_1","IIPImageStorage_1","enableSizeReports","sixelSupport","iipSupport","kittySupport","_handlers","_onImageAdded","Emitter","_defaultOpts","obj","_disposeLater","args","activate","terminal","ImageStorage","windowOps","options","windowOptions","getWinSizePixels","getCellSizePixels","getWinSizeChars","parser","registerCsiHandler","prefix","_decset","_decrst","_da1","_xtermGraphicsAttributes","onRender","intermediates","registerEscHandler","onRequestReset","onBufferChange","onResize","sixelStorage","SixelImageStorage","sixelHandler","SixelHandler","_parser","registerDcsHandler","iipStorage","IIPImageStorage","iipHandler","IIPHandler","registerOscHandler","kittyStorage","kittyHandler","KittyGraphicsHandler","registerApcHandler","storageUsage","_report","sqrt"],"sourceRoot":""} \ No newline at end of file diff --git a/lib/addon-image.mjs b/lib/addon-image.mjs -index 753a4f833c038a3f45802377dcb16a93695f2161..29c3984db57b888a058165c8aa02ccbcf8efcd2f 100644 +index 753a4f833c038a3f45802377dcb16a93695f2161..aca74ad0c769e8525bc5e4ab8cc6dda03959f760 100644 --- a/lib/addon-image.mjs +++ b/lib/addon-image.mjs @@ -14,5 +14,5 @@ @@ -26,10 +26,10 @@ index 753a4f833c038a3f45802377dcb16a93695f2161..29c3984db57b888a058165c8aa02ccbc * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -var it=Object.create;var Te=Object.defineProperty;var At=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var st=Object.getPrototypeOf,nt=Object.prototype.hasOwnProperty;var x=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var at=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let A of rt(e))!nt.call(r,A)&&A!==t&&Te(r,A,{get:()=>e[A],enumerable:!(i=At(e,A))||i.enumerable});return r};var M=(r,e,t)=>(t=r!=null?it(st(r)):{},at(e||!r||!r.__esModule?Te(t,"default",{value:r,enumerable:!0}):t,r));var X=x(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.DEFAULT_FOREGROUND=_.DEFAULT_BACKGROUND=_.PALETTE_ANSI_256=_.PALETTE_VT340_GREY=_.PALETTE_VT340_COLOR=_.normalizeHLS=_.normalizeRGB=_.nearestColorIndex=_.fromRGBA8888=_.toRGBA8888=_.alpha=_.blue=_.green=_.red=_.BIG_ENDIAN=void 0;_.BIG_ENDIAN=new Uint8Array(new Uint32Array([4278190080]).buffer)[0]===255;_.BIG_ENDIAN&&console.warn("BE platform detected. This version of node-sixel works only on LE properly.");function xe(r){return r&255}_.red=xe;function Me(r){return r>>>8&255}_.green=Me;function ve(r){return r>>>16&255}_.blue=ve;function ht(r){return r>>>24&255}_.alpha=ht;function B(r,e,t,i=255){return((i&255)<<24|(t&255)<<16|(e&255)<<8|r&255)>>>0}_.toRGBA8888=B;function gt(r){return[r&255,r>>8&255,r>>16&255,r>>>24]}_.fromRGBA8888=gt;function It(r,e){let t=xe(r),i=Me(r),A=ve(r),s=Number.MAX_SAFE_INTEGER,n=-1;for(let a=0;a1&&(t-=1),t*6<1?e+(r-e)*6*t:t*2<1?r:t*3<2?e+(r-e)*(4-t*6):e}function dt(r,e,t){if(!t){let s=Math.round(e*255);return B(s,s,s)}let i=e<.5?e*(1+t):e+t-e*t,A=2*e-i;return B(ge(0,255,Math.round(Ie(i,A,r+1/3)*255)),ge(0,255,Math.round(Ie(i,A,r)*255)),ge(0,255,Math.round(Ie(i,A,r-1/3)*255)))}function m(r,e,t){return(4278190080|Math.round(t/100*255)<<16|Math.round(e/100*255)<<8|Math.round(r/100*255))>>>0}_.normalizeRGB=m;function lt(r,e,t){return dt((r+240%360)/360,e/100,t/100)}_.normalizeHLS=lt;_.PALETTE_VT340_COLOR=new Uint32Array([m(0,0,0),m(20,20,80),m(80,13,13),m(20,80,20),m(80,20,80),m(20,80,80),m(80,80,20),m(53,53,53),m(26,26,26),m(33,33,60),m(60,26,26),m(33,60,33),m(60,33,60),m(33,60,60),m(60,60,33),m(80,80,80)]);_.PALETTE_VT340_GREY=new Uint32Array([m(0,0,0),m(13,13,13),m(26,26,26),m(40,40,40),m(6,6,6),m(20,20,20),m(33,33,33),m(46,46,46),m(0,0,0),m(13,13,13),m(26,26,26),m(40,40,40),m(6,6,6),m(20,20,20),m(33,33,33),m(46,46,46)]);_.PALETTE_ANSI_256=(()=>{let r=[B(0,0,0),B(205,0,0),B(0,205,0),B(205,205,0),B(0,0,238),B(205,0,205),B(0,250,205),B(229,229,229),B(127,127,127),B(255,0,0),B(0,255,0),B(255,255,0),B(92,92,255),B(255,0,255),B(0,255,255),B(255,255,255)],e=[0,95,135,175,215,255];for(let t=0;t<6;++t)for(let i=0;i<6;++i)for(let A=0;A<6;++A)r.push(B(e[t],e[i],e[A]));for(let t=8;t<=238;t+=10)r.push(B(t,t,t));return new Uint32Array(r)})();_.DEFAULT_BACKGROUND=B(0,0,0,255);_.DEFAULT_FOREGROUND=B(255,255,255,255)});var ce=x(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.InWasm=Ct;var v=r=>{if(Uint8Array.fromBase64)return Uint8Array.fromBase64(r);if(typeof Buffer<"u")return Buffer.from(r,"base64");let e=atob(r),t=new Uint8Array(e.length);for(let i=0;inew n.Instance(s||(s=new n.Module(A||(A=v(i)))),a):a=>s?n.instantiate(s,a):n.instantiate(A||(A=v(i)),a).then(o=>(s=o.module)&&o.instance):e===1?t?()=>s||(s=new n.Module(A||(A=v(i)))):()=>s?Promise.resolve(s):n.compile(A||(A=v(i))).then(a=>s=a):t?()=>A||(A=v(i)):()=>Promise.resolve(A||(A=v(i)))}if(typeof _wasmCtx>"u")throw new Error('must run "inwasm"');_wasmCtx.add(r)}});var ue=x(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});var pt=ce(),Bt=(0,pt.InWasm)({s:1,t:0,d:"AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML"}),S=new Uint8Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map(r=>r.charCodeAt(0))),R=new Uint32Array(1024);R.fill(4278190080);for(let r=0;r>4|(r<<4&255)<<8;for(let r=0;r>2<<8|(r<<6&255)<<16;for(let r=0;rthis.maxBytes||this.maxBytes>4294901760)throw new Error("invalid byte settings")}get data8(){return this._inst?this._d.subarray(0,this._m32[1282]):ft}release(){this._inst&&(this._bytes>this.keepSize?this._inst=this._m32=this._d=this._mem=null:(this._m32[1280]=0,this._m32[1281]=0,this._m32[1282]=0))}init(e,t){if(this.maxBytes=e??this.maxBytes,this._bytes=t??Math.min(this._bytes,this.maxBytes),this._bytes>this.maxBytes||this.maxBytes>4294901760)throw Error("invalid byte settings");let i=this._m32,A=this._bytes+5152;this._inst?this._mem.buffer.byteLengththis.maxBytes)return-3;let i=this._bytes;for(;(i*=2)this._mem.buffer.byteLength){let A=Math.ceil((i+5152-this._mem.buffer.byteLength)/65536);this._mem.grow(A),this._m32=new Uint32Array(this._mem.buffer,0),this._d=new Uint8Array(this._mem.buffer,5152)}this._bytes=i}return 0}put(e){if(!this._inst||this._ended)return-2;if(this._realloc(e.length))return-3;let t=this._m32;return this._d.set(e,t[1280]),t[1280]+=e.length,t[1280]-t[1281]>=131072?this._inst.exports.dec():0}end(){return this._ended=!0,this._inst?this._inst.exports.end():-2}get loadedBytes(){return this._inst?this._m32[1280]:0}get freeBytes(){return this._inst?this.maxBytes-this._m32[1280]:0}};_e.default=me});var Re=x(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});var Qt=ce(),Dt=(0,Qt.InWasm)({s:1,t:0,d:"AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=="}),Ee=class{constructor(e){this.keepSize=e,this.width=0,this.height=0}decode(e){this.width=e[4]<<24|e[5]<<16|e[6]<<8|e[7],this.height=e[8]<<24|e[9]<<16|e[10]<<8|e[11];let t=this.width*this.height,i=t*4,A=e.length,s=Math.max(i,A)+(Math.min(i,A)>>1)+4096;this._inst?this._mem.buffer.byteLengththis.keepSize&&(this._inst=this._d=this._mem=null)}};Ce.default=Ee});var Ke=x(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.LIMITS=void 0;ie.LIMITS={CHUNK_SIZE:16384,PALETTE_SIZE:4096,MAX_WIDTH:16384,BYTES:"AGFzbQEAAAABJAdgAAF/YAJ/fwBgA39/fwF/YAF/AX9gAABgBH9/f38AYAF/AAIlAgNlbnYLaGFuZGxlX2JhbmQAAwNlbnYLbW9kZV9wYXJzZWQAAwMTEgQAAAAAAQQBAQUBAAACAgAGAwQFAXABBwcFBAEBBwcGCAF/AUGAihoLB9wBDgZtZW1vcnkCABFnZXRfc3RhdGVfYWRkcmVzcwADEWdldF9jaHVua19hZGRyZXNzAAQOZ2V0X3AwX2FkZHJlc3MABRNnZXRfcGFsZXR0ZV9hZGRyZXNzAAYEaW5pdAALBmRlY29kZQAMDWN1cnJlbnRfd2lkdGgADQ5jdXJyZW50X2hlaWdodAAOGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtfaW5pdGlhbGl6ZQACCXN0YWNrU2F2ZQARDHN0YWNrUmVzdG9yZQASCnN0YWNrQWxsb2MAEwkMAQBBAQsGCgcJDxACDAEBCq5UEgMAAQsFAEGgCAsGAEGQiQELBgBBsIkC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wIgADcDAEHoiwIgADcDAEHgiwIgADcDAEHYiwIgADcDAEHQiwIgADcDAEHIiwIgADcDAEHAiwIgADcDAEG4iwIgADcDAEGwiwIgADcDAEGoiwIgADcDAEGgiwIgADcDAEGYiwIgADcDAEGQiwIgADcDAEGIiwIgADcDAEGAiwIgADcDAEH4igIgADcDAEHwigIgADcDAEHoigIgADcDAEHgigIgADcDAEHYigIgADcDAEHQigIgADcDAEHIigIgADcDAEHAigIgADcDAEG4igIgADcDAEGwigIgADcDAEGoigIgADcDAEGgigIgADcDAEGYigIgADcDAEGQigIgADcDAEGIigIgADcDAEGAigIgADcDAEH4iQIgADcDAEHwiQIgADcDAEHoiQIgADcDAEHgiQIgADcDAEHYiQIgADcDAEHQiQIgADcDAEHIiQIgADcDAEHAiQIgADcDAEG4iQIgADcDAEGwiQIgADcDAEGoCCgCACIEQf8AakGAAW0hCAJAIARBgQFIDQBBASEBIAhBAiAIQQJKG0EBayICQQFxIQMgBEGBAk4EQCACQX5xIQIDQCABQQl0IgdBEHJBoIkCakGwiQJBgAT8CgAAIAdBsI0CakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsLIANFDQAgAUEJdEEQckGgiQJqQbCJAkGABPwKAAALAkAgBEEBSA0AIAhBASAIQQFKGyIDQQFxIQUCQCADQQFrIgdFBEBBACEBDAELIANB/v///wdxIQJBACEBA0AgAUEJdCIGQRByQbCJBmpBsIkCQYAE/AoAACAGQZAEckGwiQZqQbCJAkGABPwKAAAgAUECaiEBIAJBAmsiAg0ACwsgBQRAIAFBCXRBEHJBsIkGakGwiQJBgAT8CgAACyAEQQFIDQAgA0EBcSEFIAcEfyADQf7///8HcSECQQAhAQNAIAFBCXQiBkEQckHAiQpqQbCJAkGABPwKAAAgBkGQBHJBwIkKakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsgAUEHdEEEcgVBBAshASAFBEAgAUECdEHAiQpqQbCJAkGABPwKAAALIARBAUgNACADQQFxIQUgBwR/IANB/v///wdxI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sEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwsYAQBBgAgLEQEAAAACAAAAAwAAAAQAAAAF"}});var We=x(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.decodeAsync=b.decode=b.Decoder=b.DecoderAsync=void 0;var O=X(),f=Ke();function yt(r){if(typeof Buffer<"u")return Buffer.from(r,"base64");let e=atob(r),t=new Uint8Array(e.length);for(let i=0;i1,this.modeHandler=e=>1}handle_band(e){return this.bandHandler(e)}mode_parsed(e){return this.modeHandler(e)}},St={memoryLimit:2048*65536,sixelColor:O.DEFAULT_FOREGROUND,fillColor:O.DEFAULT_BACKGROUND,palette:O.PALETTE_VT340_COLOR,paletteLimit:f.LIMITS.PALETTE_SIZE,truncate:!0};function qe(r){let e=new ye,t={env:{handle_band:e.handle_band.bind(e),mode_parsed:e.mode_parsed.bind(e)}};return WebAssembly.instantiate(J||Ye,t).then(i=>(J=J||i.module,new P(r,i.instance||i,e)))}b.DecoderAsync=qe;var P=class{constructor(e,t,i){if(this._PIXEL_OFFSET=f.LIMITS.MAX_WIDTH+4,this._canvas=Ae,this._bandWidths=[],this._maxWidth=0,this._minWidth=f.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0,this._opts=Object.assign({},St,e),this._opts.paletteLimit>f.LIMITS.PALETTE_SIZE)throw new Error(`DecoderOptions.paletteLimit must not exceed ${f.LIMITS.PALETTE_SIZE}`);if(t)i.bandHandler=this._handle_band.bind(this),i.modeHandler=this._initCanvas.bind(this);else{let A=J||(J=new WebAssembly.Module(Ye));t=new WebAssembly.Instance(A,{env:{handle_band:this._handle_band.bind(this),mode_parsed:this._initCanvas.bind(this)}})}this._instance=t,this._wasm=this._instance.exports,this._chunk=new Uint8Array(this._wasm.memory.buffer,this._wasm.get_chunk_address(),f.LIMITS.CHUNK_SIZE),this._states=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_state_address(),12),this._palette=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_palette_address(),f.LIMITS.PALETTE_SIZE),this._palette.set(this._opts.palette),this._pSrc=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_p0_address()),this._wasm.init(O.DEFAULT_FOREGROUND,0,this._opts.paletteLimit,0)}get _fillColor(){return this._states[0]}get _truncate(){return this._states[8]}get _rasterWidth(){return this._states[6]}get _rasterHeight(){return this._states[7]}get _width(){return this._states[2]?this._states[2]-4:0}get _height(){return this._states[3]}get _level(){return this._states[9]}get _mode(){return this._states[10]}get _paletteLimit(){return this._states[11]}_initCanvas(e){if(e===2){let t=this.width*this.height;if(t>this._canvas.length){if(this._opts.memoryLimit&&t*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(t)}this._maxWidth=this._width}else if(e===1)if(this._level===2){let t=Math.min(this._rasterWidth,f.LIMITS.MAX_WIDTH)*this._rasterHeight;if(t>this._canvas.length){if(this._opts.memoryLimit&&t*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(t)}}else this._canvas.length<65536&&(this._canvas=new Uint32Array(65536));return 0}_realloc(e,t){let i=e+t;if(i>this._canvas.length){if(this._opts.memoryLimit&&i*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");let A=new Uint32Array(Math.ceil(i/65536)*65536);A.set(this._canvas),this._canvas=A}}_handle_band(e){let t=this._PIXEL_OFFSET,i=this._lastOffset;if(this._mode===2){let A=this.height-this._currentHeight,s=0;for(;s<6&&A>0;)this._canvas.set(this._pSrc.subarray(t*s,t*s+e),i+e*s),s++,A--;this._lastOffset+=e*s,this._currentHeight+=s}else if(this._mode===1){this._realloc(i,e*6),this._maxWidth=Math.max(this._maxWidth,e),this._minWidth=Math.min(this._minWidth,e);for(let A=0;A<6;++A)this._canvas.set(this._pSrc.subarray(t*A,t*A+e),i+e*A);this._bandWidths.push(e),this._lastOffset+=e*6,this._currentHeight+=6}return 0}get width(){return this._mode!==1?this._width:Math.max(this._maxWidth,this._wasm.current_width())}get height(){return this._mode!==1?this._height:this._wasm.current_width()?this._bandWidths.length*6+this._wasm.current_height():this._bandWidths.length*6}get palette(){return this._palette.subarray(0,this._paletteLimit)}get memoryUsage(){return this._canvas.byteLength+this._wasm.memory.buffer.byteLength+8*this._bandWidths.length}get properties(){return{width:this.width,height:this.height,mode:this._mode,level:this._level,truncate:!!this._truncate,paletteLimit:this._paletteLimit,fillColor:this._fillColor,memUsage:this.memoryUsage,rasterAttributes:{numerator:this._states[4],denominator:this._states[5],width:this._rasterWidth,height:this._rasterHeight}}}init(e=this._opts.fillColor,t=this._opts.palette,i=this._opts.paletteLimit,A=this._opts.truncate){this._wasm.init(this._opts.sixelColor,e,i,A?1:0),t&&this._palette.set(t.subarray(0,f.LIMITS.PALETTE_SIZE)),this._bandWidths.length=0,this._maxWidth=0,this._minWidth=f.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0}decode(e,t=0,i=e.length){let A=t;for(;A0){let i=this._PIXEL_OFFSET,A=this._lastOffset,s=0;for(;s<6&&t>0;)this._canvas.set(this._pSrc.subarray(i*s,i*s+e),A+e*s),s++,t--;t&&this._canvas.fill(this._fillColor,A+e*s)}return this._canvas.subarray(0,this.width*this.height)}if(this._mode===1){if(this._minWidth===this._maxWidth){let s=!1;if(e)if(e!==this._minWidth)s=!0;else{let n=this._PIXEL_OFFSET,a=this._lastOffset;this._realloc(a,e*6);for(let o=0;o<6;++o)this._canvas.set(this._pSrc.subarray(n*o,n*o+e),a+e*o)}if(!s)return this._canvas.subarray(0,this.width*this.height)}let t=new Uint32Array(this.width*this.height);t.fill(this._fillColor);let i=0,A=0;for(let s=0;s{if(this._disposed)return H(()=>{});let A={fn:e,thisArgs:t};this._listeners=this._listeners.slice(),this._listeners.push(A);let s=H(()=>{let n=this._listeners.indexOf(A);n!==-1&&(this._listeners=this._listeners.slice(),this._listeners.splice(n,1))});return i&&(Array.isArray(i)?i.push(s):i.add(s)),s},this._event)}fire(e){if(this._disposed||!this._listeners.length)return;if(this._listeners.length===1){this._listeners[0].fn.call(this._listeners[0].thisArgs,e);return}let t=this._listeners;for(let i=0,A=t.length;i{function r(s,n){return s(a=>n.fire(a))}A.forward=r;function e(s,n){return(a,o,g)=>s(h=>a.call(o,n(h)),void 0,g)}A.map=e;function t(...s){return(n,a,o)=>{let g=new N;for(let h of s)g.add(h(I=>n.call(a,I)));return o&&(Array.isArray(o)?o.push(g):o.add(g)),g}}A.any=t;function i(s,n,a){return n(a),s(o=>n(o))}A.runAndSubscribe=i})(ot||={});var de=M(X());var D=class r extends k{constructor(t){super();this._terminal=t;this._layers=new Map;this._optionsRefresh=this._register(new W);this._oldOpen=this._terminal._core.open,this._terminal._core.open=i=>{this._oldOpen?.call(this._terminal._core,i),this._open()},this._terminal._core.screenElement&&this._open(),this._optionsRefresh.value=this._terminal._core.optionsService.onOptionChange(i=>{i==="fontSize"&&(this.rescaleCanvas(),this._renderService?.refreshRows(0,this._terminal.rows))}),this._register(H(()=>{this.removeLayerFromDom(),this.removeLayerFromDom("bottom"),this._terminal._core&&this._oldOpen&&(this._terminal._core.open=this._oldOpen,this._oldOpen=void 0),this._renderService&&this._oldSetRenderer&&(this._renderService.setRenderer=this._oldSetRenderer,this._oldSetRenderer=void 0),this._renderService=void 0,this._layers.clear(),this._placeholderBitmap?.close(),this._placeholderBitmap=void 0,this._placeholder=void 0}))}get canvas(){return this._layers.get("top")?.canvas}static createCanvas(t,i,A){let s=(t??document).createElement("canvas");return s.width=i|0,s.height=A|0,s}static createImageData(t,i,A,s){if(typeof ImageData!="function"){let n=t.createImageData(i,A);return s&&n.data.set(new Uint8ClampedArray(s,0,i*A*4)),n}return s?new ImageData(new Uint8ClampedArray(s,0,i*A*4),i,A):new ImageData(i,A)}static createImageBitmap(t){return typeof createImageBitmap!="function"?Promise.resolve(void 0):createImageBitmap(t)}showPlaceholder(t){t?!this._placeholder&&this.cellSize.height!==-1&&this._createPlaceHolder(Math.max(this.cellSize.height+1,24)):(this._placeholderBitmap?.close(),this._placeholderBitmap=void 0,this._placeholder=void 0),this._renderService?.refreshRows(0,this._terminal.rows)}get dimensions(){return this._terminal.dimensions}get cellSize(){return{width:this.dimensions?.css.cell.width||-1,height:this.dimensions?.css.cell.height||-1}}clearLines(t,i,A){let s=t*(this.dimensions?.css.cell.height||0),n=this.dimensions?.css.canvas.width||0,a=(i+1-t)*(this.dimensions?.css.cell.height||0);(!A||A==="top")&&this._layers.get("top")?.clearRect(0,s,n,a),(!A||A==="bottom")&&this._layers.get("bottom")?.clearRect(0,s,n,a)}clearAll(t){if(!t||t==="top"){let i=this._layers.get("top");i?.clearRect(0,0,i.canvas.width,i.canvas.height)}if(!t||t==="bottom"){let i=this._layers.get("bottom");i?.clearRect(0,0,i.canvas.width,i.canvas.height)}}draw(t,i,A,s,n=1){let a=this._layers.get(t.layer);if(!a)return;let{width:o,height:g}=this.cellSize;if(o===-1||g===-1)return;this._rescaleImage(t,o,g);let h=t.actual,I=Math.ceil(h.width/o),d=i%I*o,c=Math.floor(i/I)*g,l=A*o,E=s*g,p=n*o+d>h.width?h.width-d:n*o,u=c+g>h.height?h.height-c:g;a.drawImage(h,Math.floor(d),Math.floor(c),Math.ceil(p),Math.ceil(u),Math.floor(l),Math.floor(E),Math.ceil(p),Math.ceil(u))}extractTile(t,i){let{width:A,height:s}=this.cellSize;if(A===-1||s===-1)return;this._rescaleImage(t,A,s);let n=t.actual,a=Math.ceil(n.width/A),o=i%a*A,g=Math.floor(i/a)*s,h=A+o>n.width?n.width-o:A,I=g+s>n.height?n.height-g:s,d=r.createCanvas(this.document,h,I),c=d.getContext("2d");if(c)return c.drawImage(n,Math.floor(o),Math.floor(g),Math.floor(h),Math.floor(I),0,0,Math.floor(h),Math.floor(I)),d}drawPlaceholder(t,i,A=1){let s=this._layers.get("top");if(s){let{width:n,height:a}=this.cellSize;if(n===-1||a===-1||(this._placeholder?a>=this._placeholder.height&&this._createPlaceHolder(a+1):this._createPlaceHolder(Math.max(a+1,24)),!this._placeholder))return;s.drawImage(this._placeholderBitmap??this._placeholder,t*n,i*a%2?0:1,n*A,a,t*n,i*a,n*A,a)}}rescaleCanvas(){let t=this.dimensions?.css.canvas.width||0,i=this.dimensions?.css.canvas.height||0;for(let A of this._layers.values())(A.canvas.width!==t||A.canvas.height!==i)&&(A.canvas.width=t,A.canvas.height=i)}_rescaleImage(t,i,A){if(i===t.actualCellSize.width&&A===t.actualCellSize.height)return;let{width:s,height:n}=t.origCellSize;if(i===s&&A===n){t.actual=t.orig,t.actualCellSize.width=s,t.actualCellSize.height=n;return}let a=r.createCanvas(this.document,Math.ceil(t.orig.width*i/s),Math.ceil(t.orig.height*A/n)),o=a.getContext("2d");o&&(o.drawImage(t.orig,0,0,a.width,a.height),t.actual=a,t.actualCellSize.width=i,t.actualCellSize.height=A)}_open(){this._renderService=this._terminal._core._renderService,this._oldSetRenderer=this._renderService.setRenderer.bind(this._renderService),this._renderService.setRenderer=t=>{for(let i of[...this._layers.keys()])this.removeLayerFromDom(i);this._oldSetRenderer?.call(this._renderService,t)}}insertLayerToDom(t="top"){if(!this.document||!this._terminal._core.screenElement){console.warn("image addon: cannot insert output canvas to DOM, missing document or screenElement");return}if(this._layers.has(t))return;let i=r.createCanvas(this.document,this.dimensions?.css.canvas.width||0,this.dimensions?.css.canvas.height||0);i.classList.add(`xterm-image-layer-${t}`);let A=this._terminal._core.screenElement;A.style.isolation="isolate",t==="bottom"?(i.style.zIndex="-1",A.insertBefore(i,A.firstChild)):(i.style.zIndex="0",A.appendChild(i));let s=i.getContext("2d",{alpha:!0});if(!s){i.remove();return}this._layers.set(t,s),this.clearAll(t)}removeLayerFromDom(t="top"){let i=this._layers.get(t);i&&(i.canvas.remove(),this._layers.delete(t))}hasLayer(t){return this._layers.has(t)}_createPlaceHolder(t=24){this._placeholderBitmap?.close(),this._placeholderBitmap=void 0;let i=32,A=r.createCanvas(this.document,i,t),s=A.getContext("2d",{alpha:!1});if(!s)return;let n=r.createImageData(s,i,t),a=new Uint32Array(n.data.buffer),o=(0,de.toRGBA8888)(0,0,0),g=(0,de.toRGBA8888)(255,255,255);a.fill(o);for(let d=0;dthis._placeholderBitmap=d)}get document(){return this._terminal._core._coreBrowserService?.window.document}};var w={width:7,height:14},G=class r{constructor(e=0,t=0,i=-1,A=-1){this.imageId=i;this.tileId=A;this._ext=0;this._urlId=0;this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}get urlId(){return this._urlId}set urlId(e){this._urlId=e}clone(){return new r(this._ext,this._urlId,this.imageId,this.tileId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0&&this.imageId===-1}},F=new G,Z=class{constructor(e,t,i){this._terminal=e;this._renderer=t;this._opts=i;this._images=new Map;this._lastId=0;this._lowestId=0;this._fullyCleared=!1;this._needsFullClear=!1;this._pixelLimit=25e5;try{this.setLimit(this._opts.storageLimit)}catch(A){A instanceof Error&&console.error(A.message),console.warn(`storageLimit is set to ${this.getLimit()} MB`)}this._viewportMetrics={cols:this._terminal.cols,rows:this._terminal.rows}}dispose(){this.reset()}reset(){for(let e of this._images.values())e.marker?.dispose();this._images.clear(),this._renderer.clearAll()}getLimit(){return this._pixelLimit*4/1e6}setLimit(e){if(e<.5||e>1e3)throw RangeError("invalid storageLimit, should be at least 0.5 MB and not exceed 1G");this._pixelLimit=e/4*1e6>>>0,this._evictOldest(0)}getUsage(){return this._getStoredPixels()*4/1e6}_getStoredPixels(){let e=0;for(let t of this._images.values())t.orig&&(e+=t.orig.width*t.orig.height,t.actual&&t.actual!==t.orig&&(e+=t.actual.width*t.actual.height));return e}_delImg(e){let t=this._images.get(e);t&&(this._images.delete(e),window.ImageBitmap&&t.orig instanceof ImageBitmap&&t.orig.close(),this.onImageDeleted?.(e))}wipeAlternate(){let e=[];for(let[t,i]of this._images.entries())i.bufferType==="alternate"&&(i.marker?.dispose(),e.push(t));for(let t of e)this._delImg(t);this._needsFullClear=!0,this._fullyCleared=!1}deleteImage(e){let t=this._images.get(e);t&&(t.marker?.dispose(),this._delImg(e))}addImage(e,t){this._evictOldest(e.width*e.height);let i=this._renderer.cellSize;(i.width===-1||i.height===-1)&&(i=w);let A=Math.ceil(e.width/i.width),s=Math.ceil(e.height/i.height),n=++this._lastId,a=this._terminal._core.buffer,o=this._terminal.cols,g=this._terminal.rows,h=a.x,I=a.y,d=h,c=0;t.scrolling||(a.x=0,a.y=0,d=0),this._terminal._core._inputHandler._dirtyRowTracker.markDirty(a.y);for(let u=0;u=o);++Q)this._writeToCell(C,d+Q,n,u*A+Q),c++;if(t.scrolling)u=g)break;a.x=d}this._terminal._core._inputHandler._dirtyRowTracker.markDirty(a.y),t.scrolling?t.cursorPos==="iip"?a.x=Math.min(d+A,o):a.x=d:(a.x=h,a.y=I);let l=[];for(let[u,C]of this._images.entries())C.tileCount<1&&(C.marker?.dispose(),l.push(u));for(let u of l)this._delImg(u);let E=this._terminal.registerMarker(0);E?.onDispose(()=>{this._images.get(n)&&this._delImg(n)}),this._terminal.buffer.active.type==="alternate"&&this._evictOnAlternate();let p={orig:e,origCellSize:i,actual:e,actualCellSize:{...i},marker:E||void 0,tileCount:c,bufferType:this._terminal.buffer.active.type,layer:t.layer,zIndex:t.zIndex};return this._images.set(n,p),this.onImageAdded?.(),n}render(e){let t=!1,i=!1;for(let h of this._images.values())if(h.layer==="bottom"?i=!0:t=!0,t&&i)break;if(t&&!this._renderer.hasLayer("top")&&(this._renderer.insertLayerToDom("top"),!this._renderer.hasLayer("top")))return;if(i&&!this._renderer.hasLayer("bottom")&&this._renderer.insertLayerToDom("bottom"),this._renderer.rescaleCanvas(),!this._images.size){this._fullyCleared||(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1),this._renderer.hasLayer("top")&&this._renderer.removeLayerFromDom("top"),this._renderer.hasLayer("bottom")&&this._renderer.removeLayerFromDom("bottom");return}!t&&this._renderer.hasLayer("top")&&(this._renderer.clearAll("top"),this._renderer.removeLayerFromDom("top")),!i&&this._renderer.hasLayer("bottom")&&(this._renderer.clearAll("bottom"),this._renderer.removeLayerFromDom("bottom")),this._needsFullClear&&(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1);let{start:A,end:s}=e,n=this._terminal._core.buffer,a=this._terminal._core.cols;this._renderer.clearLines(A,s);let o=[],g=[];for(let h=A;h<=s;++h){let I=n.lines.get(h+n.ydisp);if(!I)return;for(let d=0;dh.imgSpec.zIndex-I.imgSpec.zIndex);for(let h of g)this._renderer.drawPlaceholder(h.col,h.row,h.count);for(let h of o)this._renderer.draw(h.imgSpec,h.tileId,h.col,h.row,h.count)}viewportResize(e){if(!this._images.size){this._viewportMetrics=e;return}if(this._viewportMetrics.cols>=e.cols){this._viewportMetrics=e;return}let t=this._terminal._core.buffer,i=t.lines.length,A=this._viewportMetrics.cols-1;for(let s=0;s=h)continue;let I=!1;for(let l=A+1;l>e.cols;++l)if(n._data[l*3+0]&4194303){I=!0;break}if(I)continue;let d=Math.min(e.cols,h-a.tileId%h+A),c=a.tileId;for(let l=A+1;l57)throw new Error("illegal char");e=e*10+r[t]-48}return e}function ke(r){let e=j(r);if(!e.match(/^((auto)|(\d+?((px)|(%)){0,1}))$/))throw new Error("illegal size");return e}function wt(r){if(typeof Buffer<"u")return Buffer.from(j(r),"base64").toString();let e=atob(j(r)),t=new Uint8Array(e.length);for(let i=0;i14)return-1;for(let a=t;a=De)return this._a();n[s++]=o}break;case 58:return A===3&&!this._storeValue(s)?this._a():(this.state=4,a+1);default:if(s>=De)return this._a();n[s++]=o}}return this.state=A,this._position=s,-2}_a(){return this.fields.type=0,this.state=1,-1}_storeKey(e){let t=j(this._buffer.subarray(0,e));return t?(this._key=t,this.fields[t]=null,!0):!1}_storeValue(e){if(this._key){try{let t=this._buffer.slice(0,e);this.fields[this._key]=Ne[this._key]?Ne[this._key](t):t}catch{return!1}return!0}return!1}};var L={mime:"unsupported",width:0,height:0};function Ge(r){if(r.length<32)return L;let e=new Uint32Array(r.buffer,r.byteOffset,8);if(e[0]===1196314761&&e[1]===169478669&&e[3]===1380206665)return{mime:"image/png",width:r[16]<<24|r[17]<<16|r[18]<<8|r[19],height:r[20]<<24|r[21]<<16|r[22]<<8|r[23]};if(r[0]===255&&r[1]===216&&r[2]===255){let[t,i]=bt(r);return{mime:"image/jpeg",width:t,height:i}}if(e[0]===944130375&&(r[4]===55||r[4]===57)&&r[5]===97)return{mime:"image/gif",width:r[7]<<8|r[6],height:r[9]<<8|r[8]};if(e[0]===1718185841)return{mime:"image/qoi",width:r[4]<<24|r[5]<<16|r[6]<<8|r[7],height:r[8]<<24|r[9]<<16|r[10]<<8|r[11]};if(e[0]===1179011410&&e[2]===1346520407&&(e[3]&16777215)===3690582){switch(r[15]){case 88:return{mime:"image/webp",width:(r[24]|r[25]<<8|r[26]<<16)+1,height:(r[27]|r[28]<<8|r[29]<<16)+1};case 76:if(r[20]!==47)return L;let t=r[21]|r[22]<<8|r[23]<<16|r[24]<<24;return{mime:"image/webp",width:(t&16383)+1,height:(t>>>14&16383)+1};case 32:return r[23]!==157||r[24]!==1||r[25]!==42?L:{mime:"image/webp",width:(r[26]|r[27]<<8)&16383,height:(r[28]|r[29]<<8)&16383}}return L}if(e[1]===1887007846&&(e[2]===1718187617||e[2]===1936291425)){let t=-1,i=Math.min(r.length-16,1024);for(let A=8;A0&&s>0)return{mime:"image/avif",width:A,height:s}}return L}return L}function bt(r){let e=r.length,t=4,i=r[t]<<8|r[t+1];for(;;){if(t+=i,t>=e)return[0,0];if(r[t]!==255)return[0,0];if(r[t+1]===192||r[t+1]===194)return t+80){if(this._hp.fields.type===1){if(this._isMultipart&&(this._isMultipart=!1,this._abortMulti=!1,this._dec.release()),this._header=Object.assign({},we,this._hp.fields),!this._header.inline){this._aborted=!0;return}this._dec.init()}else if(this._abortMulti){this._aborted=!0;return}this._dec.put(e.subarray(A,i))!==0&&(this._dec.release(),this._aborted=!0,this._isMultipart&&(this._abortMulti=!0))}}}end(e){if(this._aborted||this._hp.state!==4&&this._hp.end())return!0;let t=this._hp.fields.type;if(t===3)return!0;if(t===5){let o=w.width,g=w.height;this._renderer.dimensions&&(o=this._renderer.dimensions.css.canvas.width/this._coreTerminal.cols,g=this._renderer.dimensions.css.canvas.height/this._coreTerminal.rows);let h=this._coreTerminal._core._coreBrowserService?.dpr??1,I=`\x1B]1337;ReportCellSize=${g.toFixed(3)};${o.toFixed(3)};${h.toFixed(3)}\x1B\\`;return this._coreTerminal.input(I,!1),!0}if(t===2)return this._header=Object.assign({},we,this._hp.fields),this._isMultipart=!0,this._abortMulti=!1,this._dec.release(),this._dec.init(),!0;if(t===4&&(!this._isMultipart||(this._isMultipart=!1,this._abortMulti||this._header.type!==2)))return!0;let i=0,A=0,s,n=L;if((s=e)&&((s=!this._dec.end())?(n=Ge(this._dec.data8),(s=n.mime!=="unsupported")?(i=n.width,A=n.height,(s=i&&A&&i*A(this._storage.addImage(o),!0)).catch(o=>(console.warn(`IIP: decoding error ${n.mime} ${n.width}x${n.height}`,o),!0))}_resize(e,t){let i=this._renderer.dimensions?.css.cell.width||w.width,A=this._renderer.dimensions?.css.cell.height||w.height,s=this._renderer.dimensions?.css.canvas.width||i*this._coreTerminal.cols,n=this._renderer.dimensions?.css.canvas.height||A*this._coreTerminal.rows,a=this._dim(this._header.width,s,i),o=this._dim(this._header.height,n,A);if(!a&&!o){let g=s/e,h=(n-A)/t,I=Math.min(g,h);return I<1?[e*I,t*I]:[e,t]}return a?this._header.preserveAspectRatio||!a||!o?[a,t*a/e]:[a,o]:[e*o/t,o]}_dim(e,t,i){return e==="auto"?0:e.endsWith("%")?parseInt(e.slice(0,-1),10)*t/100:e.endsWith("px")?parseInt(e.slice(0,-2),10):parseInt(e,10)*i}};var Pe=M(ue());function be(r){let e={},t=r.split(",");for(let i of t){let A=i.indexOf("=");if(A===-1)continue;let s=i.substring(0,A),n=i.substring(A+1);if(s==="a"){e.action=n;continue}if(s==="o"){e.compression=n;continue}if(s==="t"){e.transmission=n;continue}if(s==="d"){e.deleteSelector=n;continue}let a=parseInt(n,10);switch(s){case"f":e.format=a;break;case"i":e.id=a;break;case"I":e.imageNumber=a;break;case"s":e.width=a;break;case"v":e.height=a;break;case"x":e.x=a;break;case"y":e.y=a;break;case"w":e.sourceWidth=a;break;case"h":e.sourceHeight=a;break;case"X":e.xOffset=a;break;case"Y":e.yOffset=a;break;case"c":e.columns=a;break;case"r":e.rows=a;break;case"m":e.more=a;break;case"q":e.quiet=a;break;case"C":e.cursorMovement=a;break;case"z":e.zIndex=a;break;case"p":e.placementId=a;break}}return e}var Je=0,ee=class{constructor(e,t,i,A){this._opts=e;this._renderer=t;this._kittyStorage=i;this._coreTerminal=A;this._aborted=!1;this._decodeError=!1;this._activeDecoder=null;this._inControlData=!0;this._controlData=new Uint32Array(512);this._controlLength=0;this._encodedSizeLimit=0;this._totalEncodedSize=0;this._parsedCommand=null;this._pendingTransmissions=new Map;this._maxEncodedBytes=Math.ceil(this._opts.kittySizeLimit*4/3),this._initialEncodedBytes=Math.min(4194304,this._maxEncodedBytes)}reset(){this._cleanupAllPending(),this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),this._kittyStorage.reset()}dispose(){this.reset()}_removePendingEntry(e){this._pendingTransmissions.delete(e),this._lastPendingKey===e&&(this._lastPendingKey=void 0)}_cleanupAllPending(){for(let e of this._pendingTransmissions.values())e.decoder.release();this._pendingTransmissions.clear(),this._lastPendingKey=void 0}start(){this._aborted=!1,this._decodeError=!1,this._inControlData=!0,this._controlLength=0,this._parsedCommand=null,this._encodedSizeLimit=this._maxEncodedBytes,this._totalEncodedSize=0,this._activeDecoder=null}put(e,t,i){if(!this._aborted)if(!this._inControlData)this._streamPayload(e,t,i);else{let A=i;for(let n=t;n512){this._aborted=!0;return}if(this._controlData.set(e.subarray(t,A),this._controlLength),this._controlLength+=s,!this._inControlData){if(this._parsedCommand=be(this._parseControlDataString()),this._parsedCommand.id!==void 0&&this._parsedCommand.imageNumber!==void 0){this._sendResponse(this._parsedCommand.id,"EINVAL:cannot specify both i and I keys",this._parsedCommand.quiet??0),this._aborted=!0;return}if(this._parsedCommand.action==="d")return;let n=A+1;nthis._encodedSizeLimit){let o=this._activeDecoder??s?.decoder;o&&o.release(),this._activeDecoder=null,s&&this._removePendingEntry(A),this._aborted=!0;return}this._decodeError||(s?.decoder&&!this._activeDecoder&&(this._activeDecoder=s.decoder),this._activeDecoder||(this._activeDecoder=new Pe.default(4194304,this._maxEncodedBytes,this._initialEncodedBytes),this._activeDecoder.init()),this._activeDecoder.put(e.subarray(t,i))!==Je&&(this._activeDecoder.release(),this._activeDecoder=null,this._decodeError=!0,s&&this._removePendingEntry(A)))}end(e){if(this._aborted||!e)return this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),!0;if(this._inControlData)return this._handleNoPayloadCommand();let t=this._parsedCommand;if(t.action==="d")return this._handleDelete(t);let i=t.id??this._lastPendingKey??0,A=t.more===1,s=this._pendingTransmissions.get(i);if(A)return this._activeDecoder&&(s?(s.totalEncodedSize+=this._totalEncodedSize,s.decodeError=s.decodeError||this._decodeError):this._pendingTransmissions.set(i,{cmd:{...t},decoder:this._activeDecoder,totalEncodedSize:this._totalEncodedSize,decodeError:this._decodeError}),this._lastPendingKey=i,this._activeDecoder=null),!0;s&&(this._lastPendingKey=void 0);let n=this._decodeError,a=t,o=this._activeDecoder;s&&(a=s.cmd,o=s.decoder,n=n||s.decodeError,this._pendingTransmissions.delete(i));let g=new Uint8Array(0);o&&(o.end()!==Je&&(n=!0),g=o.data8),this._activeDecoder=null;let h=this._handleCommandWithBytesAndCmd(a,g,n);return o&&o.release(),h}_parseControlDataString(){let e="";for(let t=0;t0&&this._sendResponse(e.id,"OK",e.quiet??0)),s}case"T":return this._handleTransmitDisplay(e,t,i);case"q":return this._handleQuery(e,t,i);case"p":return this._handlePlacement(e);default:return e.id!==void 0&&this._sendResponse(e.id,"EINVAL:unsupported action",e.quiet??0),!0}}_handlePlacement(e){if(e.id===void 0)return!0;let t=e.id,i=this._kittyStorage.getImage(t);return i?this._displayImage(i,e).then(s=>(this._sendResponse(t,s?"OK":"EINVAL:image rendering failed",e.quiet??0,e.placementId),!0)):(this._sendResponse(t,"ENOENT:image not found",e.quiet??0,e.placementId),!0)}_handleTransmit(e,t,i){return(e.transmission??"d")!=="d"?(e.id!==void 0&&this._sendResponse(e.id,"EINVAL:unsupported transmission medium",e.quiet??0),!0):(i||t.length===0||this._kittyStorage.storeImage(e.id,{data:new Blob([t]),width:e.width??0,height:e.height??0,format:e.format??32,compression:e.compression??""}),!0)}_handleTransmitDisplay(e,t,i){if(i)return e.id!==void 0&&this._sendResponse(e.id,"EINVAL:invalid base64 data",e.quiet??0),!0;this._handleTransmit(e,t,i);let A=e.id??this._kittyStorage.lastImageId,s=this._kittyStorage.getImage(A);if(s){let n=this._displayImage(s,e);return e.id!==void 0?n.then(a=>(this._sendResponse(A,a?"OK":"EINVAL:image rendering failed",e.quiet??0),!0)):n.then(()=>!0)}return!0}_handleQuery(e,t,i){let A=e.id??0,s=e.quiet??0;if((e.transmission??"d")!=="d")return this._sendResponse(A,"EINVAL:unsupported transmission medium",s),!0;if(i)return this._sendResponse(A,"EINVAL:invalid base64 data",s),!0;if(t.length===0)return this._sendResponse(A,"OK",s),!0;let a=e.format??32;if(a===100)this._sendResponse(A,"OK",s);else{let o=e.width??0,g=e.height??0;if(!o||!g)return this._sendResponse(A,"EINVAL:width and height required for raw pixel data",s),!0;let h=a===32?4:3,I=o*g*h;if(t.length=1||!s&&i>=2)return;let n=A?`,p=${A}`:"",a=`\x1B_Gi=${e}${n};${t}\x1B\\`;this._coreTerminal._core.coreService.triggerDataEvent(a)}_displayImage(e,t){return this._decodeAndDisplay(e,t).then(()=>!0).catch(()=>!1)}async _decodeAndDisplay(e,t){let i=await this._createBitmap(e);try{let A=Math.max(0,t.x??0),s=Math.max(0,t.y??0),n=t.sourceWidth||i.width-A,a=t.sourceHeight||i.height-s,o=Math.max(0,i.width-A),g=Math.max(0,i.height-s),h=Math.max(0,Math.min(n,o)),I=Math.max(0,Math.min(a,g));if(h===0||I===0)throw new Error("invalid source rectangle");if(A!==0||s!==0||h!==i.width||I!==i.height){let T=await createImageBitmap(i,A,s,h,I);i.close(),i=T}let d=this._renderer.dimensions?.css.cell.width||w.width,c=this._renderer.dimensions?.css.cell.height||w.height,l,E;t.columns!==void 0&&t.rows!==void 0?(l=t.columns,E=t.rows):t.columns!==void 0?(l=t.columns,E=Math.max(1,Math.ceil(i.height/i.width*(l*d)/c))):t.rows!==void 0?(E=t.rows,l=Math.max(1,Math.ceil(i.width/i.height*(E*c)/d))):(l=Math.ceil(i.width/d),E=Math.ceil(i.height/c));let p=i.width,u=i.height;if((t.columns!==void 0||t.rows!==void 0)&&(p=Math.round(l*d),u=Math.round(E*c)),p*u>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");let C=this._coreTerminal._core.buffer,Q=C.x,K=C.y,Y=C.ybase,Ve=t.zIndex!==void 0&&t.zIndex<0?"bottom":"top";if(p!==i.width||u!==i.height){let T=await createImageBitmap(i,{resizeWidth:p,resizeHeight:u});i.close(),i=T}let oe=Math.min(Math.max(0,t.xOffset??0),d-1),he=Math.min(Math.max(0,t.yOffset??0),c-1);if(oe!==0||he!==0){let T=t.columns!==void 0?Math.round(l*d):i.width+oe,et=t.rows!==void 0?Math.round(E*c):i.height+he,q=D.createCanvas(window.document,T,et),Le=q.getContext("2d");if(!Le)throw new Error("Failed to create offset canvas context");Le.drawImage(i,oe,he);let tt=await createImageBitmap(q);if(q.width=q.height=0,i.close(),i=tt,p=i.width,u=i.height,p*u>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");t.columns===void 0&&(l=Math.ceil(i.width/d)),t.rows===void 0&&(E=Math.ceil(i.height/c))}let $e=t.zIndex??0;if(this._kittyStorage.addImage(e.id,i,!0,Ve,$e),i=void 0,t.cursorMovement===1){let T=C.ybase-Y;C.x=Q,C.y=Math.max(K-T,0)}else C.x=Math.min(Q+l,this._coreTerminal.cols)}catch(A){throw i?.close(),A}}async _createBitmap(e){let t=new Uint8Array(await e.data.arrayBuffer());if(e.compression==="z"&&(t=await this._decompressZlib(t)),e.format===100){let p=new Blob([t],{type:"image/png"});if(!window.createImageBitmap){let u=URL.createObjectURL(p),C=new Image;return new Promise((Q,K)=>{C.addEventListener("load",()=>{URL.revokeObjectURL(u);let Y=D.createCanvas(window.document,C.width,C.height);Y.getContext("2d")?.drawImage(C,0,0),createImageBitmap(Y).then(Q).catch(K)}),C.addEventListener("error",()=>{URL.revokeObjectURL(u),K(new Error("Failed to load image"))}),C.src=u})}return createImageBitmap(p)}let i=e.width,A=e.height;if(!i||!A)throw new Error("Width and height required for raw pixel data");let s=e.format===32?4:3,n=i*A*s;if(t.length>>24|C<<8,h[c++]=4278190080|C>>>16|Q<<16,h[c++]=4278190080|Q>>>8}let l=I*3,E=I*4;for(let p=I;ph+I.length,0),o=new Uint8Array(a),g=0;for(let h of s)o.set(h,g),g+=h.length;return o}get images(){return this._kittyStorage.images}get _kittyIdToStorageId(){return this._kittyStorage.kittyIdToStorageId}get pendingTransmissions(){return this._pendingTransmissions}};var U=class U{constructor(e){this._storage=e;this._nextImageId=1;this._images=new Map;this._kittyIdToStorageId=new Map;this._storageIdToKittyId=new Map;this._handleStorageImageDeleted=e=>{let t=this._storageIdToKittyId.get(e);t!==void 0&&(this._kittyIdToStorageId.delete(t),this._storageIdToKittyId.delete(e),this._images.delete(t))};this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"};this._previousOnImageDeleted=this._storage.onImageDeleted,this._wrappedOnImageDeleted=t=>{this._previousOnImageDeleted?.(t),this._handleStorageImageDeleted(t)},this._storage.onImageDeleted=this._wrappedOnImageDeleted}reset(){this._nextImageId=1,this._images.clear(),this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}dispose(){this.reset(),this._storage.onImageDeleted===this._wrappedOnImageDeleted&&(this._storage.onImageDeleted=this._previousOnImageDeleted)}storeImage(e,t){let i=e??this._nextImageId++,A=this._kittyIdToStorageId.get(i);return A!==void 0&&(this._storage.deleteImage(A),this._kittyIdToStorageId.delete(i),this._storageIdToKittyId.delete(A)),!this._images.has(i)&&this._images.size>=U._maxStoredImages&&this._evictUndisplayedImages(),this._images.set(i,{...t,id:i}),i}addImage(e,t,i,A,s){let n=this._kittyIdToStorageId.get(e);n!==void 0&&this._storageIdToKittyId.delete(n),this._addImageOpts.scrolling=i,this._addImageOpts.layer=A,this._addImageOpts.zIndex=s;let a=this._storage.addImage(t,this._addImageOpts);this._kittyIdToStorageId.set(e,a),this._storageIdToKittyId.set(a,e)}getImage(e){return this._images.get(e)}deleteById(e){this._images.delete(e);let t=this._kittyIdToStorageId.get(e);t!==void 0&&(this._storage.deleteImage(t),this._kittyIdToStorageId.delete(e),this._storageIdToKittyId.delete(t))}deleteAll(){this._images.clear();for(let e of this._kittyIdToStorageId.values())this._storage.deleteImage(e);this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}get images(){return this._images}get kittyIdToStorageId(){return this._kittyIdToStorageId}get lastImageId(){return this._nextImageId-1}_evictUndisplayedImages(){for(let[e]of this._images){if(this._images.size<=U._maxStoredImages/2)break;this._kittyIdToStorageId.has(e)||this._images.delete(e)}}};U._maxStoredImages=256;var te=U;var y=M(X());var ze=M(We());var xt=4194304,Se=y.PALETTE_ANSI_256;Se.set(y.PALETTE_VT340_COLOR);var se=class{constructor(e,t,i){this._opts=e;this._storage=t;this._coreTerminal=i;this._size=0;this._aborted=!1;(0,ze.DecoderAsync)({memoryLimit:this._opts.pixelLimit*4,palette:Se,paletteLimit:this._opts.sixelPaletteLimit}).then(A=>this._dec=A)}reset(){this._dec&&(this._dec.release(),this._dec._palette.fill(0),this._dec.init(0,Se,this._opts.sixelPaletteLimit))}hook(e){if(this._size=0,this._aborted=!1,this._dec){let t=e.params[1]===1?0:Mt(this._coreTerminal._core._inputHandler._curAttrData,this._coreTerminal._core._themeService?.colors);this._dec.init(t,null,this._opts.sixelPaletteLimit)}}put(e,t,i){if(!(this._aborted||!this._dec)){if(this._size+=i-t,this._size>this._opts.sixelSizeLimit){console.warn("SIXEL: too much data, aborting"),this._aborted=!0,this._dec.release();return}try{this._dec.decode(e,t,i)}catch(A){console.warn(`SIXEL: error while decoding image - ${A}`),this._aborted=!0,this._dec.release()}}}unhook(e){if(this._aborted||!e||!this._dec)return!0;let t=this._dec.width,i=this._dec.height;if(!t||!i)return i&&this._storage.advanceCursor(i),!0;let A=D.createCanvas(void 0,t,i);return A.getContext("2d")?.putImageData(new ImageData(this._dec.data8,t,i),0,0),this._dec.memoryUsage>xt&&this._dec.release(),this._storage.addImage(A),!0}};function Mt(r,e){let t=0;if(!e)return t;if(r.isInverse())if(r.isFgDefault())t=re(e.foreground.rgba);else if(r.isFgRGB()){let i=r.constructor.toColorRGB(r.getFgColor());t=(0,y.toRGBA8888)(...i)}else t=re(e.ansi[r.getFgColor()].rgba);else if(r.isBgDefault())t=re(e.background.rgba);else if(r.isBgRGB()){let i=r.constructor.toColorRGB(r.getBgColor());t=(0,y.toRGBA8888)(...i)}else t=re(e.ansi[r.getBgColor()].rgba);return t}function re(r){return y.BIG_ENDIAN?r:(r&255)<<24|(r>>>8&255)<<16|(r>>>16&255)<<8|r>>>24&255}var ne=class{constructor(e,t,i,A){this._storage=e;this._opts=t;this._renderer=i;this._terminal=A;this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"vt340"}}addImage(e){this._addImageOpts.scrolling=this._opts.sixelScrolling,this._storage.addImage(e,this._addImageOpts)}advanceCursor(e){if(this._opts.sixelScrolling){let t=this._renderer.cellSize;(t.width===-1||t.height===-1)&&(t=w);let i=Math.ceil(e/t.height);for(let A=1;Athis._onImageAdded.fire(),this._opts.enableSizeReports){let t=e.options.windowOptions??{};t.getWinSizePixels=!0,t.getCellSizePixels=!0,t.getWinSizeChars=!0,e.options.windowOptions=t}if(this._disposeLater(this._renderer,this._storage,e.parser.registerCsiHandler({prefix:"?",final:"h"},t=>this._decset(t)),e.parser.registerCsiHandler({prefix:"?",final:"l"},t=>this._decrst(t)),e.parser.registerCsiHandler({final:"c"},t=>this._da1(t)),e.parser.registerCsiHandler({prefix:"?",final:"S"},t=>this._xtermGraphicsAttributes(t)),e.onRender(t=>this._storage?.render(t)),e.parser.registerCsiHandler({intermediates:"!",final:"p"},()=>this.reset()),e.parser.registerEscHandler({final:"c"},()=>this.reset()),e._core._inputHandler.onRequestReset(()=>this.reset()),e.buffer.onBufferChange(()=>this._storage?.wipeAlternate()),e.onResize(t=>this._storage?.viewportResize(t))),this._opts.sixelSupport){let t=new ne(this._storage,this._opts,this._renderer,e),i=new se(this._opts,t,e);this._handlers.set("sixel",i),this._disposeLater(e._core._inputHandler._parser.registerDcsHandler({final:"q"},i))}if(this._opts.iipSupport){let t=new ae(this._storage),i=new $(this._opts,this._renderer,t,e);this._handlers.set("iip",i),this._disposeLater(e._core._inputHandler._parser.registerOscHandler(1337,i))}if(this._opts.kittySupport){let t=new te(this._storage),i=new ee(this._opts,this._renderer,t,e);this._handlers.set("kitty",i),this._disposeLater(t,i,e._core._inputHandler._parser.registerApcHandler({final:"G"},i))}}reset(){this._opts.sixelScrolling=this._defaultOpts.sixelScrolling,this._opts.sixelPaletteLimit=this._defaultOpts.sixelPaletteLimit,this._storage?.reset();for(let e of this._handlers.values())e.reset();return!1}get storageLimit(){return this._storage?.getLimit()||-1}set storageLimit(e){this._storage?.setLimit(e),this._opts.storageLimit=e}get storageUsage(){return this._storage?this._storage.getUsage():-1}get showPlaceholder(){return this._opts.showPlaceholder}set showPlaceholder(e){this._opts.showPlaceholder=e,this._renderer?.showPlaceholder(e)}getImageAtBufferCell(e,t){return this._storage?.getImageAtBufferCell(e,t)}extractTileAtBufferCell(e,t){return this._storage?.extractTileAtBufferCell(e,t)}_report(e){this._terminal?._core.input(e,!1)}_decset(e){for(let t=0;t2&&!(e[2]instanceof Array)&&e[2]<=Ze?(this._opts.sixelPaletteLimit=e[2],this._report(`\x1B[?${e[0]};0;${this._opts.sixelPaletteLimit}S`)):this._report(`\x1B[?${e[0]};2S`),!0;case 4:return this._report(`\x1B[?${e[0]};0;${Ze}S`),!0;default:return this._report(`\x1B[?${e[0]};2S`),!0}if(e[0]===2)switch(e[1]){case 1:let t=this._renderer?.dimensions?.css.canvas.width,i=this._renderer?.dimensions?.css.canvas.height;if(!t||!i){let s=w;t=(this._terminal?.cols||80)*s.width,i=(this._terminal?.rows||24)*s.height}if(t*i()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var ot=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let A of rt(e))!at.call(s,A)&&A!==t&&Me(s,A,{get:()=>e[A],enumerable:!(i=st(e,A))||i.enumerable});return s};var M=(s,e,t)=>(t=s!=null?At(nt(s)):{},ot(e||!s||!s.__esModule?Me(t,"default",{value:s,enumerable:!0}):t,s));var Z=x(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.DEFAULT_FOREGROUND=_.DEFAULT_BACKGROUND=_.PALETTE_ANSI_256=_.PALETTE_VT340_GREY=_.PALETTE_VT340_COLOR=_.normalizeHLS=_.normalizeRGB=_.nearestColorIndex=_.fromRGBA8888=_.toRGBA8888=_.alpha=_.blue=_.green=_.red=_.BIG_ENDIAN=void 0;_.BIG_ENDIAN=new Uint8Array(new Uint32Array([4278190080]).buffer)[0]===255;_.BIG_ENDIAN&&console.warn("BE platform detected. This version of node-sixel works only on LE properly.");function ve(s){return s&255}_.red=ve;function Re(s){return s>>>8&255}_.green=Re;function ke(s){return s>>>16&255}_.blue=ke;function gt(s){return s>>>24&255}_.alpha=gt;function f(s,e,t,i=255){return((i&255)<<24|(t&255)<<16|(e&255)<<8|s&255)>>>0}_.toRGBA8888=f;function dt(s){return[s&255,s>>8&255,s>>16&255,s>>>24]}_.fromRGBA8888=dt;function It(s,e){let t=ve(s),i=Re(s),A=ke(s),r=Number.MAX_SAFE_INTEGER,n=-1;for(let a=0;a1&&(t-=1),t*6<1?e+(s-e)*6*t:t*2<1?s:t*3<2?e+(s-e)*(4-t*6):e}function lt(s,e,t){if(!t){let r=Math.round(e*255);return f(r,r,r)}let i=e<.5?e*(1+t):e+t-e*t,A=2*e-i;return f(Ie(0,255,Math.round(le(i,A,s+1/3)*255)),Ie(0,255,Math.round(le(i,A,s)*255)),Ie(0,255,Math.round(le(i,A,s-1/3)*255)))}function m(s,e,t){return(4278190080|Math.round(t/100*255)<<16|Math.round(e/100*255)<<8|Math.round(s/100*255))>>>0}_.normalizeRGB=m;function ct(s,e,t){return lt((s+240%360)/360,e/100,t/100)}_.normalizeHLS=ct;_.PALETTE_VT340_COLOR=new Uint32Array([m(0,0,0),m(20,20,80),m(80,13,13),m(20,80,20),m(80,20,80),m(20,80,80),m(80,80,20),m(53,53,53),m(26,26,26),m(33,33,60),m(60,26,26),m(33,60,33),m(60,33,60),m(33,60,60),m(60,60,33),m(80,80,80)]);_.PALETTE_VT340_GREY=new Uint32Array([m(0,0,0),m(13,13,13),m(26,26,26),m(40,40,40),m(6,6,6),m(20,20,20),m(33,33,33),m(46,46,46),m(0,0,0),m(13,13,13),m(26,26,26),m(40,40,40),m(6,6,6),m(20,20,20),m(33,33,33),m(46,46,46)]);_.PALETTE_ANSI_256=(()=>{let s=[f(0,0,0),f(205,0,0),f(0,205,0),f(205,205,0),f(0,0,238),f(205,0,205),f(0,250,205),f(229,229,229),f(127,127,127),f(255,0,0),f(0,255,0),f(255,255,0),f(92,92,255),f(255,0,255),f(0,255,255),f(255,255,255)],e=[0,95,135,175,215,255];for(let t=0;t<6;++t)for(let i=0;i<6;++i)for(let A=0;A<6;++A)s.push(f(e[t],e[i],e[A]));for(let t=8;t<=238;t+=10)s.push(f(t,t,t));return new Uint32Array(s)})();_.DEFAULT_BACKGROUND=f(0,0,0,255);_.DEFAULT_FOREGROUND=f(255,255,255,255)});var _e=x(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.InWasm=pt;var v=s=>{if(Uint8Array.fromBase64)return Uint8Array.fromBase64(s);if(typeof Buffer<"u")return Buffer.from(s,"base64");let e=atob(s),t=new Uint8Array(e.length);for(let i=0;inew n.Instance(r||(r=new n.Module(A||(A=v(i)))),a):a=>r?n.instantiate(r,a):n.instantiate(A||(A=v(i)),a).then(o=>(r=o.module)&&o.instance):e===1?t?()=>r||(r=new n.Module(A||(A=v(i)))):()=>r?Promise.resolve(r):n.compile(A||(A=v(i))).then(a=>r=a):t?()=>A||(A=v(i)):()=>Promise.resolve(A||(A=v(i)))}if(typeof _wasmCtx>"u")throw new Error('must run "inwasm"');_wasmCtx.add(s)}});var Ce=x(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});var Bt=_e(),ft=(0,Bt.InWasm)({s:1,t:0,d:"AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML"}),S=new Uint8Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map(s=>s.charCodeAt(0))),R=new Uint32Array(1024);R.fill(4278190080);for(let s=0;s>4|(s<<4&255)<<8;for(let s=0;s>2<<8|(s<<6&255)<<16;for(let s=0;sthis.maxBytes||this.maxBytes>4294901760)throw new Error("invalid byte settings")}get data8(){return this._inst?this._d.subarray(0,this._m32[1282]):Qt}release(){this._inst&&(this._bytes>this.keepSize?this._inst=this._m32=this._d=this._mem=null:(this._m32[1280]=0,this._m32[1281]=0,this._m32[1282]=0))}init(e,t){if(this.maxBytes=e??this.maxBytes,this._bytes=t??Math.min(this._bytes,this.maxBytes),this._bytes>this.maxBytes||this.maxBytes>4294901760)throw Error("invalid byte settings");let i=this._m32,A=this._bytes+5152;this._inst?this._mem.buffer.byteLengththis.maxBytes)return-3;let i=this._bytes;for(;(i*=2)this._mem.buffer.byteLength){let A=Math.ceil((i+5152-this._mem.buffer.byteLength)/65536);this._mem.grow(A),this._m32=new Uint32Array(this._mem.buffer,0),this._d=new Uint8Array(this._mem.buffer,5152)}this._bytes=i}return 0}put(e){if(!this._inst||this._ended)return-2;if(this._realloc(e.length))return-3;let t=this._m32;return this._d.set(e,t[1280]),t[1280]+=e.length,t[1280]-t[1281]>=131072?this._inst.exports.dec():0}end(){return this._ended=!0,this._inst?this._inst.exports.end():-2}get loadedBytes(){return this._inst?this._m32[1280]:0}get freeBytes(){return this._inst?this.maxBytes-this._m32[1280]:0}};Ee.default=ue});var Ne=x(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});var Dt=_e(),wt=(0,Dt.InWasm)({s:1,t:0,d:"AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=="}),pe=class{constructor(e){this.keepSize=e,this.width=0,this.height=0}decode(e){this.width=e[4]<<24|e[5]<<16|e[6]<<8|e[7],this.height=e[8]<<24|e[9]<<16|e[10]<<8|e[11];let t=this.width*this.height,i=t*4,A=e.length,r=Math.max(i,A)+(Math.min(i,A)>>1)+4096;this._inst?this._mem.buffer.byteLengththis.keepSize&&(this._inst=this._d=this._mem=null)}};Be.default=pe});var Ye=x(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.LIMITS=void 0;se.LIMITS={CHUNK_SIZE:16384,PALETTE_SIZE:4096,MAX_WIDTH:16384,BYTES:"AGFzbQEAAAABJAdgAAF/YAJ/fwBgA39/fwF/YAF/AX9gAABgBH9/f38AYAF/AAIlAgNlbnYLaGFuZGxlX2JhbmQAAwNlbnYLbW9kZV9wYXJzZWQAAwMTEgQAAAAAAQQBAQUBAAACAgAGAwQFAXABBwcFBAEBBwcGCAF/AUGAihoLB9wBDgZtZW1vcnkCABFnZXRfc3RhdGVfYWRkcmVzcwADEWdldF9jaHVua19hZGRyZXNzAAQOZ2V0X3AwX2FkZHJlc3MABRNnZXRfcGFsZXR0ZV9hZGRyZXNzAAYEaW5pdAALBmRlY29kZQAMDWN1cnJlbnRfd2lkdGgADQ5jdXJyZW50X2hlaWdodAAOGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtfaW5pdGlhbGl6ZQACCXN0YWNrU2F2ZQARDHN0YWNrUmVzdG9yZQASCnN0YWNrQWxsb2MAEwkMAQBBAQsGCgcJDxACDAEBCq5UEgMAAQsFAEGg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ADcDAEH4iwIgADcDAEHwiwIgADcDAEHoiwIgADcDAEHgiwIgADcDAEHYiwIgADcDAEHQiwIgADcDAEHIiwIgADcDAEHAiwIgADcDAEG4iwIgADcDAEGwiwIgADcDAEGoiwIgADcDAEGgiwIgADcDAEGYiwIgADcDAEGQiwIgADcDAEGIiwIgADcDAEGAiwIgADcDAEH4igIgADcDAEHwigIgADcDAEHoigIgADcDAEHgigIgADcDAEHYigIgADcDAEHQigIgADcDAEHIigIgADcDAEHAigIgADcDAEG4igIgADcDAEGwigIgADcDAEGoigIgADcDAEGgigIgADcDAEGYigIgADcDAEGQigIgADcDAEGIigIgADcDAEGAigIgADcDAEH4iQIgADcDAEHwiQIgADcDAEHoiQIgADcDAEHgiQIgADcDAEHYiQIgADcDAEHQiQIgADcDAEHIiQIgADcDAEHAiQIgADcDAEG4iQIgADcDAEGwiQIgADcDAEGoCCgCACIEQf8AakGAAW0hCAJAIARBgQFIDQBBASEBIAhBAiAIQQJKG0EBayICQQFxIQMgBEGBAk4EQCACQX5xIQIDQCABQQl0IgdBEHJBoIkCakGwiQJBgAT8CgAAIAdBsI0CakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsLIANFDQAgAUEJdEEQckGgiQJqQbCJAkGABPwKAAALAkAgBEEBSA0AIAhBASAIQQFKGyIDQQFxIQUCQCADQQFrIgdFBEBBACEBDAELIANB/v///wdxIQJBACEBA0AgAUEJdCIGQRByQbCJBmpBsIkCQYAE/AoAACAGQZAEckGwiQZqQbCJAkGABPwKAAAgAUECaiEBIAJBAmsiAg0ACwsgBQRAIAFBCXRBEHJBsIkGakGwiQJBgAT8CgAACyAEQQFIDQAgA0EBcSEFIAcEfyADQf7///8HcSECQQAhAQNAIAFBCXQiBkEQckHAiQpqQbCJAkGABPwKAAAgBkGQBHJBwIkKakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsgAUEHdEEEcgVBBAshASAFBEAgAUECdEHAiQpqQbCJAkGABPwKAAALIARBAUgNACADQQF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B5ABtQRB0ckGAgIB4cgsEACMACwYAIAAkAAsQACMAIABrQXBxIgAkACAACwsYAQBBgAgLEQEAAAACAAAAAwAAAAQAAAAF"}});var We=x(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.decodeAsync=b.decode=b.Decoder=b.DecoderAsync=void 0;var O=Z(),Q=Ye();function St(s){if(typeof Buffer<"u")return Buffer.from(s,"base64");let e=atob(s),t=new Uint8Array(e.length);for(let i=0;i1,this.modeHandler=e=>1}handle_band(e){return this.bandHandler(e)}mode_parsed(e){return this.modeHandler(e)}},Lt={memoryLimit:2048*65536,sixelColor:O.DEFAULT_FOREGROUND,fillColor:O.DEFAULT_BACKGROUND,palette:O.PALETTE_VT340_COLOR,paletteLimit:Q.LIMITS.PALETTE_SIZE,truncate:!0};function ze(s){let e=new Le,t={env:{handle_band:e.handle_band.bind(e),mode_parsed:e.mode_parsed.bind(e)}};return WebAssembly.instantiate(J||qe,t).then(i=>(J=J||i.module,new P(s,i.instance||i,e)))}b.DecoderAsync=ze;var P=class{constructor(e,t,i){if(this._PIXEL_OFFSET=Q.LIMITS.MAX_WIDTH+4,this._canvas=re,this._bandWidths=[],this._maxWidth=0,this._minWidth=Q.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0,this._opts=Object.assign({},Lt,e),this._opts.paletteLimit>Q.LIMITS.PALETTE_SIZE)throw new Error(`DecoderOptions.paletteLimit must not exceed ${Q.LIMITS.PALETTE_SIZE}`);if(t)i.bandHandler=this._handle_band.bind(this),i.modeHandler=this._initCanvas.bind(this);else{let A=J||(J=new WebAssembly.Module(qe));t=new WebAssembly.Instance(A,{env:{handle_band:this._handle_band.bind(this),mode_parsed:this._initCanvas.bind(this)}})}this._instance=t,this._wasm=this._instance.exports,this._chunk=new Uint8Array(this._wasm.memory.buffer,this._wasm.get_chunk_address(),Q.LIMITS.CHUNK_SIZE),this._states=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_state_address(),12),this._palette=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_palette_address(),Q.LIMITS.PALETTE_SIZE),this._palette.set(this._opts.palette),this._pSrc=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_p0_address()),this._wasm.init(O.DEFAULT_FOREGROUND,0,this._opts.paletteLimit,0)}get _fillColor(){return this._states[0]}get _truncate(){return this._states[8]}get _rasterWidth(){return this._states[6]}get _rasterHeight(){return this._states[7]}get _width(){return this._states[2]?this._states[2]-4:0}get _height(){return this._states[3]}get _level(){return this._states[9]}get _mode(){return this._states[10]}get _paletteLimit(){return this._states[11]}_initCanvas(e){if(e===2){let t=this.width*this.height;if(t>this._canvas.length){if(this._opts.memoryLimit&&t*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(t)}this._maxWidth=this._width}else if(e===1)if(this._level===2){let t=Math.min(this._rasterWidth,Q.LIMITS.MAX_WIDTH)*this._rasterHeight;if(t>this._canvas.length){if(this._opts.memoryLimit&&t*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(t)}}else this._canvas.length<65536&&(this._canvas=new Uint32Array(65536));return 0}_realloc(e,t){let i=e+t;if(i>this._canvas.length){if(this._opts.memoryLimit&&i*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");let A=new Uint32Array(Math.ceil(i/65536)*65536);A.set(this._canvas),this._canvas=A}}_handle_band(e){let t=this._PIXEL_OFFSET,i=this._lastOffset;if(this._mode===2){let A=this.height-this._currentHeight,r=0;for(;r<6&&A>0;)this._canvas.set(this._pSrc.subarray(t*r,t*r+e),i+e*r),r++,A--;this._lastOffset+=e*r,this._currentHeight+=r}else if(this._mode===1){this._realloc(i,e*6),this._maxWidth=Math.max(this._maxWidth,e),this._minWidth=Math.min(this._minWidth,e);for(let A=0;A<6;++A)this._canvas.set(this._pSrc.subarray(t*A,t*A+e),i+e*A);this._bandWidths.push(e),this._lastOffset+=e*6,this._currentHeight+=6}return 0}get width(){return this._mode!==1?this._width:Math.max(this._maxWidth,this._wasm.current_width())}get height(){return this._mode!==1?this._height:this._wasm.current_width()?this._bandWidths.length*6+this._wasm.current_height():this._bandWidths.length*6}get palette(){return this._palette.subarray(0,this._paletteLimit)}get memoryUsage(){return this._canvas.byteLength+this._wasm.memory.buffer.byteLength+8*this._bandWidths.length}get properties(){return{width:this.width,height:this.height,mode:this._mode,level:this._level,truncate:!!this._truncate,paletteLimit:this._paletteLimit,fillColor:this._fillColor,memUsage:this.memoryUsage,rasterAttributes:{numerator:this._states[4],denominator:this._states[5],width:this._rasterWidth,height:this._rasterHeight}}}init(e=this._opts.fillColor,t=this._opts.palette,i=this._opts.paletteLimit,A=this._opts.truncate){this._wasm.init(this._opts.sixelColor,e,i,A?1:0),t&&this._palette.set(t.subarray(0,Q.LIMITS.PALETTE_SIZE)),this._bandWidths.length=0,this._maxWidth=0,this._minWidth=Q.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0}decode(e,t=0,i=e.length){let A=t;for(;A0){let i=this._PIXEL_OFFSET,A=this._lastOffset,r=0;for(;r<6&&t>0;)this._canvas.set(this._pSrc.subarray(i*r,i*r+e),A+e*r),r++,t--;t&&this._canvas.fill(this._fillColor,A+e*r)}return this._canvas.subarray(0,this.width*this.height)}if(this._mode===1){if(this._minWidth===this._maxWidth){let r=!1;if(e)if(e!==this._minWidth)r=!0;else{let n=this._PIXEL_OFFSET,a=this._lastOffset;this._realloc(a,e*6);for(let o=0;o<6;++o)this._canvas.set(this._pSrc.subarray(n*o,n*o+e),a+e*o)}if(!r)return this._canvas.subarray(0,this.width*this.height)}let t=new Uint32Array(this.width*this.height);t.fill(this._fillColor);let i=0,A=0;for(let r=0;r{if(this._disposed)return H(()=>{});let A={fn:e,thisArgs:t};this._listeners=this._listeners.slice(),this._listeners.push(A);let r=H(()=>{let n=this._listeners.indexOf(A);n!==-1&&(this._listeners=this._listeners.slice(),this._listeners.splice(n,1))});return i&&(Array.isArray(i)?i.push(r):i.add(r)),r},this._event)}fire(e){if(this._disposed||!this._listeners.length)return;if(this._listeners.length===1){this._listeners[0].fn.call(this._listeners[0].thisArgs,e);return}let t=this._listeners;for(let i=0,A=t.length;i{function s(r,n){return r(a=>n.fire(a))}A.forward=s;function e(r,n){return(a,o,h)=>r(g=>a.call(o,n(g)),void 0,h)}A.map=e;function t(...r){return(n,a,o)=>{let h=new N;for(let g of r)h.add(g(d=>n.call(a,d)));return o&&(Array.isArray(o)?o.push(h):o.add(h)),h}}A.any=t;function i(r,n,a){return n(a),r(o=>n(o))}A.runAndSubscribe=i})(ht||={});var ce=M(Z());var D=class s extends k{constructor(t){super();this._terminal=t;this._layers=new Map;this._optionsRefresh=this._register(new W);this._oldOpen=this._terminal._core.open,this._terminal._core.open=i=>{this._oldOpen?.call(this._terminal._core,i),this._open()},this._terminal._core.screenElement&&this._open(),this._optionsRefresh.value=this._terminal._core.optionsService.onOptionChange(i=>{i==="fontSize"&&(this.rescaleCanvas(),this._renderService?.refreshRows(0,this._terminal.rows))}),this._register(H(()=>{this.removeLayerFromDom(),this.removeLayerFromDom("bottom"),this._terminal._core&&this._oldOpen&&(this._terminal._core.open=this._oldOpen,this._oldOpen=void 0),this._renderService&&this._oldSetRenderer&&(this._renderService.setRenderer=this._oldSetRenderer,this._oldSetRenderer=void 0),this._renderService=void 0,this._layers.clear(),this._placeholderBitmap?.close(),this._placeholderBitmap=void 0,this._placeholder=void 0}))}get canvas(){return this._layers.get("top")?.canvas}static createCanvas(t,i,A){let r=(t??document).createElement("canvas");return r.width=i|0,r.height=A|0,r}static createImageData(t,i,A,r){if(typeof ImageData!="function"){let n=t.createImageData(i,A);return r&&n.data.set(new Uint8ClampedArray(r,0,i*A*4)),n}return r?new ImageData(new Uint8ClampedArray(r,0,i*A*4),i,A):new ImageData(i,A)}static createImageBitmap(t){return typeof createImageBitmap!="function"?Promise.resolve(void 0):createImageBitmap(t)}showPlaceholder(t){t?!this._placeholder&&this.cellSize.height!==-1&&this._createPlaceHolder(Math.max(this.cellSize.height+1,24)):(this._placeholderBitmap?.close(),this._placeholderBitmap=void 0,this._placeholder=void 0),this._renderService?.refreshRows(0,this._terminal.rows)}get dimensions(){return this._terminal.dimensions}get cellSize(){return{width:this.dimensions?.css.cell.width||-1,height:this.dimensions?.css.cell.height||-1}}clearLines(t,i,A){let r=t*(this.dimensions?.css.cell.height||0),n=this.dimensions?.css.canvas.width||0,a=(i+1-t)*(this.dimensions?.css.cell.height||0);(!A||A==="top")&&this._layers.get("top")?.clearRect(0,r,n,a),(!A||A==="bottom")&&this._layers.get("bottom")?.clearRect(0,r,n,a)}clearAll(t){if(!t||t==="top"){let i=this._layers.get("top");i?.clearRect(0,0,i.canvas.width,i.canvas.height)}if(!t||t==="bottom"){let i=this._layers.get("bottom");i?.clearRect(0,0,i.canvas.width,i.canvas.height)}}draw(t,i,A,r,n=1){let a=this._layers.get(t.layer);if(!a)return;let{width:o,height:h}=this.cellSize;if(o===-1||h===-1)return;this._rescaleImage(t,o,h);let g=t.actual,{width:d,height:I}=t.actualCellSize,l=Math.ceil(g.width/d),c=i%l*d,u=Math.floor(i/l)*I,E=A*o,C=r*h,p=n*d+c>g.width?g.width-c:n*d,B=u+I>g.height?g.height-u:I;a.drawImage(g,Math.floor(c),Math.floor(u),Math.ceil(p),Math.ceil(B),Math.floor(E),Math.floor(C),Math.ceil(p*o/d),Math.ceil(B*h/I))}extractTile(t,i){let{width:A,height:r}=this.cellSize;if(A===-1||r===-1)return;this._rescaleImage(t,A,r);let n=t.actual,{width:a,height:o}=t.actualCellSize,h=Math.ceil(n.width/a),g=i%h*a,d=Math.floor(i/h)*o,I=a+g>n.width?n.width-g:a,l=d+o>n.height?n.height-d:o,c=s.createCanvas(this.document,Math.ceil(I*A/a),Math.ceil(l*r/o)),u=c.getContext("2d");if(u)return u.drawImage(n,Math.floor(g),Math.floor(d),Math.floor(I),Math.floor(l),0,0,c.width,c.height),c}drawPlaceholder(t,i,A=1){let r=this._layers.get("top");if(r){let{width:n,height:a}=this.cellSize;if(n===-1||a===-1||(this._placeholder?a>=this._placeholder.height&&this._createPlaceHolder(a+1):this._createPlaceHolder(Math.max(a+1,24)),!this._placeholder))return;r.drawImage(this._placeholderBitmap??this._placeholder,t*n,i*a%2?0:1,n*A,a,t*n,i*a,n*A,a)}}rescaleCanvas(){let t=this.dimensions?.css.canvas.width||0,i=this.dimensions?.css.canvas.height||0;for(let A of this._layers.values())(A.canvas.width!==t||A.canvas.height!==i)&&(A.canvas.width=t,A.canvas.height=i)}_rescaleImage(t,i,A){if(i===t.actualCellSize.width&&A===t.actualCellSize.height)return;let{width:r,height:n}=t.origCellSize;if(i===r&&A===n){t.actual=t.orig,t.actualCellSize.width=r,t.actualCellSize.height=n;return}let a=Math.ceil(t.orig.width*i/r),o=Math.ceil(t.orig.height*A/n);if(a*o>t.orig.width*t.orig.height){t.actual=t.orig,t.actualCellSize.width=r,t.actualCellSize.height=n;return}let h=s.createCanvas(this.document,a,o),g=h.getContext("2d");g&&(g.drawImage(t.orig,0,0,h.width,h.height),t.actual=h,t.actualCellSize.width=i,t.actualCellSize.height=A)}_open(){this._renderService=this._terminal._core._renderService,this._oldSetRenderer=this._renderService.setRenderer.bind(this._renderService),this._renderService.setRenderer=t=>{for(let i of[...this._layers.keys()])this.removeLayerFromDom(i);this._oldSetRenderer?.call(this._renderService,t)}}insertLayerToDom(t="top"){if(!this.document||!this._terminal._core.screenElement){console.warn("image addon: cannot insert output canvas to DOM, missing document or screenElement");return}if(this._layers.has(t))return;let i=s.createCanvas(this.document,this.dimensions?.css.canvas.width||0,this.dimensions?.css.canvas.height||0);i.classList.add(`xterm-image-layer-${t}`);let A=this._terminal._core.screenElement;A.style.isolation="isolate",t==="bottom"?(i.style.zIndex="-1",A.insertBefore(i,A.firstChild)):(i.style.zIndex="0",A.appendChild(i));let r=i.getContext("2d",{alpha:!0});if(!r){i.remove();return}this._layers.set(t,r),this.clearAll(t)}removeLayerFromDom(t="top"){let i=this._layers.get(t);i&&(i.canvas.remove(),this._layers.delete(t))}hasLayer(t){return this._layers.has(t)}_createPlaceHolder(t=24){this._placeholderBitmap?.close(),this._placeholderBitmap=void 0;let i=32,A=s.createCanvas(this.document,i,t),r=A.getContext("2d",{alpha:!1});if(!r)return;let n=s.createImageData(r,i,t),a=new Uint32Array(n.data.buffer),o=(0,ce.toRGBA8888)(0,0,0),h=(0,ce.toRGBA8888)(255,255,255);a.fill(o);for(let l=0;l{this._placeholder!==I?l?.close():this._placeholderBitmap=l}).catch(()=>{})}get document(){return this._terminal._core._coreBrowserService?.window.document}};var w={width:7,height:14},G=class s{constructor(e=0,t=0,i=-1,A=-1){this.imageId=i;this.tileId=A;this._ext=0;this._urlId=0;this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}get urlId(){return this._urlId}set urlId(e){this._urlId=e}clone(){return new s(this._ext,this._urlId,this.imageId,this.tileId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0&&this.imageId===-1}},F=new G,j=class{constructor(e,t,i){this._terminal=e;this._renderer=t;this._opts=i;this._images=new Map;this._lastId=0;this._lowestId=0;this._fullyCleared=!1;this._needsFullClear=!1;this._pixelLimit=25e5;try{this.setLimit(this._opts.storageLimit)}catch(A){A instanceof Error&&console.error(A.message),console.warn(`storageLimit is set to ${this.getLimit()} MB`)}this._viewportMetrics={cols:this._terminal.cols,rows:this._terminal.rows}}dispose(){this.reset()}reset(){for(let e of this._images.values())e.marker?.dispose();this._images.clear(),this._renderer.clearAll()}getLimit(){return this._pixelLimit*4/1e6}setLimit(e){if(e<.5||e>1e3)throw RangeError("invalid storageLimit, should be at least 0.5 MB and not exceed 1G");this._pixelLimit=e/4*1e6>>>0,this._evictOldest(0)}getUsage(){return this._getStoredPixels()*4/1e6}_getStoredPixels(){let e=0;for(let t of this._images.values())t.orig&&(e+=t.orig.width*t.orig.height,t.actual&&t.actual!==t.orig&&(e+=t.actual.width*t.actual.height));return e}_delImg(e){let t=this._images.get(e);t&&(this._images.delete(e),window.ImageBitmap&&t.orig instanceof ImageBitmap&&t.orig.close(),this.onImageDeleted?.(e))}wipeAlternate(){let e=[];for(let[t,i]of this._images.entries())i.bufferType==="alternate"&&(i.marker?.dispose(),e.push(t));for(let t of e)this._delImg(t);this._needsFullClear=!0,this._fullyCleared=!1}deleteImage(e){let t=this._images.get(e);t&&(t.marker?.dispose(),this._delImg(e))}addImage(e,t){this._evictOldest(e.width*e.height);let i=this._renderer.cellSize;(i.width===-1||i.height===-1)&&(i=w);let A=Math.ceil(e.width/i.width),r=Math.ceil(e.height/i.height),n=++this._lastId,a=this._terminal._core.buffer,o=this._terminal.cols,h=this._terminal.rows,g=a.x,d=a.y,I=g,l=0;t.scrolling||(a.x=0,a.y=0,I=0),this._terminal._core._inputHandler._dirtyRowTracker.markDirty(a.y);for(let C=0;C=o);++B)this._writeToCell(p,I+B,n,C*A+B),l++;if(t.scrolling)C=h)break;a.x=I}this._terminal._core._inputHandler._dirtyRowTracker.markDirty(a.y),t.scrolling?t.cursorPos==="iip"?a.x=Math.min(I+A,o):a.x=I:(a.x=g,a.y=d);let c=[];for(let[C,p]of this._images.entries())p.tileCount<1&&(p.marker?.dispose(),c.push(C));for(let C of c)this._delImg(C);let u=this._terminal.registerMarker(0);u?.onDispose(()=>{this._images.get(n)&&this._delImg(n)}),this._terminal.buffer.active.type==="alternate"&&this._evictOnAlternate();let E={orig:e,origCellSize:i,actual:e,actualCellSize:{...i},marker:u||void 0,tileCount:l,bufferType:this._terminal.buffer.active.type,layer:t.layer,zIndex:t.zIndex};return this._images.set(n,E),this.onImageAdded?.(),n}render(e){let t=!1,i=!1;for(let g of this._images.values())if(g.layer==="bottom"?i=!0:t=!0,t&&i)break;if(t&&!this._renderer.hasLayer("top")&&(this._renderer.insertLayerToDom("top"),!this._renderer.hasLayer("top")))return;if(i&&!this._renderer.hasLayer("bottom")&&this._renderer.insertLayerToDom("bottom"),this._renderer.rescaleCanvas(),!this._images.size){this._fullyCleared||(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1),this._renderer.hasLayer("top")&&this._renderer.removeLayerFromDom("top"),this._renderer.hasLayer("bottom")&&this._renderer.removeLayerFromDom("bottom");return}!t&&this._renderer.hasLayer("top")&&(this._renderer.clearAll("top"),this._renderer.removeLayerFromDom("top")),!i&&this._renderer.hasLayer("bottom")&&(this._renderer.clearAll("bottom"),this._renderer.removeLayerFromDom("bottom")),this._needsFullClear&&(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1);let{start:A,end:r}=e,n=this._terminal._core.buffer,a=this._terminal._core.cols;this._renderer.clearLines(A,r);let o=[],h=[];for(let g=A;g<=r;++g){let d=n.lines.get(g+n.ydisp);if(!d)return;for(let I=0;Ig.imgSpec.zIndex-d.imgSpec.zIndex);for(let g of h)this._renderer.drawPlaceholder(g.col,g.row,g.count);for(let g of o)this._renderer.draw(g.imgSpec,g.tileId,g.col,g.row,g.count)}viewportResize(e){if(!this._images.size){this._viewportMetrics=e;return}if(this._viewportMetrics.cols>=e.cols){this._viewportMetrics=e;return}let t=this._terminal._core.buffer,i=t.lines.length,A=this._viewportMetrics.cols-1;for(let r=0;r=g)continue;let d=!1;for(let c=A+1;c>e.cols;++c)if(n._data[c*3+0]&4194303){d=!0;break}if(d)continue;let I=Math.min(e.cols,g-a.tileId%g+A),l=a.tileId;for(let c=A+1;c57)throw new Error("illegal char");e=e*10+s[t]-48}return e}function He(s){let e=V(s);if(!e.match(/^((auto)|(\d+?((px)|(%)){0,1}))$/))throw new Error("illegal size");return e}function bt(s){if(typeof Buffer<"u")return Buffer.from(V(s),"base64").toString();let e=atob(V(s)),t=new Uint8Array(e.length);for(let i=0;i14)return-1;for(let a=t;a=be)return this._a();n[r++]=o}break;case 58:return A===3&&!this._storeValue(r)?this._a():(this.state=4,a+1);default:if(r>=be)return this._a();n[r++]=o}}return this.state=A,this._position=r,-2}_a(){return this.fields.type=0,this.state=1,-1}_storeKey(e){let t=V(this._buffer.subarray(0,e));return t?(this._key=t,this.fields[t]=null,!0):!1}_storeValue(e){if(this._key){try{let t=this._buffer.slice(0,e);this.fields[this._key]=Fe[this._key]?Fe[this._key](t):t}catch{return!1}return!0}return!1}};var L={mime:"unsupported",width:0,height:0};function ee(s){if(s.length<32)return L;let e=new Uint32Array(s.buffer,s.byteOffset,8);if(e[0]===1196314761&&e[1]===169478669&&e[3]===1380206665)return{mime:"image/png",width:s[16]<<24|s[17]<<16|s[18]<<8|s[19],height:s[20]<<24|s[21]<<16|s[22]<<8|s[23]};if(s[0]===255&&s[1]===216&&s[2]===255){let[t,i]=yt(s);return{mime:"image/jpeg",width:t,height:i}}if(e[0]===944130375&&(s[4]===55||s[4]===57)&&s[5]===97)return{mime:"image/gif",width:s[7]<<8|s[6],height:s[9]<<8|s[8]};if(e[0]===1718185841)return{mime:"image/qoi",width:s[4]<<24|s[5]<<16|s[6]<<8|s[7],height:s[8]<<24|s[9]<<16|s[10]<<8|s[11]};if(e[0]===1179011410&&e[2]===1346520407&&(e[3]&16777215)===3690582){switch(s[15]){case 88:return{mime:"image/webp",width:(s[24]|s[25]<<8|s[26]<<16)+1,height:(s[27]|s[28]<<8|s[29]<<16)+1};case 76:if(s[20]!==47)return L;let t=s[21]|s[22]<<8|s[23]<<16|s[24]<<24;return{mime:"image/webp",width:(t&16383)+1,height:(t>>>14&16383)+1};case 32:return s[23]!==157||s[24]!==1||s[25]!==42?L:{mime:"image/webp",width:(s[26]|s[27]<<8)&16383,height:(s[28]|s[29]<<8)&16383}}return L}if(e[1]===1887007846&&(e[2]===1718187617||e[2]===1936291425)){let t=-1,i=Math.min(s.length-16,1024);for(let A=8;A0&&r>0)return{mime:"image/avif",width:A,height:r}}return L}return L}function yt(s){let e=s.length,t=4,i=s[t]<<8|s[t+1];for(;;){if(t+=i,t>=e)return[0,0];if(s[t]!==255)return[0,0];if(s[t+1]===192||s[t+1]===194)return t+80){if(this._hp.fields.type===1){if(this._isMultipart&&(this._isMultipart=!1,this._abortMulti=!1,this._dec.release()),this._header=Object.assign({},ye,this._hp.fields),!this._header.inline){this._aborted=!0;return}this._dec.init()}else if(this._abortMulti){this._aborted=!0;return}this._dec.put(e.subarray(A,i))!==0&&(this._dec.release(),this._aborted=!0,this._isMultipart&&(this._abortMulti=!0))}}}end(e){if(this._aborted||this._hp.state!==4&&this._hp.end())return!0;let t=this._hp.fields.type;if(t===3)return!0;if(t===5){let h=w.width,g=w.height;this._renderer.dimensions&&(h=this._renderer.dimensions.css.canvas.width/this._coreTerminal.cols,g=this._renderer.dimensions.css.canvas.height/this._coreTerminal.rows);let d=this._coreTerminal._core._coreBrowserService?.dpr??1,I=`\x1B]1337;ReportCellSize=${g.toFixed(3)};${h.toFixed(3)};${d.toFixed(3)}\x1B\\`;return this._coreTerminal.input(I,!1),!0}if(t===2)return this._header=Object.assign({},ye,this._hp.fields),this._isMultipart=!0,this._abortMulti=!1,this._dec.release(),this._dec.init(),!0;if(t===4&&(!this._isMultipart||(this._isMultipart=!1,this._abortMulti||this._header.type!==2)))return!0;let i=0,A=0,r,n=L;if((r=e)&&((r=!this._dec.end())?(n=ee(this._dec.data8),(r=n.mime!=="unsupported")?(i=n.width,A=n.height,(r=i&&A&&i*Ao!==this._generation?(h.close(),!0):(this._storage.addImage(h),!0)).catch(h=>(console.warn(`IIP: decoding error ${n.mime} ${n.width}x${n.height}`,h),!0))}_resize(e,t){let i=this._renderer.dimensions?.css.cell.width||w.width,A=this._renderer.dimensions?.css.cell.height||w.height,r=this._renderer.dimensions?.css.canvas.width||i*this._coreTerminal.cols,n=this._renderer.dimensions?.css.canvas.height||A*this._coreTerminal.rows,a=this._dim(this._header.width,r,i),o=this._dim(this._header.height,n,A);if(!a&&!o){let h=r/e,g=(n-A)/t,d=Math.min(h,g);return d<1?[e*d,t*d]:[e,t]}return a?this._header.preserveAspectRatio||!a||!o?[a,t*a/e]:[a,o]:[e*o/t,o]}_dim(e,t,i){return e==="auto"?0:e.endsWith("%")?parseInt(e.slice(0,-1),10)*t/100:e.endsWith("px")?parseInt(e.slice(0,-2),10):parseInt(e,10)*i}};var Ke=M(Ce());function Se(s){let e={},t=s.split(",");for(let i of t){let A=i.indexOf("=");if(A===-1)continue;let r=i.substring(0,A),n=i.substring(A+1);if(r==="a"){e.action=n;continue}if(r==="o"){e.compression=n;continue}if(r==="t"){e.transmission=n;continue}if(r==="d"){e.deleteSelector=n;continue}let a=parseInt(n,10);switch(r){case"f":e.format=a;break;case"i":e.id=a;break;case"I":e.imageNumber=a;break;case"s":e.width=a;break;case"v":e.height=a;break;case"x":e.x=a;break;case"y":e.y=a;break;case"w":e.sourceWidth=a;break;case"h":e.sourceHeight=a;break;case"X":e.xOffset=a;break;case"Y":e.yOffset=a;break;case"c":e.columns=a;break;case"r":e.rows=a;break;case"m":e.more=a;break;case"q":e.quiet=a;break;case"C":e.cursorMovement=a;break;case"z":e.zIndex=a;break;case"p":e.placementId=a;break}}return e}var Pe=0,ie=class{constructor(e,t,i,A){this._opts=e;this._renderer=t;this._kittyStorage=i;this._coreTerminal=A;this._aborted=!1;this._generation=0;this._decodeError=!1;this._activeDecoder=null;this._inControlData=!0;this._controlData=new Uint32Array(512);this._controlLength=0;this._encodedSizeLimit=0;this._totalEncodedSize=0;this._parsedCommand=null;this._pendingTransmissions=new Map;this._maxEncodedBytes=Math.ceil(this._opts.kittySizeLimit*4/3),this._initialEncodedBytes=Math.min(4194304,this._maxEncodedBytes)}reset(){this._generation++,this._cleanupAllPending(),this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),this._kittyStorage.reset()}dispose(){this.reset()}_removePendingEntry(e){this._pendingTransmissions.delete(e),this._lastPendingKey===e&&(this._lastPendingKey=void 0)}_cleanupAllPending(){for(let e of this._pendingTransmissions.values())e.decoder.release();this._pendingTransmissions.clear(),this._lastPendingKey=void 0}start(){this._aborted=!1,this._decodeError=!1,this._inControlData=!0,this._controlLength=0,this._parsedCommand=null,this._encodedSizeLimit=this._maxEncodedBytes,this._totalEncodedSize=0,this._activeDecoder=null}put(e,t,i){if(!this._aborted)if(!this._inControlData)this._streamPayload(e,t,i);else{let A=i;for(let n=t;n512){this._aborted=!0;return}if(this._controlData.set(e.subarray(t,A),this._controlLength),this._controlLength+=r,!this._inControlData){if(this._parsedCommand=Se(this._parseControlDataString()),this._parsedCommand.id!==void 0&&this._parsedCommand.imageNumber!==void 0){this._sendResponse(this._parsedCommand.id,"EINVAL:cannot specify both i and I keys",this._parsedCommand.quiet??0),this._aborted=!0;return}if(this._parsedCommand.action==="d")return;let n=A+1;nthis._encodedSizeLimit){let o=this._activeDecoder??r?.decoder;o&&o.release(),this._activeDecoder=null,r&&this._removePendingEntry(A),this._aborted=!0;return}if(!this._decodeError){if(r?.decoder&&!this._activeDecoder&&(this._activeDecoder=r.decoder),!this._activeDecoder){let o=this._maxEncodedBytes+131072;if(o>this._opts.storageLimit*1e6){this._aborted=!0,this._parsedCommand?.id!==void 0&&this._sendResponse(this._parsedCommand.id,"ENOMEM:pending image budget exceeded",this._parsedCommand.quiet??0);return}let h=Math.max(1,Math.floor(this._opts.storageLimit*1e6/o));for(;this._pendingTransmissions.size>=h;){let g=this._pendingTransmissions.entries().next().value;if(!g)break;g[1].decoder.release(),this._removePendingEntry(g[0]),g[1].cmd.id!==void 0&&this._sendResponse(g[1].cmd.id,"ENOMEM:pending image budget exceeded",g[1].cmd.quiet??0)}this._activeDecoder=new Ke.default(4194304,this._maxEncodedBytes,this._initialEncodedBytes),this._activeDecoder.init()}this._activeDecoder.put(e.subarray(t,i))!==Pe&&(this._activeDecoder.release(),this._activeDecoder=null,this._decodeError=!0,r&&this._removePendingEntry(A))}}end(e){if(this._aborted||!e)return this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),!0;if(this._inControlData)return this._handleNoPayloadCommand();let t=this._parsedCommand;if(t.action==="d")return this._handleDelete(t);let i=t.id??this._lastPendingKey??0,A=t.more===1,r=this._pendingTransmissions.get(i);if(A)return this._activeDecoder&&(r?(r.totalEncodedSize+=this._totalEncodedSize,r.decodeError=r.decodeError||this._decodeError):this._pendingTransmissions.set(i,{cmd:{...t},decoder:this._activeDecoder,totalEncodedSize:this._totalEncodedSize,decodeError:this._decodeError}),this._lastPendingKey=i,this._activeDecoder=null),!0;r&&(this._lastPendingKey=void 0);let n=this._decodeError,a=t,o=this._activeDecoder;r&&(a=r.cmd,o=r.decoder,n=n||r.decodeError,this._pendingTransmissions.delete(i));let h=new Uint8Array(0);o&&(o.end()!==Pe&&(n=!0),h=o.data8),this._activeDecoder=null;let g=this._handleCommandWithBytesAndCmd(a,h,n);return o&&o.release(),g}_parseControlDataString(){let e="";for(let t=0;t0&&this._sendResponse(e.id,"OK",e.quiet??0)),r}case"T":return this._handleTransmitDisplay(e,t,i);case"q":return this._handleQuery(e,t,i);case"p":return this._handlePlacement(e);default:return e.id!==void 0&&this._sendResponse(e.id,"EINVAL:unsupported action",e.quiet??0),!0}}_handlePlacement(e){if(e.id===void 0)return!0;let t=e.id,i=this._kittyStorage.getImage(t);return i?this._displayImage(i,e).then(r=>(this._sendResponse(t,r?"OK":"EINVAL:image rendering failed",e.quiet??0,e.placementId),!0)):(this._sendResponse(t,"ENOENT:image not found",e.quiet??0,e.placementId),!0)}_handleTransmit(e,t,i){return(e.transmission??"d")!=="d"?(e.id!==void 0&&this._sendResponse(e.id,"EINVAL:unsupported transmission medium",e.quiet??0),!0):(i||t.length===0||this._kittyStorage.storeImage(e.id,{data:new Blob([t]),width:e.width??0,height:e.height??0,format:e.format??32,compression:e.compression??""}),!0)}_handleTransmitDisplay(e,t,i){if(i)return e.id!==void 0&&this._sendResponse(e.id,"EINVAL:invalid base64 data",e.quiet??0),!0;this._handleTransmit(e,t,i);let A=e.id??this._kittyStorage.lastImageId,r=this._kittyStorage.getImage(A);if(r){let n=this._displayImage(r,e);return e.id!==void 0?n.then(a=>(this._sendResponse(A,a?"OK":"EINVAL:image rendering failed",e.quiet??0),!0)):n.then(()=>!0)}return!0}_handleQuery(e,t,i){let A=e.id??0,r=e.quiet??0;if((e.transmission??"d")!=="d")return this._sendResponse(A,"EINVAL:unsupported transmission medium",r),!0;if(i)return this._sendResponse(A,"EINVAL:invalid base64 data",r),!0;if(t.length===0)return this._sendResponse(A,"OK",r),!0;let a=e.format??32;if(a===100)this._sendResponse(A,"OK",r);else{let o=e.width??0,h=e.height??0;if(!o||!h)return this._sendResponse(A,"EINVAL:width and height required for raw pixel data",r),!0;let g=a===32?4:3,d=o*h*g;if(t.length=1||!r&&i>=2)return;let n=A?`,p=${A}`:"",a=`\x1B_Gi=${e}${n};${t}\x1B\\`;this._coreTerminal._core.coreService.triggerDataEvent(a)}_displayImage(e,t){return this._decodeAndDisplay(e,t).then(()=>!0).catch(()=>!1)}async _decodeAndDisplay(e,t){let i=this._generation,A=await this._createBitmap(e);try{if(i!==this._generation)throw new Error("image decode canceled");let r=Math.max(0,t.x??0),n=Math.max(0,t.y??0),a=t.sourceWidth||A.width-r,o=t.sourceHeight||A.height-n,h=Math.max(0,A.width-r),g=Math.max(0,A.height-n),d=Math.max(0,Math.min(a,h)),I=Math.max(0,Math.min(o,g));if(d===0||I===0)throw new Error("invalid source rectangle");if(r!==0||n!==0||d!==A.width||I!==A.height){let T=await createImageBitmap(A,r,n,d,I);A.close(),A=T}let l=this._renderer.dimensions?.css.cell.width||w.width,c=this._renderer.dimensions?.css.cell.height||w.height,u,E;t.columns!==void 0&&t.rows!==void 0?(u=t.columns,E=t.rows):t.columns!==void 0?(u=t.columns,E=Math.max(1,Math.ceil(A.height/A.width*(u*l)/c))):t.rows!==void 0?(E=t.rows,u=Math.max(1,Math.ceil(A.width/A.height*(E*c)/l))):(u=Math.ceil(A.width/l),E=Math.ceil(A.height/c));let C=A.width,p=A.height;if((t.columns!==void 0||t.rows!==void 0)&&(C=Math.round(u*l),p=Math.round(E*c)),C*p>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");let B=this._coreTerminal._core.buffer,K=B.x,Y=B.y,q=B.ybase,$e=t.zIndex!==void 0&&t.zIndex<0?"bottom":"top";if(C!==A.width||p!==A.height){let T=await createImageBitmap(A,{resizeWidth:C,resizeHeight:p});A.close(),A=T}let ge=Math.min(Math.max(0,t.xOffset??0),l-1),de=Math.min(Math.max(0,t.yOffset??0),c-1);if(ge!==0||de!==0){let T=t.columns!==void 0?Math.round(u*l):A.width+ge,tt=t.rows!==void 0?Math.round(E*c):A.height+de,z=D.createCanvas(window.document,T,tt),xe=z.getContext("2d");if(!xe)throw new Error("Failed to create offset canvas context");xe.drawImage(A,ge,de);let it=await createImageBitmap(z);if(z.width=z.height=0,A.close(),A=it,C=A.width,p=A.height,C*p>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");t.columns===void 0&&(u=Math.ceil(A.width/l)),t.rows===void 0&&(E=Math.ceil(A.height/c))}if(i!==this._generation)throw new Error("image decode canceled");let et=t.zIndex??0;if(this._kittyStorage.addImage(e.id,A,!0,$e,et),A=void 0,t.cursorMovement===1){let T=B.ybase-q;B.x=K,B.y=Math.max(Y-T,0)}else B.x=Math.min(K+u,this._coreTerminal.cols)}catch(r){throw A?.close(),r}}async _createBitmap(e){let t=new Uint8Array(await e.data.arrayBuffer());if(e.compression==="z"&&(t=await this._decompressZlib(t)),e.format===100){let E=ee(t);if(E.mime!=="image/png"||!(E.width>0)||!(E.height>0)||E.width*E.height>this._opts.pixelLimit)throw new RangeError("PNG exceeds pixel limit or has invalid dimensions");let C=new Blob([t],{type:"image/png"});if(!window.createImageBitmap){let p=URL.createObjectURL(C),B=new Image;return new Promise((K,Y)=>{B.addEventListener("load",()=>{URL.revokeObjectURL(p);let q=D.createCanvas(window.document,B.width,B.height);q.getContext("2d")?.drawImage(B,0,0),createImageBitmap(q).then(K).catch(Y)}),B.addEventListener("error",()=>{URL.revokeObjectURL(p),Y(new Error("Failed to load image"))}),B.src=p})}return createImageBitmap(C)}let i=e.width,A=e.height;if(!i||!A)throw new Error("Width and height required for raw pixel data");let r=e.format===32?4:3,n=i*A*r;if(t.length>>24|p<<8,g[l++]=4278190080|p>>>16|B<<16,g[l++]=4278190080|B>>>8}let c=d*3,u=d*4;for(let E=d;E=e.length){d.close();return}let I=Math.min(A+4096,e.length);d.enqueue(new Uint8Array(e.subarray(A,I))),A=I}}).pipeThrough(new DecompressionStream(t)).getReader(),a=[],o=0;try{for(;;){let{done:d,value:I}=await n.read();if(d)break;if(o+=I.byteLength,o>i)throw await n.cancel().catch(()=>{}),new RangeError("decompressed image exceeds byte limit");a.push(I)}}finally{n.releaseLock()}let h=new Uint8Array(o),g=0;for(let d of a)h.set(d,g),g+=d.length;return h}get images(){return this._kittyStorage.images}get _kittyIdToStorageId(){return this._kittyStorage.kittyIdToStorageId}get pendingTransmissions(){return this._pendingTransmissions}};var U=class U{constructor(e){this._storage=e;this._nextImageId=1;this._images=new Map;this._kittyIdToStorageId=new Map;this._storageIdToKittyId=new Map;this._handleStorageImageDeleted=e=>{let t=this._storageIdToKittyId.get(e);t!==void 0&&(this._kittyIdToStorageId.delete(t),this._storageIdToKittyId.delete(e),this._images.delete(t))};this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"};this._previousOnImageDeleted=this._storage.onImageDeleted,this._wrappedOnImageDeleted=t=>{this._previousOnImageDeleted?.(t),this._handleStorageImageDeleted(t)},this._storage.onImageDeleted=this._wrappedOnImageDeleted}reset(){this._nextImageId=1,this._images.clear(),this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}dispose(){this.reset(),this._storage.onImageDeleted===this._wrappedOnImageDeleted&&(this._storage.onImageDeleted=this._previousOnImageDeleted)}storeImage(e,t){let i=e??this._nextImageId++,A=this._kittyIdToStorageId.get(i);A!==void 0&&(this._storage.deleteImage(A),this._kittyIdToStorageId.delete(i),this._storageIdToKittyId.delete(A)),!this._images.has(i)&&this._images.size>=U._maxStoredImages&&this._evictUndisplayedImages();let r=this._storage.getLimit()*1e6;this._images.delete(i);let n=0;for(let a of this._images.values())n+=a.data.size;for(let a of[!1,!0])for(let[o,h]of this._images){if(n+t.data.size<=r)break;this._kittyIdToStorageId.has(o)===a&&(n-=h.data.size,this.deleteById(o))}return this._images.set(i,{...t,id:i}),i}addImage(e,t,i,A,r){let n=this._kittyIdToStorageId.get(e);n!==void 0&&this._storageIdToKittyId.delete(n),this._addImageOpts.scrolling=i,this._addImageOpts.layer=A,this._addImageOpts.zIndex=r;let a=this._storage.addImage(t,this._addImageOpts);this._kittyIdToStorageId.set(e,a),this._storageIdToKittyId.set(a,e)}getImage(e){return this._images.get(e)}deleteById(e){this._images.delete(e);let t=this._kittyIdToStorageId.get(e);t!==void 0&&(this._storage.deleteImage(t),this._kittyIdToStorageId.delete(e),this._storageIdToKittyId.delete(t))}deleteAll(){this._images.clear();for(let e of this._kittyIdToStorageId.values())this._storage.deleteImage(e);this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}get images(){return this._images}get kittyIdToStorageId(){return this._kittyIdToStorageId}get lastImageId(){return this._nextImageId-1}_evictUndisplayedImages(){for(let[e]of this._images){if(this._images.size<=U._maxStoredImages/2)break;this._kittyIdToStorageId.has(e)||this._images.delete(e)}}};U._maxStoredImages=256;var Ae=U;var y=M(Z());var Xe=M(We());var Mt=4194304,Te=y.PALETTE_ANSI_256;Te.set(y.PALETTE_VT340_COLOR);var ae=class{constructor(e,t,i){this._opts=e;this._storage=t;this._coreTerminal=i;this._size=0;this._aborted=!1;(0,Xe.DecoderAsync)({memoryLimit:this._opts.pixelLimit*4,palette:Te,paletteLimit:this._opts.sixelPaletteLimit}).then(A=>this._dec=A)}reset(){this._dec&&(this._dec.release(),this._dec._palette.fill(0),this._dec.init(0,Te,this._opts.sixelPaletteLimit))}hook(e){if(this._size=0,this._aborted=!1,this._dec){let t=e.params[1]===1?0:vt(this._coreTerminal._core._inputHandler._curAttrData,this._coreTerminal._core._themeService?.colors);this._dec.init(t,null,this._opts.sixelPaletteLimit)}}put(e,t,i){if(!(this._aborted||!this._dec)){if(this._size+=i-t,this._size>this._opts.sixelSizeLimit){console.warn("SIXEL: too much data, aborting"),this._aborted=!0,this._dec.release();return}try{this._dec.decode(e,t,i)}catch(A){console.warn(`SIXEL: error while decoding image - ${A}`),this._aborted=!0,this._dec.release()}}}unhook(e){if(this._aborted||!e||!this._dec)return!0;let t=this._dec.width,i=this._dec.height;if(!t||!i)return i&&this._storage.advanceCursor(i),!0;let A=D.createCanvas(void 0,t,i);return A.getContext("2d")?.putImageData(new ImageData(this._dec.data8,t,i),0,0),this._dec.memoryUsage>Mt&&this._dec.release(),this._storage.addImage(A),!0}};function vt(s,e){let t=0;if(!e)return t;if(s.isInverse())if(s.isFgDefault())t=ne(e.foreground.rgba);else if(s.isFgRGB()){let i=s.constructor.toColorRGB(s.getFgColor());t=(0,y.toRGBA8888)(...i)}else t=ne(e.ansi[s.getFgColor()].rgba);else if(s.isBgDefault())t=ne(e.background.rgba);else if(s.isBgRGB()){let i=s.constructor.toColorRGB(s.getBgColor());t=(0,y.toRGBA8888)(...i)}else t=ne(e.ansi[s.getBgColor()].rgba);return t}function ne(s){return y.BIG_ENDIAN?s:(s&255)<<24|(s>>>8&255)<<16|(s>>>16&255)<<8|s>>>24&255}var oe=class{constructor(e,t,i,A){this._storage=e;this._opts=t;this._renderer=i;this._terminal=A;this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"vt340"}}addImage(e){this._addImageOpts.scrolling=this._opts.sixelScrolling,this._storage.addImage(e,this._addImageOpts)}advanceCursor(e){if(this._opts.sixelScrolling){let t=this._renderer.cellSize;(t.width===-1||t.height===-1)&&(t=w);let i=Math.ceil(e/t.height);for(let A=1;Athis._onImageAdded.fire(),this._opts.enableSizeReports){let t=e.options.windowOptions??{};t.getWinSizePixels=!0,t.getCellSizePixels=!0,t.getWinSizeChars=!0,e.options.windowOptions=t}if(this._disposeLater(this._renderer,this._storage,e.parser.registerCsiHandler({prefix:"?",final:"h"},t=>this._decset(t)),e.parser.registerCsiHandler({prefix:"?",final:"l"},t=>this._decrst(t)),e.parser.registerCsiHandler({final:"c"},t=>this._da1(t)),e.parser.registerCsiHandler({prefix:"?",final:"S"},t=>this._xtermGraphicsAttributes(t)),e.onRender(t=>this._storage?.render(t)),e.parser.registerCsiHandler({intermediates:"!",final:"p"},()=>this.reset()),e.parser.registerEscHandler({final:"c"},()=>this.reset()),e._core._inputHandler.onRequestReset(()=>this.reset()),e.buffer.onBufferChange(()=>this._storage?.wipeAlternate()),e.onResize(t=>this._storage?.viewportResize(t))),this._opts.sixelSupport){let t=new oe(this._storage,this._opts,this._renderer,e),i=new ae(this._opts,t,e);this._handlers.set("sixel",i),this._disposeLater(e._core._inputHandler._parser.registerDcsHandler({final:"q"},i))}if(this._opts.iipSupport){let t=new he(this._storage),i=new te(this._opts,this._renderer,t,e);this._handlers.set("iip",i),this._disposeLater(e._core._inputHandler._parser.registerOscHandler(1337,i))}if(this._opts.kittySupport){let t=new Ae(this._storage),i=new ie(this._opts,this._renderer,t,e);this._handlers.set("kitty",i),this._disposeLater(t,i,e._core._inputHandler._parser.registerApcHandler({final:"G"},i))}}reset(){this._opts.sixelScrolling=this._defaultOpts.sixelScrolling,this._opts.sixelPaletteLimit=this._defaultOpts.sixelPaletteLimit,this._storage?.reset();for(let e of this._handlers.values())e.reset();return!1}get storageLimit(){return this._storage?.getLimit()||-1}set storageLimit(e){this._storage?.setLimit(e),this._opts.storageLimit=e}get storageUsage(){return this._storage?this._storage.getUsage():-1}get showPlaceholder(){return this._opts.showPlaceholder}set showPlaceholder(e){this._opts.showPlaceholder=e,this._renderer?.showPlaceholder(e)}getImageAtBufferCell(e,t){return this._storage?.getImageAtBufferCell(e,t)}extractTileAtBufferCell(e,t){return this._storage?.extractTileAtBufferCell(e,t)}_report(e){this._terminal?._core.input(e,!1)}_decset(e){for(let t=0;t2&&!(e[2]instanceof Array)&&e[2]<=je?(this._opts.sixelPaletteLimit=e[2],this._report(`\x1B[?${e[0]};0;${this._opts.sixelPaletteLimit}S`)):this._report(`\x1B[?${e[0]};2S`),!0;case 4:return this._report(`\x1B[?${e[0]};0;${je}S`),!0;default:return this._report(`\x1B[?${e[0]};2S`),!0}if(e[0]===2)switch(e[1]){case 1:let t=this._renderer?.dimensions?.css.canvas.width,i=this._renderer?.dimensions?.css.canvas.height;if(!t||!i){let r=w;t=(this._terminal?.cols||80)*r.width,i=(this._terminal?.rows||24)*r.height}if(t*i()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var It=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let A of ht(e))!gt.call(r,A)&&A!==t&&Ne(r,A,{get:()=>e[A],enumerable:!(i=ot(e,A))||i.enumerable});return r};var x=(r,e,t)=>(t=r!=null?at(dt(r)):{},It(e||!r||!r.__esModule?Ne(t,"default",{value:r,enumerable:!0}):t,r));var j=M(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.DEFAULT_FOREGROUND=_.DEFAULT_BACKGROUND=_.PALETTE_ANSI_256=_.PALETTE_VT340_GREY=_.PALETTE_VT340_COLOR=_.normalizeHLS=_.normalizeRGB=_.nearestColorIndex=_.fromRGBA8888=_.toRGBA8888=_.alpha=_.blue=_.green=_.red=_.BIG_ENDIAN=void 0;_.BIG_ENDIAN=new Uint8Array(new Uint32Array([4278190080]).buffer)[0]===255;_.BIG_ENDIAN&&console.warn("BE platform detected. This version of node-sixel works only on LE properly.");function He(r){return r&255}_.red=He;function Fe(r){return r>>>8&255}_.green=Fe;function Ge(r){return r>>>16&255}_.blue=Ge;function ct(r){return r>>>24&255}_.alpha=ct;function f(r,e,t,i=255){return((i&255)<<24|(t&255)<<16|(e&255)<<8|r&255)>>>0}_.toRGBA8888=f;function mt(r){return[r&255,r>>8&255,r>>16&255,r>>>24]}_.fromRGBA8888=mt;function _t(r,e){let t=He(r),i=Fe(r),A=Ge(r),s=Number.MAX_SAFE_INTEGER,n=-1;for(let a=0;a1&&(t-=1),t*6<1?e+(r-e)*6*t:t*2<1?r:t*3<2?e+(r-e)*(4-t*6):e}function ut(r,e,t){if(!t){let s=Math.round(e*255);return f(s,s,s)}let i=e<.5?e*(1+t):e+t-e*t,A=2*e-i;return f(ce(0,255,Math.round(me(i,A,r+1/3)*255)),ce(0,255,Math.round(me(i,A,r)*255)),ce(0,255,Math.round(me(i,A,r-1/3)*255)))}function m(r,e,t){return(4278190080|Math.round(t/100*255)<<16|Math.round(e/100*255)<<8|Math.round(r/100*255))>>>0}_.normalizeRGB=m;function Et(r,e,t){return ut((r+240%360)/360,e/100,t/100)}_.normalizeHLS=Et;_.PALETTE_VT340_COLOR=new Uint32Array([m(0,0,0),m(20,20,80),m(80,13,13),m(20,80,20),m(80,20,80),m(20,80,80),m(80,80,20),m(53,53,53),m(26,26,26),m(33,33,60),m(60,26,26),m(33,60,33),m(60,33,60),m(33,60,60),m(60,60,33),m(80,80,80)]);_.PALETTE_VT340_GREY=new Uint32Array([m(0,0,0),m(13,13,13),m(26,26,26),m(40,40,40),m(6,6,6),m(20,20,20),m(33,33,33),m(46,46,46),m(0,0,0),m(13,13,13),m(26,26,26),m(40,40,40),m(6,6,6),m(20,20,20),m(33,33,33),m(46,46,46)]);_.PALETTE_ANSI_256=(()=>{let r=[f(0,0,0),f(205,0,0),f(0,205,0),f(205,205,0),f(0,0,238),f(205,0,205),f(0,250,205),f(229,229,229),f(127,127,127),f(255,0,0),f(0,255,0),f(255,255,0),f(92,92,255),f(255,0,255),f(0,255,255),f(255,255,255)],e=[0,95,135,175,215,255];for(let t=0;t<6;++t)for(let i=0;i<6;++i)for(let A=0;A<6;++A)r.push(f(e[t],e[i],e[A]));for(let t=8;t<=238;t+=10)r.push(f(t,t,t));return new Uint32Array(r)})();_.DEFAULT_BACKGROUND=f(0,0,0,255);_.DEFAULT_FOREGROUND=f(255,255,255,255)});var Ee=M(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.InWasm=Dt;var v=r=>{if(Uint8Array.fromBase64)return Uint8Array.fromBase64(r);if(typeof Buffer<"u")return Buffer.from(r,"base64");let e=atob(r),t=new Uint8Array(e.length);for(let i=0;inew n.Instance(s||(s=new n.Module(A||(A=v(i)))),a):a=>s?n.instantiate(s,a):n.instantiate(A||(A=v(i)),a).then(o=>(s=o.module)&&o.instance):e===1?t?()=>s||(s=new n.Module(A||(A=v(i)))):()=>s?Promise.resolve(s):n.compile(A||(A=v(i))).then(a=>s=a):t?()=>A||(A=v(i)):()=>Promise.resolve(A||(A=v(i)))}if(typeof _wasmCtx>"u")throw new Error('must run "inwasm"');_wasmCtx.add(r)}});var Be=M(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});var wt=Ee(),bt=(0,wt.InWasm)({s:1,t:0,d:"AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML"}),S=new Uint8Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map(r=>r.charCodeAt(0))),R=new Uint32Array(1024);R.fill(4278190080);for(let r=0;r>4|(r<<4&255)<<8;for(let r=0;r>2<<8|(r<<6&255)<<16;for(let r=0;rthis.maxBytes||this.maxBytes>4294901760)throw new Error("invalid byte settings")}get data8(){return this._inst?this._d.subarray(0,this._m32[1282]):yt}release(){this._inst&&(this._bytes>this.keepSize?this._inst=this._m32=this._d=this._mem=null:(this._m32[1280]=0,this._m32[1281]=0,this._m32[1282]=0))}init(e,t){if(this.maxBytes=e??this.maxBytes,this._bytes=t??Math.min(this._bytes,this.maxBytes),this._bytes>this.maxBytes||this.maxBytes>4294901760)throw Error("invalid byte settings");let i=this._m32,A=this._bytes+5152;this._inst?this._mem.buffer.byteLengththis.maxBytes)return-3;let i=this._bytes;for(;(i*=2)this._mem.buffer.byteLength){let A=Math.ceil((i+5152-this._mem.buffer.byteLength)/65536);this._mem.grow(A),this._m32=new Uint32Array(this._mem.buffer,0),this._d=new Uint8Array(this._mem.buffer,5152)}this._bytes=i}return 0}put(e){if(!this._inst||this._ended)return-2;if(this._realloc(e.length))return-3;let t=this._m32;return this._d.set(e,t[1280]),t[1280]+=e.length,t[1280]-t[1281]>=131072?this._inst.exports.dec():0}end(){return this._ended=!0,this._inst?this._inst.exports.end():-2}get loadedBytes(){return this._inst?this._m32[1280]:0}get freeBytes(){return this._inst?this.maxBytes-this._m32[1280]:0}};pe.default=Ce});var Ue=M(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});var St=Ee(),Lt=(0,St.InWasm)({s:1,t:0,d:"AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=="}),fe=class{constructor(e){this.keepSize=e,this.width=0,this.height=0}decode(e){this.width=e[4]<<24|e[5]<<16|e[6]<<8|e[7],this.height=e[8]<<24|e[9]<<16|e[10]<<8|e[11];let t=this.width*this.height,i=t*4,A=e.length,s=Math.max(i,A)+(Math.min(i,A)>>1)+4096;this._inst?this._mem.buffer.byteLengththis.keepSize&&(this._inst=this._d=this._mem=null)}};Qe.default=fe});var xe=M(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.LIMITS=void 0;se.LIMITS={CHUNK_SIZE:16384,PALETTE_SIZE:4096,MAX_WIDTH:16384,BYTES:"AGFzbQEAAAABJAdgAAF/YAJ/fwBgA39/fwF/YAF/AX9gAABgBH9/f38AYAF/AAIlAgNlbnYLaGFuZGxlX2JhbmQAAwNlbnYLbW9kZV9wYXJzZWQAAwMTEgQAAAAAAQQBAQUBAAACAgAGAwQFAXABBwcFBAEBBwcGCAF/AUGAihoLB9wBDgZtZW1vcnkCABFnZXRfc3RhdGVfYWRkcmVzcwADEWdldF9jaHVua19hZGRyZXNzAAQOZ2V0X3AwX2FkZHJlc3MABRNnZXRfcGFsZXR0ZV9hZGRyZXNzAAYEaW5pdAALBmRlY29kZQAMDWN1cnJlbnRfd2lkdGgADQ5jdXJyZW50X2hlaWdodAAOGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtfaW5pdGlhbGl6ZQACCXN0YWNrU2F2ZQARDHN0YWNrUmVzdG9yZQASCnN0YWNrQWxsb2MAEwkMAQBBAQsGCgcJDxACDAEBCq5UEgMAAQsFAEGgCAsGAEGQiQELBgBBsIkCCwUAQZAJC+okAQh/QeQIKAIAIQVB4A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EHYiwIgADcDAEHQiwIgADcDAEHIiwIgADcDAEHAiwIgADcDAEG4iwIgADcDAEGwiwIgADcDAEGoiwIgADcDAEGgiwIgADcDAEGYiwIgADcDAEGQiwIgADcDAEGIiwIgADcDAEGAiwIgADcDAEH4igIgADcDAEHwigIgADcDAEHoigIgADcDAEHgigIgADcDAEHYigIgADcDAEHQigIgADcDAEHIigIgADcDAEHAigIgADcDAEG4igIgADcDAEGwigIgADcDAEGoigIgADcDAEGgigIgADcDAEGYigIgADcDAEGQigIgADcDAEGIigIgADcDAEGAigIgADcDAEH4iQIgADcDAEHwiQIgADcDAEHoiQIgADcDAEHgiQIgADcDAEHYiQIgADcDAEHQiQIgADcDAEHIiQIgADcDAEHAiQIgADcDAEG4iQIgADcDAEGwiQIgADcDAEGoCCgCACIEQf8AakGAAW0hCAJAIARBgQFIDQBBASEBIAhBAiAIQQJKG0EBayICQQFxIQMgBEGBAk4EQCACQX5xIQIDQCABQQl0IgdBEHJBoIkCakGwiQJBgAT8CgAAIAdBsI0CakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsLIANFDQAgAUEJdEEQckGgiQJqQbCJAkGABPwKAAALAkAgBEEBSA0AIAhBASAIQQFKGyIDQQFxIQUCQCADQQFrIgdFBEBBACEBDAELIANB/v///wdxIQJBACEBA0AgAUEJdCIGQRByQbCJBmpBsIkCQYAE/AoAACAGQZAEckGwiQZqQbCJAkGABPwKAAAgAUECaiEBIAJBAmsiAg0ACwsgBQRAIAFBCXRBEHJBsIkGakGwiQJBgAT8CgAACyAEQQFIDQAgA0EBcSEFIAcEfyADQf7///8HcSECQQAhAQNAIAFBCXQiBkEQckHAiQpqQbCJAkGABPwKAAAgBkGQBHJBwIkKakGwiQJBgAT8CgAAIAFBAmohASACQQJrIgINAAsgAUEHdEEEcgVBBAshASAFBEAgAUECdEHAiQpqQbCJAkGABPwKAAALIARBAUgNACADQQFxIQUgBwR/IANB/v///wdxIQJBACEBA0AgAUEJdCIGQRByQdCJDmpB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kACAACwsYAQBBgAgLEQEAAAACAAAAAwAAAAQAAAAF"}});var je=M(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.decodeAsync=b.decode=b.Decoder=b.DecoderAsync=void 0;var O=j(),Q=xe();function Mt(r){if(typeof Buffer<"u")return Buffer.from(r,"base64");let e=atob(r),t=new Uint8Array(e.length);for(let i=0;i1,this.modeHandler=e=>1}handle_band(e){return this.bandHandler(e)}mode_parsed(e){return this.modeHandler(e)}},vt={memoryLimit:2048*65536,sixelColor:O.DEFAULT_FOREGROUND,fillColor:O.DEFAULT_BACKGROUND,palette:O.PALETTE_VT340_COLOR,paletteLimit:Q.LIMITS.PALETTE_SIZE,truncate:!0};function Ze(r){let e=new Me,t={env:{handle_band:e.handle_band.bind(e),mode_parsed:e.mode_parsed.bind(e)}};return WebAssembly.instantiate(J||Xe,t).then(i=>(J=J||i.module,new P(r,i.instance||i,e)))}b.DecoderAsync=Ze;var P=class{constructor(e,t,i){if(this._PIXEL_OFFSET=Q.LIMITS.MAX_WIDTH+4,this._canvas=ne,this._bandWidths=[],this._maxWidth=0,this._minWidth=Q.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0,this._opts=Object.assign({},vt,e),this._opts.paletteLimit>Q.LIMITS.PALETTE_SIZE)throw new Error(`DecoderOptions.paletteLimit must not exceed ${Q.LIMITS.PALETTE_SIZE}`);if(t)i.bandHandler=this._handle_band.bind(this),i.modeHandler=this._initCanvas.bind(this);else{let A=J||(J=new WebAssembly.Module(Xe));t=new WebAssembly.Instance(A,{env:{handle_band:this._handle_band.bind(this),mode_parsed:this._initCanvas.bind(this)}})}this._instance=t,this._wasm=this._instance.exports,this._chunk=new Uint8Array(this._wasm.memory.buffer,this._wasm.get_chunk_address(),Q.LIMITS.CHUNK_SIZE),this._states=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_state_address(),12),this._palette=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_palette_address(),Q.LIMITS.PALETTE_SIZE),this._palette.set(this._opts.palette),this._pSrc=new Uint32Array(this._wasm.memory.buffer,this._wasm.get_p0_address()),this._wasm.init(O.DEFAULT_FOREGROUND,0,this._opts.paletteLimit,0)}get _fillColor(){return this._states[0]}get _truncate(){return this._states[8]}get _rasterWidth(){return this._states[6]}get _rasterHeight(){return this._states[7]}get _width(){return this._states[2]?this._states[2]-4:0}get _height(){return this._states[3]}get _level(){return this._states[9]}get _mode(){return this._states[10]}get _paletteLimit(){return this._states[11]}_initCanvas(e){if(e===2){let t=this.width*this.height;if(t>this._canvas.length){if(this._opts.memoryLimit&&t*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(t)}this._maxWidth=this._width}else if(e===1)if(this._level===2){let t=Math.min(this._rasterWidth,Q.LIMITS.MAX_WIDTH)*this._rasterHeight;if(t>this._canvas.length){if(this._opts.memoryLimit&&t*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");this._canvas=new Uint32Array(t)}}else this._canvas.length<65536&&(this._canvas=new Uint32Array(65536));return 0}_realloc(e,t){let i=e+t;if(i>this._canvas.length){if(this._opts.memoryLimit&&i*4>this._opts.memoryLimit)throw this.release(),new Error("image exceeds memory limit");let A=new Uint32Array(Math.ceil(i/65536)*65536);A.set(this._canvas),this._canvas=A}}_handle_band(e){let t=this._PIXEL_OFFSET,i=this._lastOffset;if(this._mode===2){let A=this.height-this._currentHeight,s=0;for(;s<6&&A>0;)this._canvas.set(this._pSrc.subarray(t*s,t*s+e),i+e*s),s++,A--;this._lastOffset+=e*s,this._currentHeight+=s}else if(this._mode===1){this._realloc(i,e*6),this._maxWidth=Math.max(this._maxWidth,e),this._minWidth=Math.min(this._minWidth,e);for(let A=0;A<6;++A)this._canvas.set(this._pSrc.subarray(t*A,t*A+e),i+e*A);this._bandWidths.push(e),this._lastOffset+=e*6,this._currentHeight+=6}return 0}get width(){return this._mode!==1?this._width:Math.max(this._maxWidth,this._wasm.current_width())}get height(){return this._mode!==1?this._height:this._wasm.current_width()?this._bandWidths.length*6+this._wasm.current_height():this._bandWidths.length*6}get palette(){return this._palette.subarray(0,this._paletteLimit)}get memoryUsage(){return this._canvas.byteLength+this._wasm.memory.buffer.byteLength+8*this._bandWidths.length}get properties(){return{width:this.width,height:this.height,mode:this._mode,level:this._level,truncate:!!this._truncate,paletteLimit:this._paletteLimit,fillColor:this._fillColor,memUsage:this.memoryUsage,rasterAttributes:{numerator:this._states[4],denominator:this._states[5],width:this._rasterWidth,height:this._rasterHeight}}}init(e=this._opts.fillColor,t=this._opts.palette,i=this._opts.paletteLimit,A=this._opts.truncate){this._wasm.init(this._opts.sixelColor,e,i,A?1:0),t&&this._palette.set(t.subarray(0,Q.LIMITS.PALETTE_SIZE)),this._bandWidths.length=0,this._maxWidth=0,this._minWidth=Q.LIMITS.MAX_WIDTH,this._lastOffset=0,this._currentHeight=0}decode(e,t=0,i=e.length){let A=t;for(;A0){let i=this._PIXEL_OFFSET,A=this._lastOffset,s=0;for(;s<6&&t>0;)this._canvas.set(this._pSrc.subarray(i*s,i*s+e),A+e*s),s++,t--;t&&this._canvas.fill(this._fillColor,A+e*s)}return this._canvas.subarray(0,this.width*this.height)}if(this._mode===1){if(this._minWidth===this._maxWidth){let s=!1;if(e)if(e!==this._minWidth)s=!0;else{let n=this._PIXEL_OFFSET,a=this._lastOffset;this._realloc(a,e*6);for(let o=0;o<6;++o)this._canvas.set(this._pSrc.subarray(n*o,n*o+e),a+e*o)}if(!s)return this._canvas.subarray(0,this.width*this.height)}let t=new Uint32Array(this.width*this.height);t.fill(this._fillColor);let i=0,A=0;for(let s=0;s{if(this._disposed)return H(()=>{});let A={fn:e,thisArgs:t};this._listeners=this._listeners.slice(),this._listeners.push(A);let s=H(()=>{let n=this._listeners.indexOf(A);n!==-1&&(this._listeners=this._listeners.slice(),this._listeners.splice(n,1))});return i&&(Array.isArray(i)?i.push(s):i.add(s)),s},this._event)}fire(e){if(this._disposed||!this._listeners.length)return;if(this._listeners.length===1){this._listeners[0].fn.call(this._listeners[0].thisArgs,e);return}let t=this._listeners;for(let i=0,A=t.length;i{function r(s,n){return s(a=>n.fire(a))}A.forward=r;function e(s,n){return(a,o,h)=>s(d=>a.call(o,n(d)),void 0,h)}A.map=e;function t(...s){return(n,a,o)=>{let h=new N;for(let d of s)h.add(d(g=>n.call(a,g)));return o&&(Array.isArray(o)?o.push(h):o.add(h)),h}}A.any=t;function i(s,n,a){return n(a),s(o=>n(o))}A.runAndSubscribe=i})(lt||={});var _e=x(j());var D=class r extends k{constructor(t){super();this._terminal=t;this._layers=new Map;this._optionsRefresh=this._register(new X);this._oldOpen=this._terminal._core.open,this._terminal._core.open=i=>{this._oldOpen?.call(this._terminal._core,i),this._open()},this._terminal._core.screenElement&&this._open(),this._optionsRefresh.value=this._terminal._core.optionsService.onOptionChange(i=>{i==="fontSize"&&(this.rescaleCanvas(),this._renderService?.refreshRows(0,this._terminal.rows))}),this._register(H(()=>{this.removeLayerFromDom(),this.removeLayerFromDom("bottom"),this._terminal._core&&this._oldOpen&&(this._terminal._core.open=this._oldOpen,this._oldOpen=void 0),this._renderService&&this._oldSetRenderer&&(this._renderService.setRenderer=this._oldSetRenderer,this._oldSetRenderer=void 0),this._renderService=void 0,this._layers.clear(),this._placeholderBitmap?.close(),this._placeholderBitmap=void 0,this._placeholder=void 0}))}get canvas(){return this._layers.get("top")?.canvas}static createCanvas(t,i,A){let s=(t??document).createElement("canvas");return s.width=i|0,s.height=A|0,s}static createImageData(t,i,A,s){if(typeof ImageData!="function"){let n=t.createImageData(i,A);return s&&n.data.set(new Uint8ClampedArray(s,0,i*A*4)),n}return s?new ImageData(new Uint8ClampedArray(s,0,i*A*4),i,A):new ImageData(i,A)}static createImageBitmap(t){return typeof createImageBitmap!="function"?Promise.resolve(void 0):createImageBitmap(t)}showPlaceholder(t){t?!this._placeholder&&this.cellSize.height!==-1&&this._createPlaceHolder(Math.max(this.cellSize.height+1,24)):(this._placeholderBitmap?.close(),this._placeholderBitmap=void 0,this._placeholder=void 0),this._renderService?.refreshRows(0,this._terminal.rows)}get dimensions(){return this._terminal.dimensions}get cellSize(){return{width:this.dimensions?.css.cell.width||-1,height:this.dimensions?.css.cell.height||-1}}clearLines(t,i,A){let s=t*(this.dimensions?.css.cell.height||0),n=this.dimensions?.css.canvas.width||0,a=(i+1-t)*(this.dimensions?.css.cell.height||0);(!A||A==="top")&&this._layers.get("top")?.clearRect(0,s,n,a),(!A||A==="bottom")&&this._layers.get("bottom")?.clearRect(0,s,n,a)}clearAll(t){if(!t||t==="top"){let i=this._layers.get("top");i?.clearRect(0,0,i.canvas.width,i.canvas.height)}if(!t||t==="bottom"){let i=this._layers.get("bottom");i?.clearRect(0,0,i.canvas.width,i.canvas.height)}}draw(t,i,A,s,n=1){let a=this._layers.get(t.layer);if(!a)return;let{width:o,height:h}=this.cellSize;if(o===-1||h===-1)return;this._rescaleImage(t,o,h);let d=t.actual,{width:g,height:I}=t.actualCellSize,l=Math.ceil(d.width/g),c=i%l*g,u=Math.floor(i/l)*I,E=A*o,C=s*h,p=n*g+c>d.width?d.width-c:n*g,B=u+I>d.height?d.height-u:I;a.drawImage(d,Math.floor(c),Math.floor(u),Math.ceil(p),Math.ceil(B),Math.floor(E),Math.floor(C),Math.ceil(p*o/g),Math.ceil(B*h/I))}extractTile(t,i){let{width:A,height:s}=this.cellSize;if(A===-1||s===-1)return;this._rescaleImage(t,A,s);let n=t.actual,{width:a,height:o}=t.actualCellSize,h=Math.ceil(n.width/a),d=i%h*a,g=Math.floor(i/h)*o,I=a+d>n.width?n.width-d:a,l=g+o>n.height?n.height-g:o,c=r.createCanvas(this.document,Math.ceil(I*A/a),Math.ceil(l*s/o)),u=c.getContext("2d");if(u)return u.drawImage(n,Math.floor(d),Math.floor(g),Math.floor(I),Math.floor(l),0,0,c.width,c.height),c}drawPlaceholder(t,i,A=1){let s=this._layers.get("top");if(s){let{width:n,height:a}=this.cellSize;if(n===-1||a===-1||(this._placeholder?a>=this._placeholder.height&&this._createPlaceHolder(a+1):this._createPlaceHolder(Math.max(a+1,24)),!this._placeholder))return;s.drawImage(this._placeholderBitmap??this._placeholder,t*n,i*a%2?0:1,n*A,a,t*n,i*a,n*A,a)}}rescaleCanvas(){let t=this.dimensions?.css.canvas.width||0,i=this.dimensions?.css.canvas.height||0;for(let A of this._layers.values())(A.canvas.width!==t||A.canvas.height!==i)&&(A.canvas.width=t,A.canvas.height=i)}_rescaleImage(t,i,A){if(i===t.actualCellSize.width&&A===t.actualCellSize.height)return;let{width:s,height:n}=t.origCellSize;if(i===s&&A===n){t.actual=t.orig,t.actualCellSize.width=s,t.actualCellSize.height=n;return}let a=Math.ceil(t.orig.width*i/s),o=Math.ceil(t.orig.height*A/n);if(a*o>t.orig.width*t.orig.height){t.actual=t.orig,t.actualCellSize.width=s,t.actualCellSize.height=n;return}let h=r.createCanvas(this.document,a,o),d=h.getContext("2d");d&&(d.drawImage(t.orig,0,0,h.width,h.height),t.actual=h,t.actualCellSize.width=i,t.actualCellSize.height=A)}_open(){this._renderService=this._terminal._core._renderService,this._oldSetRenderer=this._renderService.setRenderer.bind(this._renderService),this._renderService.setRenderer=t=>{for(let i of[...this._layers.keys()])this.removeLayerFromDom(i);this._oldSetRenderer?.call(this._renderService,t)}}insertLayerToDom(t="top"){if(!this.document||!this._terminal._core.screenElement){console.warn("image addon: cannot insert output canvas to DOM, missing document or screenElement");return}if(this._layers.has(t))return;let i=r.createCanvas(this.document,this.dimensions?.css.canvas.width||0,this.dimensions?.css.canvas.height||0);i.classList.add(`xterm-image-layer-${t}`);let A=this._terminal._core.screenElement;A.style.isolation="isolate",t==="bottom"?(i.style.zIndex="-1",A.insertBefore(i,A.firstChild)):(i.style.zIndex="0",A.appendChild(i));let s=i.getContext("2d",{alpha:!0});if(!s){i.remove();return}this._layers.set(t,s),this.clearAll(t)}removeLayerFromDom(t="top"){let i=this._layers.get(t);i&&(i.canvas.remove(),this._layers.delete(t))}hasLayer(t){return this._layers.has(t)}_createPlaceHolder(t=24){this._placeholderBitmap?.close(),this._placeholderBitmap=void 0;let i=32,A=r.createCanvas(this.document,i,t),s=A.getContext("2d",{alpha:!1});if(!s)return;let n=r.createImageData(s,i,t),a=new Uint32Array(n.data.buffer),o=(0,_e.toRGBA8888)(0,0,0),h=(0,_e.toRGBA8888)(255,255,255);a.fill(o);for(let l=0;l{this._placeholder!==I?l?.close():this._placeholderBitmap=l}).catch(()=>{})}get document(){return this._terminal._core._coreBrowserService?.window.document}};var w={width:7,height:14},G=class r{constructor(e=0,t=0,i=-1,A=-1){this.imageId=i;this.tileId=A;this._ext=0;this._urlId=0;this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}get urlId(){return this._urlId}set urlId(e){this._urlId=e}clone(){return new r(this._ext,this._urlId,this.imageId,this.tileId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0&&this.imageId===-1}},F=new G,V=class{constructor(e,t,i){this._terminal=e;this._renderer=t;this._opts=i;this._images=new Map;this._lastId=0;this._lowestId=0;this._fullyCleared=!1;this._needsFullClear=!1;this._pixelLimit=25e5;try{this.setLimit(this._opts.storageLimit)}catch(A){A instanceof Error&&console.error(A.message),console.warn(`storageLimit is set to ${this.getLimit()} MB`)}this._viewportMetrics={cols:this._terminal.cols,rows:this._terminal.rows}}dispose(){this.reset()}reset(){for(let e of this._images.values())e.marker?.dispose();this._images.clear(),this._renderer.clearAll()}getLimit(){return this._pixelLimit*4/1e6}setLimit(e){if(e<.5||e>1e3)throw RangeError("invalid storageLimit, should be at least 0.5 MB and not exceed 1G");this._pixelLimit=e/4*1e6>>>0,this._evictOldest(0)}getUsage(){return this._getStoredPixels()*4/1e6}_getStoredPixels(){let e=0;for(let t of this._images.values())t.orig&&(e+=t.orig.width*t.orig.height,t.actual&&t.actual!==t.orig&&(e+=t.actual.width*t.actual.height));return e}_delImg(e){let t=this._images.get(e);t&&(this._images.delete(e),window.ImageBitmap&&t.orig instanceof ImageBitmap&&t.orig.close(),this.onImageDeleted?.(e))}wipeAlternate(){let e=[];for(let[t,i]of this._images.entries())i.bufferType==="alternate"&&(i.marker?.dispose(),e.push(t));for(let t of e)this._delImg(t);this._needsFullClear=!0,this._fullyCleared=!1}deleteImage(e){let t=this._images.get(e);t&&(t.marker?.dispose(),this._delImg(e))}addImage(e,t){this._evictOldest(e.width*e.height);let i=this._renderer.cellSize;(i.width===-1||i.height===-1)&&(i=w);let A=Math.ceil(e.width/i.width),s=Math.ceil(e.height/i.height),n=++this._lastId,a=this._terminal._core.buffer,o=this._terminal.cols,h=this._terminal.rows,d=a.x,g=a.y,I=d,l=0;t.scrolling||(a.x=0,a.y=0,I=0),this._terminal._core._inputHandler._dirtyRowTracker.markDirty(a.y);for(let C=0;C=o);++B)this._writeToCell(p,I+B,n,C*A+B),l++;if(t.scrolling)C=h)break;a.x=I}this._terminal._core._inputHandler._dirtyRowTracker.markDirty(a.y),t.scrolling?t.cursorPos==="iip"?a.x=Math.min(I+A,o):a.x=I:(a.x=d,a.y=g);let c=[];for(let[C,p]of this._images.entries())p.tileCount<1&&(p.marker?.dispose(),c.push(C));for(let C of c)this._delImg(C);let u=this._terminal.registerMarker(0);u?.onDispose(()=>{this._images.get(n)&&this._delImg(n)}),this._terminal.buffer.active.type==="alternate"&&this._evictOnAlternate();let E={orig:e,origCellSize:i,actual:e,actualCellSize:{...i},marker:u||void 0,tileCount:l,bufferType:this._terminal.buffer.active.type,layer:t.layer,zIndex:t.zIndex};return this._images.set(n,E),this.onImageAdded?.(),n}render(e){let t=!1,i=!1;for(let d of this._images.values())if(d.layer==="bottom"?i=!0:t=!0,t&&i)break;if(t&&!this._renderer.hasLayer("top")&&(this._renderer.insertLayerToDom("top"),!this._renderer.hasLayer("top")))return;if(i&&!this._renderer.hasLayer("bottom")&&this._renderer.insertLayerToDom("bottom"),this._renderer.rescaleCanvas(),!this._images.size){this._fullyCleared||(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1),this._renderer.hasLayer("top")&&this._renderer.removeLayerFromDom("top"),this._renderer.hasLayer("bottom")&&this._renderer.removeLayerFromDom("bottom");return}!t&&this._renderer.hasLayer("top")&&(this._renderer.clearAll("top"),this._renderer.removeLayerFromDom("top")),!i&&this._renderer.hasLayer("bottom")&&(this._renderer.clearAll("bottom"),this._renderer.removeLayerFromDom("bottom")),this._needsFullClear&&(this._renderer.clearAll(),this._fullyCleared=!0,this._needsFullClear=!1);let{start:A,end:s}=e,n=this._terminal._core.buffer,a=this._terminal._core.cols;this._renderer.clearLines(A,s);let o=[],h=[];for(let d=A;d<=s;++d){let g=n.lines.get(d+n.ydisp);if(!g)return;for(let I=0;Id.imgSpec.zIndex-g.imgSpec.zIndex);for(let d of h)this._renderer.drawPlaceholder(d.col,d.row,d.count);for(let d of o)this._renderer.draw(d.imgSpec,d.tileId,d.col,d.row,d.count)}viewportResize(e){if(!this._images.size){this._viewportMetrics=e;return}if(this._viewportMetrics.cols>=e.cols){this._viewportMetrics=e;return}let t=this._terminal._core.buffer,i=t.lines.length,A=this._viewportMetrics.cols-1;for(let s=0;s=d)continue;let g=!1;for(let c=A+1;c>e.cols;++c)if(n._data[c*3+0]&4194303){g=!0;break}if(g)continue;let I=Math.min(e.cols,d-a.tileId%d+A),l=a.tileId;for(let c=A+1;c57)throw new Error("illegal char");e=e*10+r[t]-48}return e}function Oe(r){let e=$(r);if(!e.match(/^((auto)|(\d+?((px)|(%)){0,1}))$/))throw new Error("illegal size");return e}function Tt(r){if(typeof Buffer<"u")return Buffer.from($(r),"base64").toString();let e=atob($(r)),t=new Uint8Array(e.length);for(let i=0;i14)return-1;for(let a=t;a=Se)return this._a();n[s++]=o}break;case 58:return A===3&&!this._storeValue(s)?this._a():(this.state=4,a+1);default:if(s>=Se)return this._a();n[s++]=o}}return this.state=A,this._position=s,-2}_a(){return this.fields.type=0,this.state=1,-1}_storeKey(e){let t=$(this._buffer.subarray(0,e));return t?(this._key=t,this.fields[t]=null,!0):!1}_storeValue(e){if(this._key){try{let t=this._buffer.slice(0,e);this.fields[this._key]=Je[this._key]?Je[this._key](t):t}catch{return!1}return!0}return!1}};var L={mime:"unsupported",width:0,height:0};function te(r){if(r.length<32)return L;let e=new Uint32Array(r.buffer,r.byteOffset,8);if(e[0]===1196314761&&e[1]===169478669&&e[3]===1380206665)return{mime:"image/png",width:r[16]<<24|r[17]<<16|r[18]<<8|r[19],height:r[20]<<24|r[21]<<16|r[22]<<8|r[23]};if(r[0]===255&&r[1]===216&&r[2]===255){let[t,i]=xt(r);return{mime:"image/jpeg",width:t,height:i}}if(e[0]===944130375&&(r[4]===55||r[4]===57)&&r[5]===97)return{mime:"image/gif",width:r[7]<<8|r[6],height:r[9]<<8|r[8]};if(e[0]===1718185841)return{mime:"image/qoi",width:r[4]<<24|r[5]<<16|r[6]<<8|r[7],height:r[8]<<24|r[9]<<16|r[10]<<8|r[11]};if(e[0]===1179011410&&e[2]===1346520407&&(e[3]&16777215)===3690582){switch(r[15]){case 88:return{mime:"image/webp",width:(r[24]|r[25]<<8|r[26]<<16)+1,height:(r[27]|r[28]<<8|r[29]<<16)+1};case 76:if(r[20]!==47)return L;let t=r[21]|r[22]<<8|r[23]<<16|r[24]<<24;return{mime:"image/webp",width:(t&16383)+1,height:(t>>>14&16383)+1};case 32:return r[23]!==157||r[24]!==1||r[25]!==42?L:{mime:"image/webp",width:(r[26]|r[27]<<8)&16383,height:(r[28]|r[29]<<8)&16383}}return L}if(e[1]===1887007846&&(e[2]===1718187617||e[2]===1936291425)){let t=-1,i=Math.min(r.length-16,1024);for(let A=8;A0&&s>0)return{mime:"image/avif",width:A,height:s}}return L}return L}function xt(r){let e=r.length,t=4,i=r[t]<<8|r[t+1];for(;;){if(t+=i,t>=e)return[0,0];if(r[t]!==255)return[0,0];if(r[t+1]===192||r[t+1]===194)return t+80){if(this._hp.fields.type===1){if(this._isMultipart&&(this._isMultipart=!1,this._abortMulti=!1,this._dec.release()),this._header=Object.assign({},Le,this._hp.fields),!this._header.inline){this._aborted=!0;return}if(!this._initDecoder()){this._aborted=!0;return}}else if(this._abortMulti){this._aborted=!0;return}this._dec.put(e.subarray(A,i))!==0&&(this._dec.release(),this._aborted=!0,this._isMultipart&&(this._abortMulti=!0))}}}end(e){if(this._aborted||this._hp.state!==4&&this._hp.end())return!0;let t=this._hp.fields.type;if(t===3)return!0;if(t===5){let h=w.width,d=w.height;this._renderer.dimensions&&(h=this._renderer.dimensions.css.canvas.width/this._coreTerminal.cols,d=this._renderer.dimensions.css.canvas.height/this._coreTerminal.rows);let g=this._coreTerminal._core._coreBrowserService?.dpr??1,I=`\x1B]1337;ReportCellSize=${d.toFixed(3)};${h.toFixed(3)};${g.toFixed(3)}\x1B\\`;return this._coreTerminal.input(I,!1),!0}if(t===2)return this._header=Object.assign({},Le,this._hp.fields),this._isMultipart=!0,this._abortMulti=!1,this._dec.release(),this._initDecoder()||(this._abortMulti=!0),!0;if(t===4&&(!this._isMultipart||(this._isMultipart=!1,this._abortMulti||this._header.type!==2)))return!0;let i=0,A=0,s,n=L;if((s=e)&&((s=!this._dec.end())?(n=te(this._dec.data8),(s=n.mime!=="unsupported")?(i=n.width,A=n.height,(s=i&&A&&i*Ao!==this._generation?(h.close(),!0):(this._storage.addImage(h),!0)).catch(h=>(console.warn(`IIP: decoding error ${n.mime} ${n.width}x${n.height}`,h),!0))}_initDecoder(){try{return this._dec.init(),!0}catch(e){return console.warn("IIP: could not allocate decoder",e),this._dec.release(),!1}}_resize(e,t){let i=this._renderer.dimensions?.css.cell.width||w.width,A=this._renderer.dimensions?.css.cell.height||w.height,s=this._renderer.dimensions?.css.canvas.width||i*this._coreTerminal.cols,n=this._renderer.dimensions?.css.canvas.height||A*this._coreTerminal.rows,a=this._dim(this._header.width,s,i),o=this._dim(this._header.height,n,A);if(!a&&!o){let h=s/e,d=(n-A)/t,g=Math.min(h,d);return g<1?[e*g,t*g]:[e,t]}return a?this._header.preserveAspectRatio||!a||!o?[a,t*a/e]:[a,o]:[e*o/t,o]}_dim(e,t,i){return e==="auto"?0:e.endsWith("%")?parseInt(e.slice(0,-1),10)*t/100:e.endsWith("px")?parseInt(e.slice(0,-2),10):parseInt(e,10)*i}};var We=x(Be());function Te(r){let e={},t=r.split(",");for(let i of t){let A=i.indexOf("=");if(A===-1)continue;let s=i.substring(0,A),n=i.substring(A+1);if(s==="a"){e.action=n;continue}if(s==="o"){e.compression=n;continue}if(s==="t"){e.transmission=n;continue}if(s==="d"){e.deleteSelector=n;continue}let a=parseInt(n,10);switch(s){case"f":e.format=a;break;case"i":e.id=a;break;case"I":e.imageNumber=a;break;case"s":e.width=a;break;case"v":e.height=a;break;case"x":e.x=a;break;case"y":e.y=a;break;case"w":e.sourceWidth=a;break;case"h":e.sourceHeight=a;break;case"X":e.xOffset=a;break;case"Y":e.yOffset=a;break;case"c":e.columns=a;break;case"r":e.rows=a;break;case"m":e.more=a;break;case"q":e.quiet=a;break;case"C":e.cursorMovement=a;break;case"z":e.zIndex=a;break;case"p":e.placementId=a;break}}return e}var ze=0,Ae=class{constructor(e,t,i,A){this._opts=e;this._renderer=t;this._kittyStorage=i;this._coreTerminal=A;this._aborted=!1;this._generation=0;this._decodeError=!1;this._activeDecoder=null;this._inControlData=!0;this._controlData=new Uint32Array(512);this._controlLength=0;this._encodedSizeLimit=0;this._totalEncodedSize=0;this._parsedCommand=null;this._pendingTransmissions=new Map;this._maxEncodedBytes=Math.ceil(this._opts.kittySizeLimit*4/3),this._initialEncodedBytes=Math.min(4194304,this._maxEncodedBytes)}reset(){this._generation++,this._cleanupAllPending(),this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),this._kittyStorage.reset()}dispose(){this.reset()}_removePendingEntry(e){this._pendingTransmissions.delete(e),this._lastPendingKey===e&&(this._lastPendingKey=void 0)}_cleanupAllPending(){for(let e of this._pendingTransmissions.values())e.decoder.release();this._pendingTransmissions.clear(),this._lastPendingKey=void 0}start(){this._aborted=!1,this._decodeError=!1,this._inControlData=!0,this._controlLength=0,this._parsedCommand=null,this._encodedSizeLimit=this._maxEncodedBytes,this._totalEncodedSize=0,this._activeDecoder=null}put(e,t,i){if(!this._aborted)if(!this._inControlData)this._streamPayload(e,t,i);else{let A=i;for(let n=t;n512){this._aborted=!0;return}if(this._controlData.set(e.subarray(t,A),this._controlLength),this._controlLength+=s,!this._inControlData){if(this._parsedCommand=Te(this._parseControlDataString()),this._parsedCommand.id!==void 0&&this._parsedCommand.imageNumber!==void 0){this._sendResponse(this._parsedCommand.id,"EINVAL:cannot specify both i and I keys",this._parsedCommand.quiet??0),this._aborted=!0;return}if(this._parsedCommand.action==="d")return;let n=A+1;nthis._encodedSizeLimit){let o=this._activeDecoder??s?.decoder;o&&o.release(),this._activeDecoder=null,s&&this._removePendingEntry(A),this._aborted=!0;return}if(!this._decodeError){if(s?.decoder&&!this._activeDecoder&&(this._activeDecoder=s.decoder),!this._activeDecoder){let o=this._maxEncodedBytes+131072;if(o>this._opts.storageLimit*1e6){this._aborted=!0,this._parsedCommand?.id!==void 0&&this._sendResponse(this._parsedCommand.id,"ENOMEM:pending image budget exceeded",this._parsedCommand.quiet??0);return}let h=Math.max(1,Math.floor(this._opts.storageLimit*1e6/o));for(;this._pendingTransmissions.size>=h;){let g=this._pendingTransmissions.entries().next().value;if(!g)break;g[1].decoder.release(),this._removePendingEntry(g[0]),g[1].cmd.id!==void 0&&this._sendResponse(g[1].cmd.id,"ENOMEM:pending image budget exceeded",g[1].cmd.quiet??0)}let d=new We.default(4194304,this._maxEncodedBytes,this._initialEncodedBytes);try{d.init()}catch(g){console.warn("KITTY: could not allocate decoder",g),this._aborted=!0,this._parsedCommand?.id!==void 0&&this._sendResponse(this._parsedCommand.id,"ENOMEM:could not allocate decoder",this._parsedCommand.quiet??0);return}this._activeDecoder=d}this._activeDecoder.put(e.subarray(t,i))!==ze&&(this._activeDecoder.release(),this._activeDecoder=null,this._decodeError=!0,s&&this._removePendingEntry(A))}}end(e){if(this._aborted||!e)return this._activeDecoder&&(this._activeDecoder.release(),this._activeDecoder=null),!0;if(this._inControlData)return this._handleNoPayloadCommand();let t=this._parsedCommand;if(t.action==="d")return this._handleDelete(t);let i=t.id??this._lastPendingKey??0,A=t.more===1,s=this._pendingTransmissions.get(i);if(A)return this._activeDecoder&&(s?(s.totalEncodedSize+=this._totalEncodedSize,s.decodeError=s.decodeError||this._decodeError):this._pendingTransmissions.set(i,{cmd:{...t},decoder:this._activeDecoder,totalEncodedSize:this._totalEncodedSize,decodeError:this._decodeError}),this._lastPendingKey=i,this._activeDecoder=null),!0;s&&(this._lastPendingKey=void 0);let n=this._decodeError,a=t,o=this._activeDecoder;s&&(a=s.cmd,o=s.decoder,n=n||s.decodeError,this._pendingTransmissions.delete(i));let h=new Uint8Array(0);o&&(o.end()!==ze&&(n=!0),h=o.data8),this._activeDecoder=null;let d=this._handleCommandWithBytesAndCmd(a,h,n);return o&&o.release(),d}_parseControlDataString(){let e="";for(let t=0;t0&&this._sendResponse(e.id,"OK",e.quiet??0)),s}case"T":return this._handleTransmitDisplay(e,t,i);case"q":return this._handleQuery(e,t,i);case"p":return this._handlePlacement(e);default:return e.id!==void 0&&this._sendResponse(e.id,"EINVAL:unsupported action",e.quiet??0),!0}}_handlePlacement(e){if(e.id===void 0)return!0;let t=e.id,i=this._kittyStorage.getImage(t);return i?this._displayImage(i,e).then(s=>(this._sendResponse(t,s?"OK":"EINVAL:image rendering failed",e.quiet??0,e.placementId),!0)):(this._sendResponse(t,"ENOENT:image not found",e.quiet??0,e.placementId),!0)}_handleTransmit(e,t,i){return(e.transmission??"d")!=="d"?(e.id!==void 0&&this._sendResponse(e.id,"EINVAL:unsupported transmission medium",e.quiet??0),!0):(i||t.length===0||this._kittyStorage.storeImage(e.id,{data:new Blob([t]),width:e.width??0,height:e.height??0,format:e.format??32,compression:e.compression??""}),!0)}_handleTransmitDisplay(e,t,i){if(i)return e.id!==void 0&&this._sendResponse(e.id,"EINVAL:invalid base64 data",e.quiet??0),!0;this._handleTransmit(e,t,i);let A=e.id??this._kittyStorage.lastImageId,s=this._kittyStorage.getImage(A);if(s){let n=this._displayImage(s,e);return e.id!==void 0?n.then(a=>(this._sendResponse(A,a?"OK":"EINVAL:image rendering failed",e.quiet??0),!0)):n.then(()=>!0)}return!0}_handleQuery(e,t,i){let A=e.id??0,s=e.quiet??0;if((e.transmission??"d")!=="d")return this._sendResponse(A,"EINVAL:unsupported transmission medium",s),!0;if(i)return this._sendResponse(A,"EINVAL:invalid base64 data",s),!0;if(t.length===0)return this._sendResponse(A,"OK",s),!0;let a=e.format??32;if(a===100)this._sendResponse(A,"OK",s);else{let o=e.width??0,h=e.height??0;if(!o||!h)return this._sendResponse(A,"EINVAL:width and height required for raw pixel data",s),!0;let d=a===32?4:3,g=o*h*d;if(t.length=1||!s&&i>=2)return;let n=A?`,p=${A}`:"",a=`\x1B_Gi=${e}${n};${t}\x1B\\`;this._coreTerminal._core.coreService.triggerDataEvent(a)}_displayImage(e,t){return this._decodeAndDisplay(e,t).then(()=>!0).catch(()=>!1)}async _decodeAndDisplay(e,t){let i=this._generation,A=await this._createBitmap(e);try{if(i!==this._generation)throw new Error("image decode canceled");let s=Math.max(0,t.x??0),n=Math.max(0,t.y??0),a=t.sourceWidth||A.width-s,o=t.sourceHeight||A.height-n,h=Math.max(0,A.width-s),d=Math.max(0,A.height-n),g=Math.max(0,Math.min(a,h)),I=Math.max(0,Math.min(o,d));if(g===0||I===0)throw new Error("invalid source rectangle");if(s!==0||n!==0||g!==A.width||I!==A.height){let T=await createImageBitmap(A,s,n,g,I);A.close(),A=T}let l=this._renderer.dimensions?.css.cell.width||w.width,c=this._renderer.dimensions?.css.cell.height||w.height,u,E;t.columns!==void 0&&t.rows!==void 0?(u=t.columns,E=t.rows):t.columns!==void 0?(u=t.columns,E=Math.max(1,Math.ceil(A.height/A.width*(u*l)/c))):t.rows!==void 0?(E=t.rows,u=Math.max(1,Math.ceil(A.width/A.height*(E*c)/l))):(u=Math.ceil(A.width/l),E=Math.ceil(A.height/c));let C=A.width,p=A.height;if((t.columns!==void 0||t.rows!==void 0)&&(C=Math.round(u*l),p=Math.round(E*c)),C*p>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");let B=this._coreTerminal._core.buffer,Y=B.x,q=B.y,z=B.ybase,At=t.zIndex!==void 0&&t.zIndex<0?"bottom":"top";if(C!==A.width||p!==A.height){let T=await createImageBitmap(A,{resizeWidth:C,resizeHeight:p});A.close(),A=T}let Ie=Math.min(Math.max(0,t.xOffset??0),l-1),le=Math.min(Math.max(0,t.yOffset??0),c-1);if(Ie!==0||le!==0){let T=t.columns!==void 0?Math.round(u*l):A.width+Ie,st=t.rows!==void 0?Math.round(E*c):A.height+le,W=D.createCanvas(window.document,T,st),ke=W.getContext("2d");if(!ke)throw new Error("Failed to create offset canvas context");ke.drawImage(A,Ie,le);let nt=await createImageBitmap(W);if(W.width=W.height=0,A.close(),A=nt,C=A.width,p=A.height,C*p>this._opts.pixelLimit)throw new Error("image exceeds pixel limit");t.columns===void 0&&(u=Math.ceil(A.width/l)),t.rows===void 0&&(E=Math.ceil(A.height/c))}if(i!==this._generation)throw new Error("image decode canceled");let rt=t.zIndex??0;if(this._kittyStorage.addImage(e.id,A,!0,At,rt),A=void 0,t.cursorMovement===1){let T=B.ybase-z;B.x=Y,B.y=Math.max(q-T,0)}else B.x=Math.min(Y+u,this._coreTerminal.cols)}catch(s){throw A?.close(),s}}async _createBitmap(e){let t=new Uint8Array(await e.data.arrayBuffer());if(e.compression==="z"&&(t=await this._decompressZlib(t)),e.format===100){let E=te(t);if(E.mime!=="image/png"||!(E.width>0)||!(E.height>0)||E.width*E.height>this._opts.pixelLimit)throw new RangeError("PNG exceeds pixel limit or has invalid dimensions");let C=new Blob([t],{type:"image/png"});if(!window.createImageBitmap){let p=URL.createObjectURL(C),B=new Image;return new Promise((Y,q)=>{B.addEventListener("load",()=>{URL.revokeObjectURL(p);let z=D.createCanvas(window.document,B.width,B.height);z.getContext("2d")?.drawImage(B,0,0),createImageBitmap(z).then(Y).catch(q)}),B.addEventListener("error",()=>{URL.revokeObjectURL(p),q(new Error("Failed to load image"))}),B.src=p})}return createImageBitmap(C)}let i=e.width,A=e.height;if(!i||!A)throw new Error("Width and height required for raw pixel data");let s=e.format===32?4:3,n=i*A*s;if(t.length>>24|p<<8,d[l++]=4278190080|p>>>16|B<<16,d[l++]=4278190080|B>>>8}let c=g*3,u=g*4;for(let E=g;E=e.length){g.close();return}let I=Math.min(A+4096,e.length);g.enqueue(new Uint8Array(e.subarray(A,I))),A=I}}).pipeThrough(new DecompressionStream(t)).getReader(),a=[],o=0;try{for(;;){let{done:g,value:I}=await n.read();if(g)break;if(o+=I.byteLength,o>i)throw await n.cancel().catch(()=>{}),new RangeError("decompressed image exceeds byte limit");a.push(I)}}finally{n.releaseLock()}let h=new Uint8Array(o),d=0;for(let g of a)h.set(g,d),d+=g.length;return h}get images(){return this._kittyStorage.images}get _kittyIdToStorageId(){return this._kittyStorage.kittyIdToStorageId}get pendingTransmissions(){return this._pendingTransmissions}};var U=class U{constructor(e){this._storage=e;this._nextImageId=1;this._images=new Map;this._kittyIdToStorageId=new Map;this._storageIdToKittyId=new Map;this._handleStorageImageDeleted=e=>{let t=this._storageIdToKittyId.get(e);t!==void 0&&(this._kittyIdToStorageId.delete(t),this._storageIdToKittyId.delete(e),this._images.delete(t))};this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"iip"};this._previousOnImageDeleted=this._storage.onImageDeleted,this._wrappedOnImageDeleted=t=>{this._previousOnImageDeleted?.(t),this._handleStorageImageDeleted(t)},this._storage.onImageDeleted=this._wrappedOnImageDeleted}reset(){this._nextImageId=1,this._images.clear(),this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}dispose(){this.reset(),this._storage.onImageDeleted===this._wrappedOnImageDeleted&&(this._storage.onImageDeleted=this._previousOnImageDeleted)}storeImage(e,t){let i=e??this._nextImageId++,A=this._kittyIdToStorageId.get(i);A!==void 0&&(this._storage.deleteImage(A),this._kittyIdToStorageId.delete(i),this._storageIdToKittyId.delete(A)),!this._images.has(i)&&this._images.size>=U._maxStoredImages&&this._evictUndisplayedImages();let s=this._storage.getLimit()*1e6;this._images.delete(i);let n=0;for(let a of this._images.values())n+=a.data.size;for(let a of[!1,!0])for(let[o,h]of this._images){if(n+t.data.size<=s)break;this._kittyIdToStorageId.has(o)===a&&(n-=h.data.size,this.deleteById(o))}return this._images.set(i,{...t,id:i}),i}addImage(e,t,i,A,s){let n=this._kittyIdToStorageId.get(e);n!==void 0&&this._storageIdToKittyId.delete(n),this._addImageOpts.scrolling=i,this._addImageOpts.layer=A,this._addImageOpts.zIndex=s;let a=this._storage.addImage(t,this._addImageOpts);this._kittyIdToStorageId.set(e,a),this._storageIdToKittyId.set(a,e)}getImage(e){return this._images.get(e)}deleteById(e){this._images.delete(e);let t=this._kittyIdToStorageId.get(e);t!==void 0&&(this._storage.deleteImage(t),this._kittyIdToStorageId.delete(e),this._storageIdToKittyId.delete(t))}deleteAll(){this._images.clear();for(let e of this._kittyIdToStorageId.values())this._storage.deleteImage(e);this._kittyIdToStorageId.clear(),this._storageIdToKittyId.clear()}get images(){return this._images}get kittyIdToStorageId(){return this._kittyIdToStorageId}get lastImageId(){return this._nextImageId-1}_evictUndisplayedImages(){for(let[e]of this._images){if(this._images.size<=U._maxStoredImages/2)break;this._kittyIdToStorageId.has(e)||this._images.delete(e)}}};U._maxStoredImages=256;var re=U;var y=x(j());var he=x(je()),Ve=x(xe());var Nt=4194304,K=y.PALETTE_ANSI_256;K.set(y.PALETTE_VT340_COLOR);var Ht=2,Re=new Map,ve=!1;function Ft(r){ve||(ve=!0,(0,he.DecoderAsync)({memoryLimit:r,palette:K}).then(e=>$e(e,r),()=>{ve=!1}))}function Gt(r){return Re.get(r)?.pop()??new he.Decoder({memoryLimit:r,palette:K})}function $e(r,e){r.memoryUsage>Nt&&r.release();let t=Re.get(e)??[];t.lengththis._opts.sixelSizeLimit){console.warn("SIXEL: too much data, aborting"),this._aborted=!0,this._dec.release();return}try{this._dec.decode(e,t,i)}catch(A){console.warn(`SIXEL: error while decoding image - ${A}`),this._aborted=!0,this._dec.release()}}}unhook(e){try{return this._unhook(e)}finally{this._returnDecoder()}}_unhook(e){if(this._aborted||!e||!this._dec)return!0;let t=this._dec.width,i=this._dec.height;if(!t||!i)return i&&this._storage.advanceCursor(i),!0;let A=D.createCanvas(void 0,t,i);return A.getContext("2d")?.putImageData(new ImageData(this._dec.data8,t,i),0,0),this._storage.addImage(A),!0}};function Ut(r,e){let t=0;if(!e)return t;if(r.isInverse())if(r.isFgDefault())t=ae(e.foreground.rgba);else if(r.isFgRGB()){let i=r.constructor.toColorRGB(r.getFgColor());t=(0,y.toRGBA8888)(...i)}else t=ae(e.ansi[r.getFgColor()].rgba);else if(r.isBgDefault())t=ae(e.background.rgba);else if(r.isBgRGB()){let i=r.constructor.toColorRGB(r.getBgColor());t=(0,y.toRGBA8888)(...i)}else t=ae(e.ansi[r.getBgColor()].rgba);return t}function ae(r){return y.BIG_ENDIAN?r:(r&255)<<24|(r>>>8&255)<<16|(r>>>16&255)<<8|r>>>24&255}var de=class{constructor(e,t,i,A){this._storage=e;this._opts=t;this._renderer=i;this._terminal=A;this._addImageOpts={scrolling:!0,layer:"top",zIndex:0,cursorPos:"vt340"}}addImage(e){this._addImageOpts.scrolling=this._opts.sixelScrolling,this._storage.addImage(e,this._addImageOpts)}advanceCursor(e){if(this._opts.sixelScrolling){let t=this._renderer.cellSize;(t.width===-1||t.height===-1)&&(t=w);let i=Math.ceil(e/t.height);for(let A=1;Athis._onImageAdded.fire(),this._opts.enableSizeReports){let t=e.options.windowOptions??{};t.getWinSizePixels=!0,t.getCellSizePixels=!0,t.getWinSizeChars=!0,e.options.windowOptions=t}if(this._disposeLater(this._renderer,this._storage,e.parser.registerCsiHandler({prefix:"?",final:"h"},t=>this._decset(t)),e.parser.registerCsiHandler({prefix:"?",final:"l"},t=>this._decrst(t)),e.parser.registerCsiHandler({final:"c"},t=>this._da1(t)),e.parser.registerCsiHandler({prefix:"?",final:"S"},t=>this._xtermGraphicsAttributes(t)),e.onRender(t=>this._storage?.render(t)),e.parser.registerCsiHandler({intermediates:"!",final:"p"},()=>this.reset()),e.parser.registerEscHandler({final:"c"},()=>this.reset()),e._core._inputHandler.onRequestReset(()=>this.reset()),e.buffer.onBufferChange(()=>this._storage?.wipeAlternate()),e.onResize(t=>this._storage?.viewportResize(t))),this._opts.sixelSupport){let t=new de(this._storage,this._opts,this._renderer,e),i=new oe(this._opts,t,e);this._handlers.set("sixel",i),this._disposeLater(e._core._inputHandler._parser.registerDcsHandler({final:"q"},i))}if(this._opts.iipSupport){let t=new ge(this._storage),i=new ie(this._opts,this._renderer,t,e);this._handlers.set("iip",i),this._disposeLater(e._core._inputHandler._parser.registerOscHandler(1337,i))}if(this._opts.kittySupport){let t=new re(this._storage),i=new Ae(this._opts,this._renderer,t,e);this._handlers.set("kitty",i),this._disposeLater(t,i,e._core._inputHandler._parser.registerApcHandler({final:"G"},i))}}reset(){this._opts.sixelScrolling=this._defaultOpts.sixelScrolling,this._opts.sixelPaletteLimit=this._defaultOpts.sixelPaletteLimit,this._storage?.reset();for(let e of this._handlers.values())e.reset();return!1}get storageLimit(){return this._storage?.getLimit()||-1}set storageLimit(e){this._storage?.setLimit(e),this._opts.storageLimit=e}get storageUsage(){return this._storage?this._storage.getUsage():-1}get showPlaceholder(){return this._opts.showPlaceholder}set showPlaceholder(e){this._opts.showPlaceholder=e,this._renderer?.showPlaceholder(e)}getImageAtBufferCell(e,t){return this._storage?.getImageAtBufferCell(e,t)}extractTileAtBufferCell(e,t){return this._storage?.extractTileAtBufferCell(e,t)}_report(e){this._terminal?._core.input(e,!1)}_decset(e){for(let t=0;t2&&!(e[2]instanceof Array)&&e[2]<=tt?(this._opts.sixelPaletteLimit=e[2],this._report(`\x1B[?${e[0]};0;${this._opts.sixelPaletteLimit}S`)):this._report(`\x1B[?${e[0]};2S`),!0;case 4:return this._report(`\x1B[?${e[0]};0;${tt}S`),!0;default:return this._report(`\x1B[?${e[0]};2S`),!0}if(e[0]===2)switch(e[1]){case 1:let t=this._renderer?.dimensions?.css.canvas.width,i=this._renderer?.dimensions?.css.canvas.height;if(!t||!i){let s=w;t=(this._terminal?.cols||80)*s.width,i=(this._terminal?.rows||24)*s.height}if(t*i {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(s);\n if (typeof Buffer !== 'undefined')\n return Buffer.from(s, 'base64');\n const b = atob(s);\n const r = new Uint8Array(b.length);\n for (let i = 0; i < r.length; ++i)\n r[i] = b.charCodeAt(i);\n return r;\n};\nfunction InWasm(def) {\n if (def.d) {\n const { t, s, d } = def;\n let b;\n let m;\n const W = WebAssembly;\n if (t === 0 /* OutputType.INSTANCE */) {\n if (s)\n return (e) => new W.Instance(m || (m = new W.Module(b || (b = z(d)))), e);\n return (e) => m\n ? W.instantiate(m, e)\n : W.instantiate(b || (b = z(d)), e).then(r => (m = r.module) && r.instance);\n }\n if (t === 1 /* OutputType.MODULE */) {\n if (s)\n return () => m || (m = new W.Module(b || (b = z(d))));\n return () => m\n ? Promise.resolve(m)\n : W.compile(b || (b = z(d))).then(r => m = r);\n }\n if (s)\n return () => b || (b = z(d));\n return () => Promise.resolve(b || (b = z(d)));\n }\n if (typeof _wasmCtx === 'undefined')\n throw new Error('must run \"inwasm\"');\n _wasmCtx.add(def);\n}\n//# sourceMappingURL=index.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023, 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\n/**\n * wasm base64 decoder.\n */\nconst wasmDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#828e69684093b2c6:rdef-start:\"decode\"*/{s:1,t:0,d:'AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML'}/*inwasm#828e69684093b2c6:rdef-end:\"decode\"*/);\n// SIMD version (speedup ~1.4x, not covered by tests yet)\n/*\nconst wasmDecode = InWasm({\n name: 'decode',\n type: OutputType.INSTANCE,\n mode: OutputMode.SYNC,\n srctype: 'Clang-C',\n imports: {\n env: { memory: new WebAssembly.Memory({ initial: 1 }) }\n },\n exports: {\n dec: () => 0,\n end: () => 0\n },\n compile: {\n switches: ['-msimd128', '-Wl,-z,stack-size=0', '-Wl,--stack-first']\n },\n code: `\n #include \n typedef struct {\n unsigned int wp;\n unsigned int sp;\n unsigned int dp;\n unsigned int e_size;\n unsigned int dummy[4];\n unsigned char data[0];\n } State;\n\n unsigned int *D0 = (unsigned int *) ${P32.D0 * 4};\n unsigned int *D1 = (unsigned int *) ${P32.D1 * 4};\n unsigned int *D2 = (unsigned int *) ${P32.D2 * 4};\n unsigned int *D3 = (unsigned int *) ${P32.D3 * 4};\n State *state = (State *) ${P32.STATE * 4};\n\n #define packed_byte(x) wasm_i8x16_splat((char) x)\n #define packed_dword(x) wasm_i32x4_splat(x)\n #define masked(x, mask) wasm_v128_and(x, wasm_i32x4_splat(mask))\n\n __attribute__((noinline)) int dec() {\n unsigned int nsp = (state->wp - 1) & ~3;\n unsigned char *src = state->data + state->sp;\n unsigned char *end = state->data + nsp;\n unsigned char *dst = state->data + state->dp;\n unsigned int error = 0;\n\n v128_t err = wasm_i8x16_splat(0);\n unsigned char *end16 = state->data + (nsp & ~15);\n while (src < end16) {\n v128_t data = wasm_v128_load((v128_t *) src);\n\n // wasm-simd rewrite of http://0x80.pl/notesen/2016-01-17-sse-base64-decoding.html#vector-lookup-pshufb\n const v128_t higher_nibble = wasm_u32x4_shr(data, 4) & packed_byte(0x0f);\n const char linv = 1;\n const char hinv = 0;\n\n const v128_t lower_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n linv, linv, 0x2b, 0x30,\n 0x41, 0x50, 0x61, 0x70,\n linv, linv, linv, linv,\n linv, linv, linv, linv\n );\n const v128_t upper_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n hinv, hinv, 0x2b, 0x39,\n 0x4f, 0x5a, 0x6f, 0x7a,\n hinv, hinv, hinv, hinv,\n hinv, hinv, hinv, hinv\n );\n // the difference between the shift and lower bound\n const v128_t shift_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n 0x00, 0x00, 0x3e - 0x2b, 0x34 - 0x30,\n 0x00 - 0x41, 0x0f - 0x50, 0x1a - 0x61, 0x29 - 0x70,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00\n );\n\n const v128_t upper_bound = wasm_i8x16_swizzle(upper_bound_LUT, higher_nibble);\n const v128_t lower_bound = wasm_i8x16_swizzle(lower_bound_LUT, higher_nibble);\n\n const v128_t below = wasm_i8x16_lt(data, lower_bound);\n const v128_t above = wasm_i8x16_gt(data, upper_bound);\n const v128_t eq_2f = wasm_i8x16_eq(data, packed_byte(0x2f));\n\n // in_range = not (below or above) or eq_2f\n // outside = not in_range = below or above and not eq_2f (from deMorgan law)\n const v128_t outside = wasm_v128_andnot(eq_2f, above | below);\n err = wasm_v128_or(err, outside);\n\n const v128_t shift = wasm_i8x16_swizzle(shift_LUT, higher_nibble);\n const v128_t t0 = wasm_i8x16_add(data, shift);\n v128_t v = wasm_i8x16_add(t0, wasm_v128_and(eq_2f, packed_byte(-3)));\n\n // pack bytes\n const v128_t ca = masked(v, 0x003f003f);\n const v128_t db = masked(v, 0x3f003f00);\n const v128_t t00 = wasm_v128_or(wasm_u32x4_shr(db, 8), wasm_i32x4_shl(ca, 6));\n v128_t res = wasm_v128_or(wasm_u32x4_shr(t00, 16), wasm_i32x4_shl(t00, 12));\n res = wasm_i8x16_swizzle(res, wasm_i8x16_const(2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, 16, 16, 16, 16));\n\n wasm_v128_store((v128_t *) dst, res);\n dst += 12;\n src += 16;\n }\n //if (wasm_i8x16_bitmask(err) != 0) return -1;\n if (wasm_v128_any_true(err)) return -1;\n\n // operate on 4-byte blocks\n while (src < end) {\n error |= *((unsigned int *) dst) = D0[src[0]] | D1[src[1]] | D2[src[2]] | D3[src[3]];\n dst += 3;\n src += 4;\n }\n if (error >> 24) return -1;\n state->sp = nsp;\n state->dp = dst - state->data;\n return 0;\n }\n\n int end() {\n int rem = state->wp - state->sp;\n if (rem > 4 && dec()) return -1;\n rem = state->wp - state->sp;\n if (rem < 2) return -1;\n\n unsigned char *src = state->data + state->sp;\n if (rem == 4) {\n if (src[3] == 61) rem--;\n if (src[2] == 61) rem--;\n }\n unsigned int accu = D0[src[0]] | D1[src[1]];\n int dp = 1;\n if (rem > 2) {\n accu |= D2[src[2]];\n dp++;\n if (rem == 4) {\n accu |= D3[src[3]];\n dp++;\n }\n }\n if (accu >> 24) return -1;\n *((unsigned int *) (state->data + state->dp)) = accu;\n state->dp += dp;\n return 0;\n }\n `\n});\n*/\n// base64 map\nconst MAP = new Uint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n .split('')\n .map(el => el.charCodeAt(0)));\n// init decoder maps in LE order\nconst D = new Uint32Array(1024);\nD.fill(0xFF000000);\nfor (let i = 0; i < MAP.length; ++i)\n D[MAP[i]] = i << 2;\nfor (let i = 0; i < MAP.length; ++i)\n D[256 + MAP[i]] = i >> 4 | ((i << 4) & 0xFF) << 8;\nfor (let i = 0; i < MAP.length; ++i)\n D[512 + MAP[i]] = (i >> 2) << 8 | ((i << 6) & 0xFF) << 16;\nfor (let i = 0; i < MAP.length; ++i)\n D[768 + MAP[i]] = i << 16;\nconst EMPTY = new Uint8Array(0);\n/**\n * base64 stream decoder.\n *\n * Features / assumptions:\n * - lazy chunkwise decoding\n * - errors out on any non base64 chars (no support for NL formatted base64)\n * - decodes in wasm\n * - inplace decoding to save memory\n * - supports a keepSize for lazy memory release\n */\nclass Base64Decoder {\n /**\n * @param keepSize Keep the wasm instance below this limit when calling `release()`.\n * @param maxBytes Max allowed bytes to allocate.\n * @param initialBytes Initial bytes to allocate.\n */\n constructor(keepSize, maxBytes, initialBytes) {\n this._inst = null;\n this._ended = true;\n this._bytes = 0;\n this.keepSize = keepSize !== null && keepSize !== void 0 ? keepSize : 1048576 /* Bytes.KEEP */;\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : 4294901760 /* Bytes.MAX */;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : 32768 /* Bytes.INITIAL */;\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw new Error('invalid byte settings');\n }\n }\n /**\n * Currently decoded bytes (borrowed).\n * Must be accessed before calling `release` or `init`.\n */\n get data8() {\n return this._inst ? this._d.subarray(0, this._m32[1282 /* P32.STATE_DP */]) : EMPTY;\n }\n /**\n * Release memory conditionally based on `keepSize`.\n * If memory gets released, also the wasm instance will be freed and recreated on next `init`,\n * otherwise the instance will be reused.\n */\n release() {\n if (!this._inst)\n return;\n if (this._bytes > this.keepSize) {\n this._inst = this._m32 = this._d = this._mem = null;\n }\n else {\n this._m32[1280 /* P32.STATE_WP */] = 0;\n this._m32[1281 /* P32.STATE_SP */] = 0;\n this._m32[1282 /* P32.STATE_DP */] = 0;\n }\n }\n /**\n * Initializes the decoder for new base64 data.\n * Must be called before doing any decoding attempts.\n * The method will either spawn a new wasm instance or grow\n * the needed memory of an existing instance.\n * @param maxBytes Max allowed bytes to allocate (overwrites ctor value).\n * @param initialBytes Initial bytes to allocate (overwrites ctor value).\n */\n init(maxBytes, initialBytes) {\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : this.maxBytes;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : Math.min(this._bytes, this.maxBytes);\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw Error('invalid byte settings');\n }\n let m = this._m32;\n const bytes = this._bytes + 5152 /* Bytes._DATA_OFFSET */;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmDecode({ env: { memory: this._mem } });\n m = new Uint32Array(this._mem.buffer, 0);\n m.set(D, 256 /* P32.D0 */);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n m = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n m[1280 /* P32.STATE_WP */] = 0;\n m[1281 /* P32.STATE_SP */] = 0;\n m[1282 /* P32.STATE_DP */] = 0;\n this._m32 = m;\n this._ended = false;\n }\n /**\n * Realloc memory. Realloc only happens, if the requested\n * size doesn't fit in the current memory.\n * The new size will be capped by `maxBytes`.\n * @param requested Bytes to be stored.\n */\n _realloc(requested) {\n const needed = this._m32[1280 /* P32.STATE_WP */] + requested;\n if (this._bytes < needed) {\n if (needed > this.maxBytes) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n let newSize = this._bytes;\n while ((newSize *= 2) < needed) { }\n newSize = Math.min(newSize, this.maxBytes);\n if (newSize < needed) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n if (newSize + 5152 /* Bytes._DATA_OFFSET */ > this._mem.buffer.byteLength) {\n const addPages = Math.ceil((newSize + 5152 /* Bytes._DATA_OFFSET */ - this._mem.buffer.byteLength) / 65536);\n this._mem.grow(addPages);\n this._m32 = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n this._bytes = newSize;\n }\n return 0 /* DecodeStatus.OK */;\n }\n /**\n * Put bytes in `data` into the decoder.\n * Additionally decodes the payload, if it reached 2^17 bytes.\n * The return value indicates the type of issue.\n * @param data Bytes to be loaded.\n */\n put(data) {\n if (!this._inst || this._ended) {\n return -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n if (this._realloc(data.length)) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n const m = this._m32;\n this._d.set(data, m[1280 /* P32.STATE_WP */]);\n m[1280 /* P32.STATE_WP */] += data.length;\n // max chunk in input handler is 2^17, try to run in \"tandem mode\"\n return m[1280 /* P32.STATE_WP */] - m[1281 /* P32.STATE_SP */] >= 131072\n ? this._inst.exports.dec()\n : 0 /* DecodeStatus.OK */;\n }\n /**\n * End the current decoding.\n * Also decodes leftover payload from previous put calls.\n */\n end() {\n this._ended = true;\n return this._inst\n ? this._inst.exports.end()\n : -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n /**\n * Bytes loaded into the decoder.\n */\n get loadedBytes() {\n return this._inst\n ? this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n /**\n * Free bytes to feed to the decoder.\n */\n get freeBytes() {\n return this._inst\n ? this.maxBytes - this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n}\nexports.default = Base64Decoder;\n//# sourceMappingURL=Base64Decoder.wasm.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\nconst wasmQoiDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#459f9e1bfb80b1a8:rdef-start:\"qoi_decode\"*/{s:1,t:0,d:'AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=='}/*inwasm#459f9e1bfb80b1a8:rdef-end:\"qoi_decode\"*/);\nclass QoiDecoder {\n constructor(keepSize) {\n this.keepSize = keepSize;\n this.width = 0;\n this.height = 0;\n }\n decode(d) {\n this.width = d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7];\n this.height = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];\n const pixels = this.width * this.height;\n const ib = pixels * 4;\n const dl = d.length;\n /**\n * byte/offset calculation:\n * To save some memory we dont reserve full memory for decoded + encoded,\n * but place encoded at the end of decoded plus 50% security distance\n * to avoid reads before writes positions:\n *\n * encoded < decoded (good compression)\n * enc ####################\n * dec #######################################\n * ^ ^\n * DST_P CHUNK_P\n *\n * encoded > decoded (degenerated compression, should not happen)\n * enc ##############################\n * dec ####################\n * ^ ^\n * DST_P CHUNK_P\n *\n * There is still a chance for overlapping r/w positions in case the compressed\n * data has very different pixel progression, yet the 50% security distance\n * should deal with that, as QOI will bloat data by 25% at max (RGB -> OP byte + RGB).\n * Since we always assume RGBA at decoding stage, the possible bloat reduces to 20% at max.\n */\n const bytes = Math.max(ib, dl) + (Math.min(ib, dl) >> 1) + 4096;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmQoiDecode({ env: { memory: this._mem } });\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n this._d = null;\n }\n if (!this._d) {\n this._d = new Uint8Array(this._mem.buffer);\n }\n // put src data at the end of memory, also align to 256\n const chunkP = (this._mem.buffer.byteLength - dl) & ~0xFF;\n this._d.set(d, chunkP);\n this._inst.exports.dec(chunkP, dl, pixels);\n return this._d.subarray(1024 /* P8.DST_P */, 1024 /* P8.DST_P */ + ib);\n }\n release() {\n if (!this._inst)\n return;\n if (this._mem.buffer.byteLength > this.keepSize) {\n this._inst = this._d = this._mem = null;\n }\n }\n}\nexports.default = QoiDecoder;\n//# sourceMappingURL=QoiDecoder.wasm.js.map", null, null, "/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal lifecycle utilities for xterm.js core.\n * Simplified from VS Code's lifecycle.ts - no tracking/leak detection.\n */\n\nexport interface IDisposable {\n dispose(): void;\n}\n\nexport function toDisposable(fn: () => void): IDisposable {\n return { dispose: fn };\n}\n\nexport function dispose(disposable: T): T;\nexport function dispose(disposable: T | undefined): T | undefined;\nexport function dispose(disposables: T[]): T[];\nexport function dispose(arg: T | T[] | undefined): T | T[] | undefined {\n if (!arg) {\n return arg;\n }\n if (Array.isArray(arg)) {\n for (const d of arg) {\n d.dispose();\n }\n return [];\n }\n arg.dispose();\n return arg;\n}\n\nexport function combinedDisposable(...disposables: IDisposable[]): IDisposable {\n return toDisposable(() => dispose(disposables));\n}\n\nexport class DisposableStore implements IDisposable {\n private readonly _disposables = new Set();\n private _isDisposed = false;\n\n public get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n public add(o: T): T {\n if (this._isDisposed) {\n o.dispose();\n } else {\n this._disposables.add(o);\n }\n return o;\n }\n\n public dispose(): void {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n\n public clear(): void {\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n}\n\nexport abstract class Disposable implements IDisposable {\n public static readonly None: IDisposable = Object.freeze({ dispose() { } });\n\n protected readonly _store = new DisposableStore();\n\n public dispose(): void {\n this._store.dispose();\n }\n\n protected _register(o: T): T {\n return this._store.add(o);\n }\n}\n\nexport class MutableDisposable implements IDisposable {\n private _value: T | undefined;\n private _isDisposed = false;\n\n public get value(): T | undefined {\n return this._isDisposed ? undefined : this._value;\n }\n\n public set value(value: T | undefined) {\n if (this._isDisposed || value === this._value) {\n return;\n }\n this._value?.dispose();\n this._value = value;\n }\n\n public clear(): void {\n this.value = undefined;\n }\n\n public dispose(): void {\n this._isDisposed = true;\n this._value?.dispose();\n this._value = undefined;\n }\n}\n", "/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal event utilities for xterm.js core.\n * Simplified from VS Code's event.ts - no leak detection/profiling.\n */\n\nimport { IDisposable, DisposableStore, toDisposable } from './Lifecycle';\n\nexport interface IEvent {\n (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable;\n}\n\nexport class Emitter {\n private _listeners: { fn: (e: T) => any, thisArgs: any }[] = [];\n private _disposed = false;\n private _event: IEvent | undefined;\n\n public get event(): IEvent {\n if (this._event) {\n return this._event;\n }\n this._event = (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n if (this._disposed) {\n return toDisposable(() => {});\n }\n\n const entry = { fn: listener, thisArgs };\n this._listeners = this._listeners.slice();\n this._listeners.push(entry);\n\n const result = toDisposable(() => {\n const idx = this._listeners.indexOf(entry);\n if (idx !== -1) {\n this._listeners = this._listeners.slice();\n this._listeners.splice(idx, 1);\n }\n });\n\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(result);\n } else {\n disposables.add(result);\n }\n }\n\n return result;\n };\n return this._event;\n }\n\n public fire(event: T): void {\n if (this._disposed || !this._listeners.length) {\n return;\n }\n if (this._listeners.length === 1) {\n this._listeners[0].fn.call(this._listeners[0].thisArgs, event);\n return;\n }\n const listeners = this._listeners;\n for (let i = 0, len = listeners.length; i < len; ++i) {\n listeners[i].fn.call(listeners[i].thisArgs, event);\n }\n }\n\n public dispose(): void {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._listeners.length = 0;\n }\n}\n\nexport namespace EventUtils {\n export function forward(from: IEvent, to: Emitter): IDisposable {\n return from(e => to.fire(e));\n }\n\n export function map(event: IEvent, map: (i: I) => O): IEvent {\n return (listener: (e: O) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n return event(i => listener.call(thisArgs, map(i)), undefined, disposables);\n };\n }\n\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent {\n return (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n const store = new DisposableStore();\n for (const event of events) {\n store.add(event(e => listener.call(thisArgs, e)));\n }\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(store);\n } else {\n disposables.add(store);\n }\n }\n return store;\n };\n }\n\n export function runAndSubscribe(event: IEvent, handler: (e: T) => void, initial: T): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void, initial?: T): IDisposable {\n handler(initial);\n return event(e => handler(e));\n }\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { toRGBA8888 } from 'sixel/lib/Colors';\nimport { IDisposable } from '@xterm/xterm';\nimport { ICellSize, ImageLayer, ITerminalExt, IImageSpec, IRenderDimensions, IRenderService } from './Types';\nimport { Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';\n\nconst enum Constants {\n PLACEHOLDER_LENGTH = 4096,\n PLACEHOLDER_HEIGHT = 24\n}\n\n/**\n * ImageRenderer - terminal frontend extension:\n * - provide primitives for canvas, ImageData, Bitmap (static)\n * - add canvas layer to DOM (browser only for now)\n * - draw image tiles onRender\n */\nexport class ImageRenderer extends Disposable implements IDisposable {\n /** @deprecated Kept for backward compat \u2014 points to top layer canvas. */\n public get canvas(): HTMLCanvasElement | undefined { return this._layers.get('top')?.canvas; }\n private _layers = new Map();\n private _placeholder: HTMLCanvasElement | undefined;\n private _placeholderBitmap: ImageBitmap | undefined;\n private _optionsRefresh = this._register(new MutableDisposable());\n private _oldOpen: ((parent: HTMLElement) => void) | undefined;\n private _renderService: IRenderService | undefined;\n private _oldSetRenderer: ((renderer: any) => void) | undefined;\n\n // drawing primitive - canvas\n public static createCanvas(localDocument: Document | undefined, width: number, height: number): HTMLCanvasElement {\n /**\n * NOTE: We normally dont care, from which document the canvas\n * gets created, so we can fall back to global document,\n * if the terminal has no document associated yet.\n * This way early image loads before calling .open keep working\n * (still discouraged though, as the metrics will be screwed up).\n * Only the DOM output canvas should be on the terminal's document,\n * which gets explicitly checked in `insertLayerToDom`.\n */\n const canvas = (localDocument ?? document).createElement('canvas');\n canvas.width = width | 0;\n canvas.height = height | 0;\n return canvas;\n }\n\n // drawing primitive - ImageData with optional buffer\n public static createImageData(ctx: CanvasRenderingContext2D, width: number, height: number, buffer?: ArrayBuffer): ImageData {\n if (typeof ImageData !== 'function') {\n const imgData = ctx.createImageData(width, height);\n if (buffer) {\n imgData.data.set(new Uint8ClampedArray(buffer, 0, width * height * 4));\n }\n return imgData;\n }\n return buffer\n ? new ImageData(new Uint8ClampedArray(buffer, 0, width * height * 4), width, height)\n : new ImageData(width, height);\n }\n\n // drawing primitive - ImageBitmap\n public static createImageBitmap(img: ImageBitmapSource): Promise {\n if (typeof createImageBitmap !== 'function') {\n return Promise.resolve(undefined);\n }\n return createImageBitmap(img);\n }\n\n\n constructor(private _terminal: ITerminalExt) {\n super();\n this._oldOpen = this._terminal._core.open;\n this._terminal._core.open = (parent: HTMLElement): void => {\n this._oldOpen?.call(this._terminal._core, parent);\n this._open();\n };\n if (this._terminal._core.screenElement) {\n this._open();\n }\n // hack to spot fontSize changes\n this._optionsRefresh.value = this._terminal._core.optionsService.onOptionChange(option => {\n if (option === 'fontSize') {\n this.rescaleCanvas();\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n });\n this._register(toDisposable(() => {\n this.removeLayerFromDom();\n this.removeLayerFromDom('bottom');\n if (this._terminal._core && this._oldOpen) {\n this._terminal._core.open = this._oldOpen;\n this._oldOpen = undefined;\n }\n if (this._renderService && this._oldSetRenderer) {\n this._renderService.setRenderer = this._oldSetRenderer;\n this._oldSetRenderer = undefined;\n }\n this._renderService = undefined;\n this._layers.clear();\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }));\n }\n\n /**\n * Enable the placeholder.\n */\n public showPlaceholder(value: boolean): void {\n if (value) {\n if (!this._placeholder && this.cellSize.height !== -1) {\n this._createPlaceHolder(Math.max(this.cellSize.height + 1, Constants.PLACEHOLDER_HEIGHT));\n }\n } else {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n\n /**\n * Dimensions of the terminal.\n * Forwarded from internal render service.\n */\n public get dimensions(): IRenderDimensions | undefined {\n return this._terminal.dimensions;\n }\n\n /**\n * Current cell size (float).\n */\n public get cellSize(): ICellSize {\n return {\n width: this.dimensions?.css.cell.width || -1,\n height: this.dimensions?.css.cell.height || -1\n };\n }\n\n /**\n * Clear a region of the image layer canvas.\n */\n public clearLines(start: number, end: number, layer?: ImageLayer): void {\n const y = start * (this.dimensions?.css.cell.height || 0);\n const w = this.dimensions?.css.canvas.width || 0;\n const h = (end + 1 - start) * (this.dimensions?.css.cell.height || 0);\n if (!layer || layer === 'top') {\n this._layers.get('top')?.clearRect(0, y, w, h);\n }\n if (!layer || layer === 'bottom') {\n this._layers.get('bottom')?.clearRect(0, y, w, h);\n }\n }\n\n /**\n * Clear whole image canvas.\n */\n public clearAll(layer?: ImageLayer): void {\n if (!layer || layer === 'top') {\n const ctx = this._layers.get('top');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n if (!layer || layer === 'bottom') {\n const ctx = this._layers.get('bottom');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n }\n\n /**\n * Draw neighboring tiles on the image layer canvas.\n */\n public draw(imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get(imgSpec.layer);\n if (!ctx) {\n return;\n }\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const cols = Math.ceil(img.width / width);\n\n const sx = (tileId % cols) * width;\n const sy = Math.floor(tileId / cols) * height;\n const dx = col * width;\n const dy = row * height;\n\n // safari bug: never access image source out of bounds\n const finalWidth = count * width + sx > img.width ? img.width - sx : count * width;\n const finalHeight = sy + height > img.height ? img.height - sy : height;\n\n // Floor all pixel offsets to get stable tile mapping without any overflows.\n // Note: For not pixel perfect aligned cells like in the DOM renderer\n // this will move a tile slightly to the top/left (subpixel range, thus ignore it).\n // FIX #34: avoid striping on displays with pixelDeviceRatio != 1 by ceiling height and width\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.ceil(finalWidth), Math.ceil(finalHeight),\n Math.floor(dx), Math.floor(dy), Math.ceil(finalWidth), Math.ceil(finalHeight)\n );\n }\n\n /**\n * Extract a single tile from an image.\n */\n public extractTile(imgSpec: IImageSpec, tileId: number): HTMLCanvasElement | undefined {\n const { width, height } = this.cellSize;\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const cols = Math.ceil(img.width / width);\n const sx = (tileId % cols) * width;\n const sy = Math.floor(tileId / cols) * height;\n const finalWidth = width + sx > img.width ? img.width - sx : width;\n const finalHeight = sy + height > img.height ? img.height - sy : height;\n\n const canvas = ImageRenderer.createCanvas(this.document, finalWidth, finalHeight);\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.floor(finalWidth), Math.floor(finalHeight),\n 0, 0, Math.floor(finalWidth), Math.floor(finalHeight)\n );\n return canvas;\n }\n }\n\n /**\n * Draw a line with placeholder on the image layer canvas.\n */\n public drawPlaceholder(col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get('top');\n if (ctx) {\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n if (!this._placeholder) {\n this._createPlaceHolder(Math.max(height + 1, Constants.PLACEHOLDER_HEIGHT));\n } else if (height >= this._placeholder!.height) {\n this._createPlaceHolder(height + 1);\n }\n if (!this._placeholder) return;\n ctx.drawImage(\n this._placeholderBitmap ?? this._placeholder!,\n col * width,\n (row * height) % 2 ? 0 : 1, // needs %2 offset correction\n width * count,\n height,\n col * width,\n row * height,\n width * count,\n height\n );\n }\n }\n\n /**\n * Rescale image layer canvas if needed.\n * Checked once from `ImageStorage.render`.\n */\n public rescaleCanvas(): void {\n const w = this.dimensions?.css.canvas.width || 0;\n const h = this.dimensions?.css.canvas.height || 0;\n for (const ctx of this._layers.values()) {\n if (ctx.canvas.width !== w || ctx.canvas.height !== h) {\n ctx.canvas.width = w;\n ctx.canvas.height = h;\n }\n }\n }\n\n /**\n * Rescale image in storage if needed.\n */\n private _rescaleImage(spec: IImageSpec, currentWidth: number, currentHeight: number): void {\n if (currentWidth === spec.actualCellSize.width && currentHeight === spec.actualCellSize.height) {\n return;\n }\n const { width: originalWidth, height: originalHeight } = spec.origCellSize;\n if (currentWidth === originalWidth && currentHeight === originalHeight) {\n spec.actual = spec.orig;\n spec.actualCellSize.width = originalWidth;\n spec.actualCellSize.height = originalHeight;\n return;\n }\n const canvas = ImageRenderer.createCanvas(\n this.document,\n Math.ceil(spec.orig!.width * currentWidth / originalWidth),\n Math.ceil(spec.orig!.height * currentHeight / originalHeight)\n );\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(spec.orig!, 0, 0, canvas.width, canvas.height);\n spec.actual = canvas;\n spec.actualCellSize.width = currentWidth;\n spec.actualCellSize.height = currentHeight;\n }\n }\n\n /**\n * Lazy init for the renderer.\n */\n private _open(): void {\n this._renderService = this._terminal._core._renderService;\n this._oldSetRenderer = this._renderService.setRenderer.bind(this._renderService);\n this._renderService.setRenderer = (renderer: any) => {\n for (const key of [...this._layers.keys()]) {\n this.removeLayerFromDom(key);\n }\n this._oldSetRenderer?.call(this._renderService, renderer);\n };\n }\n\n public insertLayerToDom(layer: ImageLayer = 'top'): void {\n // make sure that the terminal is attached to a document and to DOM\n if (!this.document || !this._terminal._core.screenElement) {\n console.warn('image addon: cannot insert output canvas to DOM, missing document or screenElement');\n return;\n }\n if (this._layers.has(layer)) {\n return;\n }\n const canvas = ImageRenderer.createCanvas(\n this.document, this.dimensions?.css.canvas.width || 0,\n this.dimensions?.css.canvas.height || 0\n );\n canvas.classList.add(`xterm-image-layer-${layer}`);\n const screenElement = this._terminal._core.screenElement;\n // Use isolation to create a stacking context without overriding z-index,\n // which would conflict with integrators (e.g. VS Code) that set their\n // own z-index on the screen element.\n screenElement.style.isolation = 'isolate';\n if (layer === 'bottom') {\n // Use z-index:-1 so it paints behind non-positioned text elements.\n // The screen element needs to be a stacking context (via isolation)\n // to contain the negative z-index, otherwise it would go behind the\n // entire terminal.\n canvas.style.zIndex = '-1';\n screenElement.insertBefore(canvas, screenElement.firstChild);\n } else {\n // Explicit z-index ensures the image canvas reliably stacks above\n // the text layer (DOM renderer rows). z-index: 0 is below the\n // selection overlay (z-index: 1).\n canvas.style.zIndex = '0';\n screenElement.appendChild(canvas);\n }\n const ctx = canvas.getContext('2d', { alpha: true });\n if (!ctx) {\n canvas.remove();\n return;\n }\n this._layers.set(layer, ctx);\n this.clearAll(layer);\n }\n\n public removeLayerFromDom(layer: ImageLayer = 'top'): void {\n const ctx = this._layers.get(layer);\n if (ctx) {\n ctx.canvas.remove();\n this._layers.delete(layer);\n }\n }\n\n public hasLayer(layer: ImageLayer): boolean {\n return this._layers.has(layer);\n }\n\n private _createPlaceHolder(height: number = Constants.PLACEHOLDER_HEIGHT): void {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n\n // create blueprint to fill placeholder with\n const bWidth = 32; // must be 2^n\n const blueprint = ImageRenderer.createCanvas(this.document, bWidth, height);\n const ctx = blueprint.getContext('2d', { alpha: false });\n if (!ctx) return;\n const imgData = ImageRenderer.createImageData(ctx, bWidth, height);\n const d32 = new Uint32Array(imgData.data.buffer);\n const black = toRGBA8888(0, 0, 0);\n const white = toRGBA8888(255, 255, 255);\n d32.fill(black);\n for (let y = 0; y < height; ++y) {\n const shift = y % 2;\n const offset = y * bWidth;\n for (let x = 0; x < bWidth; x += 2) {\n d32[offset + x + shift] = white;\n }\n }\n ctx.putImageData(imgData, 0, 0);\n\n // create placeholder line, width aligned to blueprint width\n const width = (screen.width + bWidth - 1) & ~(bWidth - 1) || Constants.PLACEHOLDER_LENGTH;\n this._placeholder = ImageRenderer.createCanvas(this.document, width, height);\n const ctx2 = this._placeholder.getContext('2d', { alpha: false });\n if (!ctx2) {\n this._placeholder = undefined;\n return;\n }\n for (let i = 0; i < width; i += bWidth) {\n ctx2.drawImage(blueprint, i, 0);\n }\n ImageRenderer.createImageBitmap(this._placeholder).then(bitmap => this._placeholderBitmap = bitmap);\n }\n\n public get document(): Document | undefined {\n return this._terminal._core._coreBrowserService?.window.document;\n }\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageRenderer } from './ImageRenderer';\nimport {\n ITerminalExt, IExtendedAttrsImage, IImageAddonOptions, IImageSpec,\n IBufferLineExt, BgFlags, Cell, Content, ICellSize, ExtFlags, Attributes,\n UnderlineStyle, IAddImageOpts\n} from './Types';\n\n\n// fallback default cell size\nexport const CELL_SIZE_DEFAULT: ICellSize = {\n width: 7,\n height: 14\n};\n\n/**\n * Extend extended attribute to also hold image tile information.\n *\n * Object definition is copied from base repo to fully mimick its behavior.\n * Image data is added as additional public properties `imageId` and `tileId`.\n */\nclass ExtendedAttrsImage implements IExtendedAttrsImage {\n private _ext: number = 0;\n public get ext(): number {\n if (this._urlId) {\n return (\n (this._ext & ~ExtFlags.UNDERLINE_STYLE) |\n (this.underlineStyle << 26)\n );\n }\n return this._ext;\n }\n public set ext(value: number) { this._ext = value; }\n\n public get underlineStyle(): UnderlineStyle {\n // Always return the URL style if it has one\n if (this._urlId) {\n return UnderlineStyle.DASHED;\n }\n return (this._ext & ExtFlags.UNDERLINE_STYLE) >> 26;\n }\n public set underlineStyle(value: UnderlineStyle) {\n this._ext &= ~ExtFlags.UNDERLINE_STYLE;\n this._ext |= (value << 26) & ExtFlags.UNDERLINE_STYLE;\n }\n\n public get underlineColor(): number {\n return this._ext & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n public set underlineColor(value: number) {\n this._ext &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n this._ext |= value & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n\n public get underlineVariantOffset(): number {\n const val = (this._ext & ExtFlags.VARIANT_OFFSET) >> 29;\n if (val < 0) {\n return val ^ 0xFFFFFFF8;\n }\n return val;\n }\n public set underlineVariantOffset(value: number) {\n this._ext &= ~ExtFlags.VARIANT_OFFSET;\n this._ext |= (value << 29) & ExtFlags.VARIANT_OFFSET;\n }\n\n private _urlId: number = 0;\n public get urlId(): number {\n return this._urlId;\n }\n public set urlId(value: number) {\n this._urlId = value;\n }\n\n constructor(\n ext: number = 0,\n urlId: number = 0,\n public imageId = -1,\n public tileId = -1\n ) {\n this._ext = ext;\n this._urlId = urlId;\n }\n\n public clone(): IExtendedAttrsImage {\n /**\n * Technically we dont need a clone variant of ExtendedAttrsImage,\n * as we never clone a cell holding image data.\n * Note: Clone is only meant to be used by the InputHandler for\n * sticky attributes, which is never the case for image data.\n * We still provide a proper clone method to reflect the full ext attr\n * state in case there are future use cases for clone.\n */\n return new ExtendedAttrsImage(this._ext, this._urlId, this.imageId, this.tileId);\n }\n\n public isEmpty(): boolean {\n return this.underlineStyle === UnderlineStyle.NONE && this._urlId === 0 && this.imageId === -1;\n }\n}\nconst EMPTY_ATTRS = new ExtendedAttrsImage();\n\n\n/**\n * ImageStorage - extension of CoreTerminal:\n * - hold image data\n * - write/read image data to/from buffer\n *\n * TODO: image composition for overwrites\n */\nexport class ImageStorage implements IDisposable {\n // storage\n private _images: Map = new Map();\n // last used id\n private _lastId = 0;\n // last evicted id\n private _lowestId = 0;\n // whether a full clear happened before\n private _fullyCleared = false;\n // whether render should do a full clear\n private _needsFullClear = false;\n // hard limit of stored pixels (fallback limit of 10 MB)\n private _pixelLimit: number = 2500000;\n\n private _viewportMetrics: { cols: number, rows: number };\n public onImageAdded: (() => void) | undefined;\n public onImageDeleted: ((storageId: number) => void) | undefined;\n\n constructor(\n private _terminal: ITerminalExt,\n private _renderer: ImageRenderer,\n private _opts: IImageAddonOptions\n ) {\n try {\n this.setLimit(this._opts.storageLimit);\n } catch (e: unknown) {\n if (e instanceof Error) {\n console.error(e.message);\n }\n console.warn(`storageLimit is set to ${this.getLimit()} MB`);\n }\n this._viewportMetrics = {\n cols: this._terminal.cols,\n rows: this._terminal.rows\n };\n }\n\n public dispose(): void {\n this.reset();\n }\n\n public reset(): void {\n for (const spec of this._images.values()) {\n spec.marker?.dispose();\n }\n // NOTE: marker.dispose above already calls ImageBitmap.close\n // therefore we can just wipe the map here\n this._images.clear();\n this._renderer.clearAll();\n }\n\n public getLimit(): number {\n return this._pixelLimit * 4 / 1000000;\n }\n\n public setLimit(value: number): void {\n if (value < 0.5 || value > 1000) {\n throw RangeError('invalid storageLimit, should be at least 0.5 MB and not exceed 1G');\n }\n this._pixelLimit = (value / 4 * 1000000) >>> 0;\n this._evictOldest(0);\n }\n\n public getUsage(): number {\n return this._getStoredPixels() * 4 / 1000000;\n }\n\n private _getStoredPixels(): number {\n let storedPixels = 0;\n for (const spec of this._images.values()) {\n if (spec.orig) {\n storedPixels += spec.orig.width * spec.orig.height;\n if (spec.actual && spec.actual !== spec.orig) {\n storedPixels += spec.actual.width * spec.actual.height;\n }\n }\n }\n return storedPixels;\n }\n\n private _delImg(id: number): void {\n const spec = this._images.get(id);\n if (!spec) return;\n this._images.delete(id);\n // FIXME: really ugly workaround to get bitmaps deallocated :(\n if (window.ImageBitmap && spec.orig instanceof ImageBitmap) {\n spec.orig.close();\n }\n this.onImageDeleted?.(id);\n }\n\n /**\n * Wipe canvas and images on alternate buffer.\n */\n public wipeAlternate(): void {\n // remove all alternate tagged images\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate') {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n // mark canvas to be wiped on next render\n this._needsFullClear = true;\n this._fullyCleared = false;\n }\n\n /**\n * Delete an image by its internal storage ID.\n * Used by protocols that support explicit deletion (e.g. Kitty a=d).\n */\n public deleteImage(id: number): void {\n const spec = this._images.get(id);\n if (spec) {\n spec.marker?.dispose();\n this._delImg(id);\n }\n }\n\n /**\n * Method to add an image to the storage.\n * @param img - The image to add (canvas or bitmap).\n * @param opts - Options for addImage:\n * - scrolling: When true, cursor advances with the image.\n * When false, image is placed at ORIGIN and cursor does not move.\n * - layer: Which canvas layer to render on ('top' or 'bottom').\n * - zIndex: Z-index for image layering within the same layer.\n * - cursorPos: 'vt340' for bottom-left, 'iip' for bottom.right.\n * @returns The internal image ID assigned to the stored image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap, opts: IAddImageOpts): number {\n // never allow storage to exceed memory limit\n this._evictOldest(img.width * img.height);\n\n // calc rows x cols needed to display the image\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const cols = Math.ceil(img.width / cellSize.width);\n const rows = Math.ceil(img.height / cellSize.height);\n\n const imageId = ++this._lastId;\n\n const buffer = this._terminal._core.buffer;\n const termCols = this._terminal.cols;\n const termRows = this._terminal.rows;\n const originX = buffer.x;\n const originY = buffer.y;\n let offset = originX;\n let tileCount = 0;\n\n if (!opts.scrolling) {\n buffer.x = 0;\n buffer.y = 0;\n offset = 0;\n }\n\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(buffer.y + buffer.ybase);\n for (let col = 0; col < cols; ++col) {\n if (offset + col >= termCols) break;\n this._writeToCell(line as IBufferLineExt, offset + col, imageId, row * cols + col);\n tileCount++;\n }\n if (opts.scrolling) {\n if (row < rows - 1) this._terminal._core._inputHandler.lineFeed();\n } else {\n if (++buffer.y >= termRows) break;\n }\n buffer.x = offset;\n }\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n\n // cursor positioning modes\n if (opts.scrolling) {\n if (opts.cursorPos === 'iip') {\n buffer.x = Math.min(offset + cols, termCols);\n } else {\n buffer.x = offset;\n }\n } else {\n buffer.x = originX;\n buffer.y = originY;\n }\n\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.tileCount < 1) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n\n // eviction marker:\n // delete the image when the marker gets disposed\n const endMarker = this._terminal.registerMarker(0);\n endMarker?.onDispose(() => {\n const spec = this._images.get(imageId);\n if (spec) {\n this._delImg(imageId);\n }\n });\n\n // since markers do not work on alternate for some reason,\n // we evict images here manually\n if (this._terminal.buffer.active.type === 'alternate') {\n this._evictOnAlternate();\n }\n\n // create storage entry\n const imgSpec: IImageSpec = {\n orig: img,\n origCellSize: cellSize,\n actual: img,\n actualCellSize: { ...cellSize }, // clone needed, since later modified\n marker: endMarker || undefined,\n tileCount,\n bufferType: this._terminal.buffer.active.type,\n layer: opts.layer,\n zIndex: opts.zIndex\n };\n\n // finally add the image\n this._images.set(imageId, imgSpec);\n this.onImageAdded?.();\n return imageId;\n }\n\n\n /**\n * Render method. Collects buffer information and triggers\n * canvas updates.\n */\n // TODO: Should we move this to the ImageRenderer?\n public render(range: { start: number, end: number }): void {\n // Determine which layers have images\n let hasTopImages = false;\n let hasBottomImages = false;\n for (const spec of this._images.values()) {\n if (spec.layer === 'bottom') {\n hasBottomImages = true;\n } else {\n hasTopImages = true;\n }\n if (hasTopImages && hasBottomImages) break;\n }\n\n // Lazily insert layers that are needed\n if (hasTopImages && !this._renderer.hasLayer('top')) {\n this._renderer.insertLayerToDom('top');\n if (!this._renderer.hasLayer('top')) return;\n }\n if (hasBottomImages && !this._renderer.hasLayer('bottom')) {\n this._renderer.insertLayerToDom('bottom');\n }\n\n // rescale if needed\n this._renderer.rescaleCanvas();\n\n // exit early if we dont have any images to test for\n if (!this._images.size) {\n if (!this._fullyCleared) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n if (this._renderer.hasLayer('top')) {\n this._renderer.removeLayerFromDom('top');\n }\n if (this._renderer.hasLayer('bottom')) {\n this._renderer.removeLayerFromDom('bottom');\n }\n return;\n }\n\n // Remove layers no longer needed\n if (!hasTopImages && this._renderer.hasLayer('top')) {\n this._renderer.clearAll('top');\n this._renderer.removeLayerFromDom('top');\n }\n if (!hasBottomImages && this._renderer.hasLayer('bottom')) {\n this._renderer.clearAll('bottom');\n this._renderer.removeLayerFromDom('bottom');\n }\n\n // buffer switches force a full clear\n if (this._needsFullClear) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n\n const { start, end } = range;\n const buffer = this._terminal._core.buffer;\n const cols = this._terminal._core.cols;\n\n // clear drawing area\n this._renderer.clearLines(start, end);\n\n // Collect draw calls so we can sort by z-index (lower z drawn first).\n const drawCalls: { imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number }[] = [];\n const placeholderCalls: { col: number, row: number, count: number }[] = [];\n\n // walk all cells in viewport and collect tiles found\n for (let row = start; row <= end; ++row) {\n const line = buffer.lines.get(row + buffer.ydisp) as IBufferLineExt;\n if (!line) return;\n for (let col = 0; col < cols; ++col) {\n if (line.getBg(col) & BgFlags.HAS_EXTENDED) {\n let e: IExtendedAttrsImage = line._extendedAttrs[col] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (e.tileId !== -1) {\n const startTile = e.tileId;\n const startCol = col;\n let count = 1;\n /**\n * merge tiles to the right into a single draw call, if:\n * - not at end of line\n * - cell has same image id\n * - cell has consecutive tile id\n */\n while (\n ++col < cols\n && (line.getBg(col) & BgFlags.HAS_EXTENDED)\n && (e = line._extendedAttrs[col] ?? EMPTY_ATTRS)\n && (e.imageId === imageId)\n && (e.tileId === startTile + count)\n ) {\n count++;\n }\n col--;\n if (imgSpec) {\n if (imgSpec.actual) {\n drawCalls.push({ imgSpec, tileId: startTile, col: startCol, row, count });\n }\n } else if (this._opts.showPlaceholder) {\n placeholderCalls.push({ col: startCol, row, count });\n }\n this._fullyCleared = false;\n }\n }\n }\n }\n\n // Sort by z-index so lower z draws first (higher z renders on top)\n drawCalls.sort((a, b) => a.imgSpec.zIndex - b.imgSpec.zIndex);\n\n // Draw placeholders first (lowest priority)\n for (const call of placeholderCalls) {\n this._renderer.drawPlaceholder(call.col, call.row, call.count);\n }\n\n // Draw images in z-index order\n for (const call of drawCalls) {\n this._renderer.draw(call.imgSpec, call.tileId, call.col, call.row, call.count);\n }\n }\n\n public viewportResize(metrics: { cols: number, rows: number }): void {\n // exit early if we have nothing in storage\n if (!this._images.size) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // handle only viewport width enlargements, exit all other cases\n // TODO: needs patch for tile counter\n if (this._viewportMetrics.cols >= metrics.cols) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // walk scrollbuffer at old col width to find all possible expansion matches\n const buffer = this._terminal._core.buffer;\n const rows = buffer.lines.length;\n const oldCol = this._viewportMetrics.cols - 1;\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(row) as IBufferLineExt;\n if (line.getBg(oldCol) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[oldCol] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (!imgSpec) {\n continue;\n }\n // found an image tile at oldCol, check if it qualifies for right exapansion\n const tilesPerRow = Math.ceil((imgSpec.actual?.width || 0) / imgSpec.actualCellSize.width);\n if ((e.tileId % tilesPerRow) + 1 >= tilesPerRow) {\n continue;\n }\n // expand only if right side is empty (nothing got wrapped from below)\n let hasData = false;\n for (let rightCol = oldCol + 1; rightCol > metrics.cols; ++rightCol) {\n if (line._data[rightCol * Cell.SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK) {\n hasData = true;\n break;\n }\n }\n if (hasData) {\n continue;\n }\n // do right expansion on terminal buffer\n const end = Math.min(metrics.cols, tilesPerRow - (e.tileId % tilesPerRow) + oldCol);\n let lastTile = e.tileId;\n for (let expandCol = oldCol + 1; expandCol < end; ++expandCol) {\n this._writeToCell(line as IBufferLineExt, expandCol, imageId, ++lastTile);\n imgSpec.tileCount++;\n }\n }\n }\n // store new viewport metrics\n this._viewportMetrics = metrics;\n }\n\n /**\n * Retrieve original canvas at buffer position.\n */\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1) {\n const orig = this._images.get(e.imageId)?.orig;\n if (window.ImageBitmap && orig instanceof ImageBitmap) {\n const canvas = ImageRenderer.createCanvas(window.document, orig.width, orig.height);\n canvas.getContext('2d')?.drawImage(orig, 0, 0, orig.width, orig.height);\n return canvas;\n }\n return orig as HTMLCanvasElement;\n }\n }\n }\n\n /**\n * Extract active single tile at buffer position.\n */\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1 && e.tileId !== -1) {\n const spec = this._images.get(e.imageId);\n if (spec) {\n return this._renderer.extractTile(spec, e.tileId);\n }\n }\n }\n }\n\n // TODO: Do we need some blob offloading tricks here to avoid early eviction?\n // also see https://stackoverflow.com/questions/28307789/is-there-any-limitation-on-javascript-max-blob-size\n private _evictOldest(room: number): number {\n const used = this._getStoredPixels();\n let current = used;\n while (this._pixelLimit < current + room && this._images.size) {\n const spec = this._images.get(++this._lowestId);\n if (spec && spec.orig) {\n current -= spec.orig.width * spec.orig.height;\n if (spec.actual && spec.orig !== spec.actual) {\n current -= spec.actual.width * spec.actual.height;\n }\n spec.marker?.dispose();\n this._delImg(this._lowestId);\n }\n }\n return used - current;\n }\n\n private _writeToCell(line: IBufferLineExt, x: number, imageId: number, tileId: number): void {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const old = line._extendedAttrs[x];\n if (old) {\n if (old.imageId !== undefined) {\n // found an old ExtendedAttrsImage, since we know that\n // they are always isolated instances (single cell usage),\n // we can re-use it and just update their id entries\n const oldSpec = this._images.get(old.imageId);\n if (oldSpec) {\n // early eviction for in-viewport overwrites\n oldSpec.tileCount--;\n }\n old.imageId = imageId;\n old.tileId = tileId;\n return;\n }\n // found a plain ExtendedAttrs instance, clone it to new entry\n line._extendedAttrs[x] = new ExtendedAttrsImage(old.ext, old.urlId, imageId, tileId);\n return;\n }\n }\n // fall-through: always create new ExtendedAttrsImage entry\n line._data[x * Cell.SIZE + Cell.BG] |= BgFlags.HAS_EXTENDED;\n line._extendedAttrs[x] = new ExtendedAttrsImage(0, 0, imageId, tileId);\n }\n\n private _evictOnAlternate(): void {\n // nullify tile count of all images on alternate buffer\n for (const spec of this._images.values()) {\n if (spec.bufferType === 'alternate') {\n spec.tileCount = 0;\n }\n }\n // re-count tiles on whole buffer\n const buffer = this._terminal._core.buffer;\n for (let y = 0; y < this._terminal.rows; ++y) {\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (!line) {\n continue;\n }\n for (let x = 0; x < this._terminal.cols; ++x) {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const imgId = line._extendedAttrs[x]?.imageId;\n if (imgId) {\n const spec = this._images.get(imgId);\n if (spec) {\n spec.tileCount++;\n }\n }\n }\n }\n }\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate' && !spec.tileCount) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IImageAddonOptions, IOscHandler, IResetHandler, ITerminalExt } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { CELL_SIZE_DEFAULT } from './ImageStorage';\nimport Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport QoiDecoder from 'xterm-wasm-parts/lib/qoi/QoiDecoder.wasm';\nimport { HeaderParser, IHeaderFields, HeaderState, SequenceType } from './IIPHeaderParser';\nimport { imageType, UNSUPPORTED_TYPE } from './IIPMetrics';\n\n// Local const enum mirror - esbuild can't inline const enums from external packages\nconst enum DecoderConst {\n // Limit held memory in base64 decoder (encoded bytes).\n KEEP_DATA = 4194304,\n // Initial buffer allocation for the decoder.\n INITIAL_DATA = 1048576,\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n OK = 0\n}\n\n// default IIP header values\nconst DEFAULT_HEADER: IHeaderFields = {\n type: SequenceType.INVALID,\n name: 'Unnamed file',\n size: 0,\n width: 'auto',\n height: 'auto',\n preserveAspectRatio: 1,\n inline: 0\n};\n\n\nexport class IIPHandler implements IOscHandler, IResetHandler {\n private _aborted = false;\n private _hp = new HeaderParser();\n private _header: IHeaderFields = DEFAULT_HEADER;\n private _dec: Base64Decoder;\n private _qoiDec: QoiDecoder;\n private _isMultipart = false;\n private _abortMulti = false;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _storage: IIPImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n const maxEncodedBytes = Math.ceil(this._opts.iipSizeLimit * 4 / 3);\n const initialBytes = Math.min(DecoderConst.INITIAL_DATA, maxEncodedBytes);\n this._dec = new Base64Decoder(DecoderConst.KEEP_DATA, maxEncodedBytes, initialBytes);\n this._qoiDec = new QoiDecoder(DecoderConst.KEEP_DATA);\n }\n\n public reset(): void {\n this._hp.reset();\n this._dec.release();\n this._qoiDec.release();\n }\n\n public start(): void {\n this._aborted = false;\n this._hp.reset();\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (this._hp.state === HeaderState.END) {\n if ((this._dec.put(data.subarray(start, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n }\n } else {\n const dataPos = this._hp.parse(data, start, end);\n if (dataPos === -1) {\n this._aborted = true;\n return;\n }\n if (dataPos > 0) {\n const seqType = this._hp.fields.type;\n if (seqType === SequenceType.FILE) {\n if (this._isMultipart) {\n this._isMultipart = false;\n this._abortMulti = false;\n this._dec.release();\n }\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n if (!this._header.inline) {\n this._aborted = true;\n return;\n }\n this._dec.init();\n } else if (this._abortMulti) {\n this._aborted = true;\n return;\n }\n if ((this._dec.put(data.subarray(dataPos, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n if (this._isMultipart) this._abortMulti = true;\n }\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted) return true;\n\n if (this._hp.state !== HeaderState.END) {\n if (this._hp.end()) return true;\n }\n const seqType = this._hp.fields.type;\n\n if (seqType === SequenceType.FILEPART) return true;\n\n if (seqType === SequenceType.REPORTCELLSIZE) {\n // OSC 1337 ; ReportCellSize=[height];[width];[scale] ST\n let w = CELL_SIZE_DEFAULT.width;\n let h = CELL_SIZE_DEFAULT.height;\n if (this._renderer.dimensions) {\n w = this._renderer.dimensions.css.canvas.width / this._coreTerminal.cols;\n h = this._renderer.dimensions.css.canvas.height / this._coreTerminal.rows;\n }\n const scale = this._coreTerminal._core._coreBrowserService?.dpr ?? 1;\n const report = `\\x1b]1337;ReportCellSize=${h.toFixed(3)};${w.toFixed(3)};${scale.toFixed(3)}\\x1b\\\\`;\n this._coreTerminal.input(report, false);\n return true;\n }\n\n if (seqType === SequenceType.MULTIPARTFILE) {\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n this._isMultipart = true;\n this._abortMulti = false;\n this._dec.release();\n this._dec.init();\n return true;\n }\n\n if (seqType === SequenceType.FILEEND) {\n if (!this._isMultipart) return true;\n this._isMultipart = false;\n if (this._abortMulti || this._header.type !== SequenceType.MULTIPARTFILE) return true;\n }\n\n // fallthrough for SequenceType.FILE & SequenceType.FILEEND\n\n let w = 0;\n let h = 0;\n\n // early exit condition chain\n let cond: number | boolean;\n let metrics = UNSUPPORTED_TYPE;\n if (cond = success) {\n if (cond = !this._dec.end()) {\n metrics = imageType(this._dec.data8);\n if (cond = metrics.mime !== 'unsupported') {\n w = metrics.width;\n h = metrics.height;\n if (cond = w && h && w * h < this._opts.pixelLimit) {\n [w, h] = this._resize(w, h).map(Math.floor);\n cond = w && h && w * h < this._opts.pixelLimit;\n } else {\n console.warn(`IIP: image dimension issue ${metrics.width}x${metrics.height}`);\n }\n } else {\n console.warn('IIP: unsupported image type');\n }\n } else {\n console.warn('IIP: error during BASE64 decoding');\n }\n }\n if (!cond) {\n this._dec.release();\n return true;\n }\n\n let blob: Blob | ImageData;\n if (metrics.mime === 'image/qoi') {\n const data = this._qoiDec.decode(this._dec.data8);\n blob = new ImageData(\n new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength),\n this._qoiDec.width,\n this._qoiDec.height\n );\n this._qoiDec.release();\n if (w === this._qoiDec.width && h === this._qoiDec.height) {\n // use fast-path if we don't need to rescale\n this._dec.release();\n const canvas = ImageRenderer.createCanvas(undefined, this._qoiDec.width, this._qoiDec.height);\n canvas.getContext('2d')?.putImageData(blob, 0, 0);\n this._storage.addImage(canvas);\n return true;\n }\n } else {\n blob = new Blob([this._dec.data8], { type: metrics.mime });\n }\n this._dec.release();\n return createImageBitmap(blob, { resizeWidth: w, resizeHeight: h })\n .then(bm => {\n this._storage.addImage(bm);\n return true;\n })\n .catch(e => {\n console.warn(`IIP: decoding error ${metrics.mime} ${metrics.width}x${metrics.height}`, e);\n return true;\n });\n }\n\n private _resize(w: number, h: number): [number, number] {\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n const width = this._renderer.dimensions?.css.canvas.width || cw * this._coreTerminal.cols;\n const height = this._renderer.dimensions?.css.canvas.height || ch * this._coreTerminal.rows;\n\n const rw = this._dim(this._header.width!, width, cw);\n const rh = this._dim(this._header.height!, height, ch);\n if (!rw && !rh) {\n const wf = width / w; // TODO: should this respect initial cursor offset?\n const hf = (height - ch) / h; // TODO: fix offset issues from float cell height\n const f = Math.min(wf, hf);\n return f < 1 ? [w * f, h * f] : [w, h];\n }\n return !rw\n ? [w * rh / h, rh]\n : this._header.preserveAspectRatio || !rw || !rh\n ? [rw, h * rw / w] : [rw, rh];\n }\n\n private _dim(s: string, total: number, cdim: number): number {\n if (s === 'auto') return 0;\n if (s.endsWith('%')) return parseInt(s.slice(0, -1), 10) * total / 100;\n if (s.endsWith('px')) return parseInt(s.slice(0, -2), 10);\n return parseInt(s, 10) * cdim;\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n// eslint-disable-next-line\ndeclare const Buffer: any;\n\nexport const enum HeaderState {\n START = 0,\n ABORT = 1,\n KEY = 2,\n VALUE = 3,\n END = 4\n}\n\nexport const enum SequenceType {\n INVALID = 0,\n FILE = 1,\n MULTIPARTFILE = 2,\n FILEPART = 3,\n FILEEND = 4,\n REPORTCELLSIZE = 5\n}\n\nexport interface IHeaderFields {\n [key: string]: number | string | Uint32Array | null | undefined;\n // sequence type\n type: SequenceType;\n // base-64 encoded filename. Defaults to \"Unnamed file\".\n name: string;\n // File size in bytes. The file transfer will be canceled if this size is exceeded.\n size: number;\n /**\n * Optional width and height to render:\n * - N: N character cells.\n * - Npx: N pixels.\n * - N%: N percent of the session's width or height.\n * - auto: The image's inherent size will be used to determine an appropriate dimension.\n */\n width?: string;\n height?: string;\n // Optional, defaults to 1 respecting aspect ratio (width takes precedence).\n preserveAspectRatio?: number;\n // Optional, defaults to 0. If set to 1, the file will be displayed inline, else downloaded\n // (download not supported).\n inline?: number;\n}\n\n// field value decoders\n\n// ASCII bytes to string\nfunction toStr(data: Uint32Array): string {\n let s = '';\n for (let i = 0; i < data.length; ++i) {\n s += String.fromCharCode(data[i]);\n }\n return s;\n}\n\n// digits to integer\nfunction toInt(data: Uint32Array): number {\n let v = 0;\n for (let i = 0; i < data.length; ++i) {\n if (data[i] < 48 || data[i] > 57) {\n throw new Error('illegal char');\n }\n v = v * 10 + data[i] - 48;\n }\n return v;\n}\n\n// check for correct size entry\nfunction toSize(data: Uint32Array): string {\n const v = toStr(data);\n if (!v.match(/^((auto)|(\\d+?((px)|(%)){0,1}))$/)) {\n throw new Error('illegal size');\n }\n return v;\n}\n\n// name is base64 encoded utf-8\nfunction toName(data: Uint32Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(toStr(data), 'base64').toString();\n }\n const bs = atob(toStr(data));\n const b = new Uint8Array(bs.length);\n for (let i = 0; i < b.length; ++i) {\n b[i] = bs.charCodeAt(i);\n }\n return new TextDecoder().decode(b);\n}\n\nconst DECODERS: {[key: string]: (v: Uint32Array) => number | string} = {\n inline: toInt,\n size: toInt,\n name: toName,\n width: toSize,\n height: toSize,\n preserveAspectRatio: toInt\n};\n\n\n// sequence type markers\n// File\nconst FILE_MARKER = [70, 105, 108, 101];\n// MultipartFile\nconst MULTIPARTFILE_MARKER = [77, 117, 108, 116, 105, 112, 97, 114, 116, 70, 105, 108, 101];\n// FilePart\nconst FILEPART_MARKER = [70, 105, 108, 101, 80, 97, 114, 116];\n// FileEnd\nconst FILEEND_MARKER = [70, 105, 108, 101, 69, 110, 100];\n// ReportCellSize\nconst REPORTCELLSIZE_MARKER = [82, 101, 112, 111, 114, 116, 67, 101, 108, 108, 83, 105, 122, 101];\n\n// max allowed chars for sequence header\nconst MAX_FIELDCHARS = 1024;\n\n\nexport class HeaderParser {\n public state: HeaderState = HeaderState.START;\n private _buffer = new Uint32Array(MAX_FIELDCHARS);\n private _position = 0;\n private _key = '';\n public fields: {[key: string]: number | string | Uint32Array | null | undefined} = {};\n\n public reset(): void {\n this._buffer.fill(0);\n this.state = HeaderState.START;\n this._position = 0;\n this.fields = {};\n this._key = '';\n }\n\n public end(): number {\n if (this.state === HeaderState.START) {\n if (this._position === FILEEND_MARKER.length) {\n for (let k = 0; k < FILEEND_MARKER.length; ++k) {\n if (this._buffer[k] !== FILEEND_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEEND;\n this.state = HeaderState.END;\n return 0;\n }\n if (this._position === REPORTCELLSIZE_MARKER.length) {\n for (let k = 0; k < REPORTCELLSIZE_MARKER.length; ++k) {\n if (this._buffer[k] !== REPORTCELLSIZE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.REPORTCELLSIZE;\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n if (this.state === HeaderState.END) return 0;\n if (this.state === HeaderState.VALUE\n && this.fields.type === SequenceType.MULTIPARTFILE\n ) {\n if (!this._storeValue(this._position)) return this._a();\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n\n public parse(data: Uint32Array, start: number, end: number): number {\n let state = this.state;\n let pos = this._position;\n const buffer = this._buffer;\n if (state === HeaderState.ABORT || state === HeaderState.END) return -1;\n if (state === HeaderState.START && pos > 14) return -1;\n for (let i = start; i < end; ++i) {\n const c = data[i];\n switch (c) {\n case 59: // ;\n if (!this._storeValue(pos)) return this._a();\n state = HeaderState.KEY;\n pos = 0;\n break;\n case 61: // =\n if (state === HeaderState.START) {\n if (buffer[0] === 70) {\n // 'File' or 'FilePart'\n let k = 0;\n for (; k < FILE_MARKER.length; ++k) {\n if (buffer[k] !== FILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILE;\n if (pos === FILEPART_MARKER.length) {\n for (; k < FILEPART_MARKER.length; ++k) {\n if (buffer[k] !== FILEPART_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEPART;\n this.state = HeaderState.END;\n return i + 1;\n }\n } else if (buffer[0] === 77) {\n // 'MultipartFile'\n for (let k = 0; k < MULTIPARTFILE_MARKER.length; ++k) {\n if (buffer[k] !== MULTIPARTFILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.MULTIPARTFILE;\n } else {\n return this._a();\n }\n state = HeaderState.KEY;\n pos = 0;\n } else if (state === HeaderState.KEY) {\n if (!this._storeKey(pos)) return this._a();\n state = HeaderState.VALUE;\n pos = 0;\n } else if (state === HeaderState.VALUE) {\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n break;\n case 58: // :\n if (state === HeaderState.VALUE) {\n if (!this._storeValue(pos)) return this._a();\n }\n this.state = HeaderState.END;\n return i + 1;\n default:\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n }\n this.state = state;\n this._position = pos;\n return -2;\n }\n\n private _a(): number {\n this.fields.type = SequenceType.INVALID;\n this.state = HeaderState.ABORT;\n return -1;\n }\n\n private _storeKey(pos: number): boolean {\n const k = toStr(this._buffer.subarray(0, pos));\n if (k) {\n this._key = k;\n this.fields[k] = null;\n return true;\n }\n return false;\n }\n\n private _storeValue(pos: number): boolean {\n if (this._key) {\n try {\n const v = this._buffer.slice(0, pos);\n this.fields[this._key] = DECODERS[this._key] ? DECODERS[this._key](v) : v;\n } catch {\n return false;\n }\n return true;\n }\n return false;\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n\nexport type ImageType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/qoi' | 'image/webp' | 'image/avif' | 'unsupported' | '';\n\nexport interface IMetrics {\n mime: ImageType;\n width: number;\n height: number;\n}\n\nexport const UNSUPPORTED_TYPE: IMetrics = {\n mime: 'unsupported',\n width: 0,\n height: 0\n};\n\nexport function imageType(d: Uint8Array): IMetrics {\n if (d.length < 32) {\n return UNSUPPORTED_TYPE;\n }\n const d32 = new Uint32Array(d.buffer, d.byteOffset, 8);\n // PNG: 89 50 4E 47 0D 0A 1A 0A (8 first bytes == magic number for PNG)\n // + first chunk must be IHDR\n if (d32[0] === 0x474E5089 && d32[1] === 0x0A1A0A0D && d32[3] === 0x52444849) {\n return {\n mime: 'image/png',\n width: d[16] << 24 | d[17] << 16 | d[18] << 8 | d[19],\n height: d[20] << 24 | d[21] << 16 | d[22] << 8 | d[23]\n };\n }\n // JPEG: FF D8 FF\n if (d[0] === 0xFF && d[1] === 0xD8 && d[2] === 0xFF) {\n const [width, height] = jpgSize(d);\n return { mime: 'image/jpeg', width, height };\n }\n // GIF: GIF87a or GIF89a\n if (d32[0] === 0x38464947 && (d[4] === 0x37 || d[4] === 0x39) && d[5] === 0x61) {\n return {\n mime: 'image/gif',\n width: d[7] << 8 | d[6],\n height: d[9] << 8 | d[8]\n };\n }\n // QOI: qoif\n if (d32[0] === 0x66696F71) {\n return {\n mime: 'image/qoi',\n width: d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7],\n height: d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11]\n };\n }\n // WEBP: RIFF | xxxx | WEBP | VP8x\n if (d32[0] === 0x46464952 && d32[2] === 0x50424557 && (d32[3] & 0xFFFFFF) === 0x385056) {\n switch (d[15]) {\n case 0x58: // Extended WebP VP8X --> \"X\"\n return {\n mime: 'image/webp',\n width: (d[24] | d[25] << 8 | d[26] << 16) + 1,\n height: (d[27] | d[28] << 8 | d[29] << 16) + 1\n };\n case 0x4C: // Lossless WebP VP8L --> \"L\"\n if (d[20] !== 0x2f) return UNSUPPORTED_TYPE;\n const dim = d[21] | d[22] << 8 | d[23] << 16 | d[24] << 24;\n return {\n mime: 'image/webp',\n width: (dim & 0x3FFF) + 1,\n height: (dim >>> 14 & 0x3FFF) + 1\n };\n case 0x20: // Lossy WebP VP8 --> \" \"\n if (d[23] !== 0x9d || d[24] !== 0x01 || d[25] !== 0x2a) return UNSUPPORTED_TYPE;\n return {\n mime: 'image/webp',\n width: (d[26] | d[27] << 8) & 0x3FFF,\n height: (d[28] | d[29] << 8) & 0x3FFF\n };\n }\n return UNSUPPORTED_TYPE;\n }\n // AVIF: Box size | ftyp | avif/avis\n if (d32[1] === 0x70797466 && (d32[2] === 0x66697661 || d32[2] === 0x73697661)) {\n let pos = -1;\n // search for ispe box within first 1024 bytes\n const limit = Math.min(d.length - 16, 1024);\n for (let i = 8; i < limit; i++) {\n // scan for ispe\n if (d[i] === 0x69 && d[i + 1] === 0x73 && d[i + 2] === 0x70 && d[i + 3] === 0x65) {\n pos = i;\n break;\n }\n }\n if (pos !== -1) {\n // dimensions are in BE at +8 (width) at +12 (height)\n const width =\n d[pos + 8] << 24 |\n d[pos + 9] << 16 |\n d[pos + 10] << 8 |\n d[pos + 11];\n const height =\n d[pos + 12] << 24 |\n d[pos + 13] << 16 |\n d[pos + 14] << 8 |\n d[pos + 15];\n if (width > 0 && height > 0) {\n return { mime: 'image/avif', width, height };\n }\n }\n return UNSUPPORTED_TYPE;\n }\n return UNSUPPORTED_TYPE;\n}\n\n\nfunction jpgSize(d: Uint8Array): [number, number] {\n const len = d.length;\n let i = 4;\n let blockLength = d[i] << 8 | d[i + 1];\n while (true) {\n i += blockLength;\n if (i >= len) {\n // exhausted without size info\n return [0, 0];\n }\n if (d[i] !== 0xFF) {\n return [0, 0];\n }\n if (d[i + 1] === 0xC0 || d[i + 1] === 0xC2) {\n if (i + 8 < len) {\n return [\n d[i + 7] << 8 | d[i + 8],\n d[i + 5] << 8 | d[i + 6]\n ];\n }\n return [0, 0];\n }\n i += 2;\n blockLength = d[i] << 8 | d[i + 1];\n }\n}\n", "/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { IApcHandler, IImageAddonOptions, IResetHandler, ITerminalExt, ImageLayer } from '../Types';\nimport { ImageRenderer } from '../ImageRenderer';\nimport { CELL_SIZE_DEFAULT } from '../ImageStorage';\nimport { KittyImageStorage } from './KittyImageStorage';\nimport Base64Decoder, { type DecodeStatus } from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport {\n KittyAction,\n KittyFormat,\n KittyCompression,\n IKittyCommand,\n IPendingTransmission,\n IKittyImageData,\n KittyPixelConstants,\n parseKittyCommand\n} from './KittyGraphicsTypes';\n\nconst enum Constants {\n // Memory limit for base64 decoder (4MB, same as IIPHandler)\n DECODER_KEEP_DATA = 4194304,\n DECODER_INITIAL_DATA = 4194304, // 4MB\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n DECODER_OK = 0,\n // Maximum control data size\n MAX_CONTROL_DATA_SIZE = 512,\n // Semicolon codepoint\n SEMICOLON = 0x3B\n}\n\nconst DECODER_OK = Constants.DECODER_OK as unknown as DecodeStatus.OK;\n\n// Kitty graphics protocol handler with streaming base64 decoding.\nexport class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDisposable {\n private _aborted = false;\n private _decodeError = false;\n\n private _activeDecoder: Base64Decoder | null = null;\n private readonly _maxEncodedBytes: number;\n private readonly _initialEncodedBytes: number;\n\n // Streaming related states\n\n // True while receiving control data (before semicolon).\n private _inControlData = true;\n\n // Buffer for control data.\n private _controlData = new Uint32Array(Constants.MAX_CONTROL_DATA_SIZE);\n private _controlLength = 0;\n\n // Pre-calculated encoded size limit\n private _encodedSizeLimit = 0;\n private _totalEncodedSize = 0;\n\n // Parsed command. These are the control data before semicolon.\n private _parsedCommand: IKittyCommand | null = null;\n\n // Storage related states\n\n private _pendingTransmissions: Map = new Map();\n // Tracks the pending key of the most recently started chunked upload.\n // Per spec, subsequent chunks only need m= (and optionally q=), without i=.\n // When a chunk arrives with no i=, this key is used to find the pending upload.\n private _lastPendingKey: number | undefined;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _kittyStorage: KittyImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n // Convert decoded size limit -> max encoded bytes.\n this._maxEncodedBytes = Math.ceil(this._opts.kittySizeLimit * 4 / 3);\n // ensure we preallocate more than configured limit while using 4mb initial size.\n this._initialEncodedBytes = Math.min(Constants.DECODER_INITIAL_DATA, this._maxEncodedBytes);\n }\n\n public reset(): void {\n this._cleanupAllPending();\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n this._kittyStorage.reset();\n }\n\n public dispose(): void {\n this.reset();\n }\n\n private _removePendingEntry(key: number): void {\n this._pendingTransmissions.delete(key);\n if (this._lastPendingKey === key) {\n this._lastPendingKey = undefined;\n }\n }\n\n private _cleanupAllPending(): void {\n for (const pending of this._pendingTransmissions.values()) {\n pending.decoder.release();\n }\n this._pendingTransmissions.clear();\n this._lastPendingKey = undefined;\n }\n\n public start(): void {\n this._aborted = false;\n this._decodeError = false;\n this._inControlData = true;\n this._controlLength = 0;\n this._parsedCommand = null;\n // Pre-calculate encoded limit once: base64 is 4 bytes encoded \u2192 3 bytes decoded\n this._encodedSizeLimit = this._maxEncodedBytes;\n this._totalEncodedSize = 0;\n this._activeDecoder = null;\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (!this._inControlData) {\n this._streamPayload(data, start, end);\n } else {\n // Scan for semicolon\n let controlEnd = end;\n for (let i = start; i < end; i++) {\n if (data[i] === Constants.SEMICOLON) {\n this._inControlData = false;\n controlEnd = i;\n break;\n }\n }\n\n // Copy control data\n const copyLength = controlEnd - start;\n if (this._controlLength + copyLength > Constants.MAX_CONTROL_DATA_SIZE) {\n this._aborted = true;\n return;\n }\n this._controlData.set(data.subarray(start, controlEnd), this._controlLength);\n this._controlLength += copyLength;\n\n if (!this._inControlData) {\n // Found semicolon - parse control data early for validation\n this._parsedCommand = parseKittyCommand(this._parseControlDataString());\n\n // Early validation: i+I conflict\n if (this._parsedCommand.id !== undefined && this._parsedCommand.imageNumber !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'EINVAL:cannot specify both i and I keys', this._parsedCommand.quiet ?? 0);\n this._aborted = true;\n return;\n }\n\n // Delete action doesn't need payload - skip streaming\n if (this._parsedCommand.action === KittyAction.DELETE) {\n return;\n }\n\n // Stream remaining as payload\n const payloadStart = controlEnd + 1;\n if (payloadStart < end) {\n this._streamPayload(data, payloadStart, end);\n }\n }\n }\n }\n\n // Stream payload bytes into the base64 decoder.\n private _streamPayload(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n // Check size limit (compare encoded bytes against pre-calculated limit)\n // Include cumulative size from pending transmission for multi-chunk images.\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = this._parsedCommand?.id ?? this._lastPendingKey ?? 0;\n const pending = this._pendingTransmissions.get(pendingKey);\n const previousEncodedSize = pending?.totalEncodedSize ?? 0;\n this._totalEncodedSize += end - start;\n const cumulativeEncodedSize = previousEncodedSize + this._totalEncodedSize;\n if (cumulativeEncodedSize > this._encodedSizeLimit) {\n const decoderToRelease = this._activeDecoder ?? pending?.decoder;\n if (decoderToRelease) {\n decoderToRelease.release();\n }\n this._activeDecoder = null;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n this._aborted = true;\n return;\n }\n\n if (this._decodeError) return;\n\n if (pending?.decoder && !this._activeDecoder) {\n this._activeDecoder = pending.decoder;\n }\n if (!this._activeDecoder) {\n this._activeDecoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes);\n this._activeDecoder.init();\n }\n\n if (this._activeDecoder.put(data.subarray(start, end)) !== DECODER_OK) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n this._decodeError = true;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted || !success) {\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n return true;\n }\n\n // No semicolon = no payload (delete, capability query)\n if (this._inControlData) {\n return this._handleNoPayloadCommand();\n }\n\n // Use command parsed early in put() - i+I already validated there\n const cmd = this._parsedCommand!;\n\n // Delete action was handled by skipping payload - just execute\n if (cmd.action === KittyAction.DELETE) {\n return this._handleDelete(cmd);\n }\n\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = cmd.id ?? this._lastPendingKey ?? 0;\n const isMoreComing = cmd.more === 1;\n const pending = this._pendingTransmissions.get(pendingKey);\n\n if (isMoreComing) {\n if (this._activeDecoder) {\n if (pending) {\n pending.totalEncodedSize += this._totalEncodedSize;\n pending.decodeError = pending.decodeError || this._decodeError;\n } else {\n this._pendingTransmissions.set(pendingKey, {\n cmd: { ...cmd },\n decoder: this._activeDecoder,\n totalEncodedSize: this._totalEncodedSize,\n decodeError: this._decodeError\n });\n }\n this._lastPendingKey = pendingKey;\n this._activeDecoder = null;\n }\n return true;\n }\n\n // Final chunk received \u2014 clear the last pending key\n if (pending) {\n this._lastPendingKey = undefined;\n }\n\n let decodeError = this._decodeError;\n let finalCmd = cmd;\n let decoder = this._activeDecoder;\n\n if (pending) {\n finalCmd = pending.cmd;\n decoder = pending.decoder;\n decodeError = decodeError || pending.decodeError;\n this._pendingTransmissions.delete(pendingKey);\n }\n\n let imageBytes = new Uint8Array(0);\n if (decoder) {\n if (decoder.end() !== DECODER_OK) {\n decodeError = true;\n }\n imageBytes = decoder.data8;\n }\n this._activeDecoder = null;\n\n // Handle command first \u2014 handlers create Blob/ImageData from imageBytes,\n // which copies the data. Only then is it safe to release the decoder's\n // wasm memory that imageBytes points into.\n const result = this._handleCommandWithBytesAndCmd(finalCmd, imageBytes, decodeError);\n if (decoder) {\n decoder.release();\n }\n return result;\n }\n\n // Command handling\n\n private _parseControlDataString(): string {\n let str = '';\n for (let i = 0; i < this._controlLength; i++) {\n str += String.fromCodePoint(this._controlData[i]);\n }\n return str;\n }\n\n private _handleNoPayloadCommand(): boolean | Promise {\n const cmd = parseKittyCommand(this._parseControlDataString());\n\n // Per spec: specifying both i and I is an error\n if (cmd.id !== undefined && cmd.imageNumber !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:cannot specify both i and I keys', cmd.quiet ?? 0);\n return true;\n }\n\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.DELETE:\n return this._handleDelete(cmd);\n case KittyAction.QUERY:\n this._sendResponse(cmd.id ?? 0, 'OK', cmd.quiet ?? 0);\n return true;\n case KittyAction.PLACEMENT:\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handleCommandWithBytesAndCmd(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.TRANSMIT: {\n const result = this._handleTransmit(cmd, bytes, decodeError);\n // Only send response when _handleTransmit didn't already respond\n // (it handles unsupported transmission medium responses internally)\n if ((cmd.transmission ?? 'd') === 'd' && cmd.id !== undefined) {\n if (decodeError) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n } else if (bytes.length > 0) {\n this._sendResponse(cmd.id, 'OK', cmd.quiet ?? 0);\n }\n }\n return result;\n }\n case KittyAction.TRANSMIT_DISPLAY:\n return this._handleTransmitDisplay(cmd, bytes, decodeError);\n case KittyAction.QUERY:\n return this._handleQuery(cmd, bytes, decodeError);\n case KittyAction.PLACEMENT:\n // a=p ignores any payload \u2014 image data was already transmitted\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handlePlacement(cmd: IKittyCommand): boolean | Promise {\n if (cmd.id === undefined) {\n return true;\n }\n const id = cmd.id;\n const image = this._kittyStorage.getImage(id);\n if (!image) {\n this._sendResponse(id, 'ENOENT:image not found', cmd.quiet ?? 0, cmd.placementId);\n return true;\n }\n const result = this._displayImage(image, cmd);\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0, cmd.placementId);\n return true;\n });\n }\n\n private _handleTransmit(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n // TODO: Support file-based transmission modes (t=f, t=t, t=s)\n // Currently only supports direct transmission (t=d, the default).\n // - t=f (file): Payload is base64-encoded file path. Terminal reads image from that path.\n // - t=t (temp file): Payload is base64-encoded path in temp directory. Terminal reads, deletes.\n // - t=s: Payload is base64-encoded POSIX shm name. Terminal reads from shared memory.\n // These modes require filesystem/IPC access not available in browsers. For Node.js/Electron:\n // 1. Check cmd.transmission (t key) before treating bytes as image data\n // 2. For t=f/t/s: decode bytes as UTF-8 string (the path/name), then read file contents\n // 3. For t=d: treat bytes as image data (current behavior)\n // When implementing, also update _handleQuery to accept these transmission mediums.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported transmission medium', cmd.quiet ?? 0);\n }\n return true;\n }\n\n if (decodeError || bytes.length === 0) return true;\n\n this._kittyStorage.storeImage(cmd.id, {\n data: new Blob([bytes as BlobPart]),\n width: cmd.width ?? 0,\n height: cmd.height ?? 0,\n format: (cmd.format ?? KittyFormat.RGBA) as 24 | 32 | 100,\n compression: cmd.compression ?? ''\n });\n return true;\n }\n\n private _handleTransmitDisplay(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n if (decodeError) {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n }\n return true;\n }\n\n this._handleTransmit(cmd, bytes, decodeError);\n\n const id = cmd.id ?? this._kittyStorage.lastImageId;\n const image = this._kittyStorage.getImage(id);\n if (image) {\n const result = this._displayImage(image, cmd);\n if (cmd.id !== undefined) {\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0);\n return true;\n });\n }\n return result.then(() => true);\n }\n return true;\n }\n\n private _handleQuery(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n const id = cmd.id ?? 0;\n const quiet = cmd.quiet ?? 0;\n\n // Per spec: reject unsupported transmission mediums (only t=d is supported atm)\n // TODO: When filesystem support is added (Node.js/Electron), update this to accept\n // t=f (file), t=t (temp file), and t=s (shared memory) and respond OK for queries.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n this._sendResponse(id, 'EINVAL:unsupported transmission medium', quiet);\n return true;\n }\n\n // Check decode error first (invalid base64)\n if (decodeError) {\n this._sendResponse(id, 'EINVAL:invalid base64 data', quiet);\n return true;\n }\n\n // Capability query (no payload) - just respond OK\n if (bytes.length === 0) {\n this._sendResponse(id, 'OK', quiet);\n return true;\n }\n\n const format = cmd.format ?? KittyFormat.RGBA;\n\n if (format === KittyFormat.PNG) {\n this._sendResponse(id, 'OK', quiet);\n } else {\n const width = cmd.width ?? 0;\n const height = cmd.height ?? 0;\n\n if (!width || !height) {\n this._sendResponse(id, 'EINVAL:width and height required for raw pixel data', quiet);\n return true;\n }\n\n const bytesPerPixel = format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n this._sendResponse(id, `EINVAL:insufficient pixel data`, quiet);\n return true;\n }\n\n this._sendResponse(id, 'OK', quiet);\n }\n return true;\n }\n\n private _handleDelete(cmd: IKittyCommand): boolean {\n // Per spec: default delete selector is 'a' (delete all visible placements)\n const selector = cmd.deleteSelector ?? 'a';\n\n // TODO: Distinguish lowercase (delete placements only) from uppercase\n // (delete placements + free stored image data). Currently both variants\n // free everything since we don't separate stored data from placements.\n switch (selector) {\n case 'a':\n case 'A':\n this._cleanupAllPending();\n this._kittyStorage.deleteAll();\n break;\n case 'i':\n case 'I':\n // TODO: When placement id tracking is implemented (see TODO in\n // KittyImageStorage), d=i with p= should delete only that\n // specific placement, while d=i without p should delete all\n // placements for the image.\n if (cmd.id !== undefined) {\n const pending = this._pendingTransmissions.get(cmd.id);\n if (pending) {\n pending.decoder.release();\n }\n this._removePendingEntry(cmd.id);\n this._kittyStorage.deleteById(cmd.id);\n }\n break;\n default:\n // Unsupported selectors (c, n, p, q, r, x, y, z, f) \u2014 ignore for now\n break;\n }\n return true;\n }\n\n private _sendResponse(id: number, message: string, quiet: number, placementId?: number): void {\n const isOk = message === 'OK';\n if (isOk && quiet >= 1) return;\n if (!isOk && quiet >= 2) return;\n\n const pPart = placementId ? `,p=${placementId}` : '';\n const response = `\\x1b_Gi=${id}${pPart};${message}\\x1b\\\\`;\n this._coreTerminal._core.coreService.triggerDataEvent(response);\n }\n\n // Image display\n\n private _displayImage(image: IKittyImageData, cmd: IKittyCommand): Promise {\n return this._decodeAndDisplay(image, cmd)\n .then(() => true)\n .catch(() => false);\n }\n\n private async _decodeAndDisplay(image: IKittyImageData, cmd: IKittyCommand): Promise {\n let bitmap: ImageBitmap | undefined = await this._createBitmap(image);\n\n try {\n const cropX = Math.max(0, cmd.x ?? 0);\n const cropY = Math.max(0, cmd.y ?? 0);\n const cropW = cmd.sourceWidth || (bitmap.width - cropX);\n const cropH = cmd.sourceHeight || (bitmap.height - cropY);\n\n const maxCropW = Math.max(0, bitmap.width - cropX);\n const maxCropH = Math.max(0, bitmap.height - cropY);\n const finalCropW = Math.max(0, Math.min(cropW, maxCropW));\n const finalCropH = Math.max(0, Math.min(cropH, maxCropH));\n\n if (finalCropW === 0 || finalCropH === 0) {\n throw new Error('invalid source rectangle');\n }\n\n if (cropX !== 0 || cropY !== 0 || finalCropW !== bitmap.width || finalCropH !== bitmap.height) {\n const cropped = await createImageBitmap(bitmap, cropX, cropY, finalCropW, finalCropH);\n bitmap.close();\n bitmap = cropped;\n }\n\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n\n // Per spec: c/r default to image's natural cell dimensions.\n // If only one of c/r is specified, compute the other from image aspect ratio.\n let imgCols: number;\n let imgRows: number;\n if (cmd.columns !== undefined && cmd.rows !== undefined) {\n imgCols = cmd.columns;\n imgRows = cmd.rows;\n } else if (cmd.columns !== undefined) {\n imgCols = cmd.columns;\n imgRows = Math.max(1, Math.ceil((bitmap.height / bitmap.width) * (imgCols * cw) / ch));\n } else if (cmd.rows !== undefined) {\n imgRows = cmd.rows;\n imgCols = Math.max(1, Math.ceil((bitmap.width / bitmap.height) * (imgRows * ch) / cw));\n } else {\n imgCols = Math.ceil(bitmap.width / cw);\n imgRows = Math.ceil(bitmap.height / ch);\n }\n\n let w = bitmap.width;\n let h = bitmap.height;\n\n // Scale bitmap to fit placement rectangle when c/r are specified\n if (cmd.columns !== undefined || cmd.rows !== undefined) {\n w = Math.round(imgCols * cw);\n h = Math.round(imgRows * ch);\n }\n\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n\n // Save cursor position before addImage modifies it\n const buffer = this._coreTerminal._core.buffer;\n const savedX = buffer.x;\n const savedY = buffer.y;\n const savedYbase = buffer.ybase;\n\n // Determine layer based on z-index: negative = behind text, 0+ = on top.\n // When z<0 we always use the bottom layer even without allowTransparency \u2014\n // the image will simply be hidden behind the opaque text background, which\n // is the correct behavior (client asked for \"behind text\").\n const wantsBottom = cmd.zIndex !== undefined && cmd.zIndex < 0;\n const layer: ImageLayer = wantsBottom ? 'bottom' : 'top';\n\n if (w !== bitmap.width || h !== bitmap.height) {\n const scaled = await createImageBitmap(bitmap, { resizeWidth: w, resizeHeight: h });\n bitmap.close();\n bitmap = scaled;\n }\n\n // Per spec: X/Y are pixel offsets within the first cell, so clamp to cell dimensions\n const xOffset = Math.min(Math.max(0, cmd.xOffset ?? 0), cw - 1);\n const yOffset = Math.min(Math.max(0, cmd.yOffset ?? 0), ch - 1);\n if (xOffset !== 0 || yOffset !== 0) {\n // Per spec: X/Y is not added to c/r area. When c/r are explicit, the\n // total placement area remains c*cw \u00D7 r*ch pixels and the offset image\n // is clipped to fit. When c/r are unset, the padded canvas determines\n // the natural cell dimensions.\n const canvasW = (cmd.columns !== undefined) ? Math.round(imgCols * cw) : bitmap.width + xOffset;\n const canvasH = (cmd.rows !== undefined) ? Math.round(imgRows * ch) : bitmap.height + yOffset;\n const offsetCanvas = ImageRenderer.createCanvas(window.document, canvasW, canvasH);\n const offsetCtx = offsetCanvas.getContext('2d');\n if (!offsetCtx) {\n throw new Error('Failed to create offset canvas context');\n }\n offsetCtx.drawImage(bitmap, xOffset, yOffset);\n\n const offsetBitmap = await createImageBitmap(offsetCanvas);\n offsetCanvas.width = offsetCanvas.height = 0;\n bitmap.close();\n bitmap = offsetBitmap;\n w = bitmap.width;\n h = bitmap.height;\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n if (cmd.columns === undefined) {\n imgCols = Math.ceil(bitmap.width / cw);\n }\n if (cmd.rows === undefined) {\n imgRows = Math.ceil(bitmap.height / ch);\n }\n }\n\n const zIndex = cmd.zIndex ?? 0;\n this._kittyStorage.addImage(image.id, bitmap, true, layer, zIndex);\n bitmap = undefined; // ownership transferred to storage\n\n // Kitty cursor movement\n // Per spec: cursor placed at first column after last image column,\n // on the last row of the image. C=1 means don't move cursor.\n if (cmd.cursorMovement === 1) {\n // C=1: restore cursor to position before image was placed\n const scrolled = buffer.ybase - savedYbase;\n buffer.x = savedX;\n // Can't restore cursor to scrollback?\n buffer.y = Math.max(savedY - scrolled, 0);\n } else {\n // Default (C=0): advance cursor horizontally past the image\n // addImage already positioned cursor on the last row via lineFeeds\n buffer.x = Math.min(savedX + imgCols, this._coreTerminal.cols);\n }\n } catch (e) {\n bitmap?.close();\n throw e;\n }\n }\n\n // Create ImageBitmap from already-decoded image data.\n private async _createBitmap(image: IKittyImageData): Promise {\n let bytes: Uint8Array = new Uint8Array(await image.data.arrayBuffer());\n\n if (image.compression === KittyCompression.ZLIB) {\n bytes = await this._decompressZlib(bytes);\n }\n\n if (image.format === KittyFormat.PNG) {\n const blob = new Blob([bytes as BlobPart], { type: 'image/png' });\n if (!window.createImageBitmap) {\n const url = URL.createObjectURL(blob);\n const img = new Image();\n return new Promise((resolve, reject) => {\n img.addEventListener('load', () => {\n URL.revokeObjectURL(url);\n const canvas = ImageRenderer.createCanvas(window.document, img.width, img.height);\n canvas.getContext('2d')?.drawImage(img, 0, 0);\n createImageBitmap(canvas).then(resolve).catch(reject);\n });\n img.addEventListener('error', () => {\n URL.revokeObjectURL(url);\n reject(new Error('Failed to load image'));\n });\n img.src = url;\n });\n }\n return createImageBitmap(blob);\n }\n\n // Raw pixel data\n const width = image.width;\n const height = image.height;\n\n if (!width || !height) {\n throw new Error('Width and height required for raw pixel data');\n }\n\n const bytesPerPixel = image.format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n throw new Error('Insufficient pixel data');\n }\n\n const pixelCount = width * height;\n\n if (image.format === KittyFormat.RGBA) {\n // RGBA: use bytes directly \u2014 no copy needed\n return createImageBitmap(new ImageData(new Uint8ClampedArray(bytes.buffer as ArrayBuffer, bytes.byteOffset, pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA), width, height));\n }\n\n // RGB\u2192RGBA: interleave alpha using uint32 block processing (4 pixels per iteration).\n // 3 uint32 reads + 4 uint32 writes per 4 pixels vs 28 byte reads/writes \u2014 ~6x faster.\n // Assumes little-endian (all modern browsers/Node.js).\n const data = new Uint8ClampedArray(pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA);\n const src32 = new Uint32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4));\n const dst32 = new Uint32Array(data.buffer);\n const alignedPixels = pixelCount & ~3; // round down to multiple of 4\n\n let srcOffset = 0;\n let dstOffset = 0;\n for (let i = 0; i < alignedPixels; i += 4) {\n const b0 = src32[srcOffset++];\n const b1 = src32[srcOffset++];\n const b2 = src32[srcOffset++];\n // Little-endian: pixel bytes are [R,G,B] \u2192 uint32 ABGR layout\n dst32[dstOffset++] = 0xFF000000 | b0;\n dst32[dstOffset++] = 0xFF000000 | (b0 >>> 24) | (b1 << 8);\n dst32[dstOffset++] = 0xFF000000 | (b1 >>> 16) | (b2 << 16);\n dst32[dstOffset++] = 0xFF000000 | (b2 >>> 8);\n }\n\n // Handle remaining 1\u20133 pixels\n let srcByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n let dstByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n for (let i = alignedPixels; i < pixelCount; i++) {\n data[dstByte] = bytes[srcByte];\n data[dstByte + 1] = bytes[srcByte + 1];\n data[dstByte + 2] = bytes[srcByte + 2];\n data[dstByte + 3] = KittyPixelConstants.ALPHA_OPAQUE;\n srcByte += KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n dstByte += KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n }\n\n return createImageBitmap(new ImageData(data, width, height));\n }\n\n private async _decompressZlib(compressed: Uint8Array): Promise {\n try {\n return await this._decompress(compressed, 'deflate');\n } catch {\n return await this._decompress(compressed, 'deflate-raw');\n }\n }\n\n private async _decompress(compressed: Uint8Array, format: 'deflate' | 'deflate-raw'): Promise {\n const ds = new DecompressionStream(format);\n const writer = ds.writable.getWriter();\n writer.write(compressed as BufferSource);\n writer.close();\n\n const chunks: Uint8Array[] = [];\n const reader = ds.readable.getReader();\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n }\n\n public get images(): ReadonlyMap {\n return this._kittyStorage.images;\n }\n\n public get _kittyIdToStorageId(): ReadonlyMap {\n return this._kittyStorage.kittyIdToStorageId;\n }\n\n public get pendingTransmissions(): ReadonlyMap {\n return this._pendingTransmissions;\n }\n}\n", "/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Kitty graphics protocol types, constants, and parsing utilities.\n */\n\nimport type Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\n\n// Kitty graphics protocol action types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'a'.\nexport const enum KittyAction {\n TRANSMIT = 't',\n TRANSMIT_DISPLAY = 'T',\n QUERY = 'q',\n PLACEMENT = 'p',\n DELETE = 'd'\n}\n\n// Kitty graphics protocol format types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyFormat {\n RGB = 24,\n RGBA = 32,\n PNG = 100\n}\n\n// Kitty graphics protocol compression types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'o'.\nexport const enum KittyCompression {\n NONE = '',\n ZLIB = 'z'\n}\n\n// Kitty graphics protocol control data keys.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyKey {\n // Action to perform (t=transmit, T=transmit+display, q=query, p=placement, d=delete)\n ACTION = 'a',\n // Image format (24=RGB, 32=RGBA, 100=PNG)\n FORMAT = 'f',\n // Image ID for referencing stored images\n ID = 'i',\n // Image number (alternative to ID, terminal assigns ID)\n IMAGE_NUMBER = 'I',\n // Source image width in pixels\n WIDTH = 's',\n // Source image height in pixels\n HEIGHT = 'v',\n // The left edge (in pixels) of the image area to display\n X_OFFSET = 'x',\n // The top edge (in pixels) of the image area to display\n Y_OFFSET = 'y',\n // Width (in pixels) of the source rectangle to display\n SOURCE_WIDTH = 'w',\n // Height (in pixels) of the source rectangle to display\n SOURCE_HEIGHT = 'h',\n // Horizontal offset (in pixels) within the first cell\n X_PLACEMENT_OFFSET = 'X',\n // Vertical offset (in pixels) within the first cell\n Y_PLACEMENT_OFFSET = 'Y',\n // Number of terminal columns to display the image over\n COLUMNS = 'c',\n // Number of terminal rows to display the image over\n ROWS = 'r',\n // More data flag (1=more chunks coming, 0=final chunk)\n MORE = 'm',\n // Compression type (z=zlib). This is essential for chunking larger images.\n COMPRESSION = 'o',\n // Quiet mode (1=suppress OK responses, 2=suppress error responses)\n QUIET = 'q',\n // Cursor movement policy (0=move cursor after image, 1=don't move cursor)\n CURSOR_MOVEMENT = 'C',\n // Z-index for image layering (negative = behind text, 0+ = on top)\n Z_INDEX = 'z',\n // Transmission medium (d=direct, f=file, t=temp file, s=shared memory)\n TRANSMISSION = 't',\n // Delete selector (a/A=all, i/I=by id, c/C=at cursor, etc.) \u2014 only used when a=d\n DELETE_SELECTOR = 'd',\n // Placement ID for targeting specific placements\n PLACEMENT_ID = 'p'\n}\n\n// Pixel format constants\nexport const enum KittyPixelConstants {\n BYTES_PER_PIXEL_RGB = 3,\n BYTES_PER_PIXEL_RGBA = 4,\n ALPHA_OPAQUE = 255\n}\n\n// Parsed Kitty graphics command.\nexport interface IKittyCommand {\n action?: string;\n format?: number;\n id?: number;\n imageNumber?: number;\n width?: number;\n height?: number;\n x?: number;\n y?: number;\n sourceWidth?: number;\n sourceHeight?: number;\n xOffset?: number;\n yOffset?: number;\n columns?: number;\n rows?: number;\n more?: number;\n quiet?: number;\n cursorMovement?: number;\n zIndex?: number;\n transmission?: string;\n deleteSelector?: string;\n placementId?: number;\n compression?: string;\n payload?: string;\n}\n\n// Pending chunked transmission state.\n// Stores metadata from the first chunk while accumulating decoded payload data.\nexport interface IPendingTransmission {\n // The parsed command from the first chunk (contains action, format, dimensions, etc.)\n cmd: IKittyCommand;\n // Decoder used across chunked payloads\n decoder: Base64Decoder;\n // Total encoded (base64) bytes received across all chunks - for size limit enforcement\n totalEncodedSize: number;\n // Whether any chunk has failed to decode\n decodeError: boolean;\n}\n\n// Stored Kitty image data.\nexport interface IKittyImageData {\n id: number;\n // Decoded image data stored as Blob (off JS heap) to avoid 2GB heap limit\n data: Blob;\n width: number;\n height: number;\n format: 24 | 32 | 100;\n compression?: string;\n}\n\n// Parses Kitty graphics control data into a command object.\nexport function parseKittyCommand(data: string): IKittyCommand {\n const cmd: IKittyCommand = {};\n const parts = data.split(',');\n\n for (const part of parts) {\n const eqIdx = part.indexOf('=');\n if (eqIdx === -1) continue;\n\n const key = part.substring(0, eqIdx);\n const value = part.substring(eqIdx + 1);\n\n // Handle string keys first\n if (key === KittyKey.ACTION) {\n cmd.action = value;\n continue;\n }\n if (key === KittyKey.COMPRESSION) {\n cmd.compression = value;\n continue;\n }\n if (key === KittyKey.TRANSMISSION) {\n cmd.transmission = value;\n continue;\n }\n if (key === KittyKey.DELETE_SELECTOR) {\n cmd.deleteSelector = value;\n continue;\n }\n const numValue = parseInt(value, 10);\n switch (key) {\n case KittyKey.FORMAT: cmd.format = numValue; break;\n case KittyKey.ID: cmd.id = numValue; break;\n case KittyKey.IMAGE_NUMBER: cmd.imageNumber = numValue; break;\n case KittyKey.WIDTH: cmd.width = numValue; break;\n case KittyKey.HEIGHT: cmd.height = numValue; break;\n case KittyKey.X_OFFSET: cmd.x = numValue; break;\n case KittyKey.Y_OFFSET: cmd.y = numValue; break;\n case KittyKey.SOURCE_WIDTH: cmd.sourceWidth = numValue; break;\n case KittyKey.SOURCE_HEIGHT: cmd.sourceHeight = numValue; break;\n case KittyKey.X_PLACEMENT_OFFSET: cmd.xOffset = numValue; break;\n case KittyKey.Y_PLACEMENT_OFFSET: cmd.yOffset = numValue; break;\n case KittyKey.COLUMNS: cmd.columns = numValue; break;\n case KittyKey.ROWS: cmd.rows = numValue; break;\n case KittyKey.MORE: cmd.more = numValue; break;\n case KittyKey.QUIET: cmd.quiet = numValue; break;\n case KittyKey.CURSOR_MOVEMENT: cmd.cursorMovement = numValue; break;\n case KittyKey.Z_INDEX: cmd.zIndex = numValue; break;\n case KittyKey.PLACEMENT_ID: cmd.placementId = numValue; break;\n }\n }\n\n return cmd;\n}\n", "/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageStorage } from '../ImageStorage';\nimport { ImageLayer, IAddImageOpts } from '../Types';\nimport { IKittyImageData } from './KittyGraphicsTypes';\n\n// Kitty-specific image storage controller.\n//\n// Wraps shared ImageStorage with kitty protocol semantics:\n// - tracks transmitted image payloads by kitty image id\n// - tracks kitty image id -> shared ImageStorage id mapping for displayed images\n// - mirrors shared-storage evictions into kitty maps\n// - applies protocol-level undisplayed-image eviction policy\nexport class KittyImageStorage implements IDisposable {\n private static readonly _maxStoredImages = 256;\n\n private _nextImageId = 1;\n private readonly _images: Map = new Map();\n // TODO: Support multiple placements per image. The kitty spec identifies\n // placements by an (image id, placement id) pair \u2014 same i + different p\n // values should coexist, and same i + same p should replace the prior\n // placement. Currently we track only one storage entry per kitty image id,\n // so multiple placements of the same image overwrite each other. Fixing\n // this requires changing these maps to Map>\n // (kittyId \u2192 placementId \u2192 storageId) and updating addImage/deleteById\n // accordingly. The underlying shared ImageStorage would also need to\n // support multiple entries per logical image.\n private readonly _kittyIdToStorageId: Map = new Map();\n private readonly _storageIdToKittyId: Map = new Map();\n\n private readonly _previousOnImageDeleted: ((storageId: number) => void) | undefined;\n private readonly _wrappedOnImageDeleted: (storageId: number) => void;\n private readonly _handleStorageImageDeleted = (storageId: number): void => {\n const kittyId = this._storageIdToKittyId.get(storageId);\n if (kittyId !== undefined) {\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n this._images.delete(kittyId);\n }\n };\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n\n constructor(\n private readonly _storage: ImageStorage\n ) {\n this._previousOnImageDeleted = this._storage.onImageDeleted;\n this._wrappedOnImageDeleted = (storageId: number) => {\n this._previousOnImageDeleted?.(storageId);\n this._handleStorageImageDeleted(storageId);\n };\n this._storage.onImageDeleted = this._wrappedOnImageDeleted;\n }\n\n public reset(): void {\n this._nextImageId = 1;\n this._images.clear();\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public dispose(): void {\n this.reset();\n if (this._storage.onImageDeleted === this._wrappedOnImageDeleted) {\n this._storage.onImageDeleted = this._previousOnImageDeleted;\n }\n }\n\n public storeImage(id: number | undefined, imageData: Omit): number {\n const imageId = id ?? this._nextImageId++;\n\n const oldStorageId = this._kittyIdToStorageId.get(imageId);\n if (oldStorageId !== undefined) {\n this._storage.deleteImage(oldStorageId);\n this._kittyIdToStorageId.delete(imageId);\n this._storageIdToKittyId.delete(oldStorageId);\n }\n\n if (!this._images.has(imageId) && this._images.size >= KittyImageStorage._maxStoredImages) {\n this._evictUndisplayedImages();\n }\n\n this._images.set(imageId, {\n ...imageData,\n id: imageId\n });\n return imageId;\n }\n\n public addImage(kittyId: number, image: HTMLCanvasElement | ImageBitmap, scrolling: boolean, layer: ImageLayer, zIndex: number): void {\n // Clean up stale reverse-mapping from a previous placement of the same\n // kitty image. The old shared-storage entry is kept (it may still be\n // visible on screen) but its reverse mapping is removed so that eviction\n // of the old entry won't incorrectly delete the kitty image data.\n const oldStorageId = this._kittyIdToStorageId.get(kittyId);\n if (oldStorageId !== undefined) {\n this._storageIdToKittyId.delete(oldStorageId);\n }\n this._addImageOpts.scrolling = scrolling;\n this._addImageOpts.layer = layer;\n this._addImageOpts.zIndex = zIndex;\n const storageId = this._storage.addImage(image, this._addImageOpts);\n this._kittyIdToStorageId.set(kittyId, storageId);\n this._storageIdToKittyId.set(storageId, kittyId);\n }\n\n public getImage(kittyId: number): IKittyImageData | undefined {\n return this._images.get(kittyId);\n }\n\n public deleteById(kittyId: number): void {\n this._images.delete(kittyId);\n const storageId = this._kittyIdToStorageId.get(kittyId);\n if (storageId !== undefined) {\n this._storage.deleteImage(storageId);\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n }\n }\n\n public deleteAll(): void {\n this._images.clear();\n for (const storageId of this._kittyIdToStorageId.values()) {\n this._storage.deleteImage(storageId);\n }\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public get images(): ReadonlyMap {\n return this._images;\n }\n\n public get kittyIdToStorageId(): ReadonlyMap {\n return this._kittyIdToStorageId;\n }\n\n public get lastImageId(): number {\n return this._nextImageId - 1;\n }\n\n private _evictUndisplayedImages(): void {\n for (const [kittyId] of this._images) {\n if (this._images.size <= KittyImageStorage._maxStoredImages / 2) {\n break;\n }\n if (!this._kittyIdToStorageId.has(kittyId)) {\n this._images.delete(kittyId);\n }\n }\n }\n}\n", "/**\n * Copyright (c) 2020, 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IDcsHandler, IParams, IImageAddonOptions, ITerminalExt, AttributeData, IResetHandler, ReadonlyColorSet } from './Types';\nimport { toRGBA8888, BIG_ENDIAN, PALETTE_ANSI_256, PALETTE_VT340_COLOR } from 'sixel/lib/Colors';\nimport { RGBA8888 } from 'sixel/lib/Types';\nimport { ImageRenderer } from './ImageRenderer';\n\nimport { DecoderAsync, Decoder } from 'sixel/lib/Decoder';\n\n// always free decoder ressources after decoding if it exceeds this limit\nconst MEM_PERMA_LIMIT = 4194304; // 1024 pixels * 1024 pixels * 4 channels = 4MB\n\n// custom default palette: VT340 (lower 16 colors) + ANSI256 (up to 256) + zeroed (up to 4096)\nconst DEFAULT_PALETTE = PALETTE_ANSI_256;\nDEFAULT_PALETTE.set(PALETTE_VT340_COLOR);\n\n\nexport class SixelHandler implements IDcsHandler, IResetHandler {\n private _size = 0;\n private _aborted = false;\n private _dec: Decoder | undefined;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _storage: SixelImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n DecoderAsync({\n memoryLimit: this._opts.pixelLimit * 4,\n palette: DEFAULT_PALETTE,\n paletteLimit: this._opts.sixelPaletteLimit\n }).then(d => this._dec = d);\n }\n\n public reset(): void {\n /**\n * reset sixel decoder to defaults:\n * - release all memory\n * - nullify palette (4096)\n * - apply default palette (256)\n */\n if (this._dec) {\n this._dec.release();\n // FIXME: missing interface on decoder to nullify full palette\n (this._dec as any)._palette.fill(0);\n this._dec.init(0, DEFAULT_PALETTE, this._opts.sixelPaletteLimit);\n }\n }\n\n public hook(params: IParams): void {\n this._size = 0;\n this._aborted = false;\n if (this._dec) {\n const fillColor = params.params[1] === 1 ? 0 : extractActiveBg(\n this._coreTerminal._core._inputHandler._curAttrData,\n this._coreTerminal._core._themeService?.colors);\n this._dec.init(fillColor, null, this._opts.sixelPaletteLimit);\n }\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted || !this._dec) {\n return;\n }\n this._size += end - start;\n if (this._size > this._opts.sixelSizeLimit) {\n console.warn(`SIXEL: too much data, aborting`);\n this._aborted = true;\n this._dec.release();\n return;\n }\n try {\n this._dec.decode(data, start, end);\n } catch (e) {\n console.warn(`SIXEL: error while decoding image - ${e}`);\n this._aborted = true;\n this._dec.release();\n }\n }\n\n public unhook(success: boolean): boolean | Promise {\n if (this._aborted || !success || !this._dec) {\n return true;\n }\n\n const width = this._dec.width;\n const height = this._dec.height;\n\n // partial fix for https://github.com/jerch/xterm-addon-image/issues/37\n if (!width || !height) {\n if (height) {\n this._storage.advanceCursor(height);\n }\n return true;\n }\n\n const canvas = ImageRenderer.createCanvas(undefined, width, height);\n canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8 as Uint8ClampedArray, width, height), 0, 0);\n if (this._dec.memoryUsage > MEM_PERMA_LIMIT) {\n this._dec.release();\n }\n this._storage.addImage(canvas);\n return true;\n }\n}\n\n\n/**\n * Some helpers to extract current terminal colors.\n */\n\n// get currently active background color from terminal\n// also respect INVERSE setting\nfunction extractActiveBg(attr: AttributeData, colors: ReadonlyColorSet | undefined): RGBA8888 {\n let bg = 0;\n if (!colors) {\n // FIXME: theme service is prolly not available yet,\n // happens if .open() was not called yet (bug in core?)\n return bg;\n }\n if (attr.isInverse()) {\n if (attr.isFgDefault()) {\n bg = convertLe(colors.foreground.rgba);\n } else if (attr.isFgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getFgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getFgColor()].rgba);\n }\n } else {\n if (attr.isBgDefault()) {\n bg = convertLe(colors.background.rgba);\n } else if (attr.isBgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getBgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getBgColor()].rgba);\n }\n }\n return bg;\n}\n\n// rgba values on the color managers are always in BE, thus convert to LE\nfunction convertLe(color: number): RGBA8888 {\n if (BIG_ENDIAN) return color;\n return (color & 0xFF) << 24 | (color >>> 8 & 0xFF) << 16 | (color >>> 16 & 0xFF) << 8 | color >>> 24 & 0xFF;\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { IImageAddonOptions, ITerminalExt, IAddImageOpts } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\n\n/**\n * Sixel-specific image storage controller.\n *\n * Wraps the shared ImageStorage with sixel protocol semantics:\n * - Cursor behavior governed by DECSET 80 (sixelScrolling option)\n * - advanceCursor for empty sixels carrying only height\n */\nexport class SixelImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'vt340' };\n constructor(\n private readonly _storage: ImageStorage,\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _terminal: ITerminalExt\n ) {}\n\n /**\n * Add a sixel image to storage.\n * Cursor behavior depends on the sixelScrolling option (DECSET 80).\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._addImageOpts.scrolling = this._opts.sixelScrolling;\n this._storage.addImage(img, this._addImageOpts);\n }\n\n /**\n * Only advance text cursor.\n * This is an edge case from empty sixels carrying only a height but no pixels.\n * Partially fixes https://github.com/jerch/xterm-addon-image/issues/37.\n */\n public advanceCursor(height: number): void {\n if (this._opts.sixelScrolling) {\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const rows = Math.ceil(height / cellSize.height);\n for (let i = 1; i < rows; ++i) {\n this._terminal._core._inputHandler.lineFeed();\n }\n }\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IAddImageOpts } from './Types';\nimport { ImageStorage } from './ImageStorage';\n\n/**\n * IIP (iTerm Image Protocol) specific image storage controller.\n *\n * Wraps the shared ImageStorage with IIP protocol semantics:\n * - Always uses scrolling mode (cursor advances with image)\n */\nexport class IIPImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n constructor(\n private readonly _storage: ImageStorage\n ) {}\n\n /**\n * Add an IIP image to storage.\n * Always uses scrolling mode \u2014 cursor advances past the image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._storage.addImage(img, this._addImageOpts);\n }\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport type { ITerminalAddon, IDisposable } from '@xterm/xterm';\nimport type { ImageAddon as IImageApi } from '@xterm/addon-image';\nimport { Emitter, type IEvent } from 'common/Event';\nimport { IIPHandler } from './IIPHandler';\nimport { ImageRenderer } from './ImageRenderer';\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { KittyGraphicsHandler } from './kitty/KittyGraphicsHandler';\nimport { KittyImageStorage } from './kitty/KittyImageStorage';\nimport { SixelHandler } from './SixelHandler';\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { ITerminalExt, IImageAddonOptions, IResetHandler } from './Types';\n\n\n/**\n * Document VT features provided by this addon.\n *\n * @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL \"SIXEL Graphics\" \"DCS Ps ; Ps ; Ps ; q Pt ST\" \"Draw SIXEL image.\"\n *\n * Sixel support is provided by the addon @xterm/addon-image with these limitations:\n * - immediate coloring (no shared palette, allows high color settings of `img2sixel`)\n * - max. palette size of 4096 colors\n * - max. pixel width of 16K\n * - max. 25 MB per sixel sequence\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] OSC 1337 \"iTerm2 Commands\" \"OSC 1337 ; Pt BEL\" \"Custom iTerm2 commands.\"\n *\n * Only the inline image protocol (IIP) is supported by the addon @xterm/addon-image with\n * the following limitations:\n * - sequence:\n * - format: `OSC 1337 ; File=inline=1 ; size= ; ... : BEL`\n * - size param must be set and payload may not exceed CEIL(size * 4 / 3)\n * - strict base64 handling as of RFC4648 \u00A74 (standard alphabet, optional padding,\n * no separator bytes allowed)\n * - supported params: size, name, width, height, preserveAspectRatio\n * - image formats: PNG, JPEG and GIF\n * - no animation support (renders first image of a GIF)\n * - no multipart support\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image)\n * and [iTerm2 IIP docs](https://iterm2.com/documentation-images.html) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] APC KITTY_GRAPHICS \"Kitty Graphics\" \"APC G Pt ST\" \"Kitty Graphics Protocol.\"\n *\n * Kitty graphics support is provided by the addon @xterm/addon-image.\n * Note that while basic image output already works, this is still work in progress.\n */\n\n// default values of addon ctor options\nconst DEFAULT_OPTIONS: IImageAddonOptions = {\n enableSizeReports: true,\n pixelLimit: 16777216, // limit to 4096 * 4096 pixels\n sixelSupport: true,\n sixelScrolling: true,\n sixelPaletteLimit: 4096,\n sixelSizeLimit: 33554432,\n storageLimit: 128,\n showPlaceholder: true,\n iipSupport: true,\n iipSizeLimit: 33554432,\n kittySupport: true,\n kittySizeLimit: 33554432\n};\n\n// max palette size supported by the sixel lib (compile time setting)\nconst MAX_SIXEL_PALETTE_SIZE = 4096;\n\n// definitions for _xtermGraphicsAttributes sequence\nconst enum GaItem {\n COLORS = 1,\n SIXEL_GEO = 2,\n REGIS_GEO = 3\n}\nconst enum GaAction {\n READ = 1,\n SET_DEFAULT = 2,\n SET = 3,\n READ_MAX = 4\n}\nconst enum GaStatus {\n SUCCESS = 0,\n ITEM_ERROR = 1,\n ACTION_ERROR = 2,\n FAILURE = 3\n}\n\n\nexport class ImageAddon implements ITerminalAddon, IImageApi {\n private _opts: IImageAddonOptions;\n private _defaultOpts: IImageAddonOptions;\n private _storage: ImageStorage | undefined;\n private _renderer: ImageRenderer | undefined;\n private _disposables: IDisposable[] = [];\n private _terminal: ITerminalExt | undefined;\n private _handlers: Map = new Map();\n private readonly _onImageAdded = new Emitter();\n public readonly onImageAdded: IEvent = this._onImageAdded.event;\n\n constructor(opts?: Partial) {\n this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);\n this._defaultOpts = Object.assign({}, DEFAULT_OPTIONS, opts);\n }\n\n public dispose(): void {\n for (const obj of this._disposables) {\n obj.dispose();\n }\n this._disposables.length = 0;\n this._handlers.clear();\n this._onImageAdded.dispose();\n }\n\n private _disposeLater(...args: IDisposable[]): void {\n for (const obj of args) {\n this._disposables.push(obj);\n }\n }\n\n public activate(terminal: ITerminalExt): void {\n this._terminal = terminal;\n\n // internal data structures\n this._renderer = new ImageRenderer(terminal);\n this._storage = new ImageStorage(terminal, this._renderer, this._opts);\n this._storage.onImageAdded = () => this._onImageAdded.fire();\n\n // enable size reports\n if (this._opts.enableSizeReports) {\n const windowOps = terminal.options.windowOptions ?? {};\n windowOps.getWinSizePixels = true;\n windowOps.getCellSizePixels = true;\n windowOps.getWinSizeChars = true;\n terminal.options.windowOptions = windowOps;\n }\n\n this._disposeLater(\n this._renderer,\n this._storage,\n\n // DECSET/DECRST/DA1/XTSMGRAPHICS handlers\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'h' }, params => this._decset(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'l' }, params => this._decrst(params)),\n terminal.parser.registerCsiHandler({ final: 'c' }, params => this._da1(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'S' }, params => this._xtermGraphicsAttributes(params)),\n\n // render hook\n terminal.onRender(range => this._storage?.render(range)),\n\n /**\n * reset handlers covered:\n * - DECSTR\n * - RIS\n * - Terminal.reset()\n */\n terminal.parser.registerCsiHandler({ intermediates: '!', final: 'p' }, () => this.reset()),\n terminal.parser.registerEscHandler({ final: 'c' }, () => this.reset()),\n terminal._core._inputHandler.onRequestReset(() => this.reset()),\n\n // wipe canvas and delete alternate images on buffer switch\n terminal.buffer.onBufferChange(() => this._storage?.wipeAlternate()),\n\n // extend images to the right on resize\n terminal.onResize(metrics => this._storage?.viewportResize(metrics))\n );\n\n // SIXEL handler\n if (this._opts.sixelSupport) {\n const sixelStorage = new SixelImageStorage(this._storage!, this._opts, this._renderer!, terminal);\n const sixelHandler = new SixelHandler(this._opts, sixelStorage, terminal);\n this._handlers.set('sixel', sixelHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerDcsHandler({ final: 'q' }, sixelHandler)\n );\n }\n\n // iTerm IIP handler\n if (this._opts.iipSupport) {\n const iipStorage = new IIPImageStorage(this._storage!);\n const iipHandler = new IIPHandler(this._opts, this._renderer!, iipStorage, terminal);\n this._handlers.set('iip', iipHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerOscHandler(1337, iipHandler)\n );\n }\n\n // Kitty graphics handler\n if (this._opts.kittySupport) {\n const kittyStorage = new KittyImageStorage(this._storage!);\n const kittyHandler = new KittyGraphicsHandler(this._opts, this._renderer!, kittyStorage, terminal);\n this._handlers.set('kitty', kittyHandler);\n this._disposeLater(\n kittyStorage,\n kittyHandler,\n terminal._core._inputHandler._parser.registerApcHandler({ final: 'G' }, kittyHandler)\n );\n }\n }\n\n // Note: storageLimit is skipped here to not intoduce a surprising side effect.\n public reset(): boolean {\n // reset options customizable by sequences to defaults\n this._opts.sixelScrolling = this._defaultOpts.sixelScrolling;\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n // also clear image storage\n this._storage?.reset();\n // reset protocol handlers\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return false;\n }\n\n public get storageLimit(): number {\n return this._storage?.getLimit() || -1;\n }\n\n public set storageLimit(limit: number) {\n this._storage?.setLimit(limit);\n this._opts.storageLimit = limit;\n }\n\n public get storageUsage(): number {\n if (this._storage) {\n return this._storage.getUsage();\n }\n return -1;\n }\n\n public get showPlaceholder(): boolean {\n return this._opts.showPlaceholder;\n }\n\n public set showPlaceholder(value: boolean) {\n this._opts.showPlaceholder = value;\n this._renderer?.showPlaceholder(value);\n }\n\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.getImageAtBufferCell(x, y);\n }\n\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.extractTileAtBufferCell(x, y);\n }\n\n private _report(s: string): void {\n this._terminal?._core.input(s, false);\n }\n\n private _decset(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = false;\n break;\n }\n }\n return false;\n }\n\n private _decrst(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = true;\n break;\n }\n }\n return false;\n }\n\n // overload DA to return something more appropriate\n private _da1(params: (number | number[])[]): boolean {\n if (params[0]) {\n return true;\n }\n // reported features:\n // 62 - VT220\n // 4 - SIXEL support\n // 9 - charsets\n // 22 - ANSI colors\n if (this._opts.sixelSupport) {\n this._report(`\\x1b[?62;4;9;22c`);\n return true;\n }\n return false;\n }\n\n /**\n * Implementation of xterm's graphics attribute sequence.\n *\n * Supported features:\n * - read/change palette limits (max 4096 by sixel lib)\n * - read SIXEL canvas geometry (reports current window canvas or\n * squared pixelLimit if canvas > pixel limit)\n *\n * Everything else is deactivated.\n */\n private _xtermGraphicsAttributes(params: (number | number[])[]): boolean {\n if (params.length < 2) {\n return true;\n }\n if (params[0] === GaItem.COLORS) {\n switch (params[1]) {\n case GaAction.READ:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n return true;\n case GaAction.SET_DEFAULT:\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n // also reset protocol handlers for now\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return true;\n case GaAction.SET:\n if (params.length > 2 && !(params[2] instanceof Array) && params[2] <= MAX_SIXEL_PALETTE_SIZE) {\n this._opts.sixelPaletteLimit = params[2];\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n } else {\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n }\n return true;\n case GaAction.READ_MAX:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${MAX_SIXEL_PALETTE_SIZE}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n if (params[0] === GaItem.SIXEL_GEO) {\n switch (params[1]) {\n // we only implement read and read_max here\n case GaAction.READ:\n let width = this._renderer?.dimensions?.css.canvas.width;\n let height = this._renderer?.dimensions?.css.canvas.height;\n if (!width || !height) {\n // for some reason we have no working image renderer\n // --> fallback to default cell size\n const cellSize = CELL_SIZE_DEFAULT;\n width = (this._terminal?.cols || 80) * cellSize.width;\n height = (this._terminal?.rows || 24) * cellSize.height;\n }\n if (width * height < this._opts.pixelLimit) {\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${width.toFixed(0)};${height.toFixed(0)}S`);\n } else {\n // if we overflow pixelLimit report that squared instead\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n }\n return true;\n case GaAction.READ_MAX:\n // read_max returns pixelLimit as square area\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n // exit with error on ReGIS or any other requests\n this._report(`\\x1b[?${params[0]};${GaStatus.ITEM_ERROR}S`);\n return true;\n }\n}\n"], - "mappings": ";;;;;;;;;;;;;;;;02BAYaA,EAAA,WAAa,IAAI,WAAW,IAAI,YAAY,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC,IAAM,IAClFA,EAAA,YACF,QAAQ,KAAK,6EAA6E,EAI5F,SAAgBC,GAAIC,EAAW,CAC7B,OAAOA,EAAI,GACb,CAFAF,EAAA,IAAAC,GAIA,SAAgBE,GAAMD,EAAW,CAC/B,OAAQA,IAAM,EAAK,GACrB,CAFAF,EAAA,MAAAG,GAIA,SAAgBC,GAAKF,EAAW,CAC9B,OAAQA,IAAM,GAAM,GACtB,CAFAF,EAAA,KAAAI,GAIA,SAAgBC,GAAMH,EAAW,CAC/B,OAAQA,IAAM,GAAM,GACtB,CAFAF,EAAA,MAAAK,GAQA,SAAgBC,EAAW,EAAWC,EAAWC,EAAWC,EAAY,IAAG,CACzE,QAASA,EAAI,MAAS,IAAMD,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O,CAAC,CAAC,MAAwBkB,CAAC,IAAIA,CAAC,GAAG,EACzD,GACT,QACE,YAAK,QAAQ,SAASlB,EAAO,CAAC,CAAC,KAA4B,EACpD,EACX,CAGF,YAAK,QAAQ,SAASA,EAAO,CAAC,CAAC,KAA0B,EAClD,EACT,CACF", - "names": ["exports", "red", "n", "green", "blue", "alpha", "toRGBA8888", "g", "b", "a", "fromRGBA8888", "color", "nearestColorIndex", "palette", "r", "min", "idx", "i", "dr", "dg", "db", "d", "clamp", "low", "high", "value", "h2c", "t1", "t2", "c", "HLStoRGB", "h", "l", "s", "v", "normalizeRGB", "normalizeHLS", "p", "require_lib", "__commonJSMin", "exports", "InWasm", "z", "s", "b", "r", "def", "t", "d", "m", "W", "e", "require_Base64Decoder_wasm", "__commonJSMin", "exports", "inwasm_runtime_1", "wasmDecode", "MAP", "el", "D", "i", "EMPTY", "Base64Decoder", "keepSize", "maxBytes", "initialBytes", "m", "bytes", "requested", "needed", "newSize", "addPages", "data", "require_QoiDecoder_wasm", "__commonJSMin", "exports", "inwasm_runtime_1", "wasmQoiDecode", "QoiDecoder", "keepSize", "d", "pixels", "ib", "dl", "bytes", "chunkP", "exports", "Colors_1", "wasm_1", "decodeBase64", "s", "bytestring", "result", "WASM_BYTES", "WASM_MODULE", "NULL_CANVAS", "CallbackProxy", "width", "mode", "DEFAULT_OPTIONS", "DecoderAsync", "opts", "cbProxy", "importObj", "inst", "Decoder", "exports", "_instance", "_cbProxy", "module", "pixels", "offset", "additionalPixels", "newCanvas", "adv", "remaining", "c", "i", "fillColor", "palette", "paletteLimit", "truncate", "data", "start", "end", "p", "length", "j", "currentWidth", "escape", "final", "finalOffset", "bw", "currentHeight", "decode", "dec", "decodeAsync", "toDisposable", "fn", "DisposableStore", "o", "d", "Disposable", "MutableDisposable", "value", "Emitter", "listener", "thisArgs", "disposables", "toDisposable", "entry", "result", "idx", "event", "listeners", "len", "EventUtils", "forward", "from", "to", "e", "map", "i", "any", "events", "store", "DisposableStore", "runAndSubscribe", "handler", "initial", "import_Colors", "ImageRenderer", "_ImageRenderer", "Disposable", "_terminal", "MutableDisposable", "parent", "option", "toDisposable", "localDocument", "width", "height", "canvas", "ctx", "buffer", "imgData", "img", "value", "start", "end", "layer", "y", "w", "h", "imgSpec", "tileId", "col", "row", "count", "cols", "sx", "sy", "dx", "dy", "finalWidth", "finalHeight", "spec", "currentWidth", "currentHeight", "originalWidth", "originalHeight", "renderer", "key", "screenElement", "bWidth", "blueprint", "d32", "black", "white", "shift", "offset", "x", "ctx2", "i", "bitmap", "CELL_SIZE_DEFAULT", "ExtendedAttrsImage", "_ExtendedAttrsImage", "ext", "urlId", "imageId", "tileId", "value", "val", "EMPTY_ATTRS", "ImageStorage", "_terminal", "_renderer", "_opts", "e", "spec", "storedPixels", "id", "zero", "img", "opts", "cellSize", "cols", "rows", "buffer", "termCols", "termRows", "originX", "originY", "offset", "tileCount", "row", "line", "col", "endMarker", "imgSpec", "range", "hasTopImages", "hasBottomImages", "start", "end", "drawCalls", "placeholderCalls", "startTile", "startCol", "count", "a", "b", "call", "metrics", "oldCol", "tilesPerRow", "hasData", "rightCol", "lastTile", "expandCol", "x", "y", "orig", "canvas", "ImageRenderer", "room", "used", "current", "old", "oldSpec", "imgId", "import_Base64Decoder", "import_QoiDecoder", "toStr", "data", "s", "i", "toInt", "v", "toSize", "toName", "bs", "b", "DECODERS", "FILE_MARKER", "MULTIPARTFILE_MARKER", "FILEPART_MARKER", "FILEEND_MARKER", "REPORTCELLSIZE_MARKER", "MAX_FIELDCHARS", "HeaderParser", "k", "start", "end", "state", "pos", "buffer", "c", "UNSUPPORTED_TYPE", "imageType", "d", "d32", "width", "height", "jpgSize", "dim", "pos", "limit", "i", "len", "blockLength", "DEFAULT_HEADER", "IIPHandler", "_opts", "_renderer", "_storage", "_coreTerminal", "HeaderParser", "maxEncodedBytes", "initialBytes", "Base64Decoder", "QoiDecoder", "data", "start", "end", "dataPos", "success", "seqType", "w", "CELL_SIZE_DEFAULT", "h", "scale", "report", "cond", "metrics", "UNSUPPORTED_TYPE", "imageType", "blob", "canvas", "ImageRenderer", "bm", "e", "cw", "ch", "width", "height", "rw", "rh", "wf", "hf", "f", "s", "total", "cdim", "import_Base64Decoder", "parseKittyCommand", "data", "cmd", "parts", "part", "eqIdx", "key", "value", "numValue", "DECODER_OK", "KittyGraphicsHandler", "_opts", "_renderer", "_kittyStorage", "_coreTerminal", "key", "pending", "data", "start", "end", "controlEnd", "i", "copyLength", "parseKittyCommand", "payloadStart", "pendingKey", "previousEncodedSize", "decoderToRelease", "Base64Decoder", "success", "cmd", "isMoreComing", "decodeError", "finalCmd", "decoder", "imageBytes", "result", "str", "bytes", "id", "image", "quiet", "format", "width", "height", "bytesPerPixel", "expectedBytes", "message", "placementId", "isOk", "pPart", "response", "bitmap", "cropX", "cropY", "cropW", "cropH", "maxCropW", "maxCropH", "finalCropW", "finalCropH", "cropped", "cw", "CELL_SIZE_DEFAULT", "ch", "imgCols", "imgRows", "w", "h", "buffer", "savedX", "savedY", "savedYbase", "layer", "scaled", "xOffset", "yOffset", "canvasW", "canvasH", "offsetCanvas", "ImageRenderer", "offsetCtx", "offsetBitmap", "zIndex", "scrolled", "e", "blob", "url", "img", "resolve", "reject", "canvas", "pixelCount", "src32", "dst32", "alignedPixels", "srcOffset", "dstOffset", "b0", "b1", "b2", "srcByte", "dstByte", "compressed", "ds", "writer", "chunks", "reader", "done", "value", "totalLength", "sum", "chunk", "offset", "_KittyImageStorage", "_storage", "storageId", "kittyId", "id", "imageData", "imageId", "oldStorageId", "image", "scrolling", "layer", "zIndex", "KittyImageStorage", "import_Colors", "import_Decoder", "MEM_PERMA_LIMIT", "DEFAULT_PALETTE", "SixelHandler", "_opts", "_storage", "_coreTerminal", "d", "params", "fillColor", "extractActiveBg", "data", "start", "end", "e", "success", "width", "height", "canvas", "ImageRenderer", "attr", "colors", "bg", "convertLe", "t", "color", "SixelImageStorage", "_storage", "_opts", "_renderer", "_terminal", "img", "height", "cellSize", "CELL_SIZE_DEFAULT", "rows", "i", "IIPImageStorage", "_storage", "img", "DEFAULT_OPTIONS", "MAX_SIXEL_PALETTE_SIZE", "ImageAddon", "opts", "Emitter", "DEFAULT_OPTIONS", "obj", "args", "terminal", "ImageRenderer", "ImageStorage", "windowOps", "params", "range", "metrics", "sixelStorage", "SixelImageStorage", "sixelHandler", "SixelHandler", "iipStorage", "IIPImageStorage", "iipHandler", "IIPHandler", "kittyStorage", "KittyImageStorage", "kittyHandler", "KittyGraphicsHandler", "handler", "limit", "value", "x", "y", "s", "i", "MAX_SIXEL_PALETTE_SIZE", "width", "height", "cellSize", "CELL_SIZE_DEFAULT"] -+ "sourcesContent": [null, "\"use strict\";\n/**\n * Copyright (c) 2022, 2026 Joerg Breitbart\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InWasm = InWasm;\nlet z = (s) => {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(s);\n if (typeof Buffer !== 'undefined')\n return Buffer.from(s, 'base64');\n const b = atob(s);\n const r = new Uint8Array(b.length);\n for (let i = 0; i < r.length; ++i)\n r[i] = b.charCodeAt(i);\n return r;\n};\nfunction InWasm(def) {\n if (def.d) {\n const { t, s, d } = def;\n let b;\n let m;\n const W = WebAssembly;\n if (t === 0 /* OutputType.INSTANCE */) {\n if (s)\n return (e) => new W.Instance(m || (m = new W.Module(b || (b = z(d)))), e);\n return (e) => m\n ? W.instantiate(m, e)\n : W.instantiate(b || (b = z(d)), e).then(r => (m = r.module) && r.instance);\n }\n if (t === 1 /* OutputType.MODULE */) {\n if (s)\n return () => m || (m = new W.Module(b || (b = z(d))));\n return () => m\n ? Promise.resolve(m)\n : W.compile(b || (b = z(d))).then(r => m = r);\n }\n if (s)\n return () => b || (b = z(d));\n return () => Promise.resolve(b || (b = z(d)));\n }\n if (typeof _wasmCtx === 'undefined')\n throw new Error('must run \"inwasm\"');\n _wasmCtx.add(def);\n}\n//# sourceMappingURL=index.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023, 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\n/**\n * wasm base64 decoder.\n */\nconst wasmDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#828e69684093b2c6:rdef-start:\"decode\"*/{s:1,t:0,d:'AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML'}/*inwasm#828e69684093b2c6:rdef-end:\"decode\"*/);\n// SIMD version (speedup ~1.4x, not covered by tests yet)\n/*\nconst wasmDecode = InWasm({\n name: 'decode',\n type: OutputType.INSTANCE,\n mode: OutputMode.SYNC,\n srctype: 'Clang-C',\n imports: {\n env: { memory: new WebAssembly.Memory({ initial: 1 }) }\n },\n exports: {\n dec: () => 0,\n end: () => 0\n },\n compile: {\n switches: ['-msimd128', '-Wl,-z,stack-size=0', '-Wl,--stack-first']\n },\n code: `\n #include \n typedef struct {\n unsigned int wp;\n unsigned int sp;\n unsigned int dp;\n unsigned int e_size;\n unsigned int dummy[4];\n unsigned char data[0];\n } State;\n\n unsigned int *D0 = (unsigned int *) ${P32.D0 * 4};\n unsigned int *D1 = (unsigned int *) ${P32.D1 * 4};\n unsigned int *D2 = (unsigned int *) ${P32.D2 * 4};\n unsigned int *D3 = (unsigned int *) ${P32.D3 * 4};\n State *state = (State *) ${P32.STATE * 4};\n\n #define packed_byte(x) wasm_i8x16_splat((char) x)\n #define packed_dword(x) wasm_i32x4_splat(x)\n #define masked(x, mask) wasm_v128_and(x, wasm_i32x4_splat(mask))\n\n __attribute__((noinline)) int dec() {\n unsigned int nsp = (state->wp - 1) & ~3;\n unsigned char *src = state->data + state->sp;\n unsigned char *end = state->data + nsp;\n unsigned char *dst = state->data + state->dp;\n unsigned int error = 0;\n\n v128_t err = wasm_i8x16_splat(0);\n unsigned char *end16 = state->data + (nsp & ~15);\n while (src < end16) {\n v128_t data = wasm_v128_load((v128_t *) src);\n\n // wasm-simd rewrite of http://0x80.pl/notesen/2016-01-17-sse-base64-decoding.html#vector-lookup-pshufb\n const v128_t higher_nibble = wasm_u32x4_shr(data, 4) & packed_byte(0x0f);\n const char linv = 1;\n const char hinv = 0;\n\n const v128_t lower_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n linv, linv, 0x2b, 0x30,\n 0x41, 0x50, 0x61, 0x70,\n linv, linv, linv, linv,\n linv, linv, linv, linv\n );\n const v128_t upper_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n hinv, hinv, 0x2b, 0x39,\n 0x4f, 0x5a, 0x6f, 0x7a,\n hinv, hinv, hinv, hinv,\n hinv, hinv, hinv, hinv\n );\n // the difference between the shift and lower bound\n const v128_t shift_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n 0x00, 0x00, 0x3e - 0x2b, 0x34 - 0x30,\n 0x00 - 0x41, 0x0f - 0x50, 0x1a - 0x61, 0x29 - 0x70,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00\n );\n\n const v128_t upper_bound = wasm_i8x16_swizzle(upper_bound_LUT, higher_nibble);\n const v128_t lower_bound = wasm_i8x16_swizzle(lower_bound_LUT, higher_nibble);\n\n const v128_t below = wasm_i8x16_lt(data, lower_bound);\n const v128_t above = wasm_i8x16_gt(data, upper_bound);\n const v128_t eq_2f = wasm_i8x16_eq(data, packed_byte(0x2f));\n\n // in_range = not (below or above) or eq_2f\n // outside = not in_range = below or above and not eq_2f (from deMorgan law)\n const v128_t outside = wasm_v128_andnot(eq_2f, above | below);\n err = wasm_v128_or(err, outside);\n\n const v128_t shift = wasm_i8x16_swizzle(shift_LUT, higher_nibble);\n const v128_t t0 = wasm_i8x16_add(data, shift);\n v128_t v = wasm_i8x16_add(t0, wasm_v128_and(eq_2f, packed_byte(-3)));\n\n // pack bytes\n const v128_t ca = masked(v, 0x003f003f);\n const v128_t db = masked(v, 0x3f003f00);\n const v128_t t00 = wasm_v128_or(wasm_u32x4_shr(db, 8), wasm_i32x4_shl(ca, 6));\n v128_t res = wasm_v128_or(wasm_u32x4_shr(t00, 16), wasm_i32x4_shl(t00, 12));\n res = wasm_i8x16_swizzle(res, wasm_i8x16_const(2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, 16, 16, 16, 16));\n\n wasm_v128_store((v128_t *) dst, res);\n dst += 12;\n src += 16;\n }\n //if (wasm_i8x16_bitmask(err) != 0) return -1;\n if (wasm_v128_any_true(err)) return -1;\n\n // operate on 4-byte blocks\n while (src < end) {\n error |= *((unsigned int *) dst) = D0[src[0]] | D1[src[1]] | D2[src[2]] | D3[src[3]];\n dst += 3;\n src += 4;\n }\n if (error >> 24) return -1;\n state->sp = nsp;\n state->dp = dst - state->data;\n return 0;\n }\n\n int end() {\n int rem = state->wp - state->sp;\n if (rem > 4 && dec()) return -1;\n rem = state->wp - state->sp;\n if (rem < 2) return -1;\n\n unsigned char *src = state->data + state->sp;\n if (rem == 4) {\n if (src[3] == 61) rem--;\n if (src[2] == 61) rem--;\n }\n unsigned int accu = D0[src[0]] | D1[src[1]];\n int dp = 1;\n if (rem > 2) {\n accu |= D2[src[2]];\n dp++;\n if (rem == 4) {\n accu |= D3[src[3]];\n dp++;\n }\n }\n if (accu >> 24) return -1;\n *((unsigned int *) (state->data + state->dp)) = accu;\n state->dp += dp;\n return 0;\n }\n `\n});\n*/\n// base64 map\nconst MAP = new Uint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n .split('')\n .map(el => el.charCodeAt(0)));\n// init decoder maps in LE order\nconst D = new Uint32Array(1024);\nD.fill(0xFF000000);\nfor (let i = 0; i < MAP.length; ++i)\n D[MAP[i]] = i << 2;\nfor (let i = 0; i < MAP.length; ++i)\n D[256 + MAP[i]] = i >> 4 | ((i << 4) & 0xFF) << 8;\nfor (let i = 0; i < MAP.length; ++i)\n D[512 + MAP[i]] = (i >> 2) << 8 | ((i << 6) & 0xFF) << 16;\nfor (let i = 0; i < MAP.length; ++i)\n D[768 + MAP[i]] = i << 16;\nconst EMPTY = new Uint8Array(0);\n/**\n * base64 stream decoder.\n *\n * Features / assumptions:\n * - lazy chunkwise decoding\n * - errors out on any non base64 chars (no support for NL formatted base64)\n * - decodes in wasm\n * - inplace decoding to save memory\n * - supports a keepSize for lazy memory release\n */\nclass Base64Decoder {\n /**\n * @param keepSize Keep the wasm instance below this limit when calling `release()`.\n * @param maxBytes Max allowed bytes to allocate.\n * @param initialBytes Initial bytes to allocate.\n */\n constructor(keepSize, maxBytes, initialBytes) {\n this._inst = null;\n this._ended = true;\n this._bytes = 0;\n this.keepSize = keepSize !== null && keepSize !== void 0 ? keepSize : 1048576 /* Bytes.KEEP */;\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : 4294901760 /* Bytes.MAX */;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : 32768 /* Bytes.INITIAL */;\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw new Error('invalid byte settings');\n }\n }\n /**\n * Currently decoded bytes (borrowed).\n * Must be accessed before calling `release` or `init`.\n */\n get data8() {\n return this._inst ? this._d.subarray(0, this._m32[1282 /* P32.STATE_DP */]) : EMPTY;\n }\n /**\n * Release memory conditionally based on `keepSize`.\n * If memory gets released, also the wasm instance will be freed and recreated on next `init`,\n * otherwise the instance will be reused.\n */\n release() {\n if (!this._inst)\n return;\n if (this._bytes > this.keepSize) {\n this._inst = this._m32 = this._d = this._mem = null;\n }\n else {\n this._m32[1280 /* P32.STATE_WP */] = 0;\n this._m32[1281 /* P32.STATE_SP */] = 0;\n this._m32[1282 /* P32.STATE_DP */] = 0;\n }\n }\n /**\n * Initializes the decoder for new base64 data.\n * Must be called before doing any decoding attempts.\n * The method will either spawn a new wasm instance or grow\n * the needed memory of an existing instance.\n * @param maxBytes Max allowed bytes to allocate (overwrites ctor value).\n * @param initialBytes Initial bytes to allocate (overwrites ctor value).\n */\n init(maxBytes, initialBytes) {\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : this.maxBytes;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : Math.min(this._bytes, this.maxBytes);\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw Error('invalid byte settings');\n }\n let m = this._m32;\n const bytes = this._bytes + 5152 /* Bytes._DATA_OFFSET */;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmDecode({ env: { memory: this._mem } });\n m = new Uint32Array(this._mem.buffer, 0);\n m.set(D, 256 /* P32.D0 */);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n m = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n m[1280 /* P32.STATE_WP */] = 0;\n m[1281 /* P32.STATE_SP */] = 0;\n m[1282 /* P32.STATE_DP */] = 0;\n this._m32 = m;\n this._ended = false;\n }\n /**\n * Realloc memory. Realloc only happens, if the requested\n * size doesn't fit in the current memory.\n * The new size will be capped by `maxBytes`.\n * @param requested Bytes to be stored.\n */\n _realloc(requested) {\n const needed = this._m32[1280 /* P32.STATE_WP */] + requested;\n if (this._bytes < needed) {\n if (needed > this.maxBytes) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n let newSize = this._bytes;\n while ((newSize *= 2) < needed) { }\n newSize = Math.min(newSize, this.maxBytes);\n if (newSize < needed) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n if (newSize + 5152 /* Bytes._DATA_OFFSET */ > this._mem.buffer.byteLength) {\n const addPages = Math.ceil((newSize + 5152 /* Bytes._DATA_OFFSET */ - this._mem.buffer.byteLength) / 65536);\n this._mem.grow(addPages);\n this._m32 = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n this._bytes = newSize;\n }\n return 0 /* DecodeStatus.OK */;\n }\n /**\n * Put bytes in `data` into the decoder.\n * Additionally decodes the payload, if it reached 2^17 bytes.\n * The return value indicates the type of issue.\n * @param data Bytes to be loaded.\n */\n put(data) {\n if (!this._inst || this._ended) {\n return -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n if (this._realloc(data.length)) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n const m = this._m32;\n this._d.set(data, m[1280 /* P32.STATE_WP */]);\n m[1280 /* P32.STATE_WP */] += data.length;\n // max chunk in input handler is 2^17, try to run in \"tandem mode\"\n return m[1280 /* P32.STATE_WP */] - m[1281 /* P32.STATE_SP */] >= 131072\n ? this._inst.exports.dec()\n : 0 /* DecodeStatus.OK */;\n }\n /**\n * End the current decoding.\n * Also decodes leftover payload from previous put calls.\n */\n end() {\n this._ended = true;\n return this._inst\n ? this._inst.exports.end()\n : -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n /**\n * Bytes loaded into the decoder.\n */\n get loadedBytes() {\n return this._inst\n ? this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n /**\n * Free bytes to feed to the decoder.\n */\n get freeBytes() {\n return this._inst\n ? this.maxBytes - this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n}\nexports.default = Base64Decoder;\n//# sourceMappingURL=Base64Decoder.wasm.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\nconst wasmQoiDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#459f9e1bfb80b1a8:rdef-start:\"qoi_decode\"*/{s:1,t:0,d:'AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=='}/*inwasm#459f9e1bfb80b1a8:rdef-end:\"qoi_decode\"*/);\nclass QoiDecoder {\n constructor(keepSize) {\n this.keepSize = keepSize;\n this.width = 0;\n this.height = 0;\n }\n decode(d) {\n this.width = d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7];\n this.height = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];\n const pixels = this.width * this.height;\n const ib = pixels * 4;\n const dl = d.length;\n /**\n * byte/offset calculation:\n * To save some memory we dont reserve full memory for decoded + encoded,\n * but place encoded at the end of decoded plus 50% security distance\n * to avoid reads before writes positions:\n *\n * encoded < decoded (good compression)\n * enc ####################\n * dec #######################################\n * ^ ^\n * DST_P CHUNK_P\n *\n * encoded > decoded (degenerated compression, should not happen)\n * enc ##############################\n * dec ####################\n * ^ ^\n * DST_P CHUNK_P\n *\n * There is still a chance for overlapping r/w positions in case the compressed\n * data has very different pixel progression, yet the 50% security distance\n * should deal with that, as QOI will bloat data by 25% at max (RGB -> OP byte + RGB).\n * Since we always assume RGBA at decoding stage, the possible bloat reduces to 20% at max.\n */\n const bytes = Math.max(ib, dl) + (Math.min(ib, dl) >> 1) + 4096;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmQoiDecode({ env: { memory: this._mem } });\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n this._d = null;\n }\n if (!this._d) {\n this._d = new Uint8Array(this._mem.buffer);\n }\n // put src data at the end of memory, also align to 256\n const chunkP = (this._mem.buffer.byteLength - dl) & ~0xFF;\n this._d.set(d, chunkP);\n this._inst.exports.dec(chunkP, dl, pixels);\n return this._d.subarray(1024 /* P8.DST_P */, 1024 /* P8.DST_P */ + ib);\n }\n release() {\n if (!this._inst)\n return;\n if (this._mem.buffer.byteLength > this.keepSize) {\n this._inst = this._d = this._mem = null;\n }\n }\n}\nexports.default = QoiDecoder;\n//# sourceMappingURL=QoiDecoder.wasm.js.map", null, null, "/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal lifecycle utilities for xterm.js core.\n * Simplified from VS Code's lifecycle.ts - no tracking/leak detection.\n */\n\nexport interface IDisposable {\n dispose(): void;\n}\n\nexport function toDisposable(fn: () => void): IDisposable {\n return { dispose: fn };\n}\n\nexport function dispose(disposable: T): T;\nexport function dispose(disposable: T | undefined): T | undefined;\nexport function dispose(disposables: T[]): T[];\nexport function dispose(arg: T | T[] | undefined): T | T[] | undefined {\n if (!arg) {\n return arg;\n }\n if (Array.isArray(arg)) {\n for (const d of arg) {\n d.dispose();\n }\n return [];\n }\n arg.dispose();\n return arg;\n}\n\nexport function combinedDisposable(...disposables: IDisposable[]): IDisposable {\n return toDisposable(() => dispose(disposables));\n}\n\nexport class DisposableStore implements IDisposable {\n private readonly _disposables = new Set();\n private _isDisposed = false;\n\n public get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n public add(o: T): T {\n if (this._isDisposed) {\n o.dispose();\n } else {\n this._disposables.add(o);\n }\n return o;\n }\n\n public dispose(): void {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n\n public clear(): void {\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n}\n\nexport abstract class Disposable implements IDisposable {\n public static readonly None: IDisposable = Object.freeze({ dispose() { } });\n\n protected readonly _store = new DisposableStore();\n\n public dispose(): void {\n this._store.dispose();\n }\n\n protected _register(o: T): T {\n return this._store.add(o);\n }\n}\n\nexport class MutableDisposable implements IDisposable {\n private _value: T | undefined;\n private _isDisposed = false;\n\n public get value(): T | undefined {\n return this._isDisposed ? undefined : this._value;\n }\n\n public set value(value: T | undefined) {\n if (this._isDisposed || value === this._value) {\n return;\n }\n this._value?.dispose();\n this._value = value;\n }\n\n public clear(): void {\n this.value = undefined;\n }\n\n public dispose(): void {\n this._isDisposed = true;\n this._value?.dispose();\n this._value = undefined;\n }\n}\n", "/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal event utilities for xterm.js core.\n * Simplified from VS Code's event.ts - no leak detection/profiling.\n */\n\nimport { IDisposable, DisposableStore, toDisposable } from './Lifecycle';\n\nexport interface IEvent {\n (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable;\n}\n\nexport class Emitter {\n private _listeners: { fn: (e: T) => any, thisArgs: any }[] = [];\n private _disposed = false;\n private _event: IEvent | undefined;\n\n public get event(): IEvent {\n if (this._event) {\n return this._event;\n }\n this._event = (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n if (this._disposed) {\n return toDisposable(() => {});\n }\n\n const entry = { fn: listener, thisArgs };\n this._listeners = this._listeners.slice();\n this._listeners.push(entry);\n\n const result = toDisposable(() => {\n const idx = this._listeners.indexOf(entry);\n if (idx !== -1) {\n this._listeners = this._listeners.slice();\n this._listeners.splice(idx, 1);\n }\n });\n\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(result);\n } else {\n disposables.add(result);\n }\n }\n\n return result;\n };\n return this._event;\n }\n\n public fire(event: T): void {\n if (this._disposed || !this._listeners.length) {\n return;\n }\n if (this._listeners.length === 1) {\n this._listeners[0].fn.call(this._listeners[0].thisArgs, event);\n return;\n }\n const listeners = this._listeners;\n for (let i = 0, len = listeners.length; i < len; ++i) {\n listeners[i].fn.call(listeners[i].thisArgs, event);\n }\n }\n\n public dispose(): void {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._listeners.length = 0;\n }\n}\n\nexport namespace EventUtils {\n export function forward(from: IEvent, to: Emitter): IDisposable {\n return from(e => to.fire(e));\n }\n\n export function map(event: IEvent, map: (i: I) => O): IEvent {\n return (listener: (e: O) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n return event(i => listener.call(thisArgs, map(i)), undefined, disposables);\n };\n }\n\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent {\n return (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n const store = new DisposableStore();\n for (const event of events) {\n store.add(event(e => listener.call(thisArgs, e)));\n }\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(store);\n } else {\n disposables.add(store);\n }\n }\n return store;\n };\n }\n\n export function runAndSubscribe(event: IEvent, handler: (e: T) => void, initial: T): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void, initial?: T): IDisposable {\n handler(initial);\n return event(e => handler(e));\n }\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { toRGBA8888 } from 'sixel/lib/Colors';\nimport { IDisposable } from '@xterm/xterm';\nimport { ICellSize, ImageLayer, ITerminalExt, IImageSpec, IRenderDimensions, IRenderService } from './Types';\nimport { Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';\n\nconst enum Constants {\n PLACEHOLDER_LENGTH = 4096,\n PLACEHOLDER_HEIGHT = 24\n}\n\n/**\n * ImageRenderer - terminal frontend extension:\n * - provide primitives for canvas, ImageData, Bitmap (static)\n * - add canvas layer to DOM (browser only for now)\n * - draw image tiles onRender\n */\nexport class ImageRenderer extends Disposable implements IDisposable {\n /** @deprecated Kept for backward compat \u2014 points to top layer canvas. */\n public get canvas(): HTMLCanvasElement | undefined { return this._layers.get('top')?.canvas; }\n private _layers = new Map();\n private _placeholder: HTMLCanvasElement | undefined;\n private _placeholderBitmap: ImageBitmap | undefined;\n private _optionsRefresh = this._register(new MutableDisposable());\n private _oldOpen: ((parent: HTMLElement) => void) | undefined;\n private _renderService: IRenderService | undefined;\n private _oldSetRenderer: ((renderer: any) => void) | undefined;\n\n // drawing primitive - canvas\n public static createCanvas(localDocument: Document | undefined, width: number, height: number): HTMLCanvasElement {\n /**\n * NOTE: We normally dont care, from which document the canvas\n * gets created, so we can fall back to global document,\n * if the terminal has no document associated yet.\n * This way early image loads before calling .open keep working\n * (still discouraged though, as the metrics will be screwed up).\n * Only the DOM output canvas should be on the terminal's document,\n * which gets explicitly checked in `insertLayerToDom`.\n */\n const canvas = (localDocument ?? document).createElement('canvas');\n canvas.width = width | 0;\n canvas.height = height | 0;\n return canvas;\n }\n\n // drawing primitive - ImageData with optional buffer\n public static createImageData(ctx: CanvasRenderingContext2D, width: number, height: number, buffer?: ArrayBuffer): ImageData {\n if (typeof ImageData !== 'function') {\n const imgData = ctx.createImageData(width, height);\n if (buffer) {\n imgData.data.set(new Uint8ClampedArray(buffer, 0, width * height * 4));\n }\n return imgData;\n }\n return buffer\n ? new ImageData(new Uint8ClampedArray(buffer, 0, width * height * 4), width, height)\n : new ImageData(width, height);\n }\n\n // drawing primitive - ImageBitmap\n public static createImageBitmap(img: ImageBitmapSource): Promise {\n if (typeof createImageBitmap !== 'function') {\n return Promise.resolve(undefined);\n }\n return createImageBitmap(img);\n }\n\n\n constructor(private _terminal: ITerminalExt) {\n super();\n this._oldOpen = this._terminal._core.open;\n this._terminal._core.open = (parent: HTMLElement): void => {\n this._oldOpen?.call(this._terminal._core, parent);\n this._open();\n };\n if (this._terminal._core.screenElement) {\n this._open();\n }\n // hack to spot fontSize changes\n this._optionsRefresh.value = this._terminal._core.optionsService.onOptionChange(option => {\n if (option === 'fontSize') {\n this.rescaleCanvas();\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n });\n this._register(toDisposable(() => {\n this.removeLayerFromDom();\n this.removeLayerFromDom('bottom');\n if (this._terminal._core && this._oldOpen) {\n this._terminal._core.open = this._oldOpen;\n this._oldOpen = undefined;\n }\n if (this._renderService && this._oldSetRenderer) {\n this._renderService.setRenderer = this._oldSetRenderer;\n this._oldSetRenderer = undefined;\n }\n this._renderService = undefined;\n this._layers.clear();\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }));\n }\n\n /**\n * Enable the placeholder.\n */\n public showPlaceholder(value: boolean): void {\n if (value) {\n if (!this._placeholder && this.cellSize.height !== -1) {\n this._createPlaceHolder(Math.max(this.cellSize.height + 1, Constants.PLACEHOLDER_HEIGHT));\n }\n } else {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n\n /**\n * Dimensions of the terminal.\n * Forwarded from internal render service.\n */\n public get dimensions(): IRenderDimensions | undefined {\n return this._terminal.dimensions;\n }\n\n /**\n * Current cell size (float).\n */\n public get cellSize(): ICellSize {\n return {\n width: this.dimensions?.css.cell.width || -1,\n height: this.dimensions?.css.cell.height || -1\n };\n }\n\n /**\n * Clear a region of the image layer canvas.\n */\n public clearLines(start: number, end: number, layer?: ImageLayer): void {\n const y = start * (this.dimensions?.css.cell.height || 0);\n const w = this.dimensions?.css.canvas.width || 0;\n const h = (end + 1 - start) * (this.dimensions?.css.cell.height || 0);\n if (!layer || layer === 'top') {\n this._layers.get('top')?.clearRect(0, y, w, h);\n }\n if (!layer || layer === 'bottom') {\n this._layers.get('bottom')?.clearRect(0, y, w, h);\n }\n }\n\n /**\n * Clear whole image canvas.\n */\n public clearAll(layer?: ImageLayer): void {\n if (!layer || layer === 'top') {\n const ctx = this._layers.get('top');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n if (!layer || layer === 'bottom') {\n const ctx = this._layers.get('bottom');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n }\n\n /**\n * Draw neighboring tiles on the image layer canvas.\n */\n public draw(imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get(imgSpec.layer);\n if (!ctx) {\n return;\n }\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const { width: sourceWidth, height: sourceHeight } = imgSpec.actualCellSize;\n const cols = Math.ceil(img.width / sourceWidth);\n\n const sx = (tileId % cols) * sourceWidth;\n const sy = Math.floor(tileId / cols) * sourceHeight;\n const dx = col * width;\n const dy = row * height;\n\n // safari bug: never access image source out of bounds\n const finalWidth = count * sourceWidth + sx > img.width ? img.width - sx : count * sourceWidth;\n const finalHeight = sy + sourceHeight > img.height ? img.height - sy : sourceHeight;\n\n // Floor all pixel offsets to get stable tile mapping without any overflows.\n // Note: For not pixel perfect aligned cells like in the DOM renderer\n // this will move a tile slightly to the top/left (subpixel range, thus ignore it).\n // FIX #34: avoid striping on displays with pixelDeviceRatio != 1 by ceiling height and width\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.ceil(finalWidth), Math.ceil(finalHeight),\n Math.floor(dx), Math.floor(dy), Math.ceil(finalWidth * width / sourceWidth), Math.ceil(finalHeight * height / sourceHeight)\n );\n }\n\n /**\n * Extract a single tile from an image.\n */\n public extractTile(imgSpec: IImageSpec, tileId: number): HTMLCanvasElement | undefined {\n const { width, height } = this.cellSize;\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const { width: sourceWidth, height: sourceHeight } = imgSpec.actualCellSize;\n const cols = Math.ceil(img.width / sourceWidth);\n const sx = (tileId % cols) * sourceWidth;\n const sy = Math.floor(tileId / cols) * sourceHeight;\n const finalWidth = sourceWidth + sx > img.width ? img.width - sx : sourceWidth;\n const finalHeight = sy + sourceHeight > img.height ? img.height - sy : sourceHeight;\n\n const canvas = ImageRenderer.createCanvas(this.document, Math.ceil(finalWidth * width / sourceWidth), Math.ceil(finalHeight * height / sourceHeight));\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.floor(finalWidth), Math.floor(finalHeight),\n 0, 0, canvas.width, canvas.height\n );\n return canvas;\n }\n }\n\n /**\n * Draw a line with placeholder on the image layer canvas.\n */\n public drawPlaceholder(col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get('top');\n if (ctx) {\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n if (!this._placeholder) {\n this._createPlaceHolder(Math.max(height + 1, Constants.PLACEHOLDER_HEIGHT));\n } else if (height >= this._placeholder!.height) {\n this._createPlaceHolder(height + 1);\n }\n if (!this._placeholder) return;\n ctx.drawImage(\n this._placeholderBitmap ?? this._placeholder!,\n col * width,\n (row * height) % 2 ? 0 : 1, // needs %2 offset correction\n width * count,\n height,\n col * width,\n row * height,\n width * count,\n height\n );\n }\n }\n\n /**\n * Rescale image layer canvas if needed.\n * Checked once from `ImageStorage.render`.\n */\n public rescaleCanvas(): void {\n const w = this.dimensions?.css.canvas.width || 0;\n const h = this.dimensions?.css.canvas.height || 0;\n for (const ctx of this._layers.values()) {\n if (ctx.canvas.width !== w || ctx.canvas.height !== h) {\n ctx.canvas.width = w;\n ctx.canvas.height = h;\n }\n }\n }\n\n /**\n * Rescale image in storage if needed.\n */\n private _rescaleImage(spec: IImageSpec, currentWidth: number, currentHeight: number): void {\n if (currentWidth === spec.actualCellSize.width && currentHeight === spec.actualCellSize.height) {\n return;\n }\n const { width: originalWidth, height: originalHeight } = spec.origCellSize;\n if (currentWidth === originalWidth && currentHeight === originalHeight) {\n spec.actual = spec.orig;\n spec.actualCellSize.width = originalWidth;\n spec.actualCellSize.height = originalHeight;\n return;\n }\n const scaledWidth = Math.ceil(spec.orig!.width * currentWidth / originalWidth);\n const scaledHeight = Math.ceil(spec.orig!.height * currentHeight / originalHeight);\n // Upscale visible tiles directly; a full zoomed copy can dwarf the image budget.\n if (scaledWidth * scaledHeight > spec.orig!.width * spec.orig!.height) {\n spec.actual = spec.orig;\n spec.actualCellSize.width = originalWidth;\n spec.actualCellSize.height = originalHeight;\n return;\n }\n const canvas = ImageRenderer.createCanvas(this.document, scaledWidth, scaledHeight);\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(spec.orig!, 0, 0, canvas.width, canvas.height);\n spec.actual = canvas;\n spec.actualCellSize.width = currentWidth;\n spec.actualCellSize.height = currentHeight;\n }\n }\n\n /**\n * Lazy init for the renderer.\n */\n private _open(): void {\n this._renderService = this._terminal._core._renderService;\n this._oldSetRenderer = this._renderService.setRenderer.bind(this._renderService);\n this._renderService.setRenderer = (renderer: any) => {\n for (const key of [...this._layers.keys()]) {\n this.removeLayerFromDom(key);\n }\n this._oldSetRenderer?.call(this._renderService, renderer);\n };\n }\n\n public insertLayerToDom(layer: ImageLayer = 'top'): void {\n // make sure that the terminal is attached to a document and to DOM\n if (!this.document || !this._terminal._core.screenElement) {\n console.warn('image addon: cannot insert output canvas to DOM, missing document or screenElement');\n return;\n }\n if (this._layers.has(layer)) {\n return;\n }\n const canvas = ImageRenderer.createCanvas(\n this.document, this.dimensions?.css.canvas.width || 0,\n this.dimensions?.css.canvas.height || 0\n );\n canvas.classList.add(`xterm-image-layer-${layer}`);\n const screenElement = this._terminal._core.screenElement;\n // Use isolation to create a stacking context without overriding z-index,\n // which would conflict with integrators (e.g. VS Code) that set their\n // own z-index on the screen element.\n screenElement.style.isolation = 'isolate';\n if (layer === 'bottom') {\n // Use z-index:-1 so it paints behind non-positioned text elements.\n // The screen element needs to be a stacking context (via isolation)\n // to contain the negative z-index, otherwise it would go behind the\n // entire terminal.\n canvas.style.zIndex = '-1';\n screenElement.insertBefore(canvas, screenElement.firstChild);\n } else {\n // Explicit z-index ensures the image canvas reliably stacks above\n // the text layer (DOM renderer rows). z-index: 0 is below the\n // selection overlay (z-index: 1).\n canvas.style.zIndex = '0';\n screenElement.appendChild(canvas);\n }\n const ctx = canvas.getContext('2d', { alpha: true });\n if (!ctx) {\n canvas.remove();\n return;\n }\n this._layers.set(layer, ctx);\n this.clearAll(layer);\n }\n\n public removeLayerFromDom(layer: ImageLayer = 'top'): void {\n const ctx = this._layers.get(layer);\n if (ctx) {\n ctx.canvas.remove();\n this._layers.delete(layer);\n }\n }\n\n public hasLayer(layer: ImageLayer): boolean {\n return this._layers.has(layer);\n }\n\n private _createPlaceHolder(height: number = Constants.PLACEHOLDER_HEIGHT): void {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n\n // create blueprint to fill placeholder with\n const bWidth = 32; // must be 2^n\n const blueprint = ImageRenderer.createCanvas(this.document, bWidth, height);\n const ctx = blueprint.getContext('2d', { alpha: false });\n if (!ctx) return;\n const imgData = ImageRenderer.createImageData(ctx, bWidth, height);\n const d32 = new Uint32Array(imgData.data.buffer);\n const black = toRGBA8888(0, 0, 0);\n const white = toRGBA8888(255, 255, 255);\n d32.fill(black);\n for (let y = 0; y < height; ++y) {\n const shift = y % 2;\n const offset = y * bWidth;\n for (let x = 0; x < bWidth; x += 2) {\n d32[offset + x + shift] = white;\n }\n }\n ctx.putImageData(imgData, 0, 0);\n\n // create placeholder line, width aligned to blueprint width\n const width = (screen.width + bWidth - 1) & ~(bWidth - 1) || Constants.PLACEHOLDER_LENGTH;\n this._placeholder = ImageRenderer.createCanvas(this.document, width, height);\n const ctx2 = this._placeholder.getContext('2d', { alpha: false });\n if (!ctx2) {\n this._placeholder = undefined;\n return;\n }\n for (let i = 0; i < width; i += bWidth) {\n ctx2.drawImage(blueprint, i, 0);\n }\n const placeholder = this._placeholder;\n ImageRenderer.createImageBitmap(placeholder).then(bitmap => {\n if (this._placeholder !== placeholder) bitmap?.close();\n else this._placeholderBitmap = bitmap;\n }).catch(() => {});\n }\n\n public get document(): Document | undefined {\n return this._terminal._core._coreBrowserService?.window.document;\n }\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageRenderer } from './ImageRenderer';\nimport {\n ITerminalExt, IExtendedAttrsImage, IImageAddonOptions, IImageSpec,\n IBufferLineExt, BgFlags, Cell, Content, ICellSize, ExtFlags, Attributes,\n UnderlineStyle, IAddImageOpts\n} from './Types';\n\n\n// fallback default cell size\nexport const CELL_SIZE_DEFAULT: ICellSize = {\n width: 7,\n height: 14\n};\n\n/**\n * Extend extended attribute to also hold image tile information.\n *\n * Object definition is copied from base repo to fully mimick its behavior.\n * Image data is added as additional public properties `imageId` and `tileId`.\n */\nclass ExtendedAttrsImage implements IExtendedAttrsImage {\n private _ext: number = 0;\n public get ext(): number {\n if (this._urlId) {\n return (\n (this._ext & ~ExtFlags.UNDERLINE_STYLE) |\n (this.underlineStyle << 26)\n );\n }\n return this._ext;\n }\n public set ext(value: number) { this._ext = value; }\n\n public get underlineStyle(): UnderlineStyle {\n // Always return the URL style if it has one\n if (this._urlId) {\n return UnderlineStyle.DASHED;\n }\n return (this._ext & ExtFlags.UNDERLINE_STYLE) >> 26;\n }\n public set underlineStyle(value: UnderlineStyle) {\n this._ext &= ~ExtFlags.UNDERLINE_STYLE;\n this._ext |= (value << 26) & ExtFlags.UNDERLINE_STYLE;\n }\n\n public get underlineColor(): number {\n return this._ext & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n public set underlineColor(value: number) {\n this._ext &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n this._ext |= value & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n\n public get underlineVariantOffset(): number {\n const val = (this._ext & ExtFlags.VARIANT_OFFSET) >> 29;\n if (val < 0) {\n return val ^ 0xFFFFFFF8;\n }\n return val;\n }\n public set underlineVariantOffset(value: number) {\n this._ext &= ~ExtFlags.VARIANT_OFFSET;\n this._ext |= (value << 29) & ExtFlags.VARIANT_OFFSET;\n }\n\n private _urlId: number = 0;\n public get urlId(): number {\n return this._urlId;\n }\n public set urlId(value: number) {\n this._urlId = value;\n }\n\n constructor(\n ext: number = 0,\n urlId: number = 0,\n public imageId = -1,\n public tileId = -1\n ) {\n this._ext = ext;\n this._urlId = urlId;\n }\n\n public clone(): IExtendedAttrsImage {\n /**\n * Technically we dont need a clone variant of ExtendedAttrsImage,\n * as we never clone a cell holding image data.\n * Note: Clone is only meant to be used by the InputHandler for\n * sticky attributes, which is never the case for image data.\n * We still provide a proper clone method to reflect the full ext attr\n * state in case there are future use cases for clone.\n */\n return new ExtendedAttrsImage(this._ext, this._urlId, this.imageId, this.tileId);\n }\n\n public isEmpty(): boolean {\n return this.underlineStyle === UnderlineStyle.NONE && this._urlId === 0 && this.imageId === -1;\n }\n}\nconst EMPTY_ATTRS = new ExtendedAttrsImage();\n\n\n/**\n * ImageStorage - extension of CoreTerminal:\n * - hold image data\n * - write/read image data to/from buffer\n *\n * TODO: image composition for overwrites\n */\nexport class ImageStorage implements IDisposable {\n // storage\n private _images: Map = new Map();\n // last used id\n private _lastId = 0;\n // last evicted id\n private _lowestId = 0;\n // whether a full clear happened before\n private _fullyCleared = false;\n // whether render should do a full clear\n private _needsFullClear = false;\n // hard limit of stored pixels (fallback limit of 10 MB)\n private _pixelLimit: number = 2500000;\n\n private _viewportMetrics: { cols: number, rows: number };\n public onImageAdded: (() => void) | undefined;\n public onImageDeleted: ((storageId: number) => void) | undefined;\n\n constructor(\n private _terminal: ITerminalExt,\n private _renderer: ImageRenderer,\n private _opts: IImageAddonOptions\n ) {\n try {\n this.setLimit(this._opts.storageLimit);\n } catch (e: unknown) {\n if (e instanceof Error) {\n console.error(e.message);\n }\n console.warn(`storageLimit is set to ${this.getLimit()} MB`);\n }\n this._viewportMetrics = {\n cols: this._terminal.cols,\n rows: this._terminal.rows\n };\n }\n\n public dispose(): void {\n this.reset();\n }\n\n public reset(): void {\n for (const spec of this._images.values()) {\n spec.marker?.dispose();\n }\n // NOTE: marker.dispose above already calls ImageBitmap.close\n // therefore we can just wipe the map here\n this._images.clear();\n this._renderer.clearAll();\n }\n\n public getLimit(): number {\n return this._pixelLimit * 4 / 1000000;\n }\n\n public setLimit(value: number): void {\n if (value < 0.5 || value > 1000) {\n throw RangeError('invalid storageLimit, should be at least 0.5 MB and not exceed 1G');\n }\n this._pixelLimit = (value / 4 * 1000000) >>> 0;\n this._evictOldest(0);\n }\n\n public getUsage(): number {\n return this._getStoredPixels() * 4 / 1000000;\n }\n\n private _getStoredPixels(): number {\n let storedPixels = 0;\n for (const spec of this._images.values()) {\n if (spec.orig) {\n storedPixels += spec.orig.width * spec.orig.height;\n if (spec.actual && spec.actual !== spec.orig) {\n storedPixels += spec.actual.width * spec.actual.height;\n }\n }\n }\n return storedPixels;\n }\n\n private _delImg(id: number): void {\n const spec = this._images.get(id);\n if (!spec) return;\n this._images.delete(id);\n // FIXME: really ugly workaround to get bitmaps deallocated :(\n if (window.ImageBitmap && spec.orig instanceof ImageBitmap) {\n spec.orig.close();\n }\n this.onImageDeleted?.(id);\n }\n\n /**\n * Wipe canvas and images on alternate buffer.\n */\n public wipeAlternate(): void {\n // remove all alternate tagged images\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate') {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n // mark canvas to be wiped on next render\n this._needsFullClear = true;\n this._fullyCleared = false;\n }\n\n /**\n * Delete an image by its internal storage ID.\n * Used by protocols that support explicit deletion (e.g. Kitty a=d).\n */\n public deleteImage(id: number): void {\n const spec = this._images.get(id);\n if (spec) {\n spec.marker?.dispose();\n this._delImg(id);\n }\n }\n\n /**\n * Method to add an image to the storage.\n * @param img - The image to add (canvas or bitmap).\n * @param opts - Options for addImage:\n * - scrolling: When true, cursor advances with the image.\n * When false, image is placed at ORIGIN and cursor does not move.\n * - layer: Which canvas layer to render on ('top' or 'bottom').\n * - zIndex: Z-index for image layering within the same layer.\n * - cursorPos: 'vt340' for bottom-left, 'iip' for bottom.right.\n * @returns The internal image ID assigned to the stored image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap, opts: IAddImageOpts): number {\n // never allow storage to exceed memory limit\n this._evictOldest(img.width * img.height);\n\n // calc rows x cols needed to display the image\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const cols = Math.ceil(img.width / cellSize.width);\n const rows = Math.ceil(img.height / cellSize.height);\n\n const imageId = ++this._lastId;\n\n const buffer = this._terminal._core.buffer;\n const termCols = this._terminal.cols;\n const termRows = this._terminal.rows;\n const originX = buffer.x;\n const originY = buffer.y;\n let offset = originX;\n let tileCount = 0;\n\n if (!opts.scrolling) {\n buffer.x = 0;\n buffer.y = 0;\n offset = 0;\n }\n\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(buffer.y + buffer.ybase);\n for (let col = 0; col < cols; ++col) {\n if (offset + col >= termCols) break;\n this._writeToCell(line as IBufferLineExt, offset + col, imageId, row * cols + col);\n tileCount++;\n }\n if (opts.scrolling) {\n if (row < rows - 1) this._terminal._core._inputHandler.lineFeed();\n } else {\n if (++buffer.y >= termRows) break;\n }\n buffer.x = offset;\n }\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n\n // cursor positioning modes\n if (opts.scrolling) {\n if (opts.cursorPos === 'iip') {\n buffer.x = Math.min(offset + cols, termCols);\n } else {\n buffer.x = offset;\n }\n } else {\n buffer.x = originX;\n buffer.y = originY;\n }\n\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.tileCount < 1) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n\n // eviction marker:\n // delete the image when the marker gets disposed\n const endMarker = this._terminal.registerMarker(0);\n endMarker?.onDispose(() => {\n const spec = this._images.get(imageId);\n if (spec) {\n this._delImg(imageId);\n }\n });\n\n // since markers do not work on alternate for some reason,\n // we evict images here manually\n if (this._terminal.buffer.active.type === 'alternate') {\n this._evictOnAlternate();\n }\n\n // create storage entry\n const imgSpec: IImageSpec = {\n orig: img,\n origCellSize: cellSize,\n actual: img,\n actualCellSize: { ...cellSize }, // clone needed, since later modified\n marker: endMarker || undefined,\n tileCount,\n bufferType: this._terminal.buffer.active.type,\n layer: opts.layer,\n zIndex: opts.zIndex\n };\n\n // finally add the image\n this._images.set(imageId, imgSpec);\n this.onImageAdded?.();\n return imageId;\n }\n\n\n /**\n * Render method. Collects buffer information and triggers\n * canvas updates.\n */\n // TODO: Should we move this to the ImageRenderer?\n public render(range: { start: number, end: number }): void {\n // Determine which layers have images\n let hasTopImages = false;\n let hasBottomImages = false;\n for (const spec of this._images.values()) {\n if (spec.layer === 'bottom') {\n hasBottomImages = true;\n } else {\n hasTopImages = true;\n }\n if (hasTopImages && hasBottomImages) break;\n }\n\n // Lazily insert layers that are needed\n if (hasTopImages && !this._renderer.hasLayer('top')) {\n this._renderer.insertLayerToDom('top');\n if (!this._renderer.hasLayer('top')) return;\n }\n if (hasBottomImages && !this._renderer.hasLayer('bottom')) {\n this._renderer.insertLayerToDom('bottom');\n }\n\n // rescale if needed\n this._renderer.rescaleCanvas();\n\n // exit early if we dont have any images to test for\n if (!this._images.size) {\n if (!this._fullyCleared) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n if (this._renderer.hasLayer('top')) {\n this._renderer.removeLayerFromDom('top');\n }\n if (this._renderer.hasLayer('bottom')) {\n this._renderer.removeLayerFromDom('bottom');\n }\n return;\n }\n\n // Remove layers no longer needed\n if (!hasTopImages && this._renderer.hasLayer('top')) {\n this._renderer.clearAll('top');\n this._renderer.removeLayerFromDom('top');\n }\n if (!hasBottomImages && this._renderer.hasLayer('bottom')) {\n this._renderer.clearAll('bottom');\n this._renderer.removeLayerFromDom('bottom');\n }\n\n // buffer switches force a full clear\n if (this._needsFullClear) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n\n const { start, end } = range;\n const buffer = this._terminal._core.buffer;\n const cols = this._terminal._core.cols;\n\n // clear drawing area\n this._renderer.clearLines(start, end);\n\n // Collect draw calls so we can sort by z-index (lower z drawn first).\n const drawCalls: { imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number }[] = [];\n const placeholderCalls: { col: number, row: number, count: number }[] = [];\n\n // walk all cells in viewport and collect tiles found\n for (let row = start; row <= end; ++row) {\n const line = buffer.lines.get(row + buffer.ydisp) as IBufferLineExt;\n if (!line) return;\n for (let col = 0; col < cols; ++col) {\n if (line.getBg(col) & BgFlags.HAS_EXTENDED) {\n let e: IExtendedAttrsImage = line._extendedAttrs[col] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (e.tileId !== -1) {\n const startTile = e.tileId;\n const startCol = col;\n let count = 1;\n /**\n * merge tiles to the right into a single draw call, if:\n * - not at end of line\n * - cell has same image id\n * - cell has consecutive tile id\n */\n while (\n ++col < cols\n && (line.getBg(col) & BgFlags.HAS_EXTENDED)\n && (e = line._extendedAttrs[col] ?? EMPTY_ATTRS)\n && (e.imageId === imageId)\n && (e.tileId === startTile + count)\n ) {\n count++;\n }\n col--;\n if (imgSpec) {\n if (imgSpec.actual) {\n drawCalls.push({ imgSpec, tileId: startTile, col: startCol, row, count });\n }\n } else if (this._opts.showPlaceholder) {\n placeholderCalls.push({ col: startCol, row, count });\n }\n this._fullyCleared = false;\n }\n }\n }\n }\n\n // Sort by z-index so lower z draws first (higher z renders on top)\n drawCalls.sort((a, b) => a.imgSpec.zIndex - b.imgSpec.zIndex);\n\n // Draw placeholders first (lowest priority)\n for (const call of placeholderCalls) {\n this._renderer.drawPlaceholder(call.col, call.row, call.count);\n }\n\n // Draw images in z-index order\n for (const call of drawCalls) {\n this._renderer.draw(call.imgSpec, call.tileId, call.col, call.row, call.count);\n }\n }\n\n public viewportResize(metrics: { cols: number, rows: number }): void {\n // exit early if we have nothing in storage\n if (!this._images.size) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // handle only viewport width enlargements, exit all other cases\n // TODO: needs patch for tile counter\n if (this._viewportMetrics.cols >= metrics.cols) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // walk scrollbuffer at old col width to find all possible expansion matches\n const buffer = this._terminal._core.buffer;\n const rows = buffer.lines.length;\n const oldCol = this._viewportMetrics.cols - 1;\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(row) as IBufferLineExt;\n if (line.getBg(oldCol) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[oldCol] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (!imgSpec) {\n continue;\n }\n // found an image tile at oldCol, check if it qualifies for right exapansion\n const tilesPerRow = Math.ceil((imgSpec.actual?.width || 0) / imgSpec.actualCellSize.width);\n if ((e.tileId % tilesPerRow) + 1 >= tilesPerRow) {\n continue;\n }\n // expand only if right side is empty (nothing got wrapped from below)\n let hasData = false;\n for (let rightCol = oldCol + 1; rightCol > metrics.cols; ++rightCol) {\n if (line._data[rightCol * Cell.SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK) {\n hasData = true;\n break;\n }\n }\n if (hasData) {\n continue;\n }\n // do right expansion on terminal buffer\n const end = Math.min(metrics.cols, tilesPerRow - (e.tileId % tilesPerRow) + oldCol);\n let lastTile = e.tileId;\n for (let expandCol = oldCol + 1; expandCol < end; ++expandCol) {\n this._writeToCell(line as IBufferLineExt, expandCol, imageId, ++lastTile);\n imgSpec.tileCount++;\n }\n }\n }\n // store new viewport metrics\n this._viewportMetrics = metrics;\n }\n\n /**\n * Retrieve original canvas at buffer position.\n */\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1) {\n const orig = this._images.get(e.imageId)?.orig;\n if (window.ImageBitmap && orig instanceof ImageBitmap) {\n const canvas = ImageRenderer.createCanvas(window.document, orig.width, orig.height);\n canvas.getContext('2d')?.drawImage(orig, 0, 0, orig.width, orig.height);\n return canvas;\n }\n return orig as HTMLCanvasElement;\n }\n }\n }\n\n /**\n * Extract active single tile at buffer position.\n */\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1 && e.tileId !== -1) {\n const spec = this._images.get(e.imageId);\n if (spec) {\n return this._renderer.extractTile(spec, e.tileId);\n }\n }\n }\n }\n\n // TODO: Do we need some blob offloading tricks here to avoid early eviction?\n // also see https://stackoverflow.com/questions/28307789/is-there-any-limitation-on-javascript-max-blob-size\n private _evictOldest(room: number): number {\n const used = this._getStoredPixels();\n let current = used;\n while (this._pixelLimit < current + room && this._images.size) {\n const spec = this._images.get(++this._lowestId);\n if (spec && spec.orig) {\n current -= spec.orig.width * spec.orig.height;\n if (spec.actual && spec.orig !== spec.actual) {\n current -= spec.actual.width * spec.actual.height;\n }\n spec.marker?.dispose();\n this._delImg(this._lowestId);\n }\n }\n return used - current;\n }\n\n private _writeToCell(line: IBufferLineExt, x: number, imageId: number, tileId: number): void {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const old = line._extendedAttrs[x];\n if (old) {\n if (old.imageId !== undefined) {\n // found an old ExtendedAttrsImage, since we know that\n // they are always isolated instances (single cell usage),\n // we can re-use it and just update their id entries\n const oldSpec = this._images.get(old.imageId);\n if (oldSpec) {\n // early eviction for in-viewport overwrites\n oldSpec.tileCount--;\n }\n old.imageId = imageId;\n old.tileId = tileId;\n return;\n }\n // found a plain ExtendedAttrs instance, clone it to new entry\n line._extendedAttrs[x] = new ExtendedAttrsImage(old.ext, old.urlId, imageId, tileId);\n return;\n }\n }\n // fall-through: always create new ExtendedAttrsImage entry\n line._data[x * Cell.SIZE + Cell.BG] |= BgFlags.HAS_EXTENDED;\n line._extendedAttrs[x] = new ExtendedAttrsImage(0, 0, imageId, tileId);\n }\n\n private _evictOnAlternate(): void {\n // nullify tile count of all images on alternate buffer\n for (const spec of this._images.values()) {\n if (spec.bufferType === 'alternate') {\n spec.tileCount = 0;\n }\n }\n // re-count tiles on whole buffer\n const buffer = this._terminal._core.buffer;\n for (let y = 0; y < this._terminal.rows; ++y) {\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (!line) {\n continue;\n }\n for (let x = 0; x < this._terminal.cols; ++x) {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const imgId = line._extendedAttrs[x]?.imageId;\n if (imgId) {\n const spec = this._images.get(imgId);\n if (spec) {\n spec.tileCount++;\n }\n }\n }\n }\n }\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate' && !spec.tileCount) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IImageAddonOptions, IOscHandler, IResetHandler, ITerminalExt } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { CELL_SIZE_DEFAULT } from './ImageStorage';\nimport Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport QoiDecoder from 'xterm-wasm-parts/lib/qoi/QoiDecoder.wasm';\nimport { HeaderParser, IHeaderFields, HeaderState, SequenceType } from './IIPHeaderParser';\nimport { imageType, UNSUPPORTED_TYPE } from './IIPMetrics';\n\n// Local const enum mirror - esbuild can't inline const enums from external packages\nconst enum DecoderConst {\n // Limit held memory in base64 decoder (encoded bytes).\n KEEP_DATA = 4194304,\n // Initial buffer allocation for the decoder.\n INITIAL_DATA = 1048576,\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n OK = 0\n}\n\n// default IIP header values\nconst DEFAULT_HEADER: IHeaderFields = {\n type: SequenceType.INVALID,\n name: 'Unnamed file',\n size: 0,\n width: 'auto',\n height: 'auto',\n preserveAspectRatio: 1,\n inline: 0\n};\n\n\nexport class IIPHandler implements IOscHandler, IResetHandler {\n private _generation = 0;\n private _aborted = false;\n private _hp = new HeaderParser();\n private _header: IHeaderFields = DEFAULT_HEADER;\n private _dec: Base64Decoder;\n private _qoiDec: QoiDecoder;\n private _isMultipart = false;\n private _abortMulti = false;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _storage: IIPImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n const maxEncodedBytes = Math.ceil(this._opts.iipSizeLimit * 4 / 3);\n const initialBytes = Math.min(DecoderConst.INITIAL_DATA, maxEncodedBytes);\n this._dec = new Base64Decoder(DecoderConst.KEEP_DATA, maxEncodedBytes, initialBytes);\n this._qoiDec = new QoiDecoder(DecoderConst.KEEP_DATA);\n }\n\n public reset(): void {\n this._generation++;\n this._hp.reset();\n this._dec.release();\n this._qoiDec.release();\n }\n\n public start(): void {\n this._aborted = false;\n this._hp.reset();\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (this._hp.state === HeaderState.END) {\n if ((this._dec.put(data.subarray(start, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n }\n } else {\n const dataPos = this._hp.parse(data, start, end);\n if (dataPos === -1) {\n this._aborted = true;\n return;\n }\n if (dataPos > 0) {\n const seqType = this._hp.fields.type;\n if (seqType === SequenceType.FILE) {\n if (this._isMultipart) {\n this._isMultipart = false;\n this._abortMulti = false;\n this._dec.release();\n }\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n if (!this._header.inline) {\n this._aborted = true;\n return;\n }\n this._dec.init();\n } else if (this._abortMulti) {\n this._aborted = true;\n return;\n }\n if ((this._dec.put(data.subarray(dataPos, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n if (this._isMultipart) this._abortMulti = true;\n }\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted) return true;\n\n if (this._hp.state !== HeaderState.END) {\n if (this._hp.end()) return true;\n }\n const seqType = this._hp.fields.type;\n\n if (seqType === SequenceType.FILEPART) return true;\n\n if (seqType === SequenceType.REPORTCELLSIZE) {\n // OSC 1337 ; ReportCellSize=[height];[width];[scale] ST\n let w = CELL_SIZE_DEFAULT.width;\n let h = CELL_SIZE_DEFAULT.height;\n if (this._renderer.dimensions) {\n w = this._renderer.dimensions.css.canvas.width / this._coreTerminal.cols;\n h = this._renderer.dimensions.css.canvas.height / this._coreTerminal.rows;\n }\n const scale = this._coreTerminal._core._coreBrowserService?.dpr ?? 1;\n const report = `\\x1b]1337;ReportCellSize=${h.toFixed(3)};${w.toFixed(3)};${scale.toFixed(3)}\\x1b\\\\`;\n this._coreTerminal.input(report, false);\n return true;\n }\n\n if (seqType === SequenceType.MULTIPARTFILE) {\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n this._isMultipart = true;\n this._abortMulti = false;\n this._dec.release();\n this._dec.init();\n return true;\n }\n\n if (seqType === SequenceType.FILEEND) {\n if (!this._isMultipart) return true;\n this._isMultipart = false;\n if (this._abortMulti || this._header.type !== SequenceType.MULTIPARTFILE) return true;\n }\n\n // fallthrough for SequenceType.FILE & SequenceType.FILEEND\n\n let w = 0;\n let h = 0;\n\n // early exit condition chain\n let cond: number | boolean;\n let metrics = UNSUPPORTED_TYPE;\n if (cond = success) {\n if (cond = !this._dec.end()) {\n metrics = imageType(this._dec.data8);\n if (cond = metrics.mime !== 'unsupported') {\n w = metrics.width;\n h = metrics.height;\n if (cond = w && h && w * h < this._opts.pixelLimit) {\n [w, h] = this._resize(w, h).map(Math.floor);\n cond = w && h && w * h < this._opts.pixelLimit;\n } else {\n console.warn(`IIP: image dimension issue ${metrics.width}x${metrics.height}`);\n }\n } else {\n console.warn('IIP: unsupported image type');\n }\n } else {\n console.warn('IIP: error during BASE64 decoding');\n }\n }\n if (!cond) {\n this._dec.release();\n return true;\n }\n\n let blob: Blob | ImageData;\n if (metrics.mime === 'image/qoi') {\n const data = this._qoiDec.decode(this._dec.data8);\n blob = new ImageData(\n new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength),\n this._qoiDec.width,\n this._qoiDec.height\n );\n this._qoiDec.release();\n if (w === this._qoiDec.width && h === this._qoiDec.height) {\n // use fast-path if we don't need to rescale\n this._dec.release();\n const canvas = ImageRenderer.createCanvas(undefined, this._qoiDec.width, this._qoiDec.height);\n canvas.getContext('2d')?.putImageData(blob, 0, 0);\n this._storage.addImage(canvas);\n return true;\n }\n } else {\n blob = new Blob([this._dec.data8], { type: metrics.mime });\n }\n this._dec.release();\n const generation = this._generation;\n return createImageBitmap(blob, { resizeWidth: w, resizeHeight: h })\n .then(bm => {\n if (generation !== this._generation) {\n bm.close();\n return true;\n }\n this._storage.addImage(bm);\n return true;\n })\n .catch(e => {\n console.warn(`IIP: decoding error ${metrics.mime} ${metrics.width}x${metrics.height}`, e);\n return true;\n });\n }\n\n private _resize(w: number, h: number): [number, number] {\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n const width = this._renderer.dimensions?.css.canvas.width || cw * this._coreTerminal.cols;\n const height = this._renderer.dimensions?.css.canvas.height || ch * this._coreTerminal.rows;\n\n const rw = this._dim(this._header.width!, width, cw);\n const rh = this._dim(this._header.height!, height, ch);\n if (!rw && !rh) {\n const wf = width / w; // TODO: should this respect initial cursor offset?\n const hf = (height - ch) / h; // TODO: fix offset issues from float cell height\n const f = Math.min(wf, hf);\n return f < 1 ? [w * f, h * f] : [w, h];\n }\n return !rw\n ? [w * rh / h, rh]\n : this._header.preserveAspectRatio || !rw || !rh\n ? [rw, h * rw / w] : [rw, rh];\n }\n\n private _dim(s: string, total: number, cdim: number): number {\n if (s === 'auto') return 0;\n if (s.endsWith('%')) return parseInt(s.slice(0, -1), 10) * total / 100;\n if (s.endsWith('px')) return parseInt(s.slice(0, -2), 10);\n return parseInt(s, 10) * cdim;\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n// eslint-disable-next-line\ndeclare const Buffer: any;\n\nexport const enum HeaderState {\n START = 0,\n ABORT = 1,\n KEY = 2,\n VALUE = 3,\n END = 4\n}\n\nexport const enum SequenceType {\n INVALID = 0,\n FILE = 1,\n MULTIPARTFILE = 2,\n FILEPART = 3,\n FILEEND = 4,\n REPORTCELLSIZE = 5\n}\n\nexport interface IHeaderFields {\n [key: string]: number | string | Uint32Array | null | undefined;\n // sequence type\n type: SequenceType;\n // base-64 encoded filename. Defaults to \"Unnamed file\".\n name: string;\n // File size in bytes. The file transfer will be canceled if this size is exceeded.\n size: number;\n /**\n * Optional width and height to render:\n * - N: N character cells.\n * - Npx: N pixels.\n * - N%: N percent of the session's width or height.\n * - auto: The image's inherent size will be used to determine an appropriate dimension.\n */\n width?: string;\n height?: string;\n // Optional, defaults to 1 respecting aspect ratio (width takes precedence).\n preserveAspectRatio?: number;\n // Optional, defaults to 0. If set to 1, the file will be displayed inline, else downloaded\n // (download not supported).\n inline?: number;\n}\n\n// field value decoders\n\n// ASCII bytes to string\nfunction toStr(data: Uint32Array): string {\n let s = '';\n for (let i = 0; i < data.length; ++i) {\n s += String.fromCharCode(data[i]);\n }\n return s;\n}\n\n// digits to integer\nfunction toInt(data: Uint32Array): number {\n let v = 0;\n for (let i = 0; i < data.length; ++i) {\n if (data[i] < 48 || data[i] > 57) {\n throw new Error('illegal char');\n }\n v = v * 10 + data[i] - 48;\n }\n return v;\n}\n\n// check for correct size entry\nfunction toSize(data: Uint32Array): string {\n const v = toStr(data);\n if (!v.match(/^((auto)|(\\d+?((px)|(%)){0,1}))$/)) {\n throw new Error('illegal size');\n }\n return v;\n}\n\n// name is base64 encoded utf-8\nfunction toName(data: Uint32Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(toStr(data), 'base64').toString();\n }\n const bs = atob(toStr(data));\n const b = new Uint8Array(bs.length);\n for (let i = 0; i < b.length; ++i) {\n b[i] = bs.charCodeAt(i);\n }\n return new TextDecoder().decode(b);\n}\n\nconst DECODERS: {[key: string]: (v: Uint32Array) => number | string} = {\n inline: toInt,\n size: toInt,\n name: toName,\n width: toSize,\n height: toSize,\n preserveAspectRatio: toInt\n};\n\n\n// sequence type markers\n// File\nconst FILE_MARKER = [70, 105, 108, 101];\n// MultipartFile\nconst MULTIPARTFILE_MARKER = [77, 117, 108, 116, 105, 112, 97, 114, 116, 70, 105, 108, 101];\n// FilePart\nconst FILEPART_MARKER = [70, 105, 108, 101, 80, 97, 114, 116];\n// FileEnd\nconst FILEEND_MARKER = [70, 105, 108, 101, 69, 110, 100];\n// ReportCellSize\nconst REPORTCELLSIZE_MARKER = [82, 101, 112, 111, 114, 116, 67, 101, 108, 108, 83, 105, 122, 101];\n\n// max allowed chars for sequence header\nconst MAX_FIELDCHARS = 1024;\n\n\nexport class HeaderParser {\n public state: HeaderState = HeaderState.START;\n private _buffer = new Uint32Array(MAX_FIELDCHARS);\n private _position = 0;\n private _key = '';\n public fields: {[key: string]: number | string | Uint32Array | null | undefined} = {};\n\n public reset(): void {\n this._buffer.fill(0);\n this.state = HeaderState.START;\n this._position = 0;\n this.fields = {};\n this._key = '';\n }\n\n public end(): number {\n if (this.state === HeaderState.START) {\n if (this._position === FILEEND_MARKER.length) {\n for (let k = 0; k < FILEEND_MARKER.length; ++k) {\n if (this._buffer[k] !== FILEEND_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEEND;\n this.state = HeaderState.END;\n return 0;\n }\n if (this._position === REPORTCELLSIZE_MARKER.length) {\n for (let k = 0; k < REPORTCELLSIZE_MARKER.length; ++k) {\n if (this._buffer[k] !== REPORTCELLSIZE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.REPORTCELLSIZE;\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n if (this.state === HeaderState.END) return 0;\n if (this.state === HeaderState.VALUE\n && this.fields.type === SequenceType.MULTIPARTFILE\n ) {\n if (!this._storeValue(this._position)) return this._a();\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n\n public parse(data: Uint32Array, start: number, end: number): number {\n let state = this.state;\n let pos = this._position;\n const buffer = this._buffer;\n if (state === HeaderState.ABORT || state === HeaderState.END) return -1;\n if (state === HeaderState.START && pos > 14) return -1;\n for (let i = start; i < end; ++i) {\n const c = data[i];\n switch (c) {\n case 59: // ;\n if (!this._storeValue(pos)) return this._a();\n state = HeaderState.KEY;\n pos = 0;\n break;\n case 61: // =\n if (state === HeaderState.START) {\n if (buffer[0] === 70) {\n // 'File' or 'FilePart'\n let k = 0;\n for (; k < FILE_MARKER.length; ++k) {\n if (buffer[k] !== FILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILE;\n if (pos === FILEPART_MARKER.length) {\n for (; k < FILEPART_MARKER.length; ++k) {\n if (buffer[k] !== FILEPART_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEPART;\n this.state = HeaderState.END;\n return i + 1;\n }\n } else if (buffer[0] === 77) {\n // 'MultipartFile'\n for (let k = 0; k < MULTIPARTFILE_MARKER.length; ++k) {\n if (buffer[k] !== MULTIPARTFILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.MULTIPARTFILE;\n } else {\n return this._a();\n }\n state = HeaderState.KEY;\n pos = 0;\n } else if (state === HeaderState.KEY) {\n if (!this._storeKey(pos)) return this._a();\n state = HeaderState.VALUE;\n pos = 0;\n } else if (state === HeaderState.VALUE) {\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n break;\n case 58: // :\n if (state === HeaderState.VALUE) {\n if (!this._storeValue(pos)) return this._a();\n }\n this.state = HeaderState.END;\n return i + 1;\n default:\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n }\n this.state = state;\n this._position = pos;\n return -2;\n }\n\n private _a(): number {\n this.fields.type = SequenceType.INVALID;\n this.state = HeaderState.ABORT;\n return -1;\n }\n\n private _storeKey(pos: number): boolean {\n const k = toStr(this._buffer.subarray(0, pos));\n if (k) {\n this._key = k;\n this.fields[k] = null;\n return true;\n }\n return false;\n }\n\n private _storeValue(pos: number): boolean {\n if (this._key) {\n try {\n const v = this._buffer.slice(0, pos);\n this.fields[this._key] = DECODERS[this._key] ? DECODERS[this._key](v) : v;\n } catch {\n return false;\n }\n return true;\n }\n return false;\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n\nexport type ImageType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/qoi' | 'image/webp' | 'image/avif' | 'unsupported' | '';\n\nexport interface IMetrics {\n mime: ImageType;\n width: number;\n height: number;\n}\n\nexport const UNSUPPORTED_TYPE: IMetrics = {\n mime: 'unsupported',\n width: 0,\n height: 0\n};\n\nexport function imageType(d: Uint8Array): IMetrics {\n if (d.length < 32) {\n return UNSUPPORTED_TYPE;\n }\n const d32 = new Uint32Array(d.buffer, d.byteOffset, 8);\n // PNG: 89 50 4E 47 0D 0A 1A 0A (8 first bytes == magic number for PNG)\n // + first chunk must be IHDR\n if (d32[0] === 0x474E5089 && d32[1] === 0x0A1A0A0D && d32[3] === 0x52444849) {\n return {\n mime: 'image/png',\n width: d[16] << 24 | d[17] << 16 | d[18] << 8 | d[19],\n height: d[20] << 24 | d[21] << 16 | d[22] << 8 | d[23]\n };\n }\n // JPEG: FF D8 FF\n if (d[0] === 0xFF && d[1] === 0xD8 && d[2] === 0xFF) {\n const [width, height] = jpgSize(d);\n return { mime: 'image/jpeg', width, height };\n }\n // GIF: GIF87a or GIF89a\n if (d32[0] === 0x38464947 && (d[4] === 0x37 || d[4] === 0x39) && d[5] === 0x61) {\n return {\n mime: 'image/gif',\n width: d[7] << 8 | d[6],\n height: d[9] << 8 | d[8]\n };\n }\n // QOI: qoif\n if (d32[0] === 0x66696F71) {\n return {\n mime: 'image/qoi',\n width: d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7],\n height: d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11]\n };\n }\n // WEBP: RIFF | xxxx | WEBP | VP8x\n if (d32[0] === 0x46464952 && d32[2] === 0x50424557 && (d32[3] & 0xFFFFFF) === 0x385056) {\n switch (d[15]) {\n case 0x58: // Extended WebP VP8X --> \"X\"\n return {\n mime: 'image/webp',\n width: (d[24] | d[25] << 8 | d[26] << 16) + 1,\n height: (d[27] | d[28] << 8 | d[29] << 16) + 1\n };\n case 0x4C: // Lossless WebP VP8L --> \"L\"\n if (d[20] !== 0x2f) return UNSUPPORTED_TYPE;\n const dim = d[21] | d[22] << 8 | d[23] << 16 | d[24] << 24;\n return {\n mime: 'image/webp',\n width: (dim & 0x3FFF) + 1,\n height: (dim >>> 14 & 0x3FFF) + 1\n };\n case 0x20: // Lossy WebP VP8 --> \" \"\n if (d[23] !== 0x9d || d[24] !== 0x01 || d[25] !== 0x2a) return UNSUPPORTED_TYPE;\n return {\n mime: 'image/webp',\n width: (d[26] | d[27] << 8) & 0x3FFF,\n height: (d[28] | d[29] << 8) & 0x3FFF\n };\n }\n return UNSUPPORTED_TYPE;\n }\n // AVIF: Box size | ftyp | avif/avis\n if (d32[1] === 0x70797466 && (d32[2] === 0x66697661 || d32[2] === 0x73697661)) {\n let pos = -1;\n // search for ispe box within first 1024 bytes\n const limit = Math.min(d.length - 16, 1024);\n for (let i = 8; i < limit; i++) {\n // scan for ispe\n if (d[i] === 0x69 && d[i + 1] === 0x73 && d[i + 2] === 0x70 && d[i + 3] === 0x65) {\n pos = i;\n break;\n }\n }\n if (pos !== -1) {\n // dimensions are in BE at +8 (width) at +12 (height)\n const width =\n d[pos + 8] << 24 |\n d[pos + 9] << 16 |\n d[pos + 10] << 8 |\n d[pos + 11];\n const height =\n d[pos + 12] << 24 |\n d[pos + 13] << 16 |\n d[pos + 14] << 8 |\n d[pos + 15];\n if (width > 0 && height > 0) {\n return { mime: 'image/avif', width, height };\n }\n }\n return UNSUPPORTED_TYPE;\n }\n return UNSUPPORTED_TYPE;\n}\n\n\nfunction jpgSize(d: Uint8Array): [number, number] {\n const len = d.length;\n let i = 4;\n let blockLength = d[i] << 8 | d[i + 1];\n while (true) {\n i += blockLength;\n if (i >= len) {\n // exhausted without size info\n return [0, 0];\n }\n if (d[i] !== 0xFF) {\n return [0, 0];\n }\n if (d[i + 1] === 0xC0 || d[i + 1] === 0xC2) {\n if (i + 8 < len) {\n return [\n d[i + 7] << 8 | d[i + 8],\n d[i + 5] << 8 | d[i + 6]\n ];\n }\n return [0, 0];\n }\n i += 2;\n blockLength = d[i] << 8 | d[i + 1];\n }\n}\n", "/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { IApcHandler, IImageAddonOptions, IResetHandler, ITerminalExt, ImageLayer } from '../Types';\nimport { ImageRenderer } from '../ImageRenderer';\nimport { CELL_SIZE_DEFAULT } from '../ImageStorage';\nimport { imageType } from '../IIPMetrics';\nimport { KittyImageStorage } from './KittyImageStorage';\nimport Base64Decoder, { type DecodeStatus } from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport {\n KittyAction,\n KittyFormat,\n KittyCompression,\n IKittyCommand,\n IPendingTransmission,\n IKittyImageData,\n KittyPixelConstants,\n parseKittyCommand\n} from './KittyGraphicsTypes';\n\nconst enum Constants {\n // Memory limit for base64 decoder (4MB, same as IIPHandler)\n DECODER_KEEP_DATA = 4194304,\n DECODER_INITIAL_DATA = 4194304, // 4MB\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n DECODER_OK = 0,\n // Maximum control data size\n MAX_CONTROL_DATA_SIZE = 512,\n // Semicolon codepoint\n SEMICOLON = 0x3B\n}\n\nconst DECODER_OK = Constants.DECODER_OK as unknown as DecodeStatus.OK;\n\n// Kitty graphics protocol handler with streaming base64 decoding.\nexport class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDisposable {\n private _aborted = false;\n private _generation = 0;\n private _decodeError = false;\n\n private _activeDecoder: Base64Decoder | null = null;\n private readonly _maxEncodedBytes: number;\n private readonly _initialEncodedBytes: number;\n\n // Streaming related states\n\n // True while receiving control data (before semicolon).\n private _inControlData = true;\n\n // Buffer for control data.\n private _controlData = new Uint32Array(Constants.MAX_CONTROL_DATA_SIZE);\n private _controlLength = 0;\n\n // Pre-calculated encoded size limit\n private _encodedSizeLimit = 0;\n private _totalEncodedSize = 0;\n\n // Parsed command. These are the control data before semicolon.\n private _parsedCommand: IKittyCommand | null = null;\n\n // Storage related states\n\n private _pendingTransmissions: Map = new Map();\n // Tracks the pending key of the most recently started chunked upload.\n // Per spec, subsequent chunks only need m= (and optionally q=), without i=.\n // When a chunk arrives with no i=, this key is used to find the pending upload.\n private _lastPendingKey: number | undefined;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _kittyStorage: KittyImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n // Convert decoded size limit -> max encoded bytes.\n this._maxEncodedBytes = Math.ceil(this._opts.kittySizeLimit * 4 / 3);\n // ensure we preallocate more than configured limit while using 4mb initial size.\n this._initialEncodedBytes = Math.min(Constants.DECODER_INITIAL_DATA, this._maxEncodedBytes);\n }\n\n public reset(): void {\n this._generation++;\n this._cleanupAllPending();\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n this._kittyStorage.reset();\n }\n\n public dispose(): void {\n this.reset();\n }\n\n private _removePendingEntry(key: number): void {\n this._pendingTransmissions.delete(key);\n if (this._lastPendingKey === key) {\n this._lastPendingKey = undefined;\n }\n }\n\n private _cleanupAllPending(): void {\n for (const pending of this._pendingTransmissions.values()) {\n pending.decoder.release();\n }\n this._pendingTransmissions.clear();\n this._lastPendingKey = undefined;\n }\n\n public start(): void {\n this._aborted = false;\n this._decodeError = false;\n this._inControlData = true;\n this._controlLength = 0;\n this._parsedCommand = null;\n // Pre-calculate encoded limit once: base64 is 4 bytes encoded \u2192 3 bytes decoded\n this._encodedSizeLimit = this._maxEncodedBytes;\n this._totalEncodedSize = 0;\n this._activeDecoder = null;\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (!this._inControlData) {\n this._streamPayload(data, start, end);\n } else {\n // Scan for semicolon\n let controlEnd = end;\n for (let i = start; i < end; i++) {\n if (data[i] === Constants.SEMICOLON) {\n this._inControlData = false;\n controlEnd = i;\n break;\n }\n }\n\n // Copy control data\n const copyLength = controlEnd - start;\n if (this._controlLength + copyLength > Constants.MAX_CONTROL_DATA_SIZE) {\n this._aborted = true;\n return;\n }\n this._controlData.set(data.subarray(start, controlEnd), this._controlLength);\n this._controlLength += copyLength;\n\n if (!this._inControlData) {\n // Found semicolon - parse control data early for validation\n this._parsedCommand = parseKittyCommand(this._parseControlDataString());\n\n // Early validation: i+I conflict\n if (this._parsedCommand.id !== undefined && this._parsedCommand.imageNumber !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'EINVAL:cannot specify both i and I keys', this._parsedCommand.quiet ?? 0);\n this._aborted = true;\n return;\n }\n\n // Delete action doesn't need payload - skip streaming\n if (this._parsedCommand.action === KittyAction.DELETE) {\n return;\n }\n\n // Stream remaining as payload\n const payloadStart = controlEnd + 1;\n if (payloadStart < end) {\n this._streamPayload(data, payloadStart, end);\n }\n }\n }\n }\n\n // Stream payload bytes into the base64 decoder.\n private _streamPayload(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n // Check size limit (compare encoded bytes against pre-calculated limit)\n // Include cumulative size from pending transmission for multi-chunk images.\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = this._parsedCommand?.id ?? this._lastPendingKey ?? 0;\n const pending = this._pendingTransmissions.get(pendingKey);\n const previousEncodedSize = pending?.totalEncodedSize ?? 0;\n this._totalEncodedSize += end - start;\n const cumulativeEncodedSize = previousEncodedSize + this._totalEncodedSize;\n if (cumulativeEncodedSize > this._encodedSizeLimit) {\n const decoderToRelease = this._activeDecoder ?? pending?.decoder;\n if (decoderToRelease) {\n decoderToRelease.release();\n }\n this._activeDecoder = null;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n this._aborted = true;\n return;\n }\n\n if (this._decodeError) return;\n\n if (pending?.decoder && !this._activeDecoder) {\n this._activeDecoder = pending.decoder;\n }\n if (!this._activeDecoder) {\n // Budget WASM capacity, including one page of decoder state and rounding.\n const decoderCapacity = this._maxEncodedBytes + 131072;\n if (decoderCapacity > this._opts.storageLimit * 1000000) {\n this._aborted = true;\n if (this._parsedCommand?.id !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'ENOMEM:pending image budget exceeded', this._parsedCommand.quiet ?? 0);\n }\n return;\n }\n const maxPending = Math.max(1, Math.floor(this._opts.storageLimit * 1000000 / decoderCapacity));\n while (this._pendingTransmissions.size >= maxPending) {\n const oldest = this._pendingTransmissions.entries().next().value;\n if (!oldest) break;\n oldest[1].decoder.release();\n this._removePendingEntry(oldest[0]);\n if (oldest[1].cmd.id !== undefined) {\n this._sendResponse(oldest[1].cmd.id, 'ENOMEM:pending image budget exceeded', oldest[1].cmd.quiet ?? 0);\n }\n }\n this._activeDecoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes);\n this._activeDecoder.init();\n }\n\n if (this._activeDecoder.put(data.subarray(start, end)) !== DECODER_OK) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n this._decodeError = true;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted || !success) {\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n return true;\n }\n\n // No semicolon = no payload (delete, capability query)\n if (this._inControlData) {\n return this._handleNoPayloadCommand();\n }\n\n // Use command parsed early in put() - i+I already validated there\n const cmd = this._parsedCommand!;\n\n // Delete action was handled by skipping payload - just execute\n if (cmd.action === KittyAction.DELETE) {\n return this._handleDelete(cmd);\n }\n\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = cmd.id ?? this._lastPendingKey ?? 0;\n const isMoreComing = cmd.more === 1;\n const pending = this._pendingTransmissions.get(pendingKey);\n\n if (isMoreComing) {\n if (this._activeDecoder) {\n if (pending) {\n pending.totalEncodedSize += this._totalEncodedSize;\n pending.decodeError = pending.decodeError || this._decodeError;\n } else {\n this._pendingTransmissions.set(pendingKey, {\n cmd: { ...cmd },\n decoder: this._activeDecoder,\n totalEncodedSize: this._totalEncodedSize,\n decodeError: this._decodeError\n });\n }\n this._lastPendingKey = pendingKey;\n this._activeDecoder = null;\n }\n return true;\n }\n\n // Final chunk received \u2014 clear the last pending key\n if (pending) {\n this._lastPendingKey = undefined;\n }\n\n let decodeError = this._decodeError;\n let finalCmd = cmd;\n let decoder = this._activeDecoder;\n\n if (pending) {\n finalCmd = pending.cmd;\n decoder = pending.decoder;\n decodeError = decodeError || pending.decodeError;\n this._pendingTransmissions.delete(pendingKey);\n }\n\n let imageBytes = new Uint8Array(0);\n if (decoder) {\n if (decoder.end() !== DECODER_OK) {\n decodeError = true;\n }\n imageBytes = decoder.data8;\n }\n this._activeDecoder = null;\n\n // Handle command first \u2014 handlers create Blob/ImageData from imageBytes,\n // which copies the data. Only then is it safe to release the decoder's\n // wasm memory that imageBytes points into.\n const result = this._handleCommandWithBytesAndCmd(finalCmd, imageBytes, decodeError);\n if (decoder) {\n decoder.release();\n }\n return result;\n }\n\n // Command handling\n\n private _parseControlDataString(): string {\n let str = '';\n for (let i = 0; i < this._controlLength; i++) {\n str += String.fromCodePoint(this._controlData[i]);\n }\n return str;\n }\n\n private _handleNoPayloadCommand(): boolean | Promise {\n const cmd = parseKittyCommand(this._parseControlDataString());\n\n // Per spec: specifying both i and I is an error\n if (cmd.id !== undefined && cmd.imageNumber !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:cannot specify both i and I keys', cmd.quiet ?? 0);\n return true;\n }\n\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.DELETE:\n return this._handleDelete(cmd);\n case KittyAction.QUERY:\n this._sendResponse(cmd.id ?? 0, 'OK', cmd.quiet ?? 0);\n return true;\n case KittyAction.PLACEMENT:\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handleCommandWithBytesAndCmd(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.TRANSMIT: {\n const result = this._handleTransmit(cmd, bytes, decodeError);\n // Only send response when _handleTransmit didn't already respond\n // (it handles unsupported transmission medium responses internally)\n if ((cmd.transmission ?? 'd') === 'd' && cmd.id !== undefined) {\n if (decodeError) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n } else if (bytes.length > 0) {\n this._sendResponse(cmd.id, 'OK', cmd.quiet ?? 0);\n }\n }\n return result;\n }\n case KittyAction.TRANSMIT_DISPLAY:\n return this._handleTransmitDisplay(cmd, bytes, decodeError);\n case KittyAction.QUERY:\n return this._handleQuery(cmd, bytes, decodeError);\n case KittyAction.PLACEMENT:\n // a=p ignores any payload \u2014 image data was already transmitted\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handlePlacement(cmd: IKittyCommand): boolean | Promise {\n if (cmd.id === undefined) {\n return true;\n }\n const id = cmd.id;\n const image = this._kittyStorage.getImage(id);\n if (!image) {\n this._sendResponse(id, 'ENOENT:image not found', cmd.quiet ?? 0, cmd.placementId);\n return true;\n }\n const result = this._displayImage(image, cmd);\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0, cmd.placementId);\n return true;\n });\n }\n\n private _handleTransmit(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n // TODO: Support file-based transmission modes (t=f, t=t, t=s)\n // Currently only supports direct transmission (t=d, the default).\n // - t=f (file): Payload is base64-encoded file path. Terminal reads image from that path.\n // - t=t (temp file): Payload is base64-encoded path in temp directory. Terminal reads, deletes.\n // - t=s: Payload is base64-encoded POSIX shm name. Terminal reads from shared memory.\n // These modes require filesystem/IPC access not available in browsers. For Node.js/Electron:\n // 1. Check cmd.transmission (t key) before treating bytes as image data\n // 2. For t=f/t/s: decode bytes as UTF-8 string (the path/name), then read file contents\n // 3. For t=d: treat bytes as image data (current behavior)\n // When implementing, also update _handleQuery to accept these transmission mediums.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported transmission medium', cmd.quiet ?? 0);\n }\n return true;\n }\n\n if (decodeError || bytes.length === 0) return true;\n\n this._kittyStorage.storeImage(cmd.id, {\n data: new Blob([bytes as BlobPart]),\n width: cmd.width ?? 0,\n height: cmd.height ?? 0,\n format: (cmd.format ?? KittyFormat.RGBA) as 24 | 32 | 100,\n compression: cmd.compression ?? ''\n });\n return true;\n }\n\n private _handleTransmitDisplay(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n if (decodeError) {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n }\n return true;\n }\n\n this._handleTransmit(cmd, bytes, decodeError);\n\n const id = cmd.id ?? this._kittyStorage.lastImageId;\n const image = this._kittyStorage.getImage(id);\n if (image) {\n const result = this._displayImage(image, cmd);\n if (cmd.id !== undefined) {\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0);\n return true;\n });\n }\n return result.then(() => true);\n }\n return true;\n }\n\n private _handleQuery(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n const id = cmd.id ?? 0;\n const quiet = cmd.quiet ?? 0;\n\n // Per spec: reject unsupported transmission mediums (only t=d is supported atm)\n // TODO: When filesystem support is added (Node.js/Electron), update this to accept\n // t=f (file), t=t (temp file), and t=s (shared memory) and respond OK for queries.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n this._sendResponse(id, 'EINVAL:unsupported transmission medium', quiet);\n return true;\n }\n\n // Check decode error first (invalid base64)\n if (decodeError) {\n this._sendResponse(id, 'EINVAL:invalid base64 data', quiet);\n return true;\n }\n\n // Capability query (no payload) - just respond OK\n if (bytes.length === 0) {\n this._sendResponse(id, 'OK', quiet);\n return true;\n }\n\n const format = cmd.format ?? KittyFormat.RGBA;\n\n if (format === KittyFormat.PNG) {\n this._sendResponse(id, 'OK', quiet);\n } else {\n const width = cmd.width ?? 0;\n const height = cmd.height ?? 0;\n\n if (!width || !height) {\n this._sendResponse(id, 'EINVAL:width and height required for raw pixel data', quiet);\n return true;\n }\n\n const bytesPerPixel = format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n this._sendResponse(id, `EINVAL:insufficient pixel data`, quiet);\n return true;\n }\n\n this._sendResponse(id, 'OK', quiet);\n }\n return true;\n }\n\n private _handleDelete(cmd: IKittyCommand): boolean {\n // Per spec: default delete selector is 'a' (delete all visible placements)\n const selector = cmd.deleteSelector ?? 'a';\n\n // TODO: Distinguish lowercase (delete placements only) from uppercase\n // (delete placements + free stored image data). Currently both variants\n // free everything since we don't separate stored data from placements.\n switch (selector) {\n case 'a':\n case 'A':\n this._cleanupAllPending();\n this._kittyStorage.deleteAll();\n break;\n case 'i':\n case 'I':\n // TODO: When placement id tracking is implemented (see TODO in\n // KittyImageStorage), d=i with p= should delete only that\n // specific placement, while d=i without p should delete all\n // placements for the image.\n if (cmd.id !== undefined) {\n const pending = this._pendingTransmissions.get(cmd.id);\n if (pending) {\n pending.decoder.release();\n }\n this._removePendingEntry(cmd.id);\n this._kittyStorage.deleteById(cmd.id);\n }\n break;\n default:\n // Unsupported selectors (c, n, p, q, r, x, y, z, f) \u2014 ignore for now\n break;\n }\n return true;\n }\n\n private _sendResponse(id: number, message: string, quiet: number, placementId?: number): void {\n const isOk = message === 'OK';\n if (isOk && quiet >= 1) return;\n if (!isOk && quiet >= 2) return;\n\n const pPart = placementId ? `,p=${placementId}` : '';\n const response = `\\x1b_Gi=${id}${pPart};${message}\\x1b\\\\`;\n this._coreTerminal._core.coreService.triggerDataEvent(response);\n }\n\n // Image display\n\n private _displayImage(image: IKittyImageData, cmd: IKittyCommand): Promise {\n return this._decodeAndDisplay(image, cmd)\n .then(() => true)\n .catch(() => false);\n }\n\n private async _decodeAndDisplay(image: IKittyImageData, cmd: IKittyCommand): Promise {\n const generation = this._generation;\n let bitmap: ImageBitmap | undefined = await this._createBitmap(image);\n\n try {\n if (generation !== this._generation) throw new Error('image decode canceled');\n const cropX = Math.max(0, cmd.x ?? 0);\n const cropY = Math.max(0, cmd.y ?? 0);\n const cropW = cmd.sourceWidth || (bitmap.width - cropX);\n const cropH = cmd.sourceHeight || (bitmap.height - cropY);\n\n const maxCropW = Math.max(0, bitmap.width - cropX);\n const maxCropH = Math.max(0, bitmap.height - cropY);\n const finalCropW = Math.max(0, Math.min(cropW, maxCropW));\n const finalCropH = Math.max(0, Math.min(cropH, maxCropH));\n\n if (finalCropW === 0 || finalCropH === 0) {\n throw new Error('invalid source rectangle');\n }\n\n if (cropX !== 0 || cropY !== 0 || finalCropW !== bitmap.width || finalCropH !== bitmap.height) {\n const cropped = await createImageBitmap(bitmap, cropX, cropY, finalCropW, finalCropH);\n bitmap.close();\n bitmap = cropped;\n }\n\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n\n // Per spec: c/r default to image's natural cell dimensions.\n // If only one of c/r is specified, compute the other from image aspect ratio.\n let imgCols: number;\n let imgRows: number;\n if (cmd.columns !== undefined && cmd.rows !== undefined) {\n imgCols = cmd.columns;\n imgRows = cmd.rows;\n } else if (cmd.columns !== undefined) {\n imgCols = cmd.columns;\n imgRows = Math.max(1, Math.ceil((bitmap.height / bitmap.width) * (imgCols * cw) / ch));\n } else if (cmd.rows !== undefined) {\n imgRows = cmd.rows;\n imgCols = Math.max(1, Math.ceil((bitmap.width / bitmap.height) * (imgRows * ch) / cw));\n } else {\n imgCols = Math.ceil(bitmap.width / cw);\n imgRows = Math.ceil(bitmap.height / ch);\n }\n\n let w = bitmap.width;\n let h = bitmap.height;\n\n // Scale bitmap to fit placement rectangle when c/r are specified\n if (cmd.columns !== undefined || cmd.rows !== undefined) {\n w = Math.round(imgCols * cw);\n h = Math.round(imgRows * ch);\n }\n\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n\n // Save cursor position before addImage modifies it\n const buffer = this._coreTerminal._core.buffer;\n const savedX = buffer.x;\n const savedY = buffer.y;\n const savedYbase = buffer.ybase;\n\n // Determine layer based on z-index: negative = behind text, 0+ = on top.\n // When z<0 we always use the bottom layer even without allowTransparency \u2014\n // the image will simply be hidden behind the opaque text background, which\n // is the correct behavior (client asked for \"behind text\").\n const wantsBottom = cmd.zIndex !== undefined && cmd.zIndex < 0;\n const layer: ImageLayer = wantsBottom ? 'bottom' : 'top';\n\n if (w !== bitmap.width || h !== bitmap.height) {\n const scaled = await createImageBitmap(bitmap, { resizeWidth: w, resizeHeight: h });\n bitmap.close();\n bitmap = scaled;\n }\n\n // Per spec: X/Y are pixel offsets within the first cell, so clamp to cell dimensions\n const xOffset = Math.min(Math.max(0, cmd.xOffset ?? 0), cw - 1);\n const yOffset = Math.min(Math.max(0, cmd.yOffset ?? 0), ch - 1);\n if (xOffset !== 0 || yOffset !== 0) {\n // Per spec: X/Y is not added to c/r area. When c/r are explicit, the\n // total placement area remains c*cw \u00D7 r*ch pixels and the offset image\n // is clipped to fit. When c/r are unset, the padded canvas determines\n // the natural cell dimensions.\n const canvasW = (cmd.columns !== undefined) ? Math.round(imgCols * cw) : bitmap.width + xOffset;\n const canvasH = (cmd.rows !== undefined) ? Math.round(imgRows * ch) : bitmap.height + yOffset;\n const offsetCanvas = ImageRenderer.createCanvas(window.document, canvasW, canvasH);\n const offsetCtx = offsetCanvas.getContext('2d');\n if (!offsetCtx) {\n throw new Error('Failed to create offset canvas context');\n }\n offsetCtx.drawImage(bitmap, xOffset, yOffset);\n\n const offsetBitmap = await createImageBitmap(offsetCanvas);\n offsetCanvas.width = offsetCanvas.height = 0;\n bitmap.close();\n bitmap = offsetBitmap;\n w = bitmap.width;\n h = bitmap.height;\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n if (cmd.columns === undefined) {\n imgCols = Math.ceil(bitmap.width / cw);\n }\n if (cmd.rows === undefined) {\n imgRows = Math.ceil(bitmap.height / ch);\n }\n }\n\n if (generation !== this._generation) throw new Error('image decode canceled');\n const zIndex = cmd.zIndex ?? 0;\n this._kittyStorage.addImage(image.id, bitmap, true, layer, zIndex);\n bitmap = undefined; // ownership transferred to storage\n\n // Kitty cursor movement\n // Per spec: cursor placed at first column after last image column,\n // on the last row of the image. C=1 means don't move cursor.\n if (cmd.cursorMovement === 1) {\n // C=1: restore cursor to position before image was placed\n const scrolled = buffer.ybase - savedYbase;\n buffer.x = savedX;\n // Can't restore cursor to scrollback?\n buffer.y = Math.max(savedY - scrolled, 0);\n } else {\n // Default (C=0): advance cursor horizontally past the image\n // addImage already positioned cursor on the last row via lineFeeds\n buffer.x = Math.min(savedX + imgCols, this._coreTerminal.cols);\n }\n } catch (e) {\n bitmap?.close();\n throw e;\n }\n }\n\n // Create ImageBitmap from already-decoded image data.\n private async _createBitmap(image: IKittyImageData): Promise {\n let bytes: Uint8Array = new Uint8Array(await image.data.arrayBuffer());\n\n if (image.compression === KittyCompression.ZLIB) {\n bytes = await this._decompressZlib(bytes);\n }\n\n if (image.format === KittyFormat.PNG) {\n const metrics = imageType(bytes);\n // IHDR dimensions are parsed with signed shifts, so a value >= 0x80000000 comes\n // back negative and a bare `>` pixel-limit test passes it; require positive.\n if (metrics.mime !== 'image/png' || !(metrics.width > 0) || !(metrics.height > 0) || metrics.width * metrics.height > this._opts.pixelLimit) {\n throw new RangeError('PNG exceeds pixel limit or has invalid dimensions');\n }\n const blob = new Blob([bytes as BlobPart], { type: 'image/png' });\n if (!window.createImageBitmap) {\n const url = URL.createObjectURL(blob);\n const img = new Image();\n return new Promise((resolve, reject) => {\n img.addEventListener('load', () => {\n URL.revokeObjectURL(url);\n const canvas = ImageRenderer.createCanvas(window.document, img.width, img.height);\n canvas.getContext('2d')?.drawImage(img, 0, 0);\n createImageBitmap(canvas).then(resolve).catch(reject);\n });\n img.addEventListener('error', () => {\n URL.revokeObjectURL(url);\n reject(new Error('Failed to load image'));\n });\n img.src = url;\n });\n }\n return createImageBitmap(blob);\n }\n\n // Raw pixel data\n const width = image.width;\n const height = image.height;\n\n if (!width || !height) {\n throw new Error('Width and height required for raw pixel data');\n }\n\n const bytesPerPixel = image.format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n throw new Error('Insufficient pixel data');\n }\n\n const pixelCount = width * height;\n\n if (image.format === KittyFormat.RGBA) {\n // RGBA: use bytes directly \u2014 no copy needed\n return createImageBitmap(new ImageData(new Uint8ClampedArray(bytes.buffer as ArrayBuffer, bytes.byteOffset, pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA), width, height));\n }\n\n // RGB\u2192RGBA: interleave alpha using uint32 block processing (4 pixels per iteration).\n // 3 uint32 reads + 4 uint32 writes per 4 pixels vs 28 byte reads/writes \u2014 ~6x faster.\n // Assumes little-endian (all modern browsers/Node.js).\n const data = new Uint8ClampedArray(pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA);\n const src32 = new Uint32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4));\n const dst32 = new Uint32Array(data.buffer);\n const alignedPixels = pixelCount & ~3; // round down to multiple of 4\n\n let srcOffset = 0;\n let dstOffset = 0;\n for (let i = 0; i < alignedPixels; i += 4) {\n const b0 = src32[srcOffset++];\n const b1 = src32[srcOffset++];\n const b2 = src32[srcOffset++];\n // Little-endian: pixel bytes are [R,G,B] \u2192 uint32 ABGR layout\n dst32[dstOffset++] = 0xFF000000 | b0;\n dst32[dstOffset++] = 0xFF000000 | (b0 >>> 24) | (b1 << 8);\n dst32[dstOffset++] = 0xFF000000 | (b1 >>> 16) | (b2 << 16);\n dst32[dstOffset++] = 0xFF000000 | (b2 >>> 8);\n }\n\n // Handle remaining 1\u20133 pixels\n let srcByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n let dstByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n for (let i = alignedPixels; i < pixelCount; i++) {\n data[dstByte] = bytes[srcByte];\n data[dstByte + 1] = bytes[srcByte + 1];\n data[dstByte + 2] = bytes[srcByte + 2];\n data[dstByte + 3] = KittyPixelConstants.ALPHA_OPAQUE;\n srcByte += KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n dstByte += KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n }\n\n return createImageBitmap(new ImageData(data, width, height));\n }\n\n private async _decompressZlib(compressed: Uint8Array): Promise {\n try {\n return await this._decompress(compressed, 'deflate');\n } catch (error) {\n if (error instanceof RangeError) throw error;\n return await this._decompress(compressed, 'deflate-raw');\n }\n }\n\n private async _decompress(compressed: Uint8Array, format: 'deflate' | 'deflate-raw'): Promise {\n const limit = Math.min(this._opts.kittySizeLimit, this._opts.pixelLimit * 4, this._opts.storageLimit * 1000000);\n let offsetIn = 0;\n // Bound inflation within one native transform before its output is budgeted.\n const source = new ReadableStream({\n pull(controller) {\n if (offsetIn >= compressed.length) {\n controller.close();\n return;\n }\n const end = Math.min(offsetIn + 4096, compressed.length);\n controller.enqueue(new Uint8Array(compressed.subarray(offsetIn, end)));\n offsetIn = end;\n }\n });\n const reader = source.pipeThrough(new DecompressionStream(format)).getReader();\n const chunks: Uint8Array[] = [];\n let totalLength = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n totalLength += value.byteLength;\n if (totalLength > limit) {\n await reader.cancel().catch(() => {});\n throw new RangeError('decompressed image exceeds byte limit');\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n }\n\n public get images(): ReadonlyMap {\n return this._kittyStorage.images;\n }\n\n public get _kittyIdToStorageId(): ReadonlyMap {\n return this._kittyStorage.kittyIdToStorageId;\n }\n\n public get pendingTransmissions(): ReadonlyMap {\n return this._pendingTransmissions;\n }\n}\n", "/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Kitty graphics protocol types, constants, and parsing utilities.\n */\n\nimport type Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\n\n// Kitty graphics protocol action types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'a'.\nexport const enum KittyAction {\n TRANSMIT = 't',\n TRANSMIT_DISPLAY = 'T',\n QUERY = 'q',\n PLACEMENT = 'p',\n DELETE = 'd'\n}\n\n// Kitty graphics protocol format types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyFormat {\n RGB = 24,\n RGBA = 32,\n PNG = 100\n}\n\n// Kitty graphics protocol compression types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'o'.\nexport const enum KittyCompression {\n NONE = '',\n ZLIB = 'z'\n}\n\n// Kitty graphics protocol control data keys.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyKey {\n // Action to perform (t=transmit, T=transmit+display, q=query, p=placement, d=delete)\n ACTION = 'a',\n // Image format (24=RGB, 32=RGBA, 100=PNG)\n FORMAT = 'f',\n // Image ID for referencing stored images\n ID = 'i',\n // Image number (alternative to ID, terminal assigns ID)\n IMAGE_NUMBER = 'I',\n // Source image width in pixels\n WIDTH = 's',\n // Source image height in pixels\n HEIGHT = 'v',\n // The left edge (in pixels) of the image area to display\n X_OFFSET = 'x',\n // The top edge (in pixels) of the image area to display\n Y_OFFSET = 'y',\n // Width (in pixels) of the source rectangle to display\n SOURCE_WIDTH = 'w',\n // Height (in pixels) of the source rectangle to display\n SOURCE_HEIGHT = 'h',\n // Horizontal offset (in pixels) within the first cell\n X_PLACEMENT_OFFSET = 'X',\n // Vertical offset (in pixels) within the first cell\n Y_PLACEMENT_OFFSET = 'Y',\n // Number of terminal columns to display the image over\n COLUMNS = 'c',\n // Number of terminal rows to display the image over\n ROWS = 'r',\n // More data flag (1=more chunks coming, 0=final chunk)\n MORE = 'm',\n // Compression type (z=zlib). This is essential for chunking larger images.\n COMPRESSION = 'o',\n // Quiet mode (1=suppress OK responses, 2=suppress error responses)\n QUIET = 'q',\n // Cursor movement policy (0=move cursor after image, 1=don't move cursor)\n CURSOR_MOVEMENT = 'C',\n // Z-index for image layering (negative = behind text, 0+ = on top)\n Z_INDEX = 'z',\n // Transmission medium (d=direct, f=file, t=temp file, s=shared memory)\n TRANSMISSION = 't',\n // Delete selector (a/A=all, i/I=by id, c/C=at cursor, etc.) \u2014 only used when a=d\n DELETE_SELECTOR = 'd',\n // Placement ID for targeting specific placements\n PLACEMENT_ID = 'p'\n}\n\n// Pixel format constants\nexport const enum KittyPixelConstants {\n BYTES_PER_PIXEL_RGB = 3,\n BYTES_PER_PIXEL_RGBA = 4,\n ALPHA_OPAQUE = 255\n}\n\n// Parsed Kitty graphics command.\nexport interface IKittyCommand {\n action?: string;\n format?: number;\n id?: number;\n imageNumber?: number;\n width?: number;\n height?: number;\n x?: number;\n y?: number;\n sourceWidth?: number;\n sourceHeight?: number;\n xOffset?: number;\n yOffset?: number;\n columns?: number;\n rows?: number;\n more?: number;\n quiet?: number;\n cursorMovement?: number;\n zIndex?: number;\n transmission?: string;\n deleteSelector?: string;\n placementId?: number;\n compression?: string;\n payload?: string;\n}\n\n// Pending chunked transmission state.\n// Stores metadata from the first chunk while accumulating decoded payload data.\nexport interface IPendingTransmission {\n // The parsed command from the first chunk (contains action, format, dimensions, etc.)\n cmd: IKittyCommand;\n // Decoder used across chunked payloads\n decoder: Base64Decoder;\n // Total encoded (base64) bytes received across all chunks - for size limit enforcement\n totalEncodedSize: number;\n // Whether any chunk has failed to decode\n decodeError: boolean;\n}\n\n// Stored Kitty image data.\nexport interface IKittyImageData {\n id: number;\n // Decoded image data stored as Blob (off JS heap) to avoid 2GB heap limit\n data: Blob;\n width: number;\n height: number;\n format: 24 | 32 | 100;\n compression?: string;\n}\n\n// Parses Kitty graphics control data into a command object.\nexport function parseKittyCommand(data: string): IKittyCommand {\n const cmd: IKittyCommand = {};\n const parts = data.split(',');\n\n for (const part of parts) {\n const eqIdx = part.indexOf('=');\n if (eqIdx === -1) continue;\n\n const key = part.substring(0, eqIdx);\n const value = part.substring(eqIdx + 1);\n\n // Handle string keys first\n if (key === KittyKey.ACTION) {\n cmd.action = value;\n continue;\n }\n if (key === KittyKey.COMPRESSION) {\n cmd.compression = value;\n continue;\n }\n if (key === KittyKey.TRANSMISSION) {\n cmd.transmission = value;\n continue;\n }\n if (key === KittyKey.DELETE_SELECTOR) {\n cmd.deleteSelector = value;\n continue;\n }\n const numValue = parseInt(value, 10);\n switch (key) {\n case KittyKey.FORMAT: cmd.format = numValue; break;\n case KittyKey.ID: cmd.id = numValue; break;\n case KittyKey.IMAGE_NUMBER: cmd.imageNumber = numValue; break;\n case KittyKey.WIDTH: cmd.width = numValue; break;\n case KittyKey.HEIGHT: cmd.height = numValue; break;\n case KittyKey.X_OFFSET: cmd.x = numValue; break;\n case KittyKey.Y_OFFSET: cmd.y = numValue; break;\n case KittyKey.SOURCE_WIDTH: cmd.sourceWidth = numValue; break;\n case KittyKey.SOURCE_HEIGHT: cmd.sourceHeight = numValue; break;\n case KittyKey.X_PLACEMENT_OFFSET: cmd.xOffset = numValue; break;\n case KittyKey.Y_PLACEMENT_OFFSET: cmd.yOffset = numValue; break;\n case KittyKey.COLUMNS: cmd.columns = numValue; break;\n case KittyKey.ROWS: cmd.rows = numValue; break;\n case KittyKey.MORE: cmd.more = numValue; break;\n case KittyKey.QUIET: cmd.quiet = numValue; break;\n case KittyKey.CURSOR_MOVEMENT: cmd.cursorMovement = numValue; break;\n case KittyKey.Z_INDEX: cmd.zIndex = numValue; break;\n case KittyKey.PLACEMENT_ID: cmd.placementId = numValue; break;\n }\n }\n\n return cmd;\n}\n", "/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageStorage } from '../ImageStorage';\nimport { ImageLayer, IAddImageOpts } from '../Types';\nimport { IKittyImageData } from './KittyGraphicsTypes';\n\n// Kitty-specific image storage controller.\n//\n// Wraps shared ImageStorage with kitty protocol semantics:\n// - tracks transmitted image payloads by kitty image id\n// - tracks kitty image id -> shared ImageStorage id mapping for displayed images\n// - mirrors shared-storage evictions into kitty maps\n// - applies protocol-level undisplayed-image eviction policy\nexport class KittyImageStorage implements IDisposable {\n private static readonly _maxStoredImages = 256;\n\n private _nextImageId = 1;\n private readonly _images: Map = new Map();\n // TODO: Support multiple placements per image. The kitty spec identifies\n // placements by an (image id, placement id) pair \u2014 same i + different p\n // values should coexist, and same i + same p should replace the prior\n // placement. Currently we track only one storage entry per kitty image id,\n // so multiple placements of the same image overwrite each other. Fixing\n // this requires changing these maps to Map>\n // (kittyId \u2192 placementId \u2192 storageId) and updating addImage/deleteById\n // accordingly. The underlying shared ImageStorage would also need to\n // support multiple entries per logical image.\n private readonly _kittyIdToStorageId: Map = new Map();\n private readonly _storageIdToKittyId: Map = new Map();\n\n private readonly _previousOnImageDeleted: ((storageId: number) => void) | undefined;\n private readonly _wrappedOnImageDeleted: (storageId: number) => void;\n private readonly _handleStorageImageDeleted = (storageId: number): void => {\n const kittyId = this._storageIdToKittyId.get(storageId);\n if (kittyId !== undefined) {\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n this._images.delete(kittyId);\n }\n };\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n\n constructor(\n private readonly _storage: ImageStorage\n ) {\n this._previousOnImageDeleted = this._storage.onImageDeleted;\n this._wrappedOnImageDeleted = (storageId: number) => {\n this._previousOnImageDeleted?.(storageId);\n this._handleStorageImageDeleted(storageId);\n };\n this._storage.onImageDeleted = this._wrappedOnImageDeleted;\n }\n\n public reset(): void {\n this._nextImageId = 1;\n this._images.clear();\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public dispose(): void {\n this.reset();\n if (this._storage.onImageDeleted === this._wrappedOnImageDeleted) {\n this._storage.onImageDeleted = this._previousOnImageDeleted;\n }\n }\n\n public storeImage(id: number | undefined, imageData: Omit): number {\n const imageId = id ?? this._nextImageId++;\n\n const oldStorageId = this._kittyIdToStorageId.get(imageId);\n if (oldStorageId !== undefined) {\n this._storage.deleteImage(oldStorageId);\n this._kittyIdToStorageId.delete(imageId);\n this._storageIdToKittyId.delete(oldStorageId);\n }\n\n if (!this._images.has(imageId) && this._images.size >= KittyImageStorage._maxStoredImages) {\n this._evictUndisplayedImages();\n }\n\n // Encoded images awaiting placement are outside ImageStorage's pixel budget.\n // Unplaced payloads are evicted first so a new upload cannot erase a visible\n // image while abandoned blobs still hold budget; placed ones go only when\n // that is not enough, because the byte cap is a hard bound. The new image is\n // always stored, so an oversized one overshoots by at most one payload\n // (itself bounded by kittySizeLimit) rather than being dropped after an OK ack.\n const byteLimit = this._storage.getLimit() * 1000000;\n this._images.delete(imageId);\n let retainedBytes = 0;\n for (const image of this._images.values()) retainedBytes += image.data.size;\n for (const evictPlaced of [false, true]) {\n for (const [oldestId, image] of this._images) {\n if (retainedBytes + imageData.data.size <= byteLimit) break;\n if (this._kittyIdToStorageId.has(oldestId) !== evictPlaced) continue;\n retainedBytes -= image.data.size;\n this.deleteById(oldestId);\n }\n }\n\n this._images.set(imageId, {\n ...imageData,\n id: imageId\n });\n return imageId;\n }\n\n public addImage(kittyId: number, image: HTMLCanvasElement | ImageBitmap, scrolling: boolean, layer: ImageLayer, zIndex: number): void {\n // Clean up stale reverse-mapping from a previous placement of the same\n // kitty image. The old shared-storage entry is kept (it may still be\n // visible on screen) but its reverse mapping is removed so that eviction\n // of the old entry won't incorrectly delete the kitty image data.\n const oldStorageId = this._kittyIdToStorageId.get(kittyId);\n if (oldStorageId !== undefined) {\n this._storageIdToKittyId.delete(oldStorageId);\n }\n this._addImageOpts.scrolling = scrolling;\n this._addImageOpts.layer = layer;\n this._addImageOpts.zIndex = zIndex;\n const storageId = this._storage.addImage(image, this._addImageOpts);\n this._kittyIdToStorageId.set(kittyId, storageId);\n this._storageIdToKittyId.set(storageId, kittyId);\n }\n\n public getImage(kittyId: number): IKittyImageData | undefined {\n return this._images.get(kittyId);\n }\n\n public deleteById(kittyId: number): void {\n this._images.delete(kittyId);\n const storageId = this._kittyIdToStorageId.get(kittyId);\n if (storageId !== undefined) {\n this._storage.deleteImage(storageId);\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n }\n }\n\n public deleteAll(): void {\n this._images.clear();\n for (const storageId of this._kittyIdToStorageId.values()) {\n this._storage.deleteImage(storageId);\n }\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public get images(): ReadonlyMap {\n return this._images;\n }\n\n public get kittyIdToStorageId(): ReadonlyMap {\n return this._kittyIdToStorageId;\n }\n\n public get lastImageId(): number {\n return this._nextImageId - 1;\n }\n\n private _evictUndisplayedImages(): void {\n for (const [kittyId] of this._images) {\n if (this._images.size <= KittyImageStorage._maxStoredImages / 2) {\n break;\n }\n if (!this._kittyIdToStorageId.has(kittyId)) {\n this._images.delete(kittyId);\n }\n }\n }\n}\n", "/**\n * Copyright (c) 2020, 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IDcsHandler, IParams, IImageAddonOptions, ITerminalExt, AttributeData, IResetHandler, ReadonlyColorSet } from './Types';\nimport { toRGBA8888, BIG_ENDIAN, PALETTE_ANSI_256, PALETTE_VT340_COLOR } from 'sixel/lib/Colors';\nimport { RGBA8888 } from 'sixel/lib/Types';\nimport { ImageRenderer } from './ImageRenderer';\n\nimport { DecoderAsync, Decoder } from 'sixel/lib/Decoder';\n\n// always free decoder ressources after decoding if it exceeds this limit\nconst MEM_PERMA_LIMIT = 4194304; // 1024 pixels * 1024 pixels * 4 channels = 4MB\n\n// custom default palette: VT340 (lower 16 colors) + ANSI256 (up to 256) + zeroed (up to 4096)\nconst DEFAULT_PALETTE = PALETTE_ANSI_256;\nDEFAULT_PALETTE.set(PALETTE_VT340_COLOR);\n\n\nexport class SixelHandler implements IDcsHandler, IResetHandler {\n private _size = 0;\n private _aborted = false;\n private _dec: Decoder | undefined;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _storage: SixelImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n DecoderAsync({\n memoryLimit: this._opts.pixelLimit * 4,\n palette: DEFAULT_PALETTE,\n paletteLimit: this._opts.sixelPaletteLimit\n }).then(d => this._dec = d);\n }\n\n public reset(): void {\n /**\n * reset sixel decoder to defaults:\n * - release all memory\n * - nullify palette (4096)\n * - apply default palette (256)\n */\n if (this._dec) {\n this._dec.release();\n // FIXME: missing interface on decoder to nullify full palette\n (this._dec as any)._palette.fill(0);\n this._dec.init(0, DEFAULT_PALETTE, this._opts.sixelPaletteLimit);\n }\n }\n\n public hook(params: IParams): void {\n this._size = 0;\n this._aborted = false;\n if (this._dec) {\n const fillColor = params.params[1] === 1 ? 0 : extractActiveBg(\n this._coreTerminal._core._inputHandler._curAttrData,\n this._coreTerminal._core._themeService?.colors);\n this._dec.init(fillColor, null, this._opts.sixelPaletteLimit);\n }\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted || !this._dec) {\n return;\n }\n this._size += end - start;\n if (this._size > this._opts.sixelSizeLimit) {\n console.warn(`SIXEL: too much data, aborting`);\n this._aborted = true;\n this._dec.release();\n return;\n }\n try {\n this._dec.decode(data, start, end);\n } catch (e) {\n console.warn(`SIXEL: error while decoding image - ${e}`);\n this._aborted = true;\n this._dec.release();\n }\n }\n\n public unhook(success: boolean): boolean | Promise {\n if (this._aborted || !success || !this._dec) {\n return true;\n }\n\n const width = this._dec.width;\n const height = this._dec.height;\n\n // partial fix for https://github.com/jerch/xterm-addon-image/issues/37\n if (!width || !height) {\n if (height) {\n this._storage.advanceCursor(height);\n }\n return true;\n }\n\n const canvas = ImageRenderer.createCanvas(undefined, width, height);\n canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8 as Uint8ClampedArray, width, height), 0, 0);\n if (this._dec.memoryUsage > MEM_PERMA_LIMIT) {\n this._dec.release();\n }\n this._storage.addImage(canvas);\n return true;\n }\n}\n\n\n/**\n * Some helpers to extract current terminal colors.\n */\n\n// get currently active background color from terminal\n// also respect INVERSE setting\nfunction extractActiveBg(attr: AttributeData, colors: ReadonlyColorSet | undefined): RGBA8888 {\n let bg = 0;\n if (!colors) {\n // FIXME: theme service is prolly not available yet,\n // happens if .open() was not called yet (bug in core?)\n return bg;\n }\n if (attr.isInverse()) {\n if (attr.isFgDefault()) {\n bg = convertLe(colors.foreground.rgba);\n } else if (attr.isFgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getFgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getFgColor()].rgba);\n }\n } else {\n if (attr.isBgDefault()) {\n bg = convertLe(colors.background.rgba);\n } else if (attr.isBgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getBgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getBgColor()].rgba);\n }\n }\n return bg;\n}\n\n// rgba values on the color managers are always in BE, thus convert to LE\nfunction convertLe(color: number): RGBA8888 {\n if (BIG_ENDIAN) return color;\n return (color & 0xFF) << 24 | (color >>> 8 & 0xFF) << 16 | (color >>> 16 & 0xFF) << 8 | color >>> 24 & 0xFF;\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { IImageAddonOptions, ITerminalExt, IAddImageOpts } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\n\n/**\n * Sixel-specific image storage controller.\n *\n * Wraps the shared ImageStorage with sixel protocol semantics:\n * - Cursor behavior governed by DECSET 80 (sixelScrolling option)\n * - advanceCursor for empty sixels carrying only height\n */\nexport class SixelImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'vt340' };\n constructor(\n private readonly _storage: ImageStorage,\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _terminal: ITerminalExt\n ) {}\n\n /**\n * Add a sixel image to storage.\n * Cursor behavior depends on the sixelScrolling option (DECSET 80).\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._addImageOpts.scrolling = this._opts.sixelScrolling;\n this._storage.addImage(img, this._addImageOpts);\n }\n\n /**\n * Only advance text cursor.\n * This is an edge case from empty sixels carrying only a height but no pixels.\n * Partially fixes https://github.com/jerch/xterm-addon-image/issues/37.\n */\n public advanceCursor(height: number): void {\n if (this._opts.sixelScrolling) {\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const rows = Math.ceil(height / cellSize.height);\n for (let i = 1; i < rows; ++i) {\n this._terminal._core._inputHandler.lineFeed();\n }\n }\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IAddImageOpts } from './Types';\nimport { ImageStorage } from './ImageStorage';\n\n/**\n * IIP (iTerm Image Protocol) specific image storage controller.\n *\n * Wraps the shared ImageStorage with IIP protocol semantics:\n * - Always uses scrolling mode (cursor advances with image)\n */\nexport class IIPImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n constructor(\n private readonly _storage: ImageStorage\n ) {}\n\n /**\n * Add an IIP image to storage.\n * Always uses scrolling mode \u2014 cursor advances past the image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._storage.addImage(img, this._addImageOpts);\n }\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport type { ITerminalAddon, IDisposable } from '@xterm/xterm';\nimport type { ImageAddon as IImageApi } from '@xterm/addon-image';\nimport { Emitter, type IEvent } from 'common/Event';\nimport { IIPHandler } from './IIPHandler';\nimport { ImageRenderer } from './ImageRenderer';\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { KittyGraphicsHandler } from './kitty/KittyGraphicsHandler';\nimport { KittyImageStorage } from './kitty/KittyImageStorage';\nimport { SixelHandler } from './SixelHandler';\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { ITerminalExt, IImageAddonOptions, IResetHandler } from './Types';\n\n\n/**\n * Document VT features provided by this addon.\n *\n * @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL \"SIXEL Graphics\" \"DCS Ps ; Ps ; Ps ; q Pt ST\" \"Draw SIXEL image.\"\n *\n * Sixel support is provided by the addon @xterm/addon-image with these limitations:\n * - immediate coloring (no shared palette, allows high color settings of `img2sixel`)\n * - max. palette size of 4096 colors\n * - max. pixel width of 16K\n * - max. 25 MB per sixel sequence\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] OSC 1337 \"iTerm2 Commands\" \"OSC 1337 ; Pt BEL\" \"Custom iTerm2 commands.\"\n *\n * Only the inline image protocol (IIP) is supported by the addon @xterm/addon-image with\n * the following limitations:\n * - sequence:\n * - format: `OSC 1337 ; File=inline=1 ; size= ; ... : BEL`\n * - size param must be set and payload may not exceed CEIL(size * 4 / 3)\n * - strict base64 handling as of RFC4648 \u00A74 (standard alphabet, optional padding,\n * no separator bytes allowed)\n * - supported params: size, name, width, height, preserveAspectRatio\n * - image formats: PNG, JPEG and GIF\n * - no animation support (renders first image of a GIF)\n * - no multipart support\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image)\n * and [iTerm2 IIP docs](https://iterm2.com/documentation-images.html) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] APC KITTY_GRAPHICS \"Kitty Graphics\" \"APC G Pt ST\" \"Kitty Graphics Protocol.\"\n *\n * Kitty graphics support is provided by the addon @xterm/addon-image.\n * Note that while basic image output already works, this is still work in progress.\n */\n\n// default values of addon ctor options\nconst DEFAULT_OPTIONS: IImageAddonOptions = {\n enableSizeReports: true,\n pixelLimit: 16777216, // limit to 4096 * 4096 pixels\n sixelSupport: true,\n sixelScrolling: true,\n sixelPaletteLimit: 4096,\n sixelSizeLimit: 33554432,\n storageLimit: 128,\n showPlaceholder: true,\n iipSupport: true,\n iipSizeLimit: 33554432,\n kittySupport: true,\n kittySizeLimit: 33554432\n};\n\n// max palette size supported by the sixel lib (compile time setting)\nconst MAX_SIXEL_PALETTE_SIZE = 4096;\n\n// definitions for _xtermGraphicsAttributes sequence\nconst enum GaItem {\n COLORS = 1,\n SIXEL_GEO = 2,\n REGIS_GEO = 3\n}\nconst enum GaAction {\n READ = 1,\n SET_DEFAULT = 2,\n SET = 3,\n READ_MAX = 4\n}\nconst enum GaStatus {\n SUCCESS = 0,\n ITEM_ERROR = 1,\n ACTION_ERROR = 2,\n FAILURE = 3\n}\n\n\nexport class ImageAddon implements ITerminalAddon, IImageApi {\n private _opts: IImageAddonOptions;\n private _defaultOpts: IImageAddonOptions;\n private _storage: ImageStorage | undefined;\n private _renderer: ImageRenderer | undefined;\n private _disposables: IDisposable[] = [];\n private _terminal: ITerminalExt | undefined;\n private _handlers: Map = new Map();\n private readonly _onImageAdded = new Emitter();\n public readonly onImageAdded: IEvent = this._onImageAdded.event;\n\n constructor(opts?: Partial) {\n this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);\n this._defaultOpts = Object.assign({}, DEFAULT_OPTIONS, opts);\n }\n\n public dispose(): void {\n for (const handler of this._handlers.values()) handler.reset();\n for (const obj of this._disposables) {\n obj.dispose();\n }\n this._disposables.length = 0;\n this._handlers.clear();\n this._onImageAdded.dispose();\n }\n\n private _disposeLater(...args: IDisposable[]): void {\n for (const obj of args) {\n this._disposables.push(obj);\n }\n }\n\n public activate(terminal: ITerminalExt): void {\n this._terminal = terminal;\n\n // internal data structures\n this._renderer = new ImageRenderer(terminal);\n this._storage = new ImageStorage(terminal, this._renderer, this._opts);\n this._storage.onImageAdded = () => this._onImageAdded.fire();\n\n // enable size reports\n if (this._opts.enableSizeReports) {\n const windowOps = terminal.options.windowOptions ?? {};\n windowOps.getWinSizePixels = true;\n windowOps.getCellSizePixels = true;\n windowOps.getWinSizeChars = true;\n terminal.options.windowOptions = windowOps;\n }\n\n this._disposeLater(\n this._renderer,\n this._storage,\n\n // DECSET/DECRST/DA1/XTSMGRAPHICS handlers\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'h' }, params => this._decset(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'l' }, params => this._decrst(params)),\n terminal.parser.registerCsiHandler({ final: 'c' }, params => this._da1(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'S' }, params => this._xtermGraphicsAttributes(params)),\n\n // render hook\n terminal.onRender(range => this._storage?.render(range)),\n\n /**\n * reset handlers covered:\n * - DECSTR\n * - RIS\n * - Terminal.reset()\n */\n terminal.parser.registerCsiHandler({ intermediates: '!', final: 'p' }, () => this.reset()),\n terminal.parser.registerEscHandler({ final: 'c' }, () => this.reset()),\n terminal._core._inputHandler.onRequestReset(() => this.reset()),\n\n // wipe canvas and delete alternate images on buffer switch\n terminal.buffer.onBufferChange(() => this._storage?.wipeAlternate()),\n\n // extend images to the right on resize\n terminal.onResize(metrics => this._storage?.viewportResize(metrics))\n );\n\n // SIXEL handler\n if (this._opts.sixelSupport) {\n const sixelStorage = new SixelImageStorage(this._storage!, this._opts, this._renderer!, terminal);\n const sixelHandler = new SixelHandler(this._opts, sixelStorage, terminal);\n this._handlers.set('sixel', sixelHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerDcsHandler({ final: 'q' }, sixelHandler)\n );\n }\n\n // iTerm IIP handler\n if (this._opts.iipSupport) {\n const iipStorage = new IIPImageStorage(this._storage!);\n const iipHandler = new IIPHandler(this._opts, this._renderer!, iipStorage, terminal);\n this._handlers.set('iip', iipHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerOscHandler(1337, iipHandler)\n );\n }\n\n // Kitty graphics handler\n if (this._opts.kittySupport) {\n const kittyStorage = new KittyImageStorage(this._storage!);\n const kittyHandler = new KittyGraphicsHandler(this._opts, this._renderer!, kittyStorage, terminal);\n this._handlers.set('kitty', kittyHandler);\n this._disposeLater(\n kittyStorage,\n kittyHandler,\n terminal._core._inputHandler._parser.registerApcHandler({ final: 'G' }, kittyHandler)\n );\n }\n }\n\n // Note: storageLimit is skipped here to not intoduce a surprising side effect.\n public reset(): boolean {\n // reset options customizable by sequences to defaults\n this._opts.sixelScrolling = this._defaultOpts.sixelScrolling;\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n // also clear image storage\n this._storage?.reset();\n // reset protocol handlers\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return false;\n }\n\n public get storageLimit(): number {\n return this._storage?.getLimit() || -1;\n }\n\n public set storageLimit(limit: number) {\n this._storage?.setLimit(limit);\n this._opts.storageLimit = limit;\n }\n\n public get storageUsage(): number {\n if (this._storage) {\n return this._storage.getUsage();\n }\n return -1;\n }\n\n public get showPlaceholder(): boolean {\n return this._opts.showPlaceholder;\n }\n\n public set showPlaceholder(value: boolean) {\n this._opts.showPlaceholder = value;\n this._renderer?.showPlaceholder(value);\n }\n\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.getImageAtBufferCell(x, y);\n }\n\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.extractTileAtBufferCell(x, y);\n }\n\n private _report(s: string): void {\n this._terminal?._core.input(s, false);\n }\n\n private _decset(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = false;\n break;\n }\n }\n return false;\n }\n\n private _decrst(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = true;\n break;\n }\n }\n return false;\n }\n\n // overload DA to return something more appropriate\n private _da1(params: (number | number[])[]): boolean {\n if (params[0]) {\n return true;\n }\n // reported features:\n // 62 - VT220\n // 4 - SIXEL support\n // 9 - charsets\n // 22 - ANSI colors\n if (this._opts.sixelSupport) {\n this._report(`\\x1b[?62;4;9;22c`);\n return true;\n }\n return false;\n }\n\n /**\n * Implementation of xterm's graphics attribute sequence.\n *\n * Supported features:\n * - read/change palette limits (max 4096 by sixel lib)\n * - read SIXEL canvas geometry (reports current window canvas or\n * squared pixelLimit if canvas > pixel limit)\n *\n * Everything else is deactivated.\n */\n private _xtermGraphicsAttributes(params: (number | number[])[]): boolean {\n if (params.length < 2) {\n return true;\n }\n if (params[0] === GaItem.COLORS) {\n switch (params[1]) {\n case GaAction.READ:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n return true;\n case GaAction.SET_DEFAULT:\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n // also reset protocol handlers for now\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return true;\n case GaAction.SET:\n if (params.length > 2 && !(params[2] instanceof Array) && params[2] <= MAX_SIXEL_PALETTE_SIZE) {\n this._opts.sixelPaletteLimit = params[2];\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n } else {\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n }\n return true;\n case GaAction.READ_MAX:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${MAX_SIXEL_PALETTE_SIZE}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n if (params[0] === GaItem.SIXEL_GEO) {\n switch (params[1]) {\n // we only implement read and read_max here\n case GaAction.READ:\n let width = this._renderer?.dimensions?.css.canvas.width;\n let height = this._renderer?.dimensions?.css.canvas.height;\n if (!width || !height) {\n // for some reason we have no working image renderer\n // --> fallback to default cell size\n const cellSize = CELL_SIZE_DEFAULT;\n width = (this._terminal?.cols || 80) * cellSize.width;\n height = (this._terminal?.rows || 24) * cellSize.height;\n }\n if (width * height < this._opts.pixelLimit) {\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${width.toFixed(0)};${height.toFixed(0)}S`);\n } else {\n // if we overflow pixelLimit report that squared instead\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n }\n return true;\n case GaAction.READ_MAX:\n // read_max returns pixelLimit as square area\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n // exit with error on ReGIS or any other requests\n this._report(`\\x1b[?${params[0]};${GaStatus.ITEM_ERROR}S`);\n return true;\n }\n}\n"], -+ "mappings": ";;;;;;;;;;;;;;;;02BAYaA,EAAA,WAAa,IAAI,WAAW,IAAI,YAAY,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC,IAAM,IAClFA,EAAA,YACF,QAAQ,KAAK,6EAA6E,EAI5F,SAAgBC,GAAIC,EAAW,CAC7B,OAAOA,EAAI,GACb,CAFAF,EAAA,IAAAC,GAIA,SAAgBE,GAAMD,EAAW,CAC/B,OAAQA,IAAM,EAAK,GACrB,CAFAF,EAAA,MAAAG,GAIA,SAAgBC,GAAKF,EAAW,CAC9B,OAAQA,IAAM,GAAM,GACtB,CAFAF,EAAA,KAAAI,GAIA,SAAgBC,GAAMH,EAAW,CAC/B,OAAQA,IAAM,GAAM,GACtB,CAFAF,EAAA,MAAAK,GAQA,SAAgBC,EAAWC,EAAWC,EAAWC,EAAWC,EAAY,IAAG,CACzE,QAASA,EAAI,MAAS,IAAMD,EAAI,MAAS,IAAMD,EAAI,MAAS,EAAKD,EAAI,OAAW,CAClF,CAFAP,EAAA,WAAAM,EAQA,SAAgBK,GAAaC,EAAe,CAC1C,MAAO,CAACA,EAAQ,IAAOA,GAA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X,CAGF,YAAK,QAAQ,SAASA,EAAO,CAAC,CAAC,KAA0B,EAClD,EACT,CACF", -+ "names": ["exports", "red", "n", "green", "blue", "alpha", "toRGBA8888", "r", "g", "b", "a", "fromRGBA8888", "color", "nearestColorIndex", "palette", "min", "idx", "i", "dr", "dg", "db", "clamp", "low", "high", "value", "h2c", "t1", "t2", "c", "HLStoRGB", "h", "l", "s", "v", "normalizeRGB", "normalizeHLS", "p", "d", "require_lib", "__commonJSMin", "exports", "InWasm", "z", "b", "r", "def", "t", "s", "d", "m", "W", "e", "require_Base64Decoder_wasm", "__commonJSMin", "exports", "inwasm_runtime_1", "wasmDecode", "MAP", "el", "D", "i", "EMPTY", "Base64Decoder", "keepSize", "maxBytes", "initialBytes", "m", "bytes", "requested", "needed", "newSize", "addPages", "data", "require_QoiDecoder_wasm", "__commonJSMin", "exports", "inwasm_runtime_1", "wasmQoiDecode", "QoiDecoder", "keepSize", "d", "pixels", "ib", "dl", "bytes", "chunkP", "exports", "Colors_1", "wasm_1", "decodeBase64", "bytestring", "result", "WASM_BYTES", "WASM_MODULE", "NULL_CANVAS", "CallbackProxy", "width", "mode", "DEFAULT_OPTIONS", "DecoderAsync", "opts", "cbProxy", "importObj", "inst", "Decoder", "exports", "_instance", "_cbProxy", "module", "pixels", "offset", "additionalPixels", "newCanvas", "adv", "remaining", "c", "i", "fillColor", "palette", "paletteLimit", "truncate", "data", "start", "end", "p", "length", "j", "currentWidth", "escape", "final", "finalOffset", "bw", "currentHeight", "decode", "dec", "decodeAsync", "toDisposable", "fn", "DisposableStore", "o", "d", "Disposable", "MutableDisposable", "value", "Emitter", "listener", "thisArgs", "disposables", "toDisposable", "entry", "result", "idx", "event", "listeners", "len", "EventUtils", "forward", "from", "to", "e", "map", "i", "any", "events", "store", "DisposableStore", "runAndSubscribe", "handler", "initial", "import_Colors", "ImageRenderer", "_ImageRenderer", "Disposable", "_terminal", "MutableDisposable", "parent", "option", "toDisposable", "localDocument", "width", "height", "canvas", "ctx", "buffer", "imgData", "img", "value", "start", "end", "layer", "y", "w", "h", "imgSpec", "tileId", "col", "row", "count", "sourceWidth", "sourceHeight", "cols", "sx", "sy", "dx", "dy", "finalWidth", "finalHeight", "spec", "currentWidth", "currentHeight", "originalWidth", "originalHeight", "scaledWidth", "scaledHeight", "renderer", "key", "screenElement", "bWidth", "blueprint", "d32", "black", "white", "shift", "offset", "x", "ctx2", "i", "placeholder", "bitmap", "CELL_SIZE_DEFAULT", "ExtendedAttrsImage", "_ExtendedAttrsImage", "ext", "urlId", "imageId", "tileId", "value", "val", "EMPTY_ATTRS", "ImageStorage", "_terminal", "_renderer", "_opts", "e", "spec", "storedPixels", "id", "zero", "img", "opts", "cellSize", "cols", "rows", "buffer", "termCols", "termRows", "originX", "originY", "offset", "tileCount", "row", "line", "col", "endMarker", "imgSpec", "range", "hasTopImages", "hasBottomImages", "start", "end", "drawCalls", "placeholderCalls", "startTile", "startCol", "count", "a", "b", "call", "metrics", "oldCol", "tilesPerRow", "hasData", "rightCol", "lastTile", "expandCol", "x", "y", "orig", "canvas", "ImageRenderer", "room", "used", "current", "old", "oldSpec", "imgId", "import_Base64Decoder", "import_QoiDecoder", "toStr", "data", "s", "i", "toInt", "v", "toSize", "toName", "bs", "b", "DECODERS", "FILE_MARKER", "MULTIPARTFILE_MARKER", "FILEPART_MARKER", "FILEEND_MARKER", "REPORTCELLSIZE_MARKER", "MAX_FIELDCHARS", "HeaderParser", "k", "start", "end", "state", "pos", "buffer", "c", "UNSUPPORTED_TYPE", "imageType", "d", "d32", "width", "height", "jpgSize", "dim", "pos", "limit", "i", "len", "blockLength", "DEFAULT_HEADER", "IIPHandler", "_opts", "_renderer", "_storage", "_coreTerminal", "HeaderParser", "maxEncodedBytes", "initialBytes", "Base64Decoder", "QoiDecoder", "data", "start", "end", "dataPos", "success", "seqType", "w", "CELL_SIZE_DEFAULT", "h", "scale", "report", "cond", "metrics", "UNSUPPORTED_TYPE", "imageType", "blob", "canvas", "ImageRenderer", "generation", "bm", "e", "cw", "ch", "width", "height", "rw", "rh", "wf", "hf", "f", "s", "total", "cdim", "import_Base64Decoder", "parseKittyCommand", "data", "cmd", "parts", "part", "eqIdx", "key", "value", "numValue", "DECODER_OK", "KittyGraphicsHandler", "_opts", "_renderer", "_kittyStorage", "_coreTerminal", "key", "pending", "data", "start", "end", "controlEnd", "i", "copyLength", "parseKittyCommand", "payloadStart", "pendingKey", "previousEncodedSize", "decoderToRelease", "decoderCapacity", "maxPending", "oldest", "Base64Decoder", "success", "cmd", "isMoreComing", "decodeError", "finalCmd", "decoder", "imageBytes", "result", "str", "bytes", "id", "image", "quiet", "format", "width", "height", "bytesPerPixel", "expectedBytes", "message", "placementId", "isOk", "pPart", "response", "generation", "bitmap", "cropX", "cropY", "cropW", "cropH", "maxCropW", "maxCropH", "finalCropW", "finalCropH", "cropped", "cw", "CELL_SIZE_DEFAULT", "ch", "imgCols", "imgRows", "w", "h", "buffer", "savedX", "savedY", "savedYbase", "layer", "scaled", "xOffset", "yOffset", "canvasW", "canvasH", "offsetCanvas", "ImageRenderer", "offsetCtx", "offsetBitmap", "zIndex", "scrolled", "e", "metrics", "imageType", "blob", "url", "img", "resolve", "reject", "canvas", "pixelCount", "src32", "dst32", "alignedPixels", "srcOffset", "dstOffset", "b0", "b1", "b2", "srcByte", "dstByte", "compressed", "error", "limit", "offsetIn", "reader", "controller", "chunks", "totalLength", "done", "value", "offset", "chunk", "_KittyImageStorage", "_storage", "storageId", "kittyId", "id", "imageData", "imageId", "oldStorageId", "byteLimit", "retainedBytes", "image", "evictPlaced", "oldestId", "scrolling", "layer", "zIndex", "KittyImageStorage", "import_Colors", "import_Decoder", "MEM_PERMA_LIMIT", "DEFAULT_PALETTE", "SixelHandler", "_opts", "_storage", "_coreTerminal", "d", "params", "fillColor", "extractActiveBg", "data", "start", "end", "e", "success", "width", "height", "canvas", "ImageRenderer", "attr", "colors", "bg", "convertLe", "t", "color", "SixelImageStorage", "_storage", "_opts", "_renderer", "_terminal", "img", "height", "cellSize", "CELL_SIZE_DEFAULT", "rows", "i", "IIPImageStorage", "_storage", "img", "DEFAULT_OPTIONS", "MAX_SIXEL_PALETTE_SIZE", "ImageAddon", "opts", "Emitter", "DEFAULT_OPTIONS", "handler", "obj", "args", "terminal", "ImageRenderer", "ImageStorage", "windowOps", "params", "range", "metrics", "sixelStorage", "SixelImageStorage", "sixelHandler", "SixelHandler", "iipStorage", "IIPImageStorage", "iipHandler", "IIPHandler", "kittyStorage", "KittyImageStorage", "kittyHandler", "KittyGraphicsHandler", "limit", "value", "x", "y", "s", "i", "MAX_SIXEL_PALETTE_SIZE", "width", "height", "cellSize", "CELL_SIZE_DEFAULT"] ++ "sourcesContent": [null, "\"use strict\";\n/**\n * Copyright (c) 2022, 2026 Joerg Breitbart\n * @license MIT\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InWasm = InWasm;\nlet z = (s) => {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(s);\n if (typeof Buffer !== 'undefined')\n return Buffer.from(s, 'base64');\n const b = atob(s);\n const r = new Uint8Array(b.length);\n for (let i = 0; i < r.length; ++i)\n r[i] = b.charCodeAt(i);\n return r;\n};\nfunction InWasm(def) {\n if (def.d) {\n const { t, s, d } = def;\n let b;\n let m;\n const W = WebAssembly;\n if (t === 0 /* OutputType.INSTANCE */) {\n if (s)\n return (e) => new W.Instance(m || (m = new W.Module(b || (b = z(d)))), e);\n return (e) => m\n ? W.instantiate(m, e)\n : W.instantiate(b || (b = z(d)), e).then(r => (m = r.module) && r.instance);\n }\n if (t === 1 /* OutputType.MODULE */) {\n if (s)\n return () => m || (m = new W.Module(b || (b = z(d))));\n return () => m\n ? Promise.resolve(m)\n : W.compile(b || (b = z(d))).then(r => m = r);\n }\n if (s)\n return () => b || (b = z(d));\n return () => Promise.resolve(b || (b = z(d)));\n }\n if (typeof _wasmCtx === 'undefined')\n throw new Error('must run \"inwasm\"');\n _wasmCtx.add(def);\n}\n//# sourceMappingURL=index.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023, 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\n/**\n * wasm base64 decoder.\n */\nconst wasmDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#828e69684093b2c6:rdef-start:\"decode\"*/{s:1,t:0,d:'AGFzbQEAAAABBQFgAAF/Ag8BA2VudgZtZW1vcnkCAAEDAwIAAAcNAgNkZWMAAANlbmQAAQqLBgKZBAEKf0GIKCgCAEGgKGohAUGEKCgCACIDQaAoaiEAQYAoKAIAQQFrQXxxIgRBoChqIQUgBEEQayADSgRAIARBkChqIQMDQCABIABBA2otAABBAnQoAoAgIABBAmotAABBAnQoAoAYIABBAWotAABBAnQoAoAQIAAtAABBAnQoAoAIcnJyIgY2AgAgAUEDaiAAQQdqLQAAQQJ0KAKAICAAQQZqLQAAQQJ0KAKAGCAAQQVqLQAAQQJ0KAKAECAAQQRqLQAAQQJ0KAKACHJyciIHNgIAIAFBBmogAEELai0AAEECdCgCgCAgAEEKai0AAEECdCgCgBggAEEJai0AAEECdCgCgBAgAEEIai0AAEECdCgCgAhycnIiCDYCACABQQlqIABBD2otAABBAnQoAoAgIABBDmotAABBAnQoAoAYIABBDWotAABBAnQoAoAQIABBDGotAABBAnQoAoAIcnJyIgk2AgAgAiAGciAHciAIciAJciECIAFBDGohASAAQRBqIgAgA0kNAAsLIAAgBUkEQANAIAEgAEEDai0AAEECdCgCgCAgAEECai0AAEECdCgCgBggAEEBai0AAEECdCgCgBAgAC0AAEECdCgCgAhycnIiAzYCACACIANyIQIgAUEDaiEBIABBBGoiACAFSQ0ACwtBfyEAIAJB////B00Ef0GEKCAENgIAQYgoIAFBoChrNgIAQQAFQX8LC+0BAQR/AkBBgCgoAgAiAUGEKCgCACIAa0EFTgRAQX8hAxAADQFBgCgoAgAhAUGEKCgCACEAC0F/IQMgASAAayIBQQJIDQAgAC0AoShBAnQoAoAQIAAtAKAoQQJ0KAKACHIhAgJ/IAFBBEYEQEEDQQQgAC0AoyhBPUYbIAAtAKIoQT1GayEBC0EBIAFBA0kNABogAC0AoihBAnQoAoAYIAJyIQJBAiABQQRHDQAaIAAtAKMoQQJ0KAKAICACciECQQMLIQEgAkH///8HSw0AQQAhA0GIKCgCACIAIAI2AKAoQYgoIAAgAWo2AgALIAML'}/*inwasm#828e69684093b2c6:rdef-end:\"decode\"*/);\n// SIMD version (speedup ~1.4x, not covered by tests yet)\n/*\nconst wasmDecode = InWasm({\n name: 'decode',\n type: OutputType.INSTANCE,\n mode: OutputMode.SYNC,\n srctype: 'Clang-C',\n imports: {\n env: { memory: new WebAssembly.Memory({ initial: 1 }) }\n },\n exports: {\n dec: () => 0,\n end: () => 0\n },\n compile: {\n switches: ['-msimd128', '-Wl,-z,stack-size=0', '-Wl,--stack-first']\n },\n code: `\n #include \n typedef struct {\n unsigned int wp;\n unsigned int sp;\n unsigned int dp;\n unsigned int e_size;\n unsigned int dummy[4];\n unsigned char data[0];\n } State;\n\n unsigned int *D0 = (unsigned int *) ${P32.D0 * 4};\n unsigned int *D1 = (unsigned int *) ${P32.D1 * 4};\n unsigned int *D2 = (unsigned int *) ${P32.D2 * 4};\n unsigned int *D3 = (unsigned int *) ${P32.D3 * 4};\n State *state = (State *) ${P32.STATE * 4};\n\n #define packed_byte(x) wasm_i8x16_splat((char) x)\n #define packed_dword(x) wasm_i32x4_splat(x)\n #define masked(x, mask) wasm_v128_and(x, wasm_i32x4_splat(mask))\n\n __attribute__((noinline)) int dec() {\n unsigned int nsp = (state->wp - 1) & ~3;\n unsigned char *src = state->data + state->sp;\n unsigned char *end = state->data + nsp;\n unsigned char *dst = state->data + state->dp;\n unsigned int error = 0;\n\n v128_t err = wasm_i8x16_splat(0);\n unsigned char *end16 = state->data + (nsp & ~15);\n while (src < end16) {\n v128_t data = wasm_v128_load((v128_t *) src);\n\n // wasm-simd rewrite of http://0x80.pl/notesen/2016-01-17-sse-base64-decoding.html#vector-lookup-pshufb\n const v128_t higher_nibble = wasm_u32x4_shr(data, 4) & packed_byte(0x0f);\n const char linv = 1;\n const char hinv = 0;\n\n const v128_t lower_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n linv, linv, 0x2b, 0x30,\n 0x41, 0x50, 0x61, 0x70,\n linv, linv, linv, linv,\n linv, linv, linv, linv\n );\n const v128_t upper_bound_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n hinv, hinv, 0x2b, 0x39,\n 0x4f, 0x5a, 0x6f, 0x7a,\n hinv, hinv, hinv, hinv,\n hinv, hinv, hinv, hinv\n );\n // the difference between the shift and lower bound\n const v128_t shift_LUT = wasm_i8x16_const(\n // order: 0 1 2 3 4 5 6 7 8 9 a b c d e f\n 0x00, 0x00, 0x3e - 0x2b, 0x34 - 0x30,\n 0x00 - 0x41, 0x0f - 0x50, 0x1a - 0x61, 0x29 - 0x70,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00\n );\n\n const v128_t upper_bound = wasm_i8x16_swizzle(upper_bound_LUT, higher_nibble);\n const v128_t lower_bound = wasm_i8x16_swizzle(lower_bound_LUT, higher_nibble);\n\n const v128_t below = wasm_i8x16_lt(data, lower_bound);\n const v128_t above = wasm_i8x16_gt(data, upper_bound);\n const v128_t eq_2f = wasm_i8x16_eq(data, packed_byte(0x2f));\n\n // in_range = not (below or above) or eq_2f\n // outside = not in_range = below or above and not eq_2f (from deMorgan law)\n const v128_t outside = wasm_v128_andnot(eq_2f, above | below);\n err = wasm_v128_or(err, outside);\n\n const v128_t shift = wasm_i8x16_swizzle(shift_LUT, higher_nibble);\n const v128_t t0 = wasm_i8x16_add(data, shift);\n v128_t v = wasm_i8x16_add(t0, wasm_v128_and(eq_2f, packed_byte(-3)));\n\n // pack bytes\n const v128_t ca = masked(v, 0x003f003f);\n const v128_t db = masked(v, 0x3f003f00);\n const v128_t t00 = wasm_v128_or(wasm_u32x4_shr(db, 8), wasm_i32x4_shl(ca, 6));\n v128_t res = wasm_v128_or(wasm_u32x4_shr(t00, 16), wasm_i32x4_shl(t00, 12));\n res = wasm_i8x16_swizzle(res, wasm_i8x16_const(2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, 16, 16, 16, 16));\n\n wasm_v128_store((v128_t *) dst, res);\n dst += 12;\n src += 16;\n }\n //if (wasm_i8x16_bitmask(err) != 0) return -1;\n if (wasm_v128_any_true(err)) return -1;\n\n // operate on 4-byte blocks\n while (src < end) {\n error |= *((unsigned int *) dst) = D0[src[0]] | D1[src[1]] | D2[src[2]] | D3[src[3]];\n dst += 3;\n src += 4;\n }\n if (error >> 24) return -1;\n state->sp = nsp;\n state->dp = dst - state->data;\n return 0;\n }\n\n int end() {\n int rem = state->wp - state->sp;\n if (rem > 4 && dec()) return -1;\n rem = state->wp - state->sp;\n if (rem < 2) return -1;\n\n unsigned char *src = state->data + state->sp;\n if (rem == 4) {\n if (src[3] == 61) rem--;\n if (src[2] == 61) rem--;\n }\n unsigned int accu = D0[src[0]] | D1[src[1]];\n int dp = 1;\n if (rem > 2) {\n accu |= D2[src[2]];\n dp++;\n if (rem == 4) {\n accu |= D3[src[3]];\n dp++;\n }\n }\n if (accu >> 24) return -1;\n *((unsigned int *) (state->data + state->dp)) = accu;\n state->dp += dp;\n return 0;\n }\n `\n});\n*/\n// base64 map\nconst MAP = new Uint8Array('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n .split('')\n .map(el => el.charCodeAt(0)));\n// init decoder maps in LE order\nconst D = new Uint32Array(1024);\nD.fill(0xFF000000);\nfor (let i = 0; i < MAP.length; ++i)\n D[MAP[i]] = i << 2;\nfor (let i = 0; i < MAP.length; ++i)\n D[256 + MAP[i]] = i >> 4 | ((i << 4) & 0xFF) << 8;\nfor (let i = 0; i < MAP.length; ++i)\n D[512 + MAP[i]] = (i >> 2) << 8 | ((i << 6) & 0xFF) << 16;\nfor (let i = 0; i < MAP.length; ++i)\n D[768 + MAP[i]] = i << 16;\nconst EMPTY = new Uint8Array(0);\n/**\n * base64 stream decoder.\n *\n * Features / assumptions:\n * - lazy chunkwise decoding\n * - errors out on any non base64 chars (no support for NL formatted base64)\n * - decodes in wasm\n * - inplace decoding to save memory\n * - supports a keepSize for lazy memory release\n */\nclass Base64Decoder {\n /**\n * @param keepSize Keep the wasm instance below this limit when calling `release()`.\n * @param maxBytes Max allowed bytes to allocate.\n * @param initialBytes Initial bytes to allocate.\n */\n constructor(keepSize, maxBytes, initialBytes) {\n this._inst = null;\n this._ended = true;\n this._bytes = 0;\n this.keepSize = keepSize !== null && keepSize !== void 0 ? keepSize : 1048576 /* Bytes.KEEP */;\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : 4294901760 /* Bytes.MAX */;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : 32768 /* Bytes.INITIAL */;\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw new Error('invalid byte settings');\n }\n }\n /**\n * Currently decoded bytes (borrowed).\n * Must be accessed before calling `release` or `init`.\n */\n get data8() {\n return this._inst ? this._d.subarray(0, this._m32[1282 /* P32.STATE_DP */]) : EMPTY;\n }\n /**\n * Release memory conditionally based on `keepSize`.\n * If memory gets released, also the wasm instance will be freed and recreated on next `init`,\n * otherwise the instance will be reused.\n */\n release() {\n if (!this._inst)\n return;\n if (this._bytes > this.keepSize) {\n this._inst = this._m32 = this._d = this._mem = null;\n }\n else {\n this._m32[1280 /* P32.STATE_WP */] = 0;\n this._m32[1281 /* P32.STATE_SP */] = 0;\n this._m32[1282 /* P32.STATE_DP */] = 0;\n }\n }\n /**\n * Initializes the decoder for new base64 data.\n * Must be called before doing any decoding attempts.\n * The method will either spawn a new wasm instance or grow\n * the needed memory of an existing instance.\n * @param maxBytes Max allowed bytes to allocate (overwrites ctor value).\n * @param initialBytes Initial bytes to allocate (overwrites ctor value).\n */\n init(maxBytes, initialBytes) {\n this.maxBytes = maxBytes !== null && maxBytes !== void 0 ? maxBytes : this.maxBytes;\n this._bytes = initialBytes !== null && initialBytes !== void 0 ? initialBytes : Math.min(this._bytes, this.maxBytes);\n if (this._bytes > this.maxBytes || this.maxBytes > 4294901760 /* Bytes.MAX */) {\n throw Error('invalid byte settings');\n }\n let m = this._m32;\n const bytes = this._bytes + 5152 /* Bytes._DATA_OFFSET */;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmDecode({ env: { memory: this._mem } });\n m = new Uint32Array(this._mem.buffer, 0);\n m.set(D, 256 /* P32.D0 */);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n m = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n m[1280 /* P32.STATE_WP */] = 0;\n m[1281 /* P32.STATE_SP */] = 0;\n m[1282 /* P32.STATE_DP */] = 0;\n this._m32 = m;\n this._ended = false;\n }\n /**\n * Realloc memory. Realloc only happens, if the requested\n * size doesn't fit in the current memory.\n * The new size will be capped by `maxBytes`.\n * @param requested Bytes to be stored.\n */\n _realloc(requested) {\n const needed = this._m32[1280 /* P32.STATE_WP */] + requested;\n if (this._bytes < needed) {\n if (needed > this.maxBytes) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n let newSize = this._bytes;\n while ((newSize *= 2) < needed) { }\n newSize = Math.min(newSize, this.maxBytes);\n if (newSize < needed) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n if (newSize + 5152 /* Bytes._DATA_OFFSET */ > this._mem.buffer.byteLength) {\n const addPages = Math.ceil((newSize + 5152 /* Bytes._DATA_OFFSET */ - this._mem.buffer.byteLength) / 65536);\n this._mem.grow(addPages);\n this._m32 = new Uint32Array(this._mem.buffer, 0);\n this._d = new Uint8Array(this._mem.buffer, 5152 /* Bytes._DATA_OFFSET */);\n }\n this._bytes = newSize;\n }\n return 0 /* DecodeStatus.OK */;\n }\n /**\n * Put bytes in `data` into the decoder.\n * Additionally decodes the payload, if it reached 2^17 bytes.\n * The return value indicates the type of issue.\n * @param data Bytes to be loaded.\n */\n put(data) {\n if (!this._inst || this._ended) {\n return -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n if (this._realloc(data.length)) {\n return -3 /* DecodeStatus.SIZE_EXCEEDED */;\n }\n const m = this._m32;\n this._d.set(data, m[1280 /* P32.STATE_WP */]);\n m[1280 /* P32.STATE_WP */] += data.length;\n // max chunk in input handler is 2^17, try to run in \"tandem mode\"\n return m[1280 /* P32.STATE_WP */] - m[1281 /* P32.STATE_SP */] >= 131072\n ? this._inst.exports.dec()\n : 0 /* DecodeStatus.OK */;\n }\n /**\n * End the current decoding.\n * Also decodes leftover payload from previous put calls.\n */\n end() {\n this._ended = true;\n return this._inst\n ? this._inst.exports.end()\n : -2 /* DecodeStatus.NOT_INITIALIZED */;\n }\n /**\n * Bytes loaded into the decoder.\n */\n get loadedBytes() {\n return this._inst\n ? this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n /**\n * Free bytes to feed to the decoder.\n */\n get freeBytes() {\n return this._inst\n ? this.maxBytes - this._m32[1280 /* P32.STATE_WP */]\n : 0;\n }\n}\nexports.default = Base64Decoder;\n//# sourceMappingURL=Base64Decoder.wasm.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nconst inwasm_runtime_1 = require(\"inwasm-runtime\");\nconst wasmQoiDecode = (0, inwasm_runtime_1.InWasm)(/*inwasm#459f9e1bfb80b1a8:rdef-start:\"qoi_decode\"*/{s:1,t:0,d:'AGFzbQEAAAABCgJgAABgA39/fwACDwEDZW52Bm1lbW9yeQIAAQMDAgABBwcBA2RlYwABCAEACu4EAgwAQQBBAEGAAvwLAAveBAEJf0EAQQBBgAL8CwAgAUEXTgRAIAAgAWpBCGshCkGACCEBIAJBAnRBgAhqIQsgAEEOaiEDQf8BIQZBACECA0AgA0EBaiEHIAMtAAAiCEE/cSEAAkACQCAIQcABcSIJRQRAIABBAnQiAC0AAyEGIAAtAAIhBCAALQABIQUgAC0AACECIAchAwwBCwJAIAhB/QFLDQAgCUHAAUcNACAFQQVsIAJBA2xqIARBB2xqIAZBC2xqQT9xQQJ0IgMgBDoAAiADIAU6AAEgAyACOgAAIANBA2ogBjoAAANAIAEgAjoAACABQQNqIAY6AAAgAUECaiAEOgAAIAFBAWogBToAACABQQRqIQEgAEUEQCAHIQMMBAsgAEEBayEAIAEgC0kNAAsgByEDDAILAn8CQAJAAkAgCEH+AWsOAgABAgsgAy0AAyEEIAMtAAIhBSADLQABIQIgA0EEagwCCyADKAIBIgJBGHYhBiACQRB2IQQgAkEIdiEFIANBBWoMAQsgCUGAAUcEQCAHIAlBwABHDQEaIAQgCEEDcWpBAmshBCACIABBBHZqQQJrIQIgBSAIQQJ2QQNxakECayEFIAcMAQsgBCAAQShrIgkgAy0AASIHQQ9xamohBCACIAdBBHYgCWpqIQIgACAFakEgayEFIANBAmoLIQMgBUEFbCACQQNsaiAEQQdsaiAGQQtsakE/cUECdCIAIAQ6AAIgACAFOgABIAAgAjoAACAAQQNqIAY6AAALIAEgBjoAAyABIAQ6AAIgASAFOgABIAEgAjoAACABQQRqIQELIAMgCkkNAAsLCw=='}/*inwasm#459f9e1bfb80b1a8:rdef-end:\"qoi_decode\"*/);\nclass QoiDecoder {\n constructor(keepSize) {\n this.keepSize = keepSize;\n this.width = 0;\n this.height = 0;\n }\n decode(d) {\n this.width = d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7];\n this.height = d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11];\n const pixels = this.width * this.height;\n const ib = pixels * 4;\n const dl = d.length;\n /**\n * byte/offset calculation:\n * To save some memory we dont reserve full memory for decoded + encoded,\n * but place encoded at the end of decoded plus 50% security distance\n * to avoid reads before writes positions:\n *\n * encoded < decoded (good compression)\n * enc ####################\n * dec #######################################\n * ^ ^\n * DST_P CHUNK_P\n *\n * encoded > decoded (degenerated compression, should not happen)\n * enc ##############################\n * dec ####################\n * ^ ^\n * DST_P CHUNK_P\n *\n * There is still a chance for overlapping r/w positions in case the compressed\n * data has very different pixel progression, yet the 50% security distance\n * should deal with that, as QOI will bloat data by 25% at max (RGB -> OP byte + RGB).\n * Since we always assume RGBA at decoding stage, the possible bloat reduces to 20% at max.\n */\n const bytes = Math.max(ib, dl) + (Math.min(ib, dl) >> 1) + 4096;\n if (!this._inst) {\n this._mem = new WebAssembly.Memory({ initial: Math.ceil(bytes / 65536) });\n this._inst = wasmQoiDecode({ env: { memory: this._mem } });\n }\n else if (this._mem.buffer.byteLength < bytes) {\n this._mem.grow(Math.ceil((bytes - this._mem.buffer.byteLength) / 65536));\n this._d = null;\n }\n if (!this._d) {\n this._d = new Uint8Array(this._mem.buffer);\n }\n // put src data at the end of memory, also align to 256\n const chunkP = (this._mem.buffer.byteLength - dl) & ~0xFF;\n this._d.set(d, chunkP);\n this._inst.exports.dec(chunkP, dl, pixels);\n return this._d.subarray(1024 /* P8.DST_P */, 1024 /* P8.DST_P */ + ib);\n }\n release() {\n if (!this._inst)\n return;\n if (this._mem.buffer.byteLength > this.keepSize) {\n this._inst = this._d = this._mem = null;\n }\n }\n}\nexports.default = QoiDecoder;\n//# sourceMappingURL=QoiDecoder.wasm.js.map", null, null, "/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal lifecycle utilities for xterm.js core.\n * Simplified from VS Code's lifecycle.ts - no tracking/leak detection.\n */\n\nexport interface IDisposable {\n dispose(): void;\n}\n\nexport function toDisposable(fn: () => void): IDisposable {\n return { dispose: fn };\n}\n\nexport function dispose(disposable: T): T;\nexport function dispose(disposable: T | undefined): T | undefined;\nexport function dispose(disposables: T[]): T[];\nexport function dispose(arg: T | T[] | undefined): T | T[] | undefined {\n if (!arg) {\n return arg;\n }\n if (Array.isArray(arg)) {\n for (const d of arg) {\n d.dispose();\n }\n return [];\n }\n arg.dispose();\n return arg;\n}\n\nexport function combinedDisposable(...disposables: IDisposable[]): IDisposable {\n return toDisposable(() => dispose(disposables));\n}\n\nexport class DisposableStore implements IDisposable {\n private readonly _disposables = new Set();\n private _isDisposed = false;\n\n public get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n public add(o: T): T {\n if (this._isDisposed) {\n o.dispose();\n } else {\n this._disposables.add(o);\n }\n return o;\n }\n\n public dispose(): void {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n\n public clear(): void {\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.clear();\n }\n}\n\nexport abstract class Disposable implements IDisposable {\n public static readonly None: IDisposable = Object.freeze({ dispose() { } });\n\n protected readonly _store = new DisposableStore();\n\n public dispose(): void {\n this._store.dispose();\n }\n\n protected _register(o: T): T {\n return this._store.add(o);\n }\n}\n\nexport class MutableDisposable implements IDisposable {\n private _value: T | undefined;\n private _isDisposed = false;\n\n public get value(): T | undefined {\n return this._isDisposed ? undefined : this._value;\n }\n\n public set value(value: T | undefined) {\n if (this._isDisposed || value === this._value) {\n return;\n }\n this._value?.dispose();\n this._value = value;\n }\n\n public clear(): void {\n this.value = undefined;\n }\n\n public dispose(): void {\n this._isDisposed = true;\n this._value?.dispose();\n this._value = undefined;\n }\n}\n", "/**\n * Copyright (c) 2024-2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Minimal event utilities for xterm.js core.\n * Simplified from VS Code's event.ts - no leak detection/profiling.\n */\n\nimport { IDisposable, DisposableStore, toDisposable } from './Lifecycle';\n\nexport interface IEvent {\n (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable;\n}\n\nexport class Emitter {\n private _listeners: { fn: (e: T) => any, thisArgs: any }[] = [];\n private _disposed = false;\n private _event: IEvent | undefined;\n\n public get event(): IEvent {\n if (this._event) {\n return this._event;\n }\n this._event = (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n if (this._disposed) {\n return toDisposable(() => {});\n }\n\n const entry = { fn: listener, thisArgs };\n this._listeners = this._listeners.slice();\n this._listeners.push(entry);\n\n const result = toDisposable(() => {\n const idx = this._listeners.indexOf(entry);\n if (idx !== -1) {\n this._listeners = this._listeners.slice();\n this._listeners.splice(idx, 1);\n }\n });\n\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(result);\n } else {\n disposables.add(result);\n }\n }\n\n return result;\n };\n return this._event;\n }\n\n public fire(event: T): void {\n if (this._disposed || !this._listeners.length) {\n return;\n }\n if (this._listeners.length === 1) {\n this._listeners[0].fn.call(this._listeners[0].thisArgs, event);\n return;\n }\n const listeners = this._listeners;\n for (let i = 0, len = listeners.length; i < len; ++i) {\n listeners[i].fn.call(listeners[i].thisArgs, event);\n }\n }\n\n public dispose(): void {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._listeners.length = 0;\n }\n}\n\nexport namespace EventUtils {\n export function forward(from: IEvent, to: Emitter): IDisposable {\n return from(e => to.fire(e));\n }\n\n export function map(event: IEvent, map: (i: I) => O): IEvent {\n return (listener: (e: O) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n return event(i => listener.call(thisArgs, map(i)), undefined, disposables);\n };\n }\n\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent;\n export function any(...events: IEvent[]): IEvent {\n return (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => {\n const store = new DisposableStore();\n for (const event of events) {\n store.add(event(e => listener.call(thisArgs, e)));\n }\n if (disposables) {\n if (Array.isArray(disposables)) {\n disposables.push(store);\n } else {\n disposables.add(store);\n }\n }\n return store;\n };\n }\n\n export function runAndSubscribe(event: IEvent, handler: (e: T) => void, initial: T): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void): IDisposable;\n export function runAndSubscribe(event: IEvent, handler: (e: T | undefined) => void, initial?: T): IDisposable {\n handler(initial);\n return event(e => handler(e));\n }\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { toRGBA8888 } from 'sixel/lib/Colors';\nimport { IDisposable } from '@xterm/xterm';\nimport { ICellSize, ImageLayer, ITerminalExt, IImageSpec, IRenderDimensions, IRenderService } from './Types';\nimport { Disposable, MutableDisposable, toDisposable } from 'common/Lifecycle';\n\nconst enum Constants {\n PLACEHOLDER_LENGTH = 4096,\n PLACEHOLDER_HEIGHT = 24\n}\n\n/**\n * ImageRenderer - terminal frontend extension:\n * - provide primitives for canvas, ImageData, Bitmap (static)\n * - add canvas layer to DOM (browser only for now)\n * - draw image tiles onRender\n */\nexport class ImageRenderer extends Disposable implements IDisposable {\n /** @deprecated Kept for backward compat \u2014 points to top layer canvas. */\n public get canvas(): HTMLCanvasElement | undefined { return this._layers.get('top')?.canvas; }\n private _layers = new Map();\n private _placeholder: HTMLCanvasElement | undefined;\n private _placeholderBitmap: ImageBitmap | undefined;\n private _optionsRefresh = this._register(new MutableDisposable());\n private _oldOpen: ((parent: HTMLElement) => void) | undefined;\n private _renderService: IRenderService | undefined;\n private _oldSetRenderer: ((renderer: any) => void) | undefined;\n\n // drawing primitive - canvas\n public static createCanvas(localDocument: Document | undefined, width: number, height: number): HTMLCanvasElement {\n /**\n * NOTE: We normally dont care, from which document the canvas\n * gets created, so we can fall back to global document,\n * if the terminal has no document associated yet.\n * This way early image loads before calling .open keep working\n * (still discouraged though, as the metrics will be screwed up).\n * Only the DOM output canvas should be on the terminal's document,\n * which gets explicitly checked in `insertLayerToDom`.\n */\n const canvas = (localDocument ?? document).createElement('canvas');\n canvas.width = width | 0;\n canvas.height = height | 0;\n return canvas;\n }\n\n // drawing primitive - ImageData with optional buffer\n public static createImageData(ctx: CanvasRenderingContext2D, width: number, height: number, buffer?: ArrayBuffer): ImageData {\n if (typeof ImageData !== 'function') {\n const imgData = ctx.createImageData(width, height);\n if (buffer) {\n imgData.data.set(new Uint8ClampedArray(buffer, 0, width * height * 4));\n }\n return imgData;\n }\n return buffer\n ? new ImageData(new Uint8ClampedArray(buffer, 0, width * height * 4), width, height)\n : new ImageData(width, height);\n }\n\n // drawing primitive - ImageBitmap\n public static createImageBitmap(img: ImageBitmapSource): Promise {\n if (typeof createImageBitmap !== 'function') {\n return Promise.resolve(undefined);\n }\n return createImageBitmap(img);\n }\n\n\n constructor(private _terminal: ITerminalExt) {\n super();\n this._oldOpen = this._terminal._core.open;\n this._terminal._core.open = (parent: HTMLElement): void => {\n this._oldOpen?.call(this._terminal._core, parent);\n this._open();\n };\n if (this._terminal._core.screenElement) {\n this._open();\n }\n // hack to spot fontSize changes\n this._optionsRefresh.value = this._terminal._core.optionsService.onOptionChange(option => {\n if (option === 'fontSize') {\n this.rescaleCanvas();\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n });\n this._register(toDisposable(() => {\n this.removeLayerFromDom();\n this.removeLayerFromDom('bottom');\n if (this._terminal._core && this._oldOpen) {\n this._terminal._core.open = this._oldOpen;\n this._oldOpen = undefined;\n }\n if (this._renderService && this._oldSetRenderer) {\n this._renderService.setRenderer = this._oldSetRenderer;\n this._oldSetRenderer = undefined;\n }\n this._renderService = undefined;\n this._layers.clear();\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }));\n }\n\n /**\n * Enable the placeholder.\n */\n public showPlaceholder(value: boolean): void {\n if (value) {\n if (!this._placeholder && this.cellSize.height !== -1) {\n this._createPlaceHolder(Math.max(this.cellSize.height + 1, Constants.PLACEHOLDER_HEIGHT));\n }\n } else {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n this._placeholder = undefined;\n }\n this._renderService?.refreshRows(0, this._terminal.rows);\n }\n\n /**\n * Dimensions of the terminal.\n * Forwarded from internal render service.\n */\n public get dimensions(): IRenderDimensions | undefined {\n return this._terminal.dimensions;\n }\n\n /**\n * Current cell size (float).\n */\n public get cellSize(): ICellSize {\n return {\n width: this.dimensions?.css.cell.width || -1,\n height: this.dimensions?.css.cell.height || -1\n };\n }\n\n /**\n * Clear a region of the image layer canvas.\n */\n public clearLines(start: number, end: number, layer?: ImageLayer): void {\n const y = start * (this.dimensions?.css.cell.height || 0);\n const w = this.dimensions?.css.canvas.width || 0;\n const h = (end + 1 - start) * (this.dimensions?.css.cell.height || 0);\n if (!layer || layer === 'top') {\n this._layers.get('top')?.clearRect(0, y, w, h);\n }\n if (!layer || layer === 'bottom') {\n this._layers.get('bottom')?.clearRect(0, y, w, h);\n }\n }\n\n /**\n * Clear whole image canvas.\n */\n public clearAll(layer?: ImageLayer): void {\n if (!layer || layer === 'top') {\n const ctx = this._layers.get('top');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n if (!layer || layer === 'bottom') {\n const ctx = this._layers.get('bottom');\n ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n }\n }\n\n /**\n * Draw neighboring tiles on the image layer canvas.\n */\n public draw(imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get(imgSpec.layer);\n if (!ctx) {\n return;\n }\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const { width: sourceWidth, height: sourceHeight } = imgSpec.actualCellSize;\n const cols = Math.ceil(img.width / sourceWidth);\n\n const sx = (tileId % cols) * sourceWidth;\n const sy = Math.floor(tileId / cols) * sourceHeight;\n const dx = col * width;\n const dy = row * height;\n\n // safari bug: never access image source out of bounds\n const finalWidth = count * sourceWidth + sx > img.width ? img.width - sx : count * sourceWidth;\n const finalHeight = sy + sourceHeight > img.height ? img.height - sy : sourceHeight;\n\n // Floor all pixel offsets to get stable tile mapping without any overflows.\n // Note: For not pixel perfect aligned cells like in the DOM renderer\n // this will move a tile slightly to the top/left (subpixel range, thus ignore it).\n // FIX #34: avoid striping on displays with pixelDeviceRatio != 1 by ceiling height and width\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.ceil(finalWidth), Math.ceil(finalHeight),\n Math.floor(dx), Math.floor(dy), Math.ceil(finalWidth * width / sourceWidth), Math.ceil(finalHeight * height / sourceHeight)\n );\n }\n\n /**\n * Extract a single tile from an image.\n */\n public extractTile(imgSpec: IImageSpec, tileId: number): HTMLCanvasElement | undefined {\n const { width, height } = this.cellSize;\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n this._rescaleImage(imgSpec, width, height);\n const img = imgSpec.actual!;\n const { width: sourceWidth, height: sourceHeight } = imgSpec.actualCellSize;\n const cols = Math.ceil(img.width / sourceWidth);\n const sx = (tileId % cols) * sourceWidth;\n const sy = Math.floor(tileId / cols) * sourceHeight;\n const finalWidth = sourceWidth + sx > img.width ? img.width - sx : sourceWidth;\n const finalHeight = sy + sourceHeight > img.height ? img.height - sy : sourceHeight;\n\n const canvas = ImageRenderer.createCanvas(this.document, Math.ceil(finalWidth * width / sourceWidth), Math.ceil(finalHeight * height / sourceHeight));\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(\n img,\n Math.floor(sx), Math.floor(sy), Math.floor(finalWidth), Math.floor(finalHeight),\n 0, 0, canvas.width, canvas.height\n );\n return canvas;\n }\n }\n\n /**\n * Draw a line with placeholder on the image layer canvas.\n */\n public drawPlaceholder(col: number, row: number, count: number = 1): void {\n const ctx = this._layers.get('top');\n if (ctx) {\n const { width, height } = this.cellSize;\n\n // Don't try to draw anything, if we cannot get valid renderer metrics.\n if (width === -1 || height === -1) {\n return;\n }\n\n if (!this._placeholder) {\n this._createPlaceHolder(Math.max(height + 1, Constants.PLACEHOLDER_HEIGHT));\n } else if (height >= this._placeholder!.height) {\n this._createPlaceHolder(height + 1);\n }\n if (!this._placeholder) return;\n ctx.drawImage(\n this._placeholderBitmap ?? this._placeholder!,\n col * width,\n (row * height) % 2 ? 0 : 1, // needs %2 offset correction\n width * count,\n height,\n col * width,\n row * height,\n width * count,\n height\n );\n }\n }\n\n /**\n * Rescale image layer canvas if needed.\n * Checked once from `ImageStorage.render`.\n */\n public rescaleCanvas(): void {\n const w = this.dimensions?.css.canvas.width || 0;\n const h = this.dimensions?.css.canvas.height || 0;\n for (const ctx of this._layers.values()) {\n if (ctx.canvas.width !== w || ctx.canvas.height !== h) {\n ctx.canvas.width = w;\n ctx.canvas.height = h;\n }\n }\n }\n\n /**\n * Rescale image in storage if needed.\n */\n private _rescaleImage(spec: IImageSpec, currentWidth: number, currentHeight: number): void {\n if (currentWidth === spec.actualCellSize.width && currentHeight === spec.actualCellSize.height) {\n return;\n }\n const { width: originalWidth, height: originalHeight } = spec.origCellSize;\n if (currentWidth === originalWidth && currentHeight === originalHeight) {\n spec.actual = spec.orig;\n spec.actualCellSize.width = originalWidth;\n spec.actualCellSize.height = originalHeight;\n return;\n }\n const scaledWidth = Math.ceil(spec.orig!.width * currentWidth / originalWidth);\n const scaledHeight = Math.ceil(spec.orig!.height * currentHeight / originalHeight);\n // Upscale visible tiles directly; a full zoomed copy can dwarf the image budget.\n if (scaledWidth * scaledHeight > spec.orig!.width * spec.orig!.height) {\n spec.actual = spec.orig;\n spec.actualCellSize.width = originalWidth;\n spec.actualCellSize.height = originalHeight;\n return;\n }\n const canvas = ImageRenderer.createCanvas(this.document, scaledWidth, scaledHeight);\n const ctx = canvas.getContext('2d');\n if (ctx) {\n ctx.drawImage(spec.orig!, 0, 0, canvas.width, canvas.height);\n spec.actual = canvas;\n spec.actualCellSize.width = currentWidth;\n spec.actualCellSize.height = currentHeight;\n }\n }\n\n /**\n * Lazy init for the renderer.\n */\n private _open(): void {\n this._renderService = this._terminal._core._renderService;\n this._oldSetRenderer = this._renderService.setRenderer.bind(this._renderService);\n this._renderService.setRenderer = (renderer: any) => {\n for (const key of [...this._layers.keys()]) {\n this.removeLayerFromDom(key);\n }\n this._oldSetRenderer?.call(this._renderService, renderer);\n };\n }\n\n public insertLayerToDom(layer: ImageLayer = 'top'): void {\n // make sure that the terminal is attached to a document and to DOM\n if (!this.document || !this._terminal._core.screenElement) {\n console.warn('image addon: cannot insert output canvas to DOM, missing document or screenElement');\n return;\n }\n if (this._layers.has(layer)) {\n return;\n }\n const canvas = ImageRenderer.createCanvas(\n this.document, this.dimensions?.css.canvas.width || 0,\n this.dimensions?.css.canvas.height || 0\n );\n canvas.classList.add(`xterm-image-layer-${layer}`);\n const screenElement = this._terminal._core.screenElement;\n // Use isolation to create a stacking context without overriding z-index,\n // which would conflict with integrators (e.g. VS Code) that set their\n // own z-index on the screen element.\n screenElement.style.isolation = 'isolate';\n if (layer === 'bottom') {\n // Use z-index:-1 so it paints behind non-positioned text elements.\n // The screen element needs to be a stacking context (via isolation)\n // to contain the negative z-index, otherwise it would go behind the\n // entire terminal.\n canvas.style.zIndex = '-1';\n screenElement.insertBefore(canvas, screenElement.firstChild);\n } else {\n // Explicit z-index ensures the image canvas reliably stacks above\n // the text layer (DOM renderer rows). z-index: 0 is below the\n // selection overlay (z-index: 1).\n canvas.style.zIndex = '0';\n screenElement.appendChild(canvas);\n }\n const ctx = canvas.getContext('2d', { alpha: true });\n if (!ctx) {\n canvas.remove();\n return;\n }\n this._layers.set(layer, ctx);\n this.clearAll(layer);\n }\n\n public removeLayerFromDom(layer: ImageLayer = 'top'): void {\n const ctx = this._layers.get(layer);\n if (ctx) {\n ctx.canvas.remove();\n this._layers.delete(layer);\n }\n }\n\n public hasLayer(layer: ImageLayer): boolean {\n return this._layers.has(layer);\n }\n\n private _createPlaceHolder(height: number = Constants.PLACEHOLDER_HEIGHT): void {\n this._placeholderBitmap?.close();\n this._placeholderBitmap = undefined;\n\n // create blueprint to fill placeholder with\n const bWidth = 32; // must be 2^n\n const blueprint = ImageRenderer.createCanvas(this.document, bWidth, height);\n const ctx = blueprint.getContext('2d', { alpha: false });\n if (!ctx) return;\n const imgData = ImageRenderer.createImageData(ctx, bWidth, height);\n const d32 = new Uint32Array(imgData.data.buffer);\n const black = toRGBA8888(0, 0, 0);\n const white = toRGBA8888(255, 255, 255);\n d32.fill(black);\n for (let y = 0; y < height; ++y) {\n const shift = y % 2;\n const offset = y * bWidth;\n for (let x = 0; x < bWidth; x += 2) {\n d32[offset + x + shift] = white;\n }\n }\n ctx.putImageData(imgData, 0, 0);\n\n // create placeholder line, width aligned to blueprint width\n const width = (screen.width + bWidth - 1) & ~(bWidth - 1) || Constants.PLACEHOLDER_LENGTH;\n this._placeholder = ImageRenderer.createCanvas(this.document, width, height);\n const ctx2 = this._placeholder.getContext('2d', { alpha: false });\n if (!ctx2) {\n this._placeholder = undefined;\n return;\n }\n for (let i = 0; i < width; i += bWidth) {\n ctx2.drawImage(blueprint, i, 0);\n }\n const placeholder = this._placeholder;\n ImageRenderer.createImageBitmap(placeholder).then(bitmap => {\n if (this._placeholder !== placeholder) bitmap?.close();\n else this._placeholderBitmap = bitmap;\n }).catch(() => {});\n }\n\n public get document(): Document | undefined {\n return this._terminal._core._coreBrowserService?.window.document;\n }\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageRenderer } from './ImageRenderer';\nimport {\n ITerminalExt, IExtendedAttrsImage, IImageAddonOptions, IImageSpec,\n IBufferLineExt, BgFlags, Cell, Content, ICellSize, ExtFlags, Attributes,\n UnderlineStyle, IAddImageOpts\n} from './Types';\n\n\n// fallback default cell size\nexport const CELL_SIZE_DEFAULT: ICellSize = {\n width: 7,\n height: 14\n};\n\n/**\n * Extend extended attribute to also hold image tile information.\n *\n * Object definition is copied from base repo to fully mimick its behavior.\n * Image data is added as additional public properties `imageId` and `tileId`.\n */\nclass ExtendedAttrsImage implements IExtendedAttrsImage {\n private _ext: number = 0;\n public get ext(): number {\n if (this._urlId) {\n return (\n (this._ext & ~ExtFlags.UNDERLINE_STYLE) |\n (this.underlineStyle << 26)\n );\n }\n return this._ext;\n }\n public set ext(value: number) { this._ext = value; }\n\n public get underlineStyle(): UnderlineStyle {\n // Always return the URL style if it has one\n if (this._urlId) {\n return UnderlineStyle.DASHED;\n }\n return (this._ext & ExtFlags.UNDERLINE_STYLE) >> 26;\n }\n public set underlineStyle(value: UnderlineStyle) {\n this._ext &= ~ExtFlags.UNDERLINE_STYLE;\n this._ext |= (value << 26) & ExtFlags.UNDERLINE_STYLE;\n }\n\n public get underlineColor(): number {\n return this._ext & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n public set underlineColor(value: number) {\n this._ext &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);\n this._ext |= value & (Attributes.CM_MASK | Attributes.RGB_MASK);\n }\n\n public get underlineVariantOffset(): number {\n const val = (this._ext & ExtFlags.VARIANT_OFFSET) >> 29;\n if (val < 0) {\n return val ^ 0xFFFFFFF8;\n }\n return val;\n }\n public set underlineVariantOffset(value: number) {\n this._ext &= ~ExtFlags.VARIANT_OFFSET;\n this._ext |= (value << 29) & ExtFlags.VARIANT_OFFSET;\n }\n\n private _urlId: number = 0;\n public get urlId(): number {\n return this._urlId;\n }\n public set urlId(value: number) {\n this._urlId = value;\n }\n\n constructor(\n ext: number = 0,\n urlId: number = 0,\n public imageId = -1,\n public tileId = -1\n ) {\n this._ext = ext;\n this._urlId = urlId;\n }\n\n public clone(): IExtendedAttrsImage {\n /**\n * Technically we dont need a clone variant of ExtendedAttrsImage,\n * as we never clone a cell holding image data.\n * Note: Clone is only meant to be used by the InputHandler for\n * sticky attributes, which is never the case for image data.\n * We still provide a proper clone method to reflect the full ext attr\n * state in case there are future use cases for clone.\n */\n return new ExtendedAttrsImage(this._ext, this._urlId, this.imageId, this.tileId);\n }\n\n public isEmpty(): boolean {\n return this.underlineStyle === UnderlineStyle.NONE && this._urlId === 0 && this.imageId === -1;\n }\n}\nconst EMPTY_ATTRS = new ExtendedAttrsImage();\n\n\n/**\n * ImageStorage - extension of CoreTerminal:\n * - hold image data\n * - write/read image data to/from buffer\n *\n * TODO: image composition for overwrites\n */\nexport class ImageStorage implements IDisposable {\n // storage\n private _images: Map = new Map();\n // last used id\n private _lastId = 0;\n // last evicted id\n private _lowestId = 0;\n // whether a full clear happened before\n private _fullyCleared = false;\n // whether render should do a full clear\n private _needsFullClear = false;\n // hard limit of stored pixels (fallback limit of 10 MB)\n private _pixelLimit: number = 2500000;\n\n private _viewportMetrics: { cols: number, rows: number };\n public onImageAdded: (() => void) | undefined;\n public onImageDeleted: ((storageId: number) => void) | undefined;\n\n constructor(\n private _terminal: ITerminalExt,\n private _renderer: ImageRenderer,\n private _opts: IImageAddonOptions\n ) {\n try {\n this.setLimit(this._opts.storageLimit);\n } catch (e: unknown) {\n if (e instanceof Error) {\n console.error(e.message);\n }\n console.warn(`storageLimit is set to ${this.getLimit()} MB`);\n }\n this._viewportMetrics = {\n cols: this._terminal.cols,\n rows: this._terminal.rows\n };\n }\n\n public dispose(): void {\n this.reset();\n }\n\n public reset(): void {\n for (const spec of this._images.values()) {\n spec.marker?.dispose();\n }\n // NOTE: marker.dispose above already calls ImageBitmap.close\n // therefore we can just wipe the map here\n this._images.clear();\n this._renderer.clearAll();\n }\n\n public getLimit(): number {\n return this._pixelLimit * 4 / 1000000;\n }\n\n public setLimit(value: number): void {\n if (value < 0.5 || value > 1000) {\n throw RangeError('invalid storageLimit, should be at least 0.5 MB and not exceed 1G');\n }\n this._pixelLimit = (value / 4 * 1000000) >>> 0;\n this._evictOldest(0);\n }\n\n public getUsage(): number {\n return this._getStoredPixels() * 4 / 1000000;\n }\n\n private _getStoredPixels(): number {\n let storedPixels = 0;\n for (const spec of this._images.values()) {\n if (spec.orig) {\n storedPixels += spec.orig.width * spec.orig.height;\n if (spec.actual && spec.actual !== spec.orig) {\n storedPixels += spec.actual.width * spec.actual.height;\n }\n }\n }\n return storedPixels;\n }\n\n private _delImg(id: number): void {\n const spec = this._images.get(id);\n if (!spec) return;\n this._images.delete(id);\n // FIXME: really ugly workaround to get bitmaps deallocated :(\n if (window.ImageBitmap && spec.orig instanceof ImageBitmap) {\n spec.orig.close();\n }\n this.onImageDeleted?.(id);\n }\n\n /**\n * Wipe canvas and images on alternate buffer.\n */\n public wipeAlternate(): void {\n // remove all alternate tagged images\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate') {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n // mark canvas to be wiped on next render\n this._needsFullClear = true;\n this._fullyCleared = false;\n }\n\n /**\n * Delete an image by its internal storage ID.\n * Used by protocols that support explicit deletion (e.g. Kitty a=d).\n */\n public deleteImage(id: number): void {\n const spec = this._images.get(id);\n if (spec) {\n spec.marker?.dispose();\n this._delImg(id);\n }\n }\n\n /**\n * Method to add an image to the storage.\n * @param img - The image to add (canvas or bitmap).\n * @param opts - Options for addImage:\n * - scrolling: When true, cursor advances with the image.\n * When false, image is placed at ORIGIN and cursor does not move.\n * - layer: Which canvas layer to render on ('top' or 'bottom').\n * - zIndex: Z-index for image layering within the same layer.\n * - cursorPos: 'vt340' for bottom-left, 'iip' for bottom.right.\n * @returns The internal image ID assigned to the stored image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap, opts: IAddImageOpts): number {\n // never allow storage to exceed memory limit\n this._evictOldest(img.width * img.height);\n\n // calc rows x cols needed to display the image\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const cols = Math.ceil(img.width / cellSize.width);\n const rows = Math.ceil(img.height / cellSize.height);\n\n const imageId = ++this._lastId;\n\n const buffer = this._terminal._core.buffer;\n const termCols = this._terminal.cols;\n const termRows = this._terminal.rows;\n const originX = buffer.x;\n const originY = buffer.y;\n let offset = originX;\n let tileCount = 0;\n\n if (!opts.scrolling) {\n buffer.x = 0;\n buffer.y = 0;\n offset = 0;\n }\n\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(buffer.y + buffer.ybase);\n for (let col = 0; col < cols; ++col) {\n if (offset + col >= termCols) break;\n this._writeToCell(line as IBufferLineExt, offset + col, imageId, row * cols + col);\n tileCount++;\n }\n if (opts.scrolling) {\n if (row < rows - 1) this._terminal._core._inputHandler.lineFeed();\n } else {\n if (++buffer.y >= termRows) break;\n }\n buffer.x = offset;\n }\n this._terminal._core._inputHandler._dirtyRowTracker.markDirty(buffer.y);\n\n // cursor positioning modes\n if (opts.scrolling) {\n if (opts.cursorPos === 'iip') {\n buffer.x = Math.min(offset + cols, termCols);\n } else {\n buffer.x = offset;\n }\n } else {\n buffer.x = originX;\n buffer.y = originY;\n }\n\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.tileCount < 1) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n\n // eviction marker:\n // delete the image when the marker gets disposed\n const endMarker = this._terminal.registerMarker(0);\n endMarker?.onDispose(() => {\n const spec = this._images.get(imageId);\n if (spec) {\n this._delImg(imageId);\n }\n });\n\n // since markers do not work on alternate for some reason,\n // we evict images here manually\n if (this._terminal.buffer.active.type === 'alternate') {\n this._evictOnAlternate();\n }\n\n // create storage entry\n const imgSpec: IImageSpec = {\n orig: img,\n origCellSize: cellSize,\n actual: img,\n actualCellSize: { ...cellSize }, // clone needed, since later modified\n marker: endMarker || undefined,\n tileCount,\n bufferType: this._terminal.buffer.active.type,\n layer: opts.layer,\n zIndex: opts.zIndex\n };\n\n // finally add the image\n this._images.set(imageId, imgSpec);\n this.onImageAdded?.();\n return imageId;\n }\n\n\n /**\n * Render method. Collects buffer information and triggers\n * canvas updates.\n */\n // TODO: Should we move this to the ImageRenderer?\n public render(range: { start: number, end: number }): void {\n // Determine which layers have images\n let hasTopImages = false;\n let hasBottomImages = false;\n for (const spec of this._images.values()) {\n if (spec.layer === 'bottom') {\n hasBottomImages = true;\n } else {\n hasTopImages = true;\n }\n if (hasTopImages && hasBottomImages) break;\n }\n\n // Lazily insert layers that are needed\n if (hasTopImages && !this._renderer.hasLayer('top')) {\n this._renderer.insertLayerToDom('top');\n if (!this._renderer.hasLayer('top')) return;\n }\n if (hasBottomImages && !this._renderer.hasLayer('bottom')) {\n this._renderer.insertLayerToDom('bottom');\n }\n\n // rescale if needed\n this._renderer.rescaleCanvas();\n\n // exit early if we dont have any images to test for\n if (!this._images.size) {\n if (!this._fullyCleared) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n if (this._renderer.hasLayer('top')) {\n this._renderer.removeLayerFromDom('top');\n }\n if (this._renderer.hasLayer('bottom')) {\n this._renderer.removeLayerFromDom('bottom');\n }\n return;\n }\n\n // Remove layers no longer needed\n if (!hasTopImages && this._renderer.hasLayer('top')) {\n this._renderer.clearAll('top');\n this._renderer.removeLayerFromDom('top');\n }\n if (!hasBottomImages && this._renderer.hasLayer('bottom')) {\n this._renderer.clearAll('bottom');\n this._renderer.removeLayerFromDom('bottom');\n }\n\n // buffer switches force a full clear\n if (this._needsFullClear) {\n this._renderer.clearAll();\n this._fullyCleared = true;\n this._needsFullClear = false;\n }\n\n const { start, end } = range;\n const buffer = this._terminal._core.buffer;\n const cols = this._terminal._core.cols;\n\n // clear drawing area\n this._renderer.clearLines(start, end);\n\n // Collect draw calls so we can sort by z-index (lower z drawn first).\n const drawCalls: { imgSpec: IImageSpec, tileId: number, col: number, row: number, count: number }[] = [];\n const placeholderCalls: { col: number, row: number, count: number }[] = [];\n\n // walk all cells in viewport and collect tiles found\n for (let row = start; row <= end; ++row) {\n const line = buffer.lines.get(row + buffer.ydisp) as IBufferLineExt;\n if (!line) return;\n for (let col = 0; col < cols; ++col) {\n if (line.getBg(col) & BgFlags.HAS_EXTENDED) {\n let e: IExtendedAttrsImage = line._extendedAttrs[col] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (e.tileId !== -1) {\n const startTile = e.tileId;\n const startCol = col;\n let count = 1;\n /**\n * merge tiles to the right into a single draw call, if:\n * - not at end of line\n * - cell has same image id\n * - cell has consecutive tile id\n */\n while (\n ++col < cols\n && (line.getBg(col) & BgFlags.HAS_EXTENDED)\n && (e = line._extendedAttrs[col] ?? EMPTY_ATTRS)\n && (e.imageId === imageId)\n && (e.tileId === startTile + count)\n ) {\n count++;\n }\n col--;\n if (imgSpec) {\n if (imgSpec.actual) {\n drawCalls.push({ imgSpec, tileId: startTile, col: startCol, row, count });\n }\n } else if (this._opts.showPlaceholder) {\n placeholderCalls.push({ col: startCol, row, count });\n }\n this._fullyCleared = false;\n }\n }\n }\n }\n\n // Sort by z-index so lower z draws first (higher z renders on top)\n drawCalls.sort((a, b) => a.imgSpec.zIndex - b.imgSpec.zIndex);\n\n // Draw placeholders first (lowest priority)\n for (const call of placeholderCalls) {\n this._renderer.drawPlaceholder(call.col, call.row, call.count);\n }\n\n // Draw images in z-index order\n for (const call of drawCalls) {\n this._renderer.draw(call.imgSpec, call.tileId, call.col, call.row, call.count);\n }\n }\n\n public viewportResize(metrics: { cols: number, rows: number }): void {\n // exit early if we have nothing in storage\n if (!this._images.size) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // handle only viewport width enlargements, exit all other cases\n // TODO: needs patch for tile counter\n if (this._viewportMetrics.cols >= metrics.cols) {\n this._viewportMetrics = metrics;\n return;\n }\n\n // walk scrollbuffer at old col width to find all possible expansion matches\n const buffer = this._terminal._core.buffer;\n const rows = buffer.lines.length;\n const oldCol = this._viewportMetrics.cols - 1;\n for (let row = 0; row < rows; ++row) {\n const line = buffer.lines.get(row) as IBufferLineExt;\n if (line.getBg(oldCol) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[oldCol] ?? EMPTY_ATTRS;\n const imageId = e.imageId;\n if (imageId === undefined || imageId === -1) {\n continue;\n }\n const imgSpec = this._images.get(imageId);\n if (!imgSpec) {\n continue;\n }\n // found an image tile at oldCol, check if it qualifies for right exapansion\n const tilesPerRow = Math.ceil((imgSpec.actual?.width || 0) / imgSpec.actualCellSize.width);\n if ((e.tileId % tilesPerRow) + 1 >= tilesPerRow) {\n continue;\n }\n // expand only if right side is empty (nothing got wrapped from below)\n let hasData = false;\n for (let rightCol = oldCol + 1; rightCol > metrics.cols; ++rightCol) {\n if (line._data[rightCol * Cell.SIZE + Cell.CONTENT] & Content.HAS_CONTENT_MASK) {\n hasData = true;\n break;\n }\n }\n if (hasData) {\n continue;\n }\n // do right expansion on terminal buffer\n const end = Math.min(metrics.cols, tilesPerRow - (e.tileId % tilesPerRow) + oldCol);\n let lastTile = e.tileId;\n for (let expandCol = oldCol + 1; expandCol < end; ++expandCol) {\n this._writeToCell(line as IBufferLineExt, expandCol, imageId, ++lastTile);\n imgSpec.tileCount++;\n }\n }\n }\n // store new viewport metrics\n this._viewportMetrics = metrics;\n }\n\n /**\n * Retrieve original canvas at buffer position.\n */\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1) {\n const orig = this._images.get(e.imageId)?.orig;\n if (window.ImageBitmap && orig instanceof ImageBitmap) {\n const canvas = ImageRenderer.createCanvas(window.document, orig.width, orig.height);\n canvas.getContext('2d')?.drawImage(orig, 0, 0, orig.width, orig.height);\n return canvas;\n }\n return orig as HTMLCanvasElement;\n }\n }\n }\n\n /**\n * Extract active single tile at buffer position.\n */\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n const buffer = this._terminal._core.buffer;\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (line && line.getBg(x) & BgFlags.HAS_EXTENDED) {\n const e: IExtendedAttrsImage = line._extendedAttrs[x] ?? EMPTY_ATTRS;\n if (e.imageId && e.imageId !== -1 && e.tileId !== -1) {\n const spec = this._images.get(e.imageId);\n if (spec) {\n return this._renderer.extractTile(spec, e.tileId);\n }\n }\n }\n }\n\n // TODO: Do we need some blob offloading tricks here to avoid early eviction?\n // also see https://stackoverflow.com/questions/28307789/is-there-any-limitation-on-javascript-max-blob-size\n private _evictOldest(room: number): number {\n const used = this._getStoredPixels();\n let current = used;\n while (this._pixelLimit < current + room && this._images.size) {\n const spec = this._images.get(++this._lowestId);\n if (spec && spec.orig) {\n current -= spec.orig.width * spec.orig.height;\n if (spec.actual && spec.orig !== spec.actual) {\n current -= spec.actual.width * spec.actual.height;\n }\n spec.marker?.dispose();\n this._delImg(this._lowestId);\n }\n }\n return used - current;\n }\n\n private _writeToCell(line: IBufferLineExt, x: number, imageId: number, tileId: number): void {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const old = line._extendedAttrs[x];\n if (old) {\n if (old.imageId !== undefined) {\n // found an old ExtendedAttrsImage, since we know that\n // they are always isolated instances (single cell usage),\n // we can re-use it and just update their id entries\n const oldSpec = this._images.get(old.imageId);\n if (oldSpec) {\n // early eviction for in-viewport overwrites\n oldSpec.tileCount--;\n }\n old.imageId = imageId;\n old.tileId = tileId;\n return;\n }\n // found a plain ExtendedAttrs instance, clone it to new entry\n line._extendedAttrs[x] = new ExtendedAttrsImage(old.ext, old.urlId, imageId, tileId);\n return;\n }\n }\n // fall-through: always create new ExtendedAttrsImage entry\n line._data[x * Cell.SIZE + Cell.BG] |= BgFlags.HAS_EXTENDED;\n line._extendedAttrs[x] = new ExtendedAttrsImage(0, 0, imageId, tileId);\n }\n\n private _evictOnAlternate(): void {\n // nullify tile count of all images on alternate buffer\n for (const spec of this._images.values()) {\n if (spec.bufferType === 'alternate') {\n spec.tileCount = 0;\n }\n }\n // re-count tiles on whole buffer\n const buffer = this._terminal._core.buffer;\n for (let y = 0; y < this._terminal.rows; ++y) {\n const line = buffer.lines.get(y) as IBufferLineExt;\n if (!line) {\n continue;\n }\n for (let x = 0; x < this._terminal.cols; ++x) {\n if (line._data[x * Cell.SIZE + Cell.BG] & BgFlags.HAS_EXTENDED) {\n const imgId = line._extendedAttrs[x]?.imageId;\n if (imgId) {\n const spec = this._images.get(imgId);\n if (spec) {\n spec.tileCount++;\n }\n }\n }\n }\n }\n // deleted images with zero tile count\n const zero = [];\n for (const [id, spec] of this._images.entries()) {\n if (spec.bufferType === 'alternate' && !spec.tileCount) {\n spec.marker?.dispose();\n zero.push(id);\n }\n }\n for (const id of zero) {\n this._delImg(id);\n }\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\nimport { IImageAddonOptions, IOscHandler, IResetHandler, ITerminalExt } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { CELL_SIZE_DEFAULT } from './ImageStorage';\nimport Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport QoiDecoder from 'xterm-wasm-parts/lib/qoi/QoiDecoder.wasm';\nimport { HeaderParser, IHeaderFields, HeaderState, SequenceType } from './IIPHeaderParser';\nimport { imageType, UNSUPPORTED_TYPE } from './IIPMetrics';\n\n// Local const enum mirror - esbuild can't inline const enums from external packages\nconst enum DecoderConst {\n // Held memory in base64/QOI decoders between images. Zero because each kept\n // decoder pins a wasm memory, and V8 caps those per process (~124 in a\n // sandboxed renderer), so idle terminals must not hold one.\n KEEP_DATA = 0,\n // Initial buffer allocation for the decoder.\n INITIAL_DATA = 1048576,\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n OK = 0\n}\n\n// default IIP header values\nconst DEFAULT_HEADER: IHeaderFields = {\n type: SequenceType.INVALID,\n name: 'Unnamed file',\n size: 0,\n width: 'auto',\n height: 'auto',\n preserveAspectRatio: 1,\n inline: 0\n};\n\n\nexport class IIPHandler implements IOscHandler, IResetHandler {\n private _generation = 0;\n private _aborted = false;\n private _hp = new HeaderParser();\n private _header: IHeaderFields = DEFAULT_HEADER;\n private _dec: Base64Decoder;\n private _qoiDec: QoiDecoder;\n private _isMultipart = false;\n private _abortMulti = false;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _storage: IIPImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n const maxEncodedBytes = Math.ceil(this._opts.iipSizeLimit * 4 / 3);\n const initialBytes = Math.min(DecoderConst.INITIAL_DATA, maxEncodedBytes);\n this._dec = new Base64Decoder(DecoderConst.KEEP_DATA, maxEncodedBytes, initialBytes);\n this._qoiDec = new QoiDecoder(DecoderConst.KEEP_DATA);\n }\n\n public reset(): void {\n this._generation++;\n this._hp.reset();\n this._dec.release();\n this._qoiDec.release();\n }\n\n public start(): void {\n this._aborted = false;\n this._hp.reset();\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (this._hp.state === HeaderState.END) {\n if ((this._dec.put(data.subarray(start, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n }\n } else {\n const dataPos = this._hp.parse(data, start, end);\n if (dataPos === -1) {\n this._aborted = true;\n return;\n }\n if (dataPos > 0) {\n const seqType = this._hp.fields.type;\n if (seqType === SequenceType.FILE) {\n if (this._isMultipart) {\n this._isMultipart = false;\n this._abortMulti = false;\n this._dec.release();\n }\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n if (!this._header.inline) {\n this._aborted = true;\n return;\n }\n if (!this._initDecoder()) {\n this._aborted = true;\n return;\n }\n } else if (this._abortMulti) {\n this._aborted = true;\n return;\n }\n if ((this._dec.put(data.subarray(dataPos, end)) as number) !== DecoderConst.OK) {\n this._dec.release();\n this._aborted = true;\n if (this._isMultipart) this._abortMulti = true;\n }\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted) return true;\n\n if (this._hp.state !== HeaderState.END) {\n if (this._hp.end()) return true;\n }\n const seqType = this._hp.fields.type;\n\n if (seqType === SequenceType.FILEPART) return true;\n\n if (seqType === SequenceType.REPORTCELLSIZE) {\n // OSC 1337 ; ReportCellSize=[height];[width];[scale] ST\n let w = CELL_SIZE_DEFAULT.width;\n let h = CELL_SIZE_DEFAULT.height;\n if (this._renderer.dimensions) {\n w = this._renderer.dimensions.css.canvas.width / this._coreTerminal.cols;\n h = this._renderer.dimensions.css.canvas.height / this._coreTerminal.rows;\n }\n const scale = this._coreTerminal._core._coreBrowserService?.dpr ?? 1;\n const report = `\\x1b]1337;ReportCellSize=${h.toFixed(3)};${w.toFixed(3)};${scale.toFixed(3)}\\x1b\\\\`;\n this._coreTerminal.input(report, false);\n return true;\n }\n\n if (seqType === SequenceType.MULTIPARTFILE) {\n this._header = Object.assign({}, DEFAULT_HEADER, this._hp.fields);\n this._isMultipart = true;\n this._abortMulti = false;\n this._dec.release();\n if (!this._initDecoder()) {\n this._abortMulti = true;\n }\n return true;\n }\n\n if (seqType === SequenceType.FILEEND) {\n if (!this._isMultipart) return true;\n this._isMultipart = false;\n if (this._abortMulti || this._header.type !== SequenceType.MULTIPARTFILE) return true;\n }\n\n // fallthrough for SequenceType.FILE & SequenceType.FILEEND\n\n let w = 0;\n let h = 0;\n\n // early exit condition chain\n let cond: number | boolean;\n let metrics = UNSUPPORTED_TYPE;\n if (cond = success) {\n if (cond = !this._dec.end()) {\n metrics = imageType(this._dec.data8);\n if (cond = metrics.mime !== 'unsupported') {\n w = metrics.width;\n h = metrics.height;\n if (cond = w && h && w * h < this._opts.pixelLimit) {\n [w, h] = this._resize(w, h).map(Math.floor);\n cond = w && h && w * h < this._opts.pixelLimit;\n } else {\n console.warn(`IIP: image dimension issue ${metrics.width}x${metrics.height}`);\n }\n } else {\n console.warn('IIP: unsupported image type');\n }\n } else {\n console.warn('IIP: error during BASE64 decoding');\n }\n }\n if (!cond) {\n this._dec.release();\n return true;\n }\n\n let blob: Blob | ImageData;\n if (metrics.mime === 'image/qoi') {\n let data: Uint8Array;\n try {\n data = this._qoiDec.decode(this._dec.data8);\n } catch (e) {\n console.warn('IIP: could not decode QOI image', e);\n this._dec.release();\n this._qoiDec.release();\n return true;\n }\n blob = new ImageData(\n new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength),\n this._qoiDec.width,\n this._qoiDec.height\n );\n this._qoiDec.release();\n if (w === this._qoiDec.width && h === this._qoiDec.height) {\n // use fast-path if we don't need to rescale\n this._dec.release();\n const canvas = ImageRenderer.createCanvas(undefined, this._qoiDec.width, this._qoiDec.height);\n canvas.getContext('2d')?.putImageData(blob, 0, 0);\n this._storage.addImage(canvas);\n return true;\n }\n } else {\n blob = new Blob([this._dec.data8], { type: metrics.mime });\n }\n this._dec.release();\n const generation = this._generation;\n return createImageBitmap(blob, { resizeWidth: w, resizeHeight: h })\n .then(bm => {\n if (generation !== this._generation) {\n bm.close();\n return true;\n }\n this._storage.addImage(bm);\n return true;\n })\n .catch(e => {\n console.warn(`IIP: decoding error ${metrics.mime} ${metrics.width}x${metrics.height}`, e);\n return true;\n });\n }\n\n // Why: wasm memory exhaustion must drop this image, not throw out of the parser and wedge the write queue.\n private _initDecoder(): boolean {\n try {\n this._dec.init();\n return true;\n } catch (e) {\n console.warn('IIP: could not allocate decoder', e);\n this._dec.release();\n return false;\n }\n }\n\n private _resize(w: number, h: number): [number, number] {\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n const width = this._renderer.dimensions?.css.canvas.width || cw * this._coreTerminal.cols;\n const height = this._renderer.dimensions?.css.canvas.height || ch * this._coreTerminal.rows;\n\n const rw = this._dim(this._header.width!, width, cw);\n const rh = this._dim(this._header.height!, height, ch);\n if (!rw && !rh) {\n const wf = width / w; // TODO: should this respect initial cursor offset?\n const hf = (height - ch) / h; // TODO: fix offset issues from float cell height\n const f = Math.min(wf, hf);\n return f < 1 ? [w * f, h * f] : [w, h];\n }\n return !rw\n ? [w * rh / h, rh]\n : this._header.preserveAspectRatio || !rw || !rh\n ? [rw, h * rw / w] : [rw, rh];\n }\n\n private _dim(s: string, total: number, cdim: number): number {\n if (s === 'auto') return 0;\n if (s.endsWith('%')) return parseInt(s.slice(0, -1), 10) * total / 100;\n if (s.endsWith('px')) return parseInt(s.slice(0, -2), 10);\n return parseInt(s, 10) * cdim;\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n// eslint-disable-next-line\ndeclare const Buffer: any;\n\nexport const enum HeaderState {\n START = 0,\n ABORT = 1,\n KEY = 2,\n VALUE = 3,\n END = 4\n}\n\nexport const enum SequenceType {\n INVALID = 0,\n FILE = 1,\n MULTIPARTFILE = 2,\n FILEPART = 3,\n FILEEND = 4,\n REPORTCELLSIZE = 5\n}\n\nexport interface IHeaderFields {\n [key: string]: number | string | Uint32Array | null | undefined;\n // sequence type\n type: SequenceType;\n // base-64 encoded filename. Defaults to \"Unnamed file\".\n name: string;\n // File size in bytes. The file transfer will be canceled if this size is exceeded.\n size: number;\n /**\n * Optional width and height to render:\n * - N: N character cells.\n * - Npx: N pixels.\n * - N%: N percent of the session's width or height.\n * - auto: The image's inherent size will be used to determine an appropriate dimension.\n */\n width?: string;\n height?: string;\n // Optional, defaults to 1 respecting aspect ratio (width takes precedence).\n preserveAspectRatio?: number;\n // Optional, defaults to 0. If set to 1, the file will be displayed inline, else downloaded\n // (download not supported).\n inline?: number;\n}\n\n// field value decoders\n\n// ASCII bytes to string\nfunction toStr(data: Uint32Array): string {\n let s = '';\n for (let i = 0; i < data.length; ++i) {\n s += String.fromCharCode(data[i]);\n }\n return s;\n}\n\n// digits to integer\nfunction toInt(data: Uint32Array): number {\n let v = 0;\n for (let i = 0; i < data.length; ++i) {\n if (data[i] < 48 || data[i] > 57) {\n throw new Error('illegal char');\n }\n v = v * 10 + data[i] - 48;\n }\n return v;\n}\n\n// check for correct size entry\nfunction toSize(data: Uint32Array): string {\n const v = toStr(data);\n if (!v.match(/^((auto)|(\\d+?((px)|(%)){0,1}))$/)) {\n throw new Error('illegal size');\n }\n return v;\n}\n\n// name is base64 encoded utf-8\nfunction toName(data: Uint32Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(toStr(data), 'base64').toString();\n }\n const bs = atob(toStr(data));\n const b = new Uint8Array(bs.length);\n for (let i = 0; i < b.length; ++i) {\n b[i] = bs.charCodeAt(i);\n }\n return new TextDecoder().decode(b);\n}\n\nconst DECODERS: {[key: string]: (v: Uint32Array) => number | string} = {\n inline: toInt,\n size: toInt,\n name: toName,\n width: toSize,\n height: toSize,\n preserveAspectRatio: toInt\n};\n\n\n// sequence type markers\n// File\nconst FILE_MARKER = [70, 105, 108, 101];\n// MultipartFile\nconst MULTIPARTFILE_MARKER = [77, 117, 108, 116, 105, 112, 97, 114, 116, 70, 105, 108, 101];\n// FilePart\nconst FILEPART_MARKER = [70, 105, 108, 101, 80, 97, 114, 116];\n// FileEnd\nconst FILEEND_MARKER = [70, 105, 108, 101, 69, 110, 100];\n// ReportCellSize\nconst REPORTCELLSIZE_MARKER = [82, 101, 112, 111, 114, 116, 67, 101, 108, 108, 83, 105, 122, 101];\n\n// max allowed chars for sequence header\nconst MAX_FIELDCHARS = 1024;\n\n\nexport class HeaderParser {\n public state: HeaderState = HeaderState.START;\n private _buffer = new Uint32Array(MAX_FIELDCHARS);\n private _position = 0;\n private _key = '';\n public fields: {[key: string]: number | string | Uint32Array | null | undefined} = {};\n\n public reset(): void {\n this._buffer.fill(0);\n this.state = HeaderState.START;\n this._position = 0;\n this.fields = {};\n this._key = '';\n }\n\n public end(): number {\n if (this.state === HeaderState.START) {\n if (this._position === FILEEND_MARKER.length) {\n for (let k = 0; k < FILEEND_MARKER.length; ++k) {\n if (this._buffer[k] !== FILEEND_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEEND;\n this.state = HeaderState.END;\n return 0;\n }\n if (this._position === REPORTCELLSIZE_MARKER.length) {\n for (let k = 0; k < REPORTCELLSIZE_MARKER.length; ++k) {\n if (this._buffer[k] !== REPORTCELLSIZE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.REPORTCELLSIZE;\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n if (this.state === HeaderState.END) return 0;\n if (this.state === HeaderState.VALUE\n && this.fields.type === SequenceType.MULTIPARTFILE\n ) {\n if (!this._storeValue(this._position)) return this._a();\n this.state = HeaderState.END;\n return 0;\n }\n return this._a();\n }\n\n public parse(data: Uint32Array, start: number, end: number): number {\n let state = this.state;\n let pos = this._position;\n const buffer = this._buffer;\n if (state === HeaderState.ABORT || state === HeaderState.END) return -1;\n if (state === HeaderState.START && pos > 14) return -1;\n for (let i = start; i < end; ++i) {\n const c = data[i];\n switch (c) {\n case 59: // ;\n if (!this._storeValue(pos)) return this._a();\n state = HeaderState.KEY;\n pos = 0;\n break;\n case 61: // =\n if (state === HeaderState.START) {\n if (buffer[0] === 70) {\n // 'File' or 'FilePart'\n let k = 0;\n for (; k < FILE_MARKER.length; ++k) {\n if (buffer[k] !== FILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILE;\n if (pos === FILEPART_MARKER.length) {\n for (; k < FILEPART_MARKER.length; ++k) {\n if (buffer[k] !== FILEPART_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.FILEPART;\n this.state = HeaderState.END;\n return i + 1;\n }\n } else if (buffer[0] === 77) {\n // 'MultipartFile'\n for (let k = 0; k < MULTIPARTFILE_MARKER.length; ++k) {\n if (buffer[k] !== MULTIPARTFILE_MARKER[k]) return this._a();\n }\n this.fields['type'] = SequenceType.MULTIPARTFILE;\n } else {\n return this._a();\n }\n state = HeaderState.KEY;\n pos = 0;\n } else if (state === HeaderState.KEY) {\n if (!this._storeKey(pos)) return this._a();\n state = HeaderState.VALUE;\n pos = 0;\n } else if (state === HeaderState.VALUE) {\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n break;\n case 58: // :\n if (state === HeaderState.VALUE) {\n if (!this._storeValue(pos)) return this._a();\n }\n this.state = HeaderState.END;\n return i + 1;\n default:\n if (pos >= MAX_FIELDCHARS) return this._a();\n buffer[pos++] = c;\n }\n }\n this.state = state;\n this._position = pos;\n return -2;\n }\n\n private _a(): number {\n this.fields.type = SequenceType.INVALID;\n this.state = HeaderState.ABORT;\n return -1;\n }\n\n private _storeKey(pos: number): boolean {\n const k = toStr(this._buffer.subarray(0, pos));\n if (k) {\n this._key = k;\n this.fields[k] = null;\n return true;\n }\n return false;\n }\n\n private _storeValue(pos: number): boolean {\n if (this._key) {\n try {\n const v = this._buffer.slice(0, pos);\n this.fields[this._key] = DECODERS[this._key] ? DECODERS[this._key](v) : v;\n } catch {\n return false;\n }\n return true;\n }\n return false;\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\n\nexport type ImageType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/qoi' | 'image/webp' | 'image/avif' | 'unsupported' | '';\n\nexport interface IMetrics {\n mime: ImageType;\n width: number;\n height: number;\n}\n\nexport const UNSUPPORTED_TYPE: IMetrics = {\n mime: 'unsupported',\n width: 0,\n height: 0\n};\n\nexport function imageType(d: Uint8Array): IMetrics {\n if (d.length < 32) {\n return UNSUPPORTED_TYPE;\n }\n const d32 = new Uint32Array(d.buffer, d.byteOffset, 8);\n // PNG: 89 50 4E 47 0D 0A 1A 0A (8 first bytes == magic number for PNG)\n // + first chunk must be IHDR\n if (d32[0] === 0x474E5089 && d32[1] === 0x0A1A0A0D && d32[3] === 0x52444849) {\n return {\n mime: 'image/png',\n width: d[16] << 24 | d[17] << 16 | d[18] << 8 | d[19],\n height: d[20] << 24 | d[21] << 16 | d[22] << 8 | d[23]\n };\n }\n // JPEG: FF D8 FF\n if (d[0] === 0xFF && d[1] === 0xD8 && d[2] === 0xFF) {\n const [width, height] = jpgSize(d);\n return { mime: 'image/jpeg', width, height };\n }\n // GIF: GIF87a or GIF89a\n if (d32[0] === 0x38464947 && (d[4] === 0x37 || d[4] === 0x39) && d[5] === 0x61) {\n return {\n mime: 'image/gif',\n width: d[7] << 8 | d[6],\n height: d[9] << 8 | d[8]\n };\n }\n // QOI: qoif\n if (d32[0] === 0x66696F71) {\n return {\n mime: 'image/qoi',\n width: d[4] << 24 | d[5] << 16 | d[6] << 8 | d[7],\n height: d[8] << 24 | d[9] << 16 | d[10] << 8 | d[11]\n };\n }\n // WEBP: RIFF | xxxx | WEBP | VP8x\n if (d32[0] === 0x46464952 && d32[2] === 0x50424557 && (d32[3] & 0xFFFFFF) === 0x385056) {\n switch (d[15]) {\n case 0x58: // Extended WebP VP8X --> \"X\"\n return {\n mime: 'image/webp',\n width: (d[24] | d[25] << 8 | d[26] << 16) + 1,\n height: (d[27] | d[28] << 8 | d[29] << 16) + 1\n };\n case 0x4C: // Lossless WebP VP8L --> \"L\"\n if (d[20] !== 0x2f) return UNSUPPORTED_TYPE;\n const dim = d[21] | d[22] << 8 | d[23] << 16 | d[24] << 24;\n return {\n mime: 'image/webp',\n width: (dim & 0x3FFF) + 1,\n height: (dim >>> 14 & 0x3FFF) + 1\n };\n case 0x20: // Lossy WebP VP8 --> \" \"\n if (d[23] !== 0x9d || d[24] !== 0x01 || d[25] !== 0x2a) return UNSUPPORTED_TYPE;\n return {\n mime: 'image/webp',\n width: (d[26] | d[27] << 8) & 0x3FFF,\n height: (d[28] | d[29] << 8) & 0x3FFF\n };\n }\n return UNSUPPORTED_TYPE;\n }\n // AVIF: Box size | ftyp | avif/avis\n if (d32[1] === 0x70797466 && (d32[2] === 0x66697661 || d32[2] === 0x73697661)) {\n let pos = -1;\n // search for ispe box within first 1024 bytes\n const limit = Math.min(d.length - 16, 1024);\n for (let i = 8; i < limit; i++) {\n // scan for ispe\n if (d[i] === 0x69 && d[i + 1] === 0x73 && d[i + 2] === 0x70 && d[i + 3] === 0x65) {\n pos = i;\n break;\n }\n }\n if (pos !== -1) {\n // dimensions are in BE at +8 (width) at +12 (height)\n const width =\n d[pos + 8] << 24 |\n d[pos + 9] << 16 |\n d[pos + 10] << 8 |\n d[pos + 11];\n const height =\n d[pos + 12] << 24 |\n d[pos + 13] << 16 |\n d[pos + 14] << 8 |\n d[pos + 15];\n if (width > 0 && height > 0) {\n return { mime: 'image/avif', width, height };\n }\n }\n return UNSUPPORTED_TYPE;\n }\n return UNSUPPORTED_TYPE;\n}\n\n\nfunction jpgSize(d: Uint8Array): [number, number] {\n const len = d.length;\n let i = 4;\n let blockLength = d[i] << 8 | d[i + 1];\n while (true) {\n i += blockLength;\n if (i >= len) {\n // exhausted without size info\n return [0, 0];\n }\n if (d[i] !== 0xFF) {\n return [0, 0];\n }\n if (d[i + 1] === 0xC0 || d[i + 1] === 0xC2) {\n if (i + 8 < len) {\n return [\n d[i + 7] << 8 | d[i + 8],\n d[i + 5] << 8 | d[i + 6]\n ];\n }\n return [0, 0];\n }\n i += 2;\n blockLength = d[i] << 8 | d[i + 1];\n }\n}\n", "/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { IApcHandler, IImageAddonOptions, IResetHandler, ITerminalExt, ImageLayer } from '../Types';\nimport { ImageRenderer } from '../ImageRenderer';\nimport { CELL_SIZE_DEFAULT } from '../ImageStorage';\nimport { imageType } from '../IIPMetrics';\nimport { KittyImageStorage } from './KittyImageStorage';\nimport Base64Decoder, { type DecodeStatus } from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\nimport {\n KittyAction,\n KittyFormat,\n KittyCompression,\n IKittyCommand,\n IPendingTransmission,\n IKittyImageData,\n KittyPixelConstants,\n parseKittyCommand\n} from './KittyGraphicsTypes';\n\nconst enum Constants {\n // Memory limit for base64 decoder (4MB, same as IIPHandler)\n DECODER_KEEP_DATA = 4194304,\n DECODER_INITIAL_DATA = 4194304, // 4MB\n // Local mirror of const enum (esbuild can't inline const enums from external packages)\n DECODER_OK = 0,\n // Maximum control data size\n MAX_CONTROL_DATA_SIZE = 512,\n // Semicolon codepoint\n SEMICOLON = 0x3B\n}\n\nconst DECODER_OK = Constants.DECODER_OK as unknown as DecodeStatus.OK;\n\n// Kitty graphics protocol handler with streaming base64 decoding.\nexport class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDisposable {\n private _aborted = false;\n private _generation = 0;\n private _decodeError = false;\n\n private _activeDecoder: Base64Decoder | null = null;\n private readonly _maxEncodedBytes: number;\n private readonly _initialEncodedBytes: number;\n\n // Streaming related states\n\n // True while receiving control data (before semicolon).\n private _inControlData = true;\n\n // Buffer for control data.\n private _controlData = new Uint32Array(Constants.MAX_CONTROL_DATA_SIZE);\n private _controlLength = 0;\n\n // Pre-calculated encoded size limit\n private _encodedSizeLimit = 0;\n private _totalEncodedSize = 0;\n\n // Parsed command. These are the control data before semicolon.\n private _parsedCommand: IKittyCommand | null = null;\n\n // Storage related states\n\n private _pendingTransmissions: Map = new Map();\n // Tracks the pending key of the most recently started chunked upload.\n // Per spec, subsequent chunks only need m= (and optionally q=), without i=.\n // When a chunk arrives with no i=, this key is used to find the pending upload.\n private _lastPendingKey: number | undefined;\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _kittyStorage: KittyImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n // Convert decoded size limit -> max encoded bytes.\n this._maxEncodedBytes = Math.ceil(this._opts.kittySizeLimit * 4 / 3);\n // ensure we preallocate more than configured limit while using 4mb initial size.\n this._initialEncodedBytes = Math.min(Constants.DECODER_INITIAL_DATA, this._maxEncodedBytes);\n }\n\n public reset(): void {\n this._generation++;\n this._cleanupAllPending();\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n this._kittyStorage.reset();\n }\n\n public dispose(): void {\n this.reset();\n }\n\n private _removePendingEntry(key: number): void {\n this._pendingTransmissions.delete(key);\n if (this._lastPendingKey === key) {\n this._lastPendingKey = undefined;\n }\n }\n\n private _cleanupAllPending(): void {\n for (const pending of this._pendingTransmissions.values()) {\n pending.decoder.release();\n }\n this._pendingTransmissions.clear();\n this._lastPendingKey = undefined;\n }\n\n public start(): void {\n this._aborted = false;\n this._decodeError = false;\n this._inControlData = true;\n this._controlLength = 0;\n this._parsedCommand = null;\n // Pre-calculate encoded limit once: base64 is 4 bytes encoded \u2192 3 bytes decoded\n this._encodedSizeLimit = this._maxEncodedBytes;\n this._totalEncodedSize = 0;\n this._activeDecoder = null;\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n if (!this._inControlData) {\n this._streamPayload(data, start, end);\n } else {\n // Scan for semicolon\n let controlEnd = end;\n for (let i = start; i < end; i++) {\n if (data[i] === Constants.SEMICOLON) {\n this._inControlData = false;\n controlEnd = i;\n break;\n }\n }\n\n // Copy control data\n const copyLength = controlEnd - start;\n if (this._controlLength + copyLength > Constants.MAX_CONTROL_DATA_SIZE) {\n this._aborted = true;\n return;\n }\n this._controlData.set(data.subarray(start, controlEnd), this._controlLength);\n this._controlLength += copyLength;\n\n if (!this._inControlData) {\n // Found semicolon - parse control data early for validation\n this._parsedCommand = parseKittyCommand(this._parseControlDataString());\n\n // Early validation: i+I conflict\n if (this._parsedCommand.id !== undefined && this._parsedCommand.imageNumber !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'EINVAL:cannot specify both i and I keys', this._parsedCommand.quiet ?? 0);\n this._aborted = true;\n return;\n }\n\n // Delete action doesn't need payload - skip streaming\n if (this._parsedCommand.action === KittyAction.DELETE) {\n return;\n }\n\n // Stream remaining as payload\n const payloadStart = controlEnd + 1;\n if (payloadStart < end) {\n this._streamPayload(data, payloadStart, end);\n }\n }\n }\n }\n\n // Stream payload bytes into the base64 decoder.\n private _streamPayload(data: Uint32Array, start: number, end: number): void {\n if (this._aborted) return;\n\n // Check size limit (compare encoded bytes against pre-calculated limit)\n // Include cumulative size from pending transmission for multi-chunk images.\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = this._parsedCommand?.id ?? this._lastPendingKey ?? 0;\n const pending = this._pendingTransmissions.get(pendingKey);\n const previousEncodedSize = pending?.totalEncodedSize ?? 0;\n this._totalEncodedSize += end - start;\n const cumulativeEncodedSize = previousEncodedSize + this._totalEncodedSize;\n if (cumulativeEncodedSize > this._encodedSizeLimit) {\n const decoderToRelease = this._activeDecoder ?? pending?.decoder;\n if (decoderToRelease) {\n decoderToRelease.release();\n }\n this._activeDecoder = null;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n this._aborted = true;\n return;\n }\n\n if (this._decodeError) return;\n\n if (pending?.decoder && !this._activeDecoder) {\n this._activeDecoder = pending.decoder;\n }\n if (!this._activeDecoder) {\n // Budget WASM capacity, including one page of decoder state and rounding.\n const decoderCapacity = this._maxEncodedBytes + 131072;\n if (decoderCapacity > this._opts.storageLimit * 1000000) {\n this._aborted = true;\n if (this._parsedCommand?.id !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'ENOMEM:pending image budget exceeded', this._parsedCommand.quiet ?? 0);\n }\n return;\n }\n const maxPending = Math.max(1, Math.floor(this._opts.storageLimit * 1000000 / decoderCapacity));\n while (this._pendingTransmissions.size >= maxPending) {\n const oldest = this._pendingTransmissions.entries().next().value;\n if (!oldest) break;\n oldest[1].decoder.release();\n this._removePendingEntry(oldest[0]);\n if (oldest[1].cmd.id !== undefined) {\n this._sendResponse(oldest[1].cmd.id, 'ENOMEM:pending image budget exceeded', oldest[1].cmd.quiet ?? 0);\n }\n }\n const decoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes);\n try {\n decoder.init();\n } catch (e) {\n // Why: wasm memory exhaustion must drop this image, not throw out of the parser and wedge the write queue.\n console.warn('KITTY: could not allocate decoder', e);\n this._aborted = true;\n if (this._parsedCommand?.id !== undefined) {\n this._sendResponse(this._parsedCommand.id, 'ENOMEM:could not allocate decoder', this._parsedCommand.quiet ?? 0);\n }\n return;\n }\n this._activeDecoder = decoder;\n }\n\n if (this._activeDecoder.put(data.subarray(start, end)) !== DECODER_OK) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n this._decodeError = true;\n if (pending) {\n this._removePendingEntry(pendingKey);\n }\n }\n }\n\n public end(success: boolean): boolean | Promise {\n if (this._aborted || !success) {\n if (this._activeDecoder) {\n this._activeDecoder.release();\n this._activeDecoder = null;\n }\n return true;\n }\n\n // No semicolon = no payload (delete, capability query)\n if (this._inControlData) {\n return this._handleNoPayloadCommand();\n }\n\n // Use command parsed early in put() - i+I already validated there\n const cmd = this._parsedCommand!;\n\n // Delete action was handled by skipping payload - just execute\n if (cmd.action === KittyAction.DELETE) {\n return this._handleDelete(cmd);\n }\n\n // Per spec, subsequent chunks may omit i=, so fall back to _lastPendingKey.\n const pendingKey = cmd.id ?? this._lastPendingKey ?? 0;\n const isMoreComing = cmd.more === 1;\n const pending = this._pendingTransmissions.get(pendingKey);\n\n if (isMoreComing) {\n if (this._activeDecoder) {\n if (pending) {\n pending.totalEncodedSize += this._totalEncodedSize;\n pending.decodeError = pending.decodeError || this._decodeError;\n } else {\n this._pendingTransmissions.set(pendingKey, {\n cmd: { ...cmd },\n decoder: this._activeDecoder,\n totalEncodedSize: this._totalEncodedSize,\n decodeError: this._decodeError\n });\n }\n this._lastPendingKey = pendingKey;\n this._activeDecoder = null;\n }\n return true;\n }\n\n // Final chunk received \u2014 clear the last pending key\n if (pending) {\n this._lastPendingKey = undefined;\n }\n\n let decodeError = this._decodeError;\n let finalCmd = cmd;\n let decoder = this._activeDecoder;\n\n if (pending) {\n finalCmd = pending.cmd;\n decoder = pending.decoder;\n decodeError = decodeError || pending.decodeError;\n this._pendingTransmissions.delete(pendingKey);\n }\n\n let imageBytes = new Uint8Array(0);\n if (decoder) {\n if (decoder.end() !== DECODER_OK) {\n decodeError = true;\n }\n imageBytes = decoder.data8;\n }\n this._activeDecoder = null;\n\n // Handle command first \u2014 handlers create Blob/ImageData from imageBytes,\n // which copies the data. Only then is it safe to release the decoder's\n // wasm memory that imageBytes points into.\n const result = this._handleCommandWithBytesAndCmd(finalCmd, imageBytes, decodeError);\n if (decoder) {\n decoder.release();\n }\n return result;\n }\n\n // Command handling\n\n private _parseControlDataString(): string {\n let str = '';\n for (let i = 0; i < this._controlLength; i++) {\n str += String.fromCodePoint(this._controlData[i]);\n }\n return str;\n }\n\n private _handleNoPayloadCommand(): boolean | Promise {\n const cmd = parseKittyCommand(this._parseControlDataString());\n\n // Per spec: specifying both i and I is an error\n if (cmd.id !== undefined && cmd.imageNumber !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:cannot specify both i and I keys', cmd.quiet ?? 0);\n return true;\n }\n\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.DELETE:\n return this._handleDelete(cmd);\n case KittyAction.QUERY:\n this._sendResponse(cmd.id ?? 0, 'OK', cmd.quiet ?? 0);\n return true;\n case KittyAction.PLACEMENT:\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handleCommandWithBytesAndCmd(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n const action = cmd.action ?? 't';\n\n switch (action) {\n case KittyAction.TRANSMIT: {\n const result = this._handleTransmit(cmd, bytes, decodeError);\n // Only send response when _handleTransmit didn't already respond\n // (it handles unsupported transmission medium responses internally)\n if ((cmd.transmission ?? 'd') === 'd' && cmd.id !== undefined) {\n if (decodeError) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n } else if (bytes.length > 0) {\n this._sendResponse(cmd.id, 'OK', cmd.quiet ?? 0);\n }\n }\n return result;\n }\n case KittyAction.TRANSMIT_DISPLAY:\n return this._handleTransmitDisplay(cmd, bytes, decodeError);\n case KittyAction.QUERY:\n return this._handleQuery(cmd, bytes, decodeError);\n case KittyAction.PLACEMENT:\n // a=p ignores any payload \u2014 image data was already transmitted\n return this._handlePlacement(cmd);\n default:\n // TODO: Implement remaining actions when needed:\n // - a=f (frame): animation frame operations\n // - a=a (animation): animation control\n // - a=c (compose): compose images\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported action', cmd.quiet ?? 0);\n }\n return true;\n }\n }\n\n private _handlePlacement(cmd: IKittyCommand): boolean | Promise {\n if (cmd.id === undefined) {\n return true;\n }\n const id = cmd.id;\n const image = this._kittyStorage.getImage(id);\n if (!image) {\n this._sendResponse(id, 'ENOENT:image not found', cmd.quiet ?? 0, cmd.placementId);\n return true;\n }\n const result = this._displayImage(image, cmd);\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0, cmd.placementId);\n return true;\n });\n }\n\n private _handleTransmit(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n // TODO: Support file-based transmission modes (t=f, t=t, t=s)\n // Currently only supports direct transmission (t=d, the default).\n // - t=f (file): Payload is base64-encoded file path. Terminal reads image from that path.\n // - t=t (temp file): Payload is base64-encoded path in temp directory. Terminal reads, deletes.\n // - t=s: Payload is base64-encoded POSIX shm name. Terminal reads from shared memory.\n // These modes require filesystem/IPC access not available in browsers. For Node.js/Electron:\n // 1. Check cmd.transmission (t key) before treating bytes as image data\n // 2. For t=f/t/s: decode bytes as UTF-8 string (the path/name), then read file contents\n // 3. For t=d: treat bytes as image data (current behavior)\n // When implementing, also update _handleQuery to accept these transmission mediums.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:unsupported transmission medium', cmd.quiet ?? 0);\n }\n return true;\n }\n\n if (decodeError || bytes.length === 0) return true;\n\n this._kittyStorage.storeImage(cmd.id, {\n data: new Blob([bytes as BlobPart]),\n width: cmd.width ?? 0,\n height: cmd.height ?? 0,\n format: (cmd.format ?? KittyFormat.RGBA) as 24 | 32 | 100,\n compression: cmd.compression ?? ''\n });\n return true;\n }\n\n private _handleTransmitDisplay(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean | Promise {\n if (decodeError) {\n if (cmd.id !== undefined) {\n this._sendResponse(cmd.id, 'EINVAL:invalid base64 data', cmd.quiet ?? 0);\n }\n return true;\n }\n\n this._handleTransmit(cmd, bytes, decodeError);\n\n const id = cmd.id ?? this._kittyStorage.lastImageId;\n const image = this._kittyStorage.getImage(id);\n if (image) {\n const result = this._displayImage(image, cmd);\n if (cmd.id !== undefined) {\n return result.then(success => {\n this._sendResponse(id, success ? 'OK' : 'EINVAL:image rendering failed', cmd.quiet ?? 0);\n return true;\n });\n }\n return result.then(() => true);\n }\n return true;\n }\n\n private _handleQuery(cmd: IKittyCommand, bytes: Uint8Array, decodeError: boolean): boolean {\n const id = cmd.id ?? 0;\n const quiet = cmd.quiet ?? 0;\n\n // Per spec: reject unsupported transmission mediums (only t=d is supported atm)\n // TODO: When filesystem support is added (Node.js/Electron), update this to accept\n // t=f (file), t=t (temp file), and t=s (shared memory) and respond OK for queries.\n const transmission = cmd.transmission ?? 'd';\n if (transmission !== 'd') {\n this._sendResponse(id, 'EINVAL:unsupported transmission medium', quiet);\n return true;\n }\n\n // Check decode error first (invalid base64)\n if (decodeError) {\n this._sendResponse(id, 'EINVAL:invalid base64 data', quiet);\n return true;\n }\n\n // Capability query (no payload) - just respond OK\n if (bytes.length === 0) {\n this._sendResponse(id, 'OK', quiet);\n return true;\n }\n\n const format = cmd.format ?? KittyFormat.RGBA;\n\n if (format === KittyFormat.PNG) {\n this._sendResponse(id, 'OK', quiet);\n } else {\n const width = cmd.width ?? 0;\n const height = cmd.height ?? 0;\n\n if (!width || !height) {\n this._sendResponse(id, 'EINVAL:width and height required for raw pixel data', quiet);\n return true;\n }\n\n const bytesPerPixel = format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n this._sendResponse(id, `EINVAL:insufficient pixel data`, quiet);\n return true;\n }\n\n this._sendResponse(id, 'OK', quiet);\n }\n return true;\n }\n\n private _handleDelete(cmd: IKittyCommand): boolean {\n // Per spec: default delete selector is 'a' (delete all visible placements)\n const selector = cmd.deleteSelector ?? 'a';\n\n // TODO: Distinguish lowercase (delete placements only) from uppercase\n // (delete placements + free stored image data). Currently both variants\n // free everything since we don't separate stored data from placements.\n switch (selector) {\n case 'a':\n case 'A':\n this._cleanupAllPending();\n this._kittyStorage.deleteAll();\n break;\n case 'i':\n case 'I':\n // TODO: When placement id tracking is implemented (see TODO in\n // KittyImageStorage), d=i with p= should delete only that\n // specific placement, while d=i without p should delete all\n // placements for the image.\n if (cmd.id !== undefined) {\n const pending = this._pendingTransmissions.get(cmd.id);\n if (pending) {\n pending.decoder.release();\n }\n this._removePendingEntry(cmd.id);\n this._kittyStorage.deleteById(cmd.id);\n }\n break;\n default:\n // Unsupported selectors (c, n, p, q, r, x, y, z, f) \u2014 ignore for now\n break;\n }\n return true;\n }\n\n private _sendResponse(id: number, message: string, quiet: number, placementId?: number): void {\n const isOk = message === 'OK';\n if (isOk && quiet >= 1) return;\n if (!isOk && quiet >= 2) return;\n\n const pPart = placementId ? `,p=${placementId}` : '';\n const response = `\\x1b_Gi=${id}${pPart};${message}\\x1b\\\\`;\n this._coreTerminal._core.coreService.triggerDataEvent(response);\n }\n\n // Image display\n\n private _displayImage(image: IKittyImageData, cmd: IKittyCommand): Promise {\n return this._decodeAndDisplay(image, cmd)\n .then(() => true)\n .catch(() => false);\n }\n\n private async _decodeAndDisplay(image: IKittyImageData, cmd: IKittyCommand): Promise {\n const generation = this._generation;\n let bitmap: ImageBitmap | undefined = await this._createBitmap(image);\n\n try {\n if (generation !== this._generation) throw new Error('image decode canceled');\n const cropX = Math.max(0, cmd.x ?? 0);\n const cropY = Math.max(0, cmd.y ?? 0);\n const cropW = cmd.sourceWidth || (bitmap.width - cropX);\n const cropH = cmd.sourceHeight || (bitmap.height - cropY);\n\n const maxCropW = Math.max(0, bitmap.width - cropX);\n const maxCropH = Math.max(0, bitmap.height - cropY);\n const finalCropW = Math.max(0, Math.min(cropW, maxCropW));\n const finalCropH = Math.max(0, Math.min(cropH, maxCropH));\n\n if (finalCropW === 0 || finalCropH === 0) {\n throw new Error('invalid source rectangle');\n }\n\n if (cropX !== 0 || cropY !== 0 || finalCropW !== bitmap.width || finalCropH !== bitmap.height) {\n const cropped = await createImageBitmap(bitmap, cropX, cropY, finalCropW, finalCropH);\n bitmap.close();\n bitmap = cropped;\n }\n\n const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width;\n const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height;\n\n // Per spec: c/r default to image's natural cell dimensions.\n // If only one of c/r is specified, compute the other from image aspect ratio.\n let imgCols: number;\n let imgRows: number;\n if (cmd.columns !== undefined && cmd.rows !== undefined) {\n imgCols = cmd.columns;\n imgRows = cmd.rows;\n } else if (cmd.columns !== undefined) {\n imgCols = cmd.columns;\n imgRows = Math.max(1, Math.ceil((bitmap.height / bitmap.width) * (imgCols * cw) / ch));\n } else if (cmd.rows !== undefined) {\n imgRows = cmd.rows;\n imgCols = Math.max(1, Math.ceil((bitmap.width / bitmap.height) * (imgRows * ch) / cw));\n } else {\n imgCols = Math.ceil(bitmap.width / cw);\n imgRows = Math.ceil(bitmap.height / ch);\n }\n\n let w = bitmap.width;\n let h = bitmap.height;\n\n // Scale bitmap to fit placement rectangle when c/r are specified\n if (cmd.columns !== undefined || cmd.rows !== undefined) {\n w = Math.round(imgCols * cw);\n h = Math.round(imgRows * ch);\n }\n\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n\n // Save cursor position before addImage modifies it\n const buffer = this._coreTerminal._core.buffer;\n const savedX = buffer.x;\n const savedY = buffer.y;\n const savedYbase = buffer.ybase;\n\n // Determine layer based on z-index: negative = behind text, 0+ = on top.\n // When z<0 we always use the bottom layer even without allowTransparency \u2014\n // the image will simply be hidden behind the opaque text background, which\n // is the correct behavior (client asked for \"behind text\").\n const wantsBottom = cmd.zIndex !== undefined && cmd.zIndex < 0;\n const layer: ImageLayer = wantsBottom ? 'bottom' : 'top';\n\n if (w !== bitmap.width || h !== bitmap.height) {\n const scaled = await createImageBitmap(bitmap, { resizeWidth: w, resizeHeight: h });\n bitmap.close();\n bitmap = scaled;\n }\n\n // Per spec: X/Y are pixel offsets within the first cell, so clamp to cell dimensions\n const xOffset = Math.min(Math.max(0, cmd.xOffset ?? 0), cw - 1);\n const yOffset = Math.min(Math.max(0, cmd.yOffset ?? 0), ch - 1);\n if (xOffset !== 0 || yOffset !== 0) {\n // Per spec: X/Y is not added to c/r area. When c/r are explicit, the\n // total placement area remains c*cw \u00D7 r*ch pixels and the offset image\n // is clipped to fit. When c/r are unset, the padded canvas determines\n // the natural cell dimensions.\n const canvasW = (cmd.columns !== undefined) ? Math.round(imgCols * cw) : bitmap.width + xOffset;\n const canvasH = (cmd.rows !== undefined) ? Math.round(imgRows * ch) : bitmap.height + yOffset;\n const offsetCanvas = ImageRenderer.createCanvas(window.document, canvasW, canvasH);\n const offsetCtx = offsetCanvas.getContext('2d');\n if (!offsetCtx) {\n throw new Error('Failed to create offset canvas context');\n }\n offsetCtx.drawImage(bitmap, xOffset, yOffset);\n\n const offsetBitmap = await createImageBitmap(offsetCanvas);\n offsetCanvas.width = offsetCanvas.height = 0;\n bitmap.close();\n bitmap = offsetBitmap;\n w = bitmap.width;\n h = bitmap.height;\n if (w * h > this._opts.pixelLimit) {\n throw new Error('image exceeds pixel limit');\n }\n if (cmd.columns === undefined) {\n imgCols = Math.ceil(bitmap.width / cw);\n }\n if (cmd.rows === undefined) {\n imgRows = Math.ceil(bitmap.height / ch);\n }\n }\n\n if (generation !== this._generation) throw new Error('image decode canceled');\n const zIndex = cmd.zIndex ?? 0;\n this._kittyStorage.addImage(image.id, bitmap, true, layer, zIndex);\n bitmap = undefined; // ownership transferred to storage\n\n // Kitty cursor movement\n // Per spec: cursor placed at first column after last image column,\n // on the last row of the image. C=1 means don't move cursor.\n if (cmd.cursorMovement === 1) {\n // C=1: restore cursor to position before image was placed\n const scrolled = buffer.ybase - savedYbase;\n buffer.x = savedX;\n // Can't restore cursor to scrollback?\n buffer.y = Math.max(savedY - scrolled, 0);\n } else {\n // Default (C=0): advance cursor horizontally past the image\n // addImage already positioned cursor on the last row via lineFeeds\n buffer.x = Math.min(savedX + imgCols, this._coreTerminal.cols);\n }\n } catch (e) {\n bitmap?.close();\n throw e;\n }\n }\n\n // Create ImageBitmap from already-decoded image data.\n private async _createBitmap(image: IKittyImageData): Promise {\n let bytes: Uint8Array = new Uint8Array(await image.data.arrayBuffer());\n\n if (image.compression === KittyCompression.ZLIB) {\n bytes = await this._decompressZlib(bytes);\n }\n\n if (image.format === KittyFormat.PNG) {\n const metrics = imageType(bytes);\n // IHDR dimensions are parsed with signed shifts, so a value >= 0x80000000 comes\n // back negative and a bare `>` pixel-limit test passes it; require positive.\n if (metrics.mime !== 'image/png' || !(metrics.width > 0) || !(metrics.height > 0) || metrics.width * metrics.height > this._opts.pixelLimit) {\n throw new RangeError('PNG exceeds pixel limit or has invalid dimensions');\n }\n const blob = new Blob([bytes as BlobPart], { type: 'image/png' });\n if (!window.createImageBitmap) {\n const url = URL.createObjectURL(blob);\n const img = new Image();\n return new Promise((resolve, reject) => {\n img.addEventListener('load', () => {\n URL.revokeObjectURL(url);\n const canvas = ImageRenderer.createCanvas(window.document, img.width, img.height);\n canvas.getContext('2d')?.drawImage(img, 0, 0);\n createImageBitmap(canvas).then(resolve).catch(reject);\n });\n img.addEventListener('error', () => {\n URL.revokeObjectURL(url);\n reject(new Error('Failed to load image'));\n });\n img.src = url;\n });\n }\n return createImageBitmap(blob);\n }\n\n // Raw pixel data\n const width = image.width;\n const height = image.height;\n\n if (!width || !height) {\n throw new Error('Width and height required for raw pixel data');\n }\n\n const bytesPerPixel = image.format === KittyFormat.RGBA ? KittyPixelConstants.BYTES_PER_PIXEL_RGBA : KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n const expectedBytes = width * height * bytesPerPixel;\n\n if (bytes.length < expectedBytes) {\n throw new Error('Insufficient pixel data');\n }\n\n const pixelCount = width * height;\n\n if (image.format === KittyFormat.RGBA) {\n // RGBA: use bytes directly \u2014 no copy needed\n return createImageBitmap(new ImageData(new Uint8ClampedArray(bytes.buffer as ArrayBuffer, bytes.byteOffset, pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA), width, height));\n }\n\n // RGB\u2192RGBA: interleave alpha using uint32 block processing (4 pixels per iteration).\n // 3 uint32 reads + 4 uint32 writes per 4 pixels vs 28 byte reads/writes \u2014 ~6x faster.\n // Assumes little-endian (all modern browsers/Node.js).\n const data = new Uint8ClampedArray(pixelCount * KittyPixelConstants.BYTES_PER_PIXEL_RGBA);\n const src32 = new Uint32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4));\n const dst32 = new Uint32Array(data.buffer);\n const alignedPixels = pixelCount & ~3; // round down to multiple of 4\n\n let srcOffset = 0;\n let dstOffset = 0;\n for (let i = 0; i < alignedPixels; i += 4) {\n const b0 = src32[srcOffset++];\n const b1 = src32[srcOffset++];\n const b2 = src32[srcOffset++];\n // Little-endian: pixel bytes are [R,G,B] \u2192 uint32 ABGR layout\n dst32[dstOffset++] = 0xFF000000 | b0;\n dst32[dstOffset++] = 0xFF000000 | (b0 >>> 24) | (b1 << 8);\n dst32[dstOffset++] = 0xFF000000 | (b1 >>> 16) | (b2 << 16);\n dst32[dstOffset++] = 0xFF000000 | (b2 >>> 8);\n }\n\n // Handle remaining 1\u20133 pixels\n let srcByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n let dstByte = alignedPixels * KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n for (let i = alignedPixels; i < pixelCount; i++) {\n data[dstByte] = bytes[srcByte];\n data[dstByte + 1] = bytes[srcByte + 1];\n data[dstByte + 2] = bytes[srcByte + 2];\n data[dstByte + 3] = KittyPixelConstants.ALPHA_OPAQUE;\n srcByte += KittyPixelConstants.BYTES_PER_PIXEL_RGB;\n dstByte += KittyPixelConstants.BYTES_PER_PIXEL_RGBA;\n }\n\n return createImageBitmap(new ImageData(data, width, height));\n }\n\n private async _decompressZlib(compressed: Uint8Array): Promise {\n try {\n return await this._decompress(compressed, 'deflate');\n } catch (error) {\n if (error instanceof RangeError) throw error;\n return await this._decompress(compressed, 'deflate-raw');\n }\n }\n\n private async _decompress(compressed: Uint8Array, format: 'deflate' | 'deflate-raw'): Promise {\n const limit = Math.min(this._opts.kittySizeLimit, this._opts.pixelLimit * 4, this._opts.storageLimit * 1000000);\n let offsetIn = 0;\n // Bound inflation within one native transform before its output is budgeted.\n const source = new ReadableStream({\n pull(controller) {\n if (offsetIn >= compressed.length) {\n controller.close();\n return;\n }\n const end = Math.min(offsetIn + 4096, compressed.length);\n controller.enqueue(new Uint8Array(compressed.subarray(offsetIn, end)));\n offsetIn = end;\n }\n });\n const reader = source.pipeThrough(new DecompressionStream(format)).getReader();\n const chunks: Uint8Array[] = [];\n let totalLength = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n totalLength += value.byteLength;\n if (totalLength > limit) {\n await reader.cancel().catch(() => {});\n throw new RangeError('decompressed image exceeds byte limit');\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n }\n\n public get images(): ReadonlyMap {\n return this._kittyStorage.images;\n }\n\n public get _kittyIdToStorageId(): ReadonlyMap {\n return this._kittyStorage.kittyIdToStorageId;\n }\n\n public get pendingTransmissions(): ReadonlyMap {\n return this._pendingTransmissions;\n }\n}\n", "/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n *\n * Kitty graphics protocol types, constants, and parsing utilities.\n */\n\nimport type Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';\n\n// Kitty graphics protocol action types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'a'.\nexport const enum KittyAction {\n TRANSMIT = 't',\n TRANSMIT_DISPLAY = 'T',\n QUERY = 'q',\n PLACEMENT = 'p',\n DELETE = 'd'\n}\n\n// Kitty graphics protocol format types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyFormat {\n RGB = 24,\n RGBA = 32,\n PNG = 100\n}\n\n// Kitty graphics protocol compression types.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference under key 'o'.\nexport const enum KittyCompression {\n NONE = '',\n ZLIB = 'z'\n}\n\n// Kitty graphics protocol control data keys.\n// See: https://sw.kovidgoyal.net/kitty/graphics-protocol/#control-data-reference\nexport const enum KittyKey {\n // Action to perform (t=transmit, T=transmit+display, q=query, p=placement, d=delete)\n ACTION = 'a',\n // Image format (24=RGB, 32=RGBA, 100=PNG)\n FORMAT = 'f',\n // Image ID for referencing stored images\n ID = 'i',\n // Image number (alternative to ID, terminal assigns ID)\n IMAGE_NUMBER = 'I',\n // Source image width in pixels\n WIDTH = 's',\n // Source image height in pixels\n HEIGHT = 'v',\n // The left edge (in pixels) of the image area to display\n X_OFFSET = 'x',\n // The top edge (in pixels) of the image area to display\n Y_OFFSET = 'y',\n // Width (in pixels) of the source rectangle to display\n SOURCE_WIDTH = 'w',\n // Height (in pixels) of the source rectangle to display\n SOURCE_HEIGHT = 'h',\n // Horizontal offset (in pixels) within the first cell\n X_PLACEMENT_OFFSET = 'X',\n // Vertical offset (in pixels) within the first cell\n Y_PLACEMENT_OFFSET = 'Y',\n // Number of terminal columns to display the image over\n COLUMNS = 'c',\n // Number of terminal rows to display the image over\n ROWS = 'r',\n // More data flag (1=more chunks coming, 0=final chunk)\n MORE = 'm',\n // Compression type (z=zlib). This is essential for chunking larger images.\n COMPRESSION = 'o',\n // Quiet mode (1=suppress OK responses, 2=suppress error responses)\n QUIET = 'q',\n // Cursor movement policy (0=move cursor after image, 1=don't move cursor)\n CURSOR_MOVEMENT = 'C',\n // Z-index for image layering (negative = behind text, 0+ = on top)\n Z_INDEX = 'z',\n // Transmission medium (d=direct, f=file, t=temp file, s=shared memory)\n TRANSMISSION = 't',\n // Delete selector (a/A=all, i/I=by id, c/C=at cursor, etc.) \u2014 only used when a=d\n DELETE_SELECTOR = 'd',\n // Placement ID for targeting specific placements\n PLACEMENT_ID = 'p'\n}\n\n// Pixel format constants\nexport const enum KittyPixelConstants {\n BYTES_PER_PIXEL_RGB = 3,\n BYTES_PER_PIXEL_RGBA = 4,\n ALPHA_OPAQUE = 255\n}\n\n// Parsed Kitty graphics command.\nexport interface IKittyCommand {\n action?: string;\n format?: number;\n id?: number;\n imageNumber?: number;\n width?: number;\n height?: number;\n x?: number;\n y?: number;\n sourceWidth?: number;\n sourceHeight?: number;\n xOffset?: number;\n yOffset?: number;\n columns?: number;\n rows?: number;\n more?: number;\n quiet?: number;\n cursorMovement?: number;\n zIndex?: number;\n transmission?: string;\n deleteSelector?: string;\n placementId?: number;\n compression?: string;\n payload?: string;\n}\n\n// Pending chunked transmission state.\n// Stores metadata from the first chunk while accumulating decoded payload data.\nexport interface IPendingTransmission {\n // The parsed command from the first chunk (contains action, format, dimensions, etc.)\n cmd: IKittyCommand;\n // Decoder used across chunked payloads\n decoder: Base64Decoder;\n // Total encoded (base64) bytes received across all chunks - for size limit enforcement\n totalEncodedSize: number;\n // Whether any chunk has failed to decode\n decodeError: boolean;\n}\n\n// Stored Kitty image data.\nexport interface IKittyImageData {\n id: number;\n // Decoded image data stored as Blob (off JS heap) to avoid 2GB heap limit\n data: Blob;\n width: number;\n height: number;\n format: 24 | 32 | 100;\n compression?: string;\n}\n\n// Parses Kitty graphics control data into a command object.\nexport function parseKittyCommand(data: string): IKittyCommand {\n const cmd: IKittyCommand = {};\n const parts = data.split(',');\n\n for (const part of parts) {\n const eqIdx = part.indexOf('=');\n if (eqIdx === -1) continue;\n\n const key = part.substring(0, eqIdx);\n const value = part.substring(eqIdx + 1);\n\n // Handle string keys first\n if (key === KittyKey.ACTION) {\n cmd.action = value;\n continue;\n }\n if (key === KittyKey.COMPRESSION) {\n cmd.compression = value;\n continue;\n }\n if (key === KittyKey.TRANSMISSION) {\n cmd.transmission = value;\n continue;\n }\n if (key === KittyKey.DELETE_SELECTOR) {\n cmd.deleteSelector = value;\n continue;\n }\n const numValue = parseInt(value, 10);\n switch (key) {\n case KittyKey.FORMAT: cmd.format = numValue; break;\n case KittyKey.ID: cmd.id = numValue; break;\n case KittyKey.IMAGE_NUMBER: cmd.imageNumber = numValue; break;\n case KittyKey.WIDTH: cmd.width = numValue; break;\n case KittyKey.HEIGHT: cmd.height = numValue; break;\n case KittyKey.X_OFFSET: cmd.x = numValue; break;\n case KittyKey.Y_OFFSET: cmd.y = numValue; break;\n case KittyKey.SOURCE_WIDTH: cmd.sourceWidth = numValue; break;\n case KittyKey.SOURCE_HEIGHT: cmd.sourceHeight = numValue; break;\n case KittyKey.X_PLACEMENT_OFFSET: cmd.xOffset = numValue; break;\n case KittyKey.Y_PLACEMENT_OFFSET: cmd.yOffset = numValue; break;\n case KittyKey.COLUMNS: cmd.columns = numValue; break;\n case KittyKey.ROWS: cmd.rows = numValue; break;\n case KittyKey.MORE: cmd.more = numValue; break;\n case KittyKey.QUIET: cmd.quiet = numValue; break;\n case KittyKey.CURSOR_MOVEMENT: cmd.cursorMovement = numValue; break;\n case KittyKey.Z_INDEX: cmd.zIndex = numValue; break;\n case KittyKey.PLACEMENT_ID: cmd.placementId = numValue; break;\n }\n }\n\n return cmd;\n}\n", "/**\n * Copyright (c) 2026 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IDisposable } from '@xterm/xterm';\nimport { ImageStorage } from '../ImageStorage';\nimport { ImageLayer, IAddImageOpts } from '../Types';\nimport { IKittyImageData } from './KittyGraphicsTypes';\n\n// Kitty-specific image storage controller.\n//\n// Wraps shared ImageStorage with kitty protocol semantics:\n// - tracks transmitted image payloads by kitty image id\n// - tracks kitty image id -> shared ImageStorage id mapping for displayed images\n// - mirrors shared-storage evictions into kitty maps\n// - applies protocol-level undisplayed-image eviction policy\nexport class KittyImageStorage implements IDisposable {\n private static readonly _maxStoredImages = 256;\n\n private _nextImageId = 1;\n private readonly _images: Map = new Map();\n // TODO: Support multiple placements per image. The kitty spec identifies\n // placements by an (image id, placement id) pair \u2014 same i + different p\n // values should coexist, and same i + same p should replace the prior\n // placement. Currently we track only one storage entry per kitty image id,\n // so multiple placements of the same image overwrite each other. Fixing\n // this requires changing these maps to Map>\n // (kittyId \u2192 placementId \u2192 storageId) and updating addImage/deleteById\n // accordingly. The underlying shared ImageStorage would also need to\n // support multiple entries per logical image.\n private readonly _kittyIdToStorageId: Map = new Map();\n private readonly _storageIdToKittyId: Map = new Map();\n\n private readonly _previousOnImageDeleted: ((storageId: number) => void) | undefined;\n private readonly _wrappedOnImageDeleted: (storageId: number) => void;\n private readonly _handleStorageImageDeleted = (storageId: number): void => {\n const kittyId = this._storageIdToKittyId.get(storageId);\n if (kittyId !== undefined) {\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n this._images.delete(kittyId);\n }\n };\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n\n constructor(\n private readonly _storage: ImageStorage\n ) {\n this._previousOnImageDeleted = this._storage.onImageDeleted;\n this._wrappedOnImageDeleted = (storageId: number) => {\n this._previousOnImageDeleted?.(storageId);\n this._handleStorageImageDeleted(storageId);\n };\n this._storage.onImageDeleted = this._wrappedOnImageDeleted;\n }\n\n public reset(): void {\n this._nextImageId = 1;\n this._images.clear();\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public dispose(): void {\n this.reset();\n if (this._storage.onImageDeleted === this._wrappedOnImageDeleted) {\n this._storage.onImageDeleted = this._previousOnImageDeleted;\n }\n }\n\n public storeImage(id: number | undefined, imageData: Omit): number {\n const imageId = id ?? this._nextImageId++;\n\n const oldStorageId = this._kittyIdToStorageId.get(imageId);\n if (oldStorageId !== undefined) {\n this._storage.deleteImage(oldStorageId);\n this._kittyIdToStorageId.delete(imageId);\n this._storageIdToKittyId.delete(oldStorageId);\n }\n\n if (!this._images.has(imageId) && this._images.size >= KittyImageStorage._maxStoredImages) {\n this._evictUndisplayedImages();\n }\n\n // Encoded images awaiting placement are outside ImageStorage's pixel budget.\n // Unplaced payloads are evicted first so a new upload cannot erase a visible\n // image while abandoned blobs still hold budget; placed ones go only when\n // that is not enough, because the byte cap is a hard bound. The new image is\n // always stored, so an oversized one overshoots by at most one payload\n // (itself bounded by kittySizeLimit) rather than being dropped after an OK ack.\n const byteLimit = this._storage.getLimit() * 1000000;\n this._images.delete(imageId);\n let retainedBytes = 0;\n for (const image of this._images.values()) retainedBytes += image.data.size;\n for (const evictPlaced of [false, true]) {\n for (const [oldestId, image] of this._images) {\n if (retainedBytes + imageData.data.size <= byteLimit) break;\n if (this._kittyIdToStorageId.has(oldestId) !== evictPlaced) continue;\n retainedBytes -= image.data.size;\n this.deleteById(oldestId);\n }\n }\n\n this._images.set(imageId, {\n ...imageData,\n id: imageId\n });\n return imageId;\n }\n\n public addImage(kittyId: number, image: HTMLCanvasElement | ImageBitmap, scrolling: boolean, layer: ImageLayer, zIndex: number): void {\n // Clean up stale reverse-mapping from a previous placement of the same\n // kitty image. The old shared-storage entry is kept (it may still be\n // visible on screen) but its reverse mapping is removed so that eviction\n // of the old entry won't incorrectly delete the kitty image data.\n const oldStorageId = this._kittyIdToStorageId.get(kittyId);\n if (oldStorageId !== undefined) {\n this._storageIdToKittyId.delete(oldStorageId);\n }\n this._addImageOpts.scrolling = scrolling;\n this._addImageOpts.layer = layer;\n this._addImageOpts.zIndex = zIndex;\n const storageId = this._storage.addImage(image, this._addImageOpts);\n this._kittyIdToStorageId.set(kittyId, storageId);\n this._storageIdToKittyId.set(storageId, kittyId);\n }\n\n public getImage(kittyId: number): IKittyImageData | undefined {\n return this._images.get(kittyId);\n }\n\n public deleteById(kittyId: number): void {\n this._images.delete(kittyId);\n const storageId = this._kittyIdToStorageId.get(kittyId);\n if (storageId !== undefined) {\n this._storage.deleteImage(storageId);\n this._kittyIdToStorageId.delete(kittyId);\n this._storageIdToKittyId.delete(storageId);\n }\n }\n\n public deleteAll(): void {\n this._images.clear();\n for (const storageId of this._kittyIdToStorageId.values()) {\n this._storage.deleteImage(storageId);\n }\n this._kittyIdToStorageId.clear();\n this._storageIdToKittyId.clear();\n }\n\n public get images(): ReadonlyMap {\n return this._images;\n }\n\n public get kittyIdToStorageId(): ReadonlyMap {\n return this._kittyIdToStorageId;\n }\n\n public get lastImageId(): number {\n return this._nextImageId - 1;\n }\n\n private _evictUndisplayedImages(): void {\n for (const [kittyId] of this._images) {\n if (this._images.size <= KittyImageStorage._maxStoredImages / 2) {\n break;\n }\n if (!this._kittyIdToStorageId.has(kittyId)) {\n this._images.delete(kittyId);\n }\n }\n }\n}\n", "/**\n * Copyright (c) 2020, 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IDcsHandler, IParams, IImageAddonOptions, ITerminalExt, AttributeData, IResetHandler, ReadonlyColorSet } from './Types';\nimport { toRGBA8888, BIG_ENDIAN, PALETTE_ANSI_256, PALETTE_VT340_COLOR } from 'sixel/lib/Colors';\nimport { RGBA8888 } from 'sixel/lib/Types';\nimport { ImageRenderer } from './ImageRenderer';\n\nimport { DecoderAsync, Decoder } from 'sixel/lib/Decoder';\nimport { LIMITS } from 'sixel/lib/wasm';\n\n// always free decoder ressources after decoding if it exceeds this limit\nconst MEM_PERMA_LIMIT = 4194304; // 1024 pixels * 1024 pixels * 4 channels = 4MB\n\n// custom default palette: VT340 (lower 16 colors) + ANSI256 (up to 256) + zeroed (up to 4096)\nconst DEFAULT_PALETTE = PALETTE_ANSI_256;\nDEFAULT_PALETTE.set(PALETTE_VT340_COLOR);\n\n// Why pooled: every decoder owns a wasm memory, and V8 caps live wasm memories\n// per process (~124 in a sandboxed renderer). Terminals borrow a decoder only\n// while a SIXEL sequence is open, so idle terminals hold none.\nconst MAX_IDLE_DECODERS = 2;\nconst idleDecoders = new Map();\nlet poolPrimed = false;\n\nfunction primeDecoderPool(memoryLimit: number): void {\n if (poolPrimed) return;\n poolPrimed = true;\n // Async compile once, off the parser's hot path; later decoders reuse the cached module.\n DecoderAsync({ memoryLimit, palette: DEFAULT_PALETTE }).then(\n d => releaseDecoder(d, memoryLimit),\n () => { poolPrimed = false; }\n );\n}\n\nfunction acquireDecoder(memoryLimit: number): Decoder {\n return idleDecoders.get(memoryLimit)?.pop() ?? new Decoder({ memoryLimit, palette: DEFAULT_PALETTE });\n}\n\nfunction releaseDecoder(dec: Decoder, memoryLimit: number): void {\n if (dec.memoryUsage > MEM_PERMA_LIMIT) {\n dec.release();\n }\n const idle = idleDecoders.get(memoryLimit) ?? [];\n if (idle.length < MAX_IDLE_DECODERS) {\n idle.push(dec);\n idleDecoders.set(memoryLimit, idle);\n }\n}\n\n\nexport class SixelHandler implements IDcsHandler, IResetHandler {\n private _size = 0;\n private _aborted = false;\n private _dec: Decoder | undefined;\n private _decMemoryLimit = 0;\n // Color registers outlive a single image, so they live here rather than in a pooled decoder.\n private readonly _palette = new Uint32Array(LIMITS.PALETTE_SIZE);\n\n constructor(\n private readonly _opts: IImageAddonOptions,\n private readonly _storage: SixelImageStorage,\n private readonly _coreTerminal: ITerminalExt\n ) {\n this._palette.set(DEFAULT_PALETTE);\n primeDecoderPool(this._opts.pixelLimit * 4);\n }\n\n public reset(): void {\n this._returnDecoder();\n this._palette.fill(0);\n this._palette.set(DEFAULT_PALETTE);\n }\n\n public hook(params: IParams): void {\n this._size = 0;\n this._aborted = false;\n this._returnDecoder();\n const memoryLimit = this._opts.pixelLimit * 4;\n try {\n this._dec = acquireDecoder(memoryLimit);\n } catch (e) {\n // Why: exhausting wasm memory must drop this image, not throw out of the parser and wedge the write queue.\n console.warn(`SIXEL: could not allocate decoder - ${e}`);\n this._aborted = true;\n return;\n }\n this._decMemoryLimit = memoryLimit;\n const fillColor = params.params[1] === 1 ? 0 : extractActiveBg(\n this._coreTerminal._core._inputHandler._curAttrData,\n this._coreTerminal._core._themeService?.colors);\n this._dec.init(fillColor, this._palette, this._opts.sixelPaletteLimit);\n }\n\n private _returnDecoder(): void {\n const dec = this._dec;\n if (!dec) return;\n this._dec = undefined;\n this._palette.set(dec.palette);\n releaseDecoder(dec, this._decMemoryLimit);\n }\n\n public put(data: Uint32Array, start: number, end: number): void {\n if (this._aborted || !this._dec) {\n return;\n }\n this._size += end - start;\n if (this._size > this._opts.sixelSizeLimit) {\n console.warn(`SIXEL: too much data, aborting`);\n this._aborted = true;\n this._dec.release();\n return;\n }\n try {\n this._dec.decode(data, start, end);\n } catch (e) {\n console.warn(`SIXEL: error while decoding image - ${e}`);\n this._aborted = true;\n this._dec.release();\n }\n }\n\n public unhook(success: boolean): boolean | Promise {\n try {\n return this._unhook(success);\n } finally {\n this._returnDecoder();\n }\n }\n\n private _unhook(success: boolean): boolean {\n if (this._aborted || !success || !this._dec) {\n return true;\n }\n\n const width = this._dec.width;\n const height = this._dec.height;\n\n // partial fix for https://github.com/jerch/xterm-addon-image/issues/37\n if (!width || !height) {\n if (height) {\n this._storage.advanceCursor(height);\n }\n return true;\n }\n\n const canvas = ImageRenderer.createCanvas(undefined, width, height);\n canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8 as Uint8ClampedArray, width, height), 0, 0);\n this._storage.addImage(canvas);\n return true;\n }\n}\n\n\n/**\n * Some helpers to extract current terminal colors.\n */\n\n// get currently active background color from terminal\n// also respect INVERSE setting\nfunction extractActiveBg(attr: AttributeData, colors: ReadonlyColorSet | undefined): RGBA8888 {\n let bg = 0;\n if (!colors) {\n // FIXME: theme service is prolly not available yet,\n // happens if .open() was not called yet (bug in core?)\n return bg;\n }\n if (attr.isInverse()) {\n if (attr.isFgDefault()) {\n bg = convertLe(colors.foreground.rgba);\n } else if (attr.isFgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getFgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getFgColor()].rgba);\n }\n } else {\n if (attr.isBgDefault()) {\n bg = convertLe(colors.background.rgba);\n } else if (attr.isBgRGB()) {\n const t = (attr.constructor as typeof AttributeData).toColorRGB(attr.getBgColor());\n bg = toRGBA8888(...t);\n } else {\n bg = convertLe(colors.ansi[attr.getBgColor()].rgba);\n }\n }\n return bg;\n}\n\n// rgba values on the color managers are always in BE, thus convert to LE\nfunction convertLe(color: number): RGBA8888 {\n if (BIG_ENDIAN) return color;\n return (color & 0xFF) << 24 | (color >>> 8 & 0xFF) << 16 | (color >>> 16 & 0xFF) << 8 | color >>> 24 & 0xFF;\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { IImageAddonOptions, ITerminalExt, IAddImageOpts } from './Types';\nimport { ImageRenderer } from './ImageRenderer';\n\n/**\n * Sixel-specific image storage controller.\n *\n * Wraps the shared ImageStorage with sixel protocol semantics:\n * - Cursor behavior governed by DECSET 80 (sixelScrolling option)\n * - advanceCursor for empty sixels carrying only height\n */\nexport class SixelImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'vt340' };\n constructor(\n private readonly _storage: ImageStorage,\n private readonly _opts: IImageAddonOptions,\n private readonly _renderer: ImageRenderer,\n private readonly _terminal: ITerminalExt\n ) {}\n\n /**\n * Add a sixel image to storage.\n * Cursor behavior depends on the sixelScrolling option (DECSET 80).\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._addImageOpts.scrolling = this._opts.sixelScrolling;\n this._storage.addImage(img, this._addImageOpts);\n }\n\n /**\n * Only advance text cursor.\n * This is an edge case from empty sixels carrying only a height but no pixels.\n * Partially fixes https://github.com/jerch/xterm-addon-image/issues/37.\n */\n public advanceCursor(height: number): void {\n if (this._opts.sixelScrolling) {\n let cellSize = this._renderer.cellSize;\n if (cellSize.width === -1 || cellSize.height === -1) {\n cellSize = CELL_SIZE_DEFAULT;\n }\n const rows = Math.ceil(height / cellSize.height);\n for (let i = 1; i < rows; ++i) {\n this._terminal._core._inputHandler.lineFeed();\n }\n }\n }\n}\n", "/**\n * Copyright (c) 2023 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport { IAddImageOpts } from './Types';\nimport { ImageStorage } from './ImageStorage';\n\n/**\n * IIP (iTerm Image Protocol) specific image storage controller.\n *\n * Wraps the shared ImageStorage with IIP protocol semantics:\n * - Always uses scrolling mode (cursor advances with image)\n */\nexport class IIPImageStorage {\n private _addImageOpts: IAddImageOpts = { scrolling: true, layer: 'top', zIndex: 0, cursorPos: 'iip' };\n constructor(\n private readonly _storage: ImageStorage\n ) {}\n\n /**\n * Add an IIP image to storage.\n * Always uses scrolling mode \u2014 cursor advances past the image.\n */\n public addImage(img: HTMLCanvasElement | ImageBitmap): void {\n this._storage.addImage(img, this._addImageOpts);\n }\n}\n", "/**\n * Copyright (c) 2020 The xterm.js authors. All rights reserved.\n * @license MIT\n */\n\nimport type { ITerminalAddon, IDisposable } from '@xterm/xterm';\nimport type { ImageAddon as IImageApi } from '@xterm/addon-image';\nimport { Emitter, type IEvent } from 'common/Event';\nimport { IIPHandler } from './IIPHandler';\nimport { ImageRenderer } from './ImageRenderer';\nimport { ImageStorage, CELL_SIZE_DEFAULT } from './ImageStorage';\nimport { KittyGraphicsHandler } from './kitty/KittyGraphicsHandler';\nimport { KittyImageStorage } from './kitty/KittyImageStorage';\nimport { SixelHandler } from './SixelHandler';\nimport { SixelImageStorage } from './SixelImageStorage';\nimport { IIPImageStorage } from './IIPImageStorage';\nimport { ITerminalExt, IImageAddonOptions, IResetHandler } from './Types';\n\n\n/**\n * Document VT features provided by this addon.\n *\n * @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL \"SIXEL Graphics\" \"DCS Ps ; Ps ; Ps ; q Pt ST\" \"Draw SIXEL image.\"\n *\n * Sixel support is provided by the addon @xterm/addon-image with these limitations:\n * - immediate coloring (no shared palette, allows high color settings of `img2sixel`)\n * - max. palette size of 4096 colors\n * - max. pixel width of 16K\n * - max. 25 MB per sixel sequence\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] OSC 1337 \"iTerm2 Commands\" \"OSC 1337 ; Pt BEL\" \"Custom iTerm2 commands.\"\n *\n * Only the inline image protocol (IIP) is supported by the addon @xterm/addon-image with\n * the following limitations:\n * - sequence:\n * - format: `OSC 1337 ; File=inline=1 ; size= ; ... : BEL`\n * - size param must be set and payload may not exceed CEIL(size * 4 / 3)\n * - strict base64 handling as of RFC4648 \u00A74 (standard alphabet, optional padding,\n * no separator bytes allowed)\n * - supported params: size, name, width, height, preserveAspectRatio\n * - image formats: PNG, JPEG and GIF\n * - no animation support (renders first image of a GIF)\n * - no multipart support\n * - VT340 cursor positioning (begin of last sixel data row)\n *\n * See [addon readme](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image)\n * and [iTerm2 IIP docs](https://iterm2.com/documentation-images.html) for more details.\n *\n *\n * @vt: #E[Supported via @xterm/addon-image.] APC KITTY_GRAPHICS \"Kitty Graphics\" \"APC G Pt ST\" \"Kitty Graphics Protocol.\"\n *\n * Kitty graphics support is provided by the addon @xterm/addon-image.\n * Note that while basic image output already works, this is still work in progress.\n */\n\n// default values of addon ctor options\nconst DEFAULT_OPTIONS: IImageAddonOptions = {\n enableSizeReports: true,\n pixelLimit: 16777216, // limit to 4096 * 4096 pixels\n sixelSupport: true,\n sixelScrolling: true,\n sixelPaletteLimit: 4096,\n sixelSizeLimit: 33554432,\n storageLimit: 128,\n showPlaceholder: true,\n iipSupport: true,\n iipSizeLimit: 33554432,\n kittySupport: true,\n kittySizeLimit: 33554432\n};\n\n// max palette size supported by the sixel lib (compile time setting)\nconst MAX_SIXEL_PALETTE_SIZE = 4096;\n\n// definitions for _xtermGraphicsAttributes sequence\nconst enum GaItem {\n COLORS = 1,\n SIXEL_GEO = 2,\n REGIS_GEO = 3\n}\nconst enum GaAction {\n READ = 1,\n SET_DEFAULT = 2,\n SET = 3,\n READ_MAX = 4\n}\nconst enum GaStatus {\n SUCCESS = 0,\n ITEM_ERROR = 1,\n ACTION_ERROR = 2,\n FAILURE = 3\n}\n\n\nexport class ImageAddon implements ITerminalAddon, IImageApi {\n private _opts: IImageAddonOptions;\n private _defaultOpts: IImageAddonOptions;\n private _storage: ImageStorage | undefined;\n private _renderer: ImageRenderer | undefined;\n private _disposables: IDisposable[] = [];\n private _terminal: ITerminalExt | undefined;\n private _handlers: Map = new Map();\n private readonly _onImageAdded = new Emitter();\n public readonly onImageAdded: IEvent = this._onImageAdded.event;\n\n constructor(opts?: Partial) {\n this._opts = Object.assign({}, DEFAULT_OPTIONS, opts);\n this._defaultOpts = Object.assign({}, DEFAULT_OPTIONS, opts);\n }\n\n public dispose(): void {\n for (const handler of this._handlers.values()) handler.reset();\n for (const obj of this._disposables) {\n obj.dispose();\n }\n this._disposables.length = 0;\n this._handlers.clear();\n this._onImageAdded.dispose();\n }\n\n private _disposeLater(...args: IDisposable[]): void {\n for (const obj of args) {\n this._disposables.push(obj);\n }\n }\n\n public activate(terminal: ITerminalExt): void {\n this._terminal = terminal;\n\n // internal data structures\n this._renderer = new ImageRenderer(terminal);\n this._storage = new ImageStorage(terminal, this._renderer, this._opts);\n this._storage.onImageAdded = () => this._onImageAdded.fire();\n\n // enable size reports\n if (this._opts.enableSizeReports) {\n const windowOps = terminal.options.windowOptions ?? {};\n windowOps.getWinSizePixels = true;\n windowOps.getCellSizePixels = true;\n windowOps.getWinSizeChars = true;\n terminal.options.windowOptions = windowOps;\n }\n\n this._disposeLater(\n this._renderer,\n this._storage,\n\n // DECSET/DECRST/DA1/XTSMGRAPHICS handlers\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'h' }, params => this._decset(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'l' }, params => this._decrst(params)),\n terminal.parser.registerCsiHandler({ final: 'c' }, params => this._da1(params)),\n terminal.parser.registerCsiHandler({ prefix: '?', final: 'S' }, params => this._xtermGraphicsAttributes(params)),\n\n // render hook\n terminal.onRender(range => this._storage?.render(range)),\n\n /**\n * reset handlers covered:\n * - DECSTR\n * - RIS\n * - Terminal.reset()\n */\n terminal.parser.registerCsiHandler({ intermediates: '!', final: 'p' }, () => this.reset()),\n terminal.parser.registerEscHandler({ final: 'c' }, () => this.reset()),\n terminal._core._inputHandler.onRequestReset(() => this.reset()),\n\n // wipe canvas and delete alternate images on buffer switch\n terminal.buffer.onBufferChange(() => this._storage?.wipeAlternate()),\n\n // extend images to the right on resize\n terminal.onResize(metrics => this._storage?.viewportResize(metrics))\n );\n\n // SIXEL handler\n if (this._opts.sixelSupport) {\n const sixelStorage = new SixelImageStorage(this._storage!, this._opts, this._renderer!, terminal);\n const sixelHandler = new SixelHandler(this._opts, sixelStorage, terminal);\n this._handlers.set('sixel', sixelHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerDcsHandler({ final: 'q' }, sixelHandler)\n );\n }\n\n // iTerm IIP handler\n if (this._opts.iipSupport) {\n const iipStorage = new IIPImageStorage(this._storage!);\n const iipHandler = new IIPHandler(this._opts, this._renderer!, iipStorage, terminal);\n this._handlers.set('iip', iipHandler);\n this._disposeLater(\n terminal._core._inputHandler._parser.registerOscHandler(1337, iipHandler)\n );\n }\n\n // Kitty graphics handler\n if (this._opts.kittySupport) {\n const kittyStorage = new KittyImageStorage(this._storage!);\n const kittyHandler = new KittyGraphicsHandler(this._opts, this._renderer!, kittyStorage, terminal);\n this._handlers.set('kitty', kittyHandler);\n this._disposeLater(\n kittyStorage,\n kittyHandler,\n terminal._core._inputHandler._parser.registerApcHandler({ final: 'G' }, kittyHandler)\n );\n }\n }\n\n // Note: storageLimit is skipped here to not intoduce a surprising side effect.\n public reset(): boolean {\n // reset options customizable by sequences to defaults\n this._opts.sixelScrolling = this._defaultOpts.sixelScrolling;\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n // also clear image storage\n this._storage?.reset();\n // reset protocol handlers\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return false;\n }\n\n public get storageLimit(): number {\n return this._storage?.getLimit() || -1;\n }\n\n public set storageLimit(limit: number) {\n this._storage?.setLimit(limit);\n this._opts.storageLimit = limit;\n }\n\n public get storageUsage(): number {\n if (this._storage) {\n return this._storage.getUsage();\n }\n return -1;\n }\n\n public get showPlaceholder(): boolean {\n return this._opts.showPlaceholder;\n }\n\n public set showPlaceholder(value: boolean) {\n this._opts.showPlaceholder = value;\n this._renderer?.showPlaceholder(value);\n }\n\n public getImageAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.getImageAtBufferCell(x, y);\n }\n\n public extractTileAtBufferCell(x: number, y: number): HTMLCanvasElement | undefined {\n return this._storage?.extractTileAtBufferCell(x, y);\n }\n\n private _report(s: string): void {\n this._terminal?._core.input(s, false);\n }\n\n private _decset(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = false;\n break;\n }\n }\n return false;\n }\n\n private _decrst(params: (number | number[])[]): boolean {\n for (let i = 0; i < params.length; ++i) {\n switch (params[i]) {\n case 80:\n this._opts.sixelScrolling = true;\n break;\n }\n }\n return false;\n }\n\n // overload DA to return something more appropriate\n private _da1(params: (number | number[])[]): boolean {\n if (params[0]) {\n return true;\n }\n // reported features:\n // 62 - VT220\n // 4 - SIXEL support\n // 9 - charsets\n // 22 - ANSI colors\n if (this._opts.sixelSupport) {\n this._report(`\\x1b[?62;4;9;22c`);\n return true;\n }\n return false;\n }\n\n /**\n * Implementation of xterm's graphics attribute sequence.\n *\n * Supported features:\n * - read/change palette limits (max 4096 by sixel lib)\n * - read SIXEL canvas geometry (reports current window canvas or\n * squared pixelLimit if canvas > pixel limit)\n *\n * Everything else is deactivated.\n */\n private _xtermGraphicsAttributes(params: (number | number[])[]): boolean {\n if (params.length < 2) {\n return true;\n }\n if (params[0] === GaItem.COLORS) {\n switch (params[1]) {\n case GaAction.READ:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n return true;\n case GaAction.SET_DEFAULT:\n this._opts.sixelPaletteLimit = this._defaultOpts.sixelPaletteLimit;\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n // also reset protocol handlers for now\n for (const handler of this._handlers.values()) {\n handler.reset();\n }\n return true;\n case GaAction.SET:\n if (params.length > 2 && !(params[2] instanceof Array) && params[2] <= MAX_SIXEL_PALETTE_SIZE) {\n this._opts.sixelPaletteLimit = params[2];\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${this._opts.sixelPaletteLimit}S`);\n } else {\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n }\n return true;\n case GaAction.READ_MAX:\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${MAX_SIXEL_PALETTE_SIZE}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n if (params[0] === GaItem.SIXEL_GEO) {\n switch (params[1]) {\n // we only implement read and read_max here\n case GaAction.READ:\n let width = this._renderer?.dimensions?.css.canvas.width;\n let height = this._renderer?.dimensions?.css.canvas.height;\n if (!width || !height) {\n // for some reason we have no working image renderer\n // --> fallback to default cell size\n const cellSize = CELL_SIZE_DEFAULT;\n width = (this._terminal?.cols || 80) * cellSize.width;\n height = (this._terminal?.rows || 24) * cellSize.height;\n }\n if (width * height < this._opts.pixelLimit) {\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${width.toFixed(0)};${height.toFixed(0)}S`);\n } else {\n // if we overflow pixelLimit report that squared instead\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n }\n return true;\n case GaAction.READ_MAX:\n // read_max returns pixelLimit as square area\n const x = Math.floor(Math.sqrt(this._opts.pixelLimit));\n this._report(`\\x1b[?${params[0]};${GaStatus.SUCCESS};${x};${x}S`);\n return true;\n default:\n this._report(`\\x1b[?${params[0]};${GaStatus.ACTION_ERROR}S`);\n return true;\n }\n }\n // exit with error on ReGIS or any other requests\n this._report(`\\x1b[?${params[0]};${GaStatus.ITEM_ERROR}S`);\n return true;\n }\n}\n"], ++ "mappings": ";;;;;;;;;;;;;;;;02BAYaA,EAAA,WAAa,IAAI,WAAW,IAAI,YAAY,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC,IAAM,IAClFA,EAAA,YACF,QAAQ,KAAK,6EAA6E,EAI5F,SAAgBC,GAAIC,EAAW,CAC7B,OAAOA,EAAI,GACb,CAFAF,EAAA,IAAAC,GAIA,SAAgBE,GAAMD,EAAW,CAC/B,OAAQA,IAAM,EAAK,GACrB,CAFAF,EAAA,MAAAG,GAIA,SAAgBC,GAAKF,EAAW,CAC9B,OAAQA,IAAM,GAAM,GACtB,CAFAF,EAAA,KAAAI,GAIA,SAAgBC,GAAMH,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KAAK,MAAM,WAC9B,KAAK,QAAQ,SAASvB,EAAO,CAAC,CAAC,MAAwBsB,EAAM,QAAQ,CAAC,CAAC,IAAIC,EAAO,QAAQ,CAAC,CAAC,GAAG,MAC1F,CAEL,IAAMN,EAAI,KAAK,MAAM,KAAK,KAAK,KAAK,MAAM,UAAU,CAAC,EACrD,KAAK,QAAQ,SAASjB,EAAO,CAAC,CAAC,MAAwBiB,CAAC,IAAIA,CAAC,GAAG,CAClE,CACA,MAAO,GACT,IAAK,GAEH,IAAMA,EAAI,KAAK,MAAM,KAAK,KAAK,KAAK,MAAM,UAAU,CAAC,EACrD,YAAK,QAAQ,SAASjB,EAAO,CAAC,CAAC,MAAwBiB,CAAC,IAAIA,CAAC,GAAG,EACzD,GACT,QACE,YAAK,QAAQ,SAASjB,EAAO,CAAC,CAAC,KAA4B,EACpD,EACX,CAGF,YAAK,QAAQ,SAASA,EAAO,CAAC,CAAC,KAA0B,EAClD,EACT,CACF", ++ "names": ["exports", "red", "n", "green", "blue", "alpha", "toRGBA8888", "g", "b", "a", "fromRGBA8888", "color", "nearestColorIndex", "palette", "r", "min", "idx", "i", "dr", "dg", "db", "d", "clamp", "low", "high", "value", "h2c", "t1", "t2", "c", "HLStoRGB", "h", "l", "s", "v", "normalizeRGB", "normalizeHLS", "p", "require_lib", "__commonJSMin", "exports", "InWasm", "z", "s", "b", "r", "def", "t", "d", "m", "W", "e", "require_Base64Decoder_wasm", "__commonJSMin", "exports", "inwasm_runtime_1", "wasmDecode", "MAP", "el", "D", "i", "EMPTY", "Base64Decoder", "keepSize", "maxBytes", "initialBytes", "m", "bytes", "requested", "needed", "newSize", "addPages", "data", "require_QoiDecoder_wasm", "__commonJSMin", "exports", "inwasm_runtime_1", "wasmQoiDecode", "QoiDecoder", "keepSize", "d", "pixels", "ib", "dl", "bytes", "chunkP", "exports", "Colors_1", "wasm_1", "decodeBase64", "s", "bytestring", "result", "WASM_BYTES", "WASM_MODULE", "NULL_CANVAS", "CallbackProxy", "width", "mode", "DEFAULT_OPTIONS", "DecoderAsync", "opts", "cbProxy", "importObj", "inst", "Decoder", "exports", "_instance", "_cbProxy", "module", "pixels", "offset", "additionalPixels", "newCanvas", "adv", "remaining", "c", "i", "fillColor", "palette", "paletteLimit", "truncate", "data", "start", "end", "p", "length", "j", "currentWidth", "escape", "final", "finalOffset", "bw", "currentHeight", "decode", "dec", "decodeAsync", "toDisposable", "fn", "DisposableStore", "o", "d", "Disposable", "MutableDisposable", "value", "Emitter", "listener", "thisArgs", "disposables", "toDisposable", "entry", "result", "idx", "event", "listeners", "len", "EventUtils", "forward", "from", "to", "e", "map", "i", "any", "events", "store", "DisposableStore", "runAndSubscribe", "handler", "initial", "import_Colors", "ImageRenderer", "_ImageRenderer", "Disposable", "_terminal", "MutableDisposable", "parent", "option", "toDisposable", "localDocument", "width", "height", "canvas", "ctx", "buffer", "imgData", "img", "value", "start", "end", "layer", "y", "w", "h", "imgSpec", "tileId", "col", "row", "count", "sourceWidth", "sourceHeight", "cols", "sx", "sy", "dx", "dy", "finalWidth", "finalHeight", "spec", "currentWidth", "currentHeight", "originalWidth", "originalHeight", "scaledWidth", "scaledHeight", "renderer", "key", "screenElement", "bWidth", "blueprint", "d32", "black", "white", "shift", "offset", "x", "ctx2", "i", "placeholder", "bitmap", "CELL_SIZE_DEFAULT", "ExtendedAttrsImage", "_ExtendedAttrsImage", "ext", "urlId", "imageId", "tileId", "value", "val", "EMPTY_ATTRS", "ImageStorage", "_terminal", "_renderer", "_opts", "e", "spec", "storedPixels", "id", "zero", "img", "opts", "cellSize", "cols", "rows", "buffer", "termCols", "termRows", "originX", "originY", "offset", "tileCount", "row", "line", "col", "endMarker", "imgSpec", "range", "hasTopImages", "hasBottomImages", "start", "end", "drawCalls", "placeholderCalls", "startTile", "startCol", "count", "a", "b", "call", "metrics", "oldCol", "tilesPerRow", "hasData", "rightCol", "lastTile", "expandCol", "x", "y", "orig", "canvas", "ImageRenderer", "room", "used", "current", "old", "oldSpec", "imgId", "import_Base64Decoder", "import_QoiDecoder", "toStr", "data", "s", "i", "toInt", "v", "toSize", "toName", "bs", "b", "DECODERS", "FILE_MARKER", "MULTIPARTFILE_MARKER", "FILEPART_MARKER", "FILEEND_MARKER", "REPORTCELLSIZE_MARKER", "MAX_FIELDCHARS", "HeaderParser", "k", "start", "end", "state", "pos", "buffer", "c", "UNSUPPORTED_TYPE", "imageType", "d", "d32", "width", "height", "jpgSize", "dim", "pos", "limit", "i", "len", "blockLength", "DEFAULT_HEADER", "IIPHandler", "_opts", "_renderer", "_storage", "_coreTerminal", "HeaderParser", "maxEncodedBytes", "initialBytes", "Base64Decoder", "QoiDecoder", "data", "start", "end", "dataPos", "success", "seqType", "w", "CELL_SIZE_DEFAULT", "h", "scale", "report", "cond", "metrics", "UNSUPPORTED_TYPE", "imageType", "blob", "e", "canvas", "ImageRenderer", "generation", "bm", "cw", "ch", "width", "height", "rw", "rh", "wf", "hf", "f", "s", "total", "cdim", "import_Base64Decoder", "parseKittyCommand", "data", "cmd", "parts", "part", "eqIdx", "key", "value", "numValue", "DECODER_OK", "KittyGraphicsHandler", "_opts", "_renderer", "_kittyStorage", "_coreTerminal", "key", "pending", "data", "start", "end", "controlEnd", "i", "copyLength", "parseKittyCommand", "payloadStart", "pendingKey", "previousEncodedSize", "decoderToRelease", "decoderCapacity", "maxPending", "oldest", "decoder", "Base64Decoder", "e", "success", "cmd", "isMoreComing", "decodeError", "finalCmd", "imageBytes", "result", "str", "bytes", "id", "image", "quiet", "format", "width", "height", "bytesPerPixel", "expectedBytes", "message", "placementId", "isOk", "pPart", "response", "generation", "bitmap", "cropX", "cropY", "cropW", "cropH", "maxCropW", "maxCropH", "finalCropW", "finalCropH", "cropped", "cw", "CELL_SIZE_DEFAULT", "ch", "imgCols", "imgRows", "w", "h", "buffer", "savedX", "savedY", "savedYbase", "layer", "scaled", "xOffset", "yOffset", "canvasW", "canvasH", "offsetCanvas", "ImageRenderer", "offsetCtx", "offsetBitmap", "zIndex", "scrolled", "metrics", "imageType", "blob", "url", "img", "resolve", "reject", "canvas", "pixelCount", "src32", "dst32", "alignedPixels", "srcOffset", "dstOffset", "b0", "b1", "b2", "srcByte", "dstByte", "compressed", "error", "limit", "offsetIn", "reader", "controller", "chunks", "totalLength", "done", "value", "offset", "chunk", "_KittyImageStorage", "_storage", "storageId", "kittyId", "id", "imageData", "imageId", "oldStorageId", "byteLimit", "retainedBytes", "image", "evictPlaced", "oldestId", "scrolling", "layer", "zIndex", "KittyImageStorage", "import_Colors", "import_Decoder", "import_wasm", "MEM_PERMA_LIMIT", "DEFAULT_PALETTE", "MAX_IDLE_DECODERS", "idleDecoders", "poolPrimed", "primeDecoderPool", "memoryLimit", "d", "releaseDecoder", "acquireDecoder", "dec", "idle", "SixelHandler", "_opts", "_storage", "_coreTerminal", "params", "e", "fillColor", "extractActiveBg", "data", "start", "end", "success", "width", "height", "canvas", "ImageRenderer", "attr", "colors", "bg", "convertLe", "t", "color", "SixelImageStorage", "_storage", "_opts", "_renderer", "_terminal", "img", "height", "cellSize", "CELL_SIZE_DEFAULT", "rows", "i", "IIPImageStorage", "_storage", "img", "DEFAULT_OPTIONS", "MAX_SIXEL_PALETTE_SIZE", "ImageAddon", "opts", "Emitter", "DEFAULT_OPTIONS", "handler", "obj", "args", "terminal", "ImageRenderer", "ImageStorage", "windowOps", "params", "range", "metrics", "sixelStorage", "SixelImageStorage", "sixelHandler", "SixelHandler", "iipStorage", "IIPImageStorage", "iipHandler", "IIPHandler", "kittyStorage", "KittyImageStorage", "kittyHandler", "KittyGraphicsHandler", "limit", "value", "x", "y", "s", "i", "MAX_SIXEL_PALETTE_SIZE", "width", "height", "cellSize", "CELL_SIZE_DEFAULT"] } diff --git a/src/IIPHandler.ts b/src/IIPHandler.ts -index 559b907416eb38318f439d060d7f89311ed34c7e..8541b4b0ea0d6b451aaae49007d69df64c5bd088 100644 +index 559b907416eb38318f439d060d7f89311ed34c7e..73cedbe99f831bffd202697cc8ba80a46a39cb99 100644 --- a/src/IIPHandler.ts +++ b/src/IIPHandler.ts -@@ -34,6 +34,7 @@ const DEFAULT_HEADER: IHeaderFields = { +@@ -13,8 +13,10 @@ import { imageType, UNSUPPORTED_TYPE } from './IIPMetrics'; + + // Local const enum mirror - esbuild can't inline const enums from external packages + const enum DecoderConst { +- // Limit held memory in base64 decoder (encoded bytes). +- KEEP_DATA = 4194304, ++ // Held memory in base64/QOI decoders between images. Zero because each kept ++ // decoder pins a wasm memory, and V8 caps those per process (~124 in a ++ // sandboxed renderer), so idle terminals must not hold one. ++ KEEP_DATA = 0, + // Initial buffer allocation for the decoder. + INITIAL_DATA = 1048576, + // Local mirror of const enum (esbuild can't inline const enums from external packages) +@@ -34,6 +36,7 @@ const DEFAULT_HEADER: IHeaderFields = { export class IIPHandler implements IOscHandler, IResetHandler { @@ -55,7 +68,7 @@ index 559b907416eb38318f439d060d7f89311ed34c7e..8541b4b0ea0d6b451aaae49007d69df6 private _aborted = false; private _hp = new HeaderParser(); private _header: IHeaderFields = DEFAULT_HEADER; -@@ -55,6 +56,7 @@ export class IIPHandler implements IOscHandler, IResetHandler { +@@ -55,6 +58,7 @@ export class IIPHandler implements IOscHandler, IResetHandler { } public reset(): void { @@ -63,7 +76,47 @@ index 559b907416eb38318f439d060d7f89311ed34c7e..8541b4b0ea0d6b451aaae49007d69df6 this._hp.reset(); this._dec.release(); this._qoiDec.release(); -@@ -198,8 +200,13 @@ export class IIPHandler implements IOscHandler, IResetHandler { +@@ -92,7 +96,10 @@ export class IIPHandler implements IOscHandler, IResetHandler { + this._aborted = true; + return; + } +- this._dec.init(); ++ if (!this._initDecoder()) { ++ this._aborted = true; ++ return; ++ } + } else if (this._abortMulti) { + this._aborted = true; + return; +@@ -135,7 +142,9 @@ export class IIPHandler implements IOscHandler, IResetHandler { + this._isMultipart = true; + this._abortMulti = false; + this._dec.release(); +- this._dec.init(); ++ if (!this._initDecoder()) { ++ this._abortMulti = true; ++ } + return true; + } + +@@ -179,7 +188,15 @@ export class IIPHandler implements IOscHandler, IResetHandler { + + let blob: Blob | ImageData; + if (metrics.mime === 'image/qoi') { +- const data = this._qoiDec.decode(this._dec.data8); ++ let data: Uint8Array; ++ try { ++ data = this._qoiDec.decode(this._dec.data8); ++ } catch (e) { ++ console.warn('IIP: could not decode QOI image', e); ++ this._dec.release(); ++ this._qoiDec.release(); ++ return true; ++ } + blob = new ImageData( + new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength), + this._qoiDec.width, +@@ -198,8 +215,13 @@ export class IIPHandler implements IOscHandler, IResetHandler { blob = new Blob([this._dec.data8], { type: metrics.mime }); } this._dec.release(); @@ -77,6 +130,25 @@ index 559b907416eb38318f439d060d7f89311ed34c7e..8541b4b0ea0d6b451aaae49007d69df6 this._storage.addImage(bm); return true; }) +@@ -209,6 +231,18 @@ export class IIPHandler implements IOscHandler, IResetHandler { + }); + } + ++ // Why: wasm memory exhaustion must drop this image, not throw out of the parser and wedge the write queue. ++ private _initDecoder(): boolean { ++ try { ++ this._dec.init(); ++ return true; ++ } catch (e) { ++ console.warn('IIP: could not allocate decoder', e); ++ this._dec.release(); ++ return false; ++ } ++ } ++ + private _resize(w: number, h: number): [number, number] { + const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width; + const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height; diff --git a/src/ImageAddon.ts b/src/ImageAddon.ts index 8fd39543118cd420e36c1614c1af370b6c7bbfbb..0c44d2a81642113417bf8dc10a4faa76d7cc5864 100644 --- a/src/ImageAddon.ts @@ -189,8 +261,156 @@ index 5854efaec1fdf9dfcb886023542998a563b6d2f2..3afaf9bd63ffd7a4cdf32bf0ac24cf33 } public get document(): Document | undefined { +diff --git a/src/SixelHandler.ts b/src/SixelHandler.ts +index 1af2d85bcdd541ed60b1e707f6186a91f1bbf1b2..0711a122ea43d5212a2851add9e744b65550ec85 100644 +--- a/src/SixelHandler.ts ++++ b/src/SixelHandler.ts +@@ -10,6 +10,7 @@ import { RGBA8888 } from 'sixel/lib/Types'; + import { ImageRenderer } from './ImageRenderer'; + + import { DecoderAsync, Decoder } from 'sixel/lib/Decoder'; ++import { LIMITS } from 'sixel/lib/wasm'; + + // always free decoder ressources after decoding if it exceeds this limit + const MEM_PERMA_LIMIT = 4194304; // 1024 pixels * 1024 pixels * 4 channels = 4MB +@@ -18,48 +19,88 @@ const MEM_PERMA_LIMIT = 4194304; // 1024 pixels * 1024 pixels * 4 channels = 4MB + const DEFAULT_PALETTE = PALETTE_ANSI_256; + DEFAULT_PALETTE.set(PALETTE_VT340_COLOR); + ++// Why pooled: every decoder owns a wasm memory, and V8 caps live wasm memories ++// per process (~124 in a sandboxed renderer). Terminals borrow a decoder only ++// while a SIXEL sequence is open, so idle terminals hold none. ++const MAX_IDLE_DECODERS = 2; ++const idleDecoders = new Map(); ++let poolPrimed = false; ++ ++function primeDecoderPool(memoryLimit: number): void { ++ if (poolPrimed) return; ++ poolPrimed = true; ++ // Async compile once, off the parser's hot path; later decoders reuse the cached module. ++ DecoderAsync({ memoryLimit, palette: DEFAULT_PALETTE }).then( ++ d => releaseDecoder(d, memoryLimit), ++ () => { poolPrimed = false; } ++ ); ++} ++ ++function acquireDecoder(memoryLimit: number): Decoder { ++ return idleDecoders.get(memoryLimit)?.pop() ?? new Decoder({ memoryLimit, palette: DEFAULT_PALETTE }); ++} ++ ++function releaseDecoder(dec: Decoder, memoryLimit: number): void { ++ if (dec.memoryUsage > MEM_PERMA_LIMIT) { ++ dec.release(); ++ } ++ const idle = idleDecoders.get(memoryLimit) ?? []; ++ if (idle.length < MAX_IDLE_DECODERS) { ++ idle.push(dec); ++ idleDecoders.set(memoryLimit, idle); ++ } ++} ++ + + export class SixelHandler implements IDcsHandler, IResetHandler { + private _size = 0; + private _aborted = false; + private _dec: Decoder | undefined; ++ private _decMemoryLimit = 0; ++ // Color registers outlive a single image, so they live here rather than in a pooled decoder. ++ private readonly _palette = new Uint32Array(LIMITS.PALETTE_SIZE); + + constructor( + private readonly _opts: IImageAddonOptions, + private readonly _storage: SixelImageStorage, + private readonly _coreTerminal: ITerminalExt + ) { +- DecoderAsync({ +- memoryLimit: this._opts.pixelLimit * 4, +- palette: DEFAULT_PALETTE, +- paletteLimit: this._opts.sixelPaletteLimit +- }).then(d => this._dec = d); ++ this._palette.set(DEFAULT_PALETTE); ++ primeDecoderPool(this._opts.pixelLimit * 4); + } + + public reset(): void { +- /** +- * reset sixel decoder to defaults: +- * - release all memory +- * - nullify palette (4096) +- * - apply default palette (256) +- */ +- if (this._dec) { +- this._dec.release(); +- // FIXME: missing interface on decoder to nullify full palette +- (this._dec as any)._palette.fill(0); +- this._dec.init(0, DEFAULT_PALETTE, this._opts.sixelPaletteLimit); +- } ++ this._returnDecoder(); ++ this._palette.fill(0); ++ this._palette.set(DEFAULT_PALETTE); + } + + public hook(params: IParams): void { + this._size = 0; + this._aborted = false; +- if (this._dec) { +- const fillColor = params.params[1] === 1 ? 0 : extractActiveBg( +- this._coreTerminal._core._inputHandler._curAttrData, +- this._coreTerminal._core._themeService?.colors); +- this._dec.init(fillColor, null, this._opts.sixelPaletteLimit); ++ this._returnDecoder(); ++ const memoryLimit = this._opts.pixelLimit * 4; ++ try { ++ this._dec = acquireDecoder(memoryLimit); ++ } catch (e) { ++ // Why: exhausting wasm memory must drop this image, not throw out of the parser and wedge the write queue. ++ console.warn(`SIXEL: could not allocate decoder - ${e}`); ++ this._aborted = true; ++ return; + } ++ this._decMemoryLimit = memoryLimit; ++ const fillColor = params.params[1] === 1 ? 0 : extractActiveBg( ++ this._coreTerminal._core._inputHandler._curAttrData, ++ this._coreTerminal._core._themeService?.colors); ++ this._dec.init(fillColor, this._palette, this._opts.sixelPaletteLimit); ++ } ++ ++ private _returnDecoder(): void { ++ const dec = this._dec; ++ if (!dec) return; ++ this._dec = undefined; ++ this._palette.set(dec.palette); ++ releaseDecoder(dec, this._decMemoryLimit); + } + + public put(data: Uint32Array, start: number, end: number): void { +@@ -83,6 +124,14 @@ export class SixelHandler implements IDcsHandler, IResetHandler { + } + + public unhook(success: boolean): boolean | Promise { ++ try { ++ return this._unhook(success); ++ } finally { ++ this._returnDecoder(); ++ } ++ } ++ ++ private _unhook(success: boolean): boolean { + if (this._aborted || !success || !this._dec) { + return true; + } +@@ -100,9 +149,6 @@ export class SixelHandler implements IDcsHandler, IResetHandler { + + const canvas = ImageRenderer.createCanvas(undefined, width, height); + canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8 as Uint8ClampedArray, width, height), 0, 0); +- if (this._dec.memoryUsage > MEM_PERMA_LIMIT) { +- this._dec.release(); +- } + this._storage.addImage(canvas); + return true; + } diff --git a/src/kitty/KittyGraphicsHandler.ts b/src/kitty/KittyGraphicsHandler.ts -index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1fa320c4f8 100644 +index de889dfff75d9ecc8ab47a025e6989ffe75bb202..cf66e5b75c78645b1641e53d1425d88201134f78 100644 --- a/src/kitty/KittyGraphicsHandler.ts +++ b/src/kitty/KittyGraphicsHandler.ts @@ -7,6 +7,7 @@ import { IDisposable } from '@xterm/xterm'; @@ -217,10 +437,12 @@ index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1f this._cleanupAllPending(); if (this._activeDecoder) { this._activeDecoder.release(); -@@ -200,6 +203,25 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos +@@ -200,8 +203,38 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos this._activeDecoder = pending.decoder; } if (!this._activeDecoder) { +- this._activeDecoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes); +- this._activeDecoder.init(); + // Budget WASM capacity, including one page of decoder state and rounding. + const decoderCapacity = this._maxEncodedBytes + 131072; + if (decoderCapacity > this._opts.storageLimit * 1000000) { @@ -240,10 +462,23 @@ index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1f + this._sendResponse(oldest[1].cmd.id, 'ENOMEM:pending image budget exceeded', oldest[1].cmd.quiet ?? 0); + } + } - this._activeDecoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes); - this._activeDecoder.init(); ++ const decoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes); ++ try { ++ decoder.init(); ++ } catch (e) { ++ // Why: wasm memory exhaustion must drop this image, not throw out of the parser and wedge the write queue. ++ console.warn('KITTY: could not allocate decoder', e); ++ this._aborted = true; ++ if (this._parsedCommand?.id !== undefined) { ++ this._sendResponse(this._parsedCommand.id, 'ENOMEM:could not allocate decoder', this._parsedCommand.quiet ?? 0); ++ } ++ return; ++ } ++ this._activeDecoder = decoder; } -@@ -550,9 +572,11 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos + + if (this._activeDecoder.put(data.subarray(start, end)) !== DECODER_OK) { +@@ -550,9 +583,11 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos } private async _decodeAndDisplay(image: IKittyImageData, cmd: IKittyCommand): Promise { @@ -255,7 +490,7 @@ index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1f const cropX = Math.max(0, cmd.x ?? 0); const cropY = Math.max(0, cmd.y ?? 0); const cropW = cmd.sourceWidth || (bitmap.width - cropX); -@@ -660,6 +684,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos +@@ -660,6 +695,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos } } @@ -263,7 +498,7 @@ index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1f const zIndex = cmd.zIndex ?? 0; this._kittyStorage.addImage(image.id, bitmap, true, layer, zIndex); bitmap = undefined; // ownership transferred to storage -@@ -693,6 +718,12 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos +@@ -693,6 +729,12 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos } if (image.format === KittyFormat.PNG) { @@ -276,7 +511,7 @@ index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1f const blob = new Blob([bytes as BlobPart], { type: 'image/png' }); if (!window.createImageBitmap) { const url = URL.createObjectURL(blob); -@@ -775,27 +806,45 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos +@@ -775,27 +817,45 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos private async _decompressZlib(compressed: Uint8Array): Promise { try { return await this._decompress(compressed, 'deflate'); diff --git a/config/patches/xterm-src/@xterm__addon-image@0.10.0-beta.300.src.patch b/config/patches/xterm-src/@xterm__addon-image@0.10.0-beta.300.src.patch index 2c5aa15fac1..3b581c30477 100644 --- a/config/patches/xterm-src/@xterm__addon-image@0.10.0-beta.300.src.patch +++ b/config/patches/xterm-src/@xterm__addon-image@0.10.0-beta.300.src.patch @@ -1,8 +1,21 @@ diff --git a/src/IIPHandler.ts b/src/IIPHandler.ts -index 559b907416eb38318f439d060d7f89311ed34c7e..8541b4b0ea0d6b451aaae49007d69df64c5bd088 100644 +index 559b907416eb38318f439d060d7f89311ed34c7e..73cedbe99f831bffd202697cc8ba80a46a39cb99 100644 --- a/src/IIPHandler.ts +++ b/src/IIPHandler.ts -@@ -34,6 +34,7 @@ const DEFAULT_HEADER: IHeaderFields = { +@@ -13,8 +13,10 @@ import { imageType, UNSUPPORTED_TYPE } from './IIPMetrics'; + + // Local const enum mirror - esbuild can't inline const enums from external packages + const enum DecoderConst { +- // Limit held memory in base64 decoder (encoded bytes). +- KEEP_DATA = 4194304, ++ // Held memory in base64/QOI decoders between images. Zero because each kept ++ // decoder pins a wasm memory, and V8 caps those per process (~124 in a ++ // sandboxed renderer), so idle terminals must not hold one. ++ KEEP_DATA = 0, + // Initial buffer allocation for the decoder. + INITIAL_DATA = 1048576, + // Local mirror of const enum (esbuild can't inline const enums from external packages) +@@ -34,6 +36,7 @@ const DEFAULT_HEADER: IHeaderFields = { export class IIPHandler implements IOscHandler, IResetHandler { @@ -10,7 +23,7 @@ index 559b907416eb38318f439d060d7f89311ed34c7e..8541b4b0ea0d6b451aaae49007d69df6 private _aborted = false; private _hp = new HeaderParser(); private _header: IHeaderFields = DEFAULT_HEADER; -@@ -55,6 +56,7 @@ export class IIPHandler implements IOscHandler, IResetHandler { +@@ -55,6 +58,7 @@ export class IIPHandler implements IOscHandler, IResetHandler { } public reset(): void { @@ -18,7 +31,47 @@ index 559b907416eb38318f439d060d7f89311ed34c7e..8541b4b0ea0d6b451aaae49007d69df6 this._hp.reset(); this._dec.release(); this._qoiDec.release(); -@@ -198,8 +200,13 @@ export class IIPHandler implements IOscHandler, IResetHandler { +@@ -92,7 +96,10 @@ export class IIPHandler implements IOscHandler, IResetHandler { + this._aborted = true; + return; + } +- this._dec.init(); ++ if (!this._initDecoder()) { ++ this._aborted = true; ++ return; ++ } + } else if (this._abortMulti) { + this._aborted = true; + return; +@@ -135,7 +142,9 @@ export class IIPHandler implements IOscHandler, IResetHandler { + this._isMultipart = true; + this._abortMulti = false; + this._dec.release(); +- this._dec.init(); ++ if (!this._initDecoder()) { ++ this._abortMulti = true; ++ } + return true; + } + +@@ -179,7 +188,15 @@ export class IIPHandler implements IOscHandler, IResetHandler { + + let blob: Blob | ImageData; + if (metrics.mime === 'image/qoi') { +- const data = this._qoiDec.decode(this._dec.data8); ++ let data: Uint8Array; ++ try { ++ data = this._qoiDec.decode(this._dec.data8); ++ } catch (e) { ++ console.warn('IIP: could not decode QOI image', e); ++ this._dec.release(); ++ this._qoiDec.release(); ++ return true; ++ } + blob = new ImageData( + new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength), + this._qoiDec.width, +@@ -198,8 +215,13 @@ export class IIPHandler implements IOscHandler, IResetHandler { blob = new Blob([this._dec.data8], { type: metrics.mime }); } this._dec.release(); @@ -32,6 +85,25 @@ index 559b907416eb38318f439d060d7f89311ed34c7e..8541b4b0ea0d6b451aaae49007d69df6 this._storage.addImage(bm); return true; }) +@@ -209,6 +231,18 @@ export class IIPHandler implements IOscHandler, IResetHandler { + }); + } + ++ // Why: wasm memory exhaustion must drop this image, not throw out of the parser and wedge the write queue. ++ private _initDecoder(): boolean { ++ try { ++ this._dec.init(); ++ return true; ++ } catch (e) { ++ console.warn('IIP: could not allocate decoder', e); ++ this._dec.release(); ++ return false; ++ } ++ } ++ + private _resize(w: number, h: number): [number, number] { + const cw = this._renderer.dimensions?.css.cell.width || CELL_SIZE_DEFAULT.width; + const ch = this._renderer.dimensions?.css.cell.height || CELL_SIZE_DEFAULT.height; diff --git a/src/ImageAddon.ts b/src/ImageAddon.ts index 8fd39543118cd420e36c1614c1af370b6c7bbfbb..0c44d2a81642113417bf8dc10a4faa76d7cc5864 100644 --- a/src/ImageAddon.ts @@ -144,8 +216,156 @@ index 5854efaec1fdf9dfcb886023542998a563b6d2f2..3afaf9bd63ffd7a4cdf32bf0ac24cf33 } public get document(): Document | undefined { +diff --git a/src/SixelHandler.ts b/src/SixelHandler.ts +index 1af2d85bcdd541ed60b1e707f6186a91f1bbf1b2..0711a122ea43d5212a2851add9e744b65550ec85 100644 +--- a/src/SixelHandler.ts ++++ b/src/SixelHandler.ts +@@ -10,6 +10,7 @@ import { RGBA8888 } from 'sixel/lib/Types'; + import { ImageRenderer } from './ImageRenderer'; + + import { DecoderAsync, Decoder } from 'sixel/lib/Decoder'; ++import { LIMITS } from 'sixel/lib/wasm'; + + // always free decoder ressources after decoding if it exceeds this limit + const MEM_PERMA_LIMIT = 4194304; // 1024 pixels * 1024 pixels * 4 channels = 4MB +@@ -18,48 +19,88 @@ const MEM_PERMA_LIMIT = 4194304; // 1024 pixels * 1024 pixels * 4 channels = 4MB + const DEFAULT_PALETTE = PALETTE_ANSI_256; + DEFAULT_PALETTE.set(PALETTE_VT340_COLOR); + ++// Why pooled: every decoder owns a wasm memory, and V8 caps live wasm memories ++// per process (~124 in a sandboxed renderer). Terminals borrow a decoder only ++// while a SIXEL sequence is open, so idle terminals hold none. ++const MAX_IDLE_DECODERS = 2; ++const idleDecoders = new Map(); ++let poolPrimed = false; ++ ++function primeDecoderPool(memoryLimit: number): void { ++ if (poolPrimed) return; ++ poolPrimed = true; ++ // Async compile once, off the parser's hot path; later decoders reuse the cached module. ++ DecoderAsync({ memoryLimit, palette: DEFAULT_PALETTE }).then( ++ d => releaseDecoder(d, memoryLimit), ++ () => { poolPrimed = false; } ++ ); ++} ++ ++function acquireDecoder(memoryLimit: number): Decoder { ++ return idleDecoders.get(memoryLimit)?.pop() ?? new Decoder({ memoryLimit, palette: DEFAULT_PALETTE }); ++} ++ ++function releaseDecoder(dec: Decoder, memoryLimit: number): void { ++ if (dec.memoryUsage > MEM_PERMA_LIMIT) { ++ dec.release(); ++ } ++ const idle = idleDecoders.get(memoryLimit) ?? []; ++ if (idle.length < MAX_IDLE_DECODERS) { ++ idle.push(dec); ++ idleDecoders.set(memoryLimit, idle); ++ } ++} ++ + + export class SixelHandler implements IDcsHandler, IResetHandler { + private _size = 0; + private _aborted = false; + private _dec: Decoder | undefined; ++ private _decMemoryLimit = 0; ++ // Color registers outlive a single image, so they live here rather than in a pooled decoder. ++ private readonly _palette = new Uint32Array(LIMITS.PALETTE_SIZE); + + constructor( + private readonly _opts: IImageAddonOptions, + private readonly _storage: SixelImageStorage, + private readonly _coreTerminal: ITerminalExt + ) { +- DecoderAsync({ +- memoryLimit: this._opts.pixelLimit * 4, +- palette: DEFAULT_PALETTE, +- paletteLimit: this._opts.sixelPaletteLimit +- }).then(d => this._dec = d); ++ this._palette.set(DEFAULT_PALETTE); ++ primeDecoderPool(this._opts.pixelLimit * 4); + } + + public reset(): void { +- /** +- * reset sixel decoder to defaults: +- * - release all memory +- * - nullify palette (4096) +- * - apply default palette (256) +- */ +- if (this._dec) { +- this._dec.release(); +- // FIXME: missing interface on decoder to nullify full palette +- (this._dec as any)._palette.fill(0); +- this._dec.init(0, DEFAULT_PALETTE, this._opts.sixelPaletteLimit); +- } ++ this._returnDecoder(); ++ this._palette.fill(0); ++ this._palette.set(DEFAULT_PALETTE); + } + + public hook(params: IParams): void { + this._size = 0; + this._aborted = false; +- if (this._dec) { +- const fillColor = params.params[1] === 1 ? 0 : extractActiveBg( +- this._coreTerminal._core._inputHandler._curAttrData, +- this._coreTerminal._core._themeService?.colors); +- this._dec.init(fillColor, null, this._opts.sixelPaletteLimit); ++ this._returnDecoder(); ++ const memoryLimit = this._opts.pixelLimit * 4; ++ try { ++ this._dec = acquireDecoder(memoryLimit); ++ } catch (e) { ++ // Why: exhausting wasm memory must drop this image, not throw out of the parser and wedge the write queue. ++ console.warn(`SIXEL: could not allocate decoder - ${e}`); ++ this._aborted = true; ++ return; + } ++ this._decMemoryLimit = memoryLimit; ++ const fillColor = params.params[1] === 1 ? 0 : extractActiveBg( ++ this._coreTerminal._core._inputHandler._curAttrData, ++ this._coreTerminal._core._themeService?.colors); ++ this._dec.init(fillColor, this._palette, this._opts.sixelPaletteLimit); ++ } ++ ++ private _returnDecoder(): void { ++ const dec = this._dec; ++ if (!dec) return; ++ this._dec = undefined; ++ this._palette.set(dec.palette); ++ releaseDecoder(dec, this._decMemoryLimit); + } + + public put(data: Uint32Array, start: number, end: number): void { +@@ -83,6 +124,14 @@ export class SixelHandler implements IDcsHandler, IResetHandler { + } + + public unhook(success: boolean): boolean | Promise { ++ try { ++ return this._unhook(success); ++ } finally { ++ this._returnDecoder(); ++ } ++ } ++ ++ private _unhook(success: boolean): boolean { + if (this._aborted || !success || !this._dec) { + return true; + } +@@ -100,9 +149,6 @@ export class SixelHandler implements IDcsHandler, IResetHandler { + + const canvas = ImageRenderer.createCanvas(undefined, width, height); + canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8 as Uint8ClampedArray, width, height), 0, 0); +- if (this._dec.memoryUsage > MEM_PERMA_LIMIT) { +- this._dec.release(); +- } + this._storage.addImage(canvas); + return true; + } diff --git a/src/kitty/KittyGraphicsHandler.ts b/src/kitty/KittyGraphicsHandler.ts -index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1fa320c4f8 100644 +index de889dfff75d9ecc8ab47a025e6989ffe75bb202..cf66e5b75c78645b1641e53d1425d88201134f78 100644 --- a/src/kitty/KittyGraphicsHandler.ts +++ b/src/kitty/KittyGraphicsHandler.ts @@ -7,6 +7,7 @@ import { IDisposable } from '@xterm/xterm'; @@ -172,10 +392,12 @@ index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1f this._cleanupAllPending(); if (this._activeDecoder) { this._activeDecoder.release(); -@@ -200,6 +203,25 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos +@@ -200,8 +203,38 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos this._activeDecoder = pending.decoder; } if (!this._activeDecoder) { +- this._activeDecoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes); +- this._activeDecoder.init(); + // Budget WASM capacity, including one page of decoder state and rounding. + const decoderCapacity = this._maxEncodedBytes + 131072; + if (decoderCapacity > this._opts.storageLimit * 1000000) { @@ -195,10 +417,23 @@ index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1f + this._sendResponse(oldest[1].cmd.id, 'ENOMEM:pending image budget exceeded', oldest[1].cmd.quiet ?? 0); + } + } - this._activeDecoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes); - this._activeDecoder.init(); ++ const decoder = new Base64Decoder(Constants.DECODER_KEEP_DATA, this._maxEncodedBytes, this._initialEncodedBytes); ++ try { ++ decoder.init(); ++ } catch (e) { ++ // Why: wasm memory exhaustion must drop this image, not throw out of the parser and wedge the write queue. ++ console.warn('KITTY: could not allocate decoder', e); ++ this._aborted = true; ++ if (this._parsedCommand?.id !== undefined) { ++ this._sendResponse(this._parsedCommand.id, 'ENOMEM:could not allocate decoder', this._parsedCommand.quiet ?? 0); ++ } ++ return; ++ } ++ this._activeDecoder = decoder; } -@@ -550,9 +572,11 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos + + if (this._activeDecoder.put(data.subarray(start, end)) !== DECODER_OK) { +@@ -550,9 +583,11 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos } private async _decodeAndDisplay(image: IKittyImageData, cmd: IKittyCommand): Promise { @@ -210,7 +445,7 @@ index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1f const cropX = Math.max(0, cmd.x ?? 0); const cropY = Math.max(0, cmd.y ?? 0); const cropW = cmd.sourceWidth || (bitmap.width - cropX); -@@ -660,6 +684,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos +@@ -660,6 +695,7 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos } } @@ -218,7 +453,7 @@ index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1f const zIndex = cmd.zIndex ?? 0; this._kittyStorage.addImage(image.id, bitmap, true, layer, zIndex); bitmap = undefined; // ownership transferred to storage -@@ -693,6 +718,12 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos +@@ -693,6 +729,12 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos } if (image.format === KittyFormat.PNG) { @@ -231,7 +466,7 @@ index de889dfff75d9ecc8ab47a025e6989ffe75bb202..54ebea9c061e5bb92b187cab7a53bc1f const blob = new Blob([bytes as BlobPart], { type: 'image/png' }); if (!window.createImageBitmap) { const url = URL.createObjectURL(blob); -@@ -775,27 +806,45 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos +@@ -775,27 +817,45 @@ export class KittyGraphicsHandler implements IApcHandler, IResetHandler, IDispos private async _decompressZlib(compressed: Uint8Array): Promise { try { return await this._decompress(compressed, 'deflate'); diff --git a/config/scripts/xterm-image-wasm-budget-contract.test.mjs b/config/scripts/xterm-image-wasm-budget-contract.test.mjs new file mode 100644 index 00000000000..9ec5f4fc750 --- /dev/null +++ b/config/scripts/xterm-image-wasm-budget-contract.test.mjs @@ -0,0 +1,160 @@ +import { createRequire } from 'node:module' +import { afterEach, describe, expect, it, vi } from 'vitest' + +const require = createRequire(import.meta.url) +const { Terminal } = require('@xterm/xterm') +const { ImageAddon } = require('@xterm/addon-image') + +// V8 caps live wasm memories per renderer (~124 under Electron's sandbox), so +// these contracts pin that idle terminals hold none and that exhaustion drops +// an image instead of wedging the terminal's write queue. + +const SIXEL_RED_REGISTER_1 = '\x1bPq#1;2;100;0;0#1~\x1b\\' +const SIXEL_USE_REGISTER_1 = '\x1bPq#1~\x1b\\' +const PNG_1X1 = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==' +const IIP_PNG = `\x1b]1337;File=inline=1;size=${Buffer.from(PNG_1X1, 'base64').length}:${PNG_1X1}\x07` + +class TrackedBitmap { + width = 1 + height = 1 + close = vi.fn() +} + +function stubCanvasGlobals() { + const painted = [] + vi.stubGlobal('ImageBitmap', TrackedBitmap) + vi.stubGlobal('window', { ImageBitmap: TrackedBitmap }) + vi.stubGlobal('createImageBitmap', async () => new TrackedBitmap()) + vi.stubGlobal( + 'ImageData', + class { + constructor(data, width, height) { + Object.assign(this, { data: new Uint8ClampedArray(data), width, height }) + } + } + ) + vi.stubGlobal('document', { + createElement: () => ({ + width: 0, + height: 0, + getContext: () => ({ putImageData: (image) => painted.push(image) }) + }) + }) + return painted +} + +function createTerminal(options = {}) { + const terminal = new Terminal({ allowProposedApi: true }) + const addon = new ImageAddon({ + enableSizeReports: false, + storageLimit: 32, + kittySizeLimit: 8 * 1024 * 1024, + ...options + }) + terminal.loadAddon(addon) + return { + terminal, + addon, + sixel: addon._handlers.get('sixel'), + iip: addon._handlers.get('iip') + } +} + +function write(terminal, data) { + return new Promise((resolve) => terminal.write(data, resolve)) +} + +// A throw out of a handler leaves xterm's write queue waiting forever. +function writeOrWedge(terminal, data) { + return Promise.race([ + write(terminal, data).then(() => 'parsed'), + new Promise((resolve) => setTimeout(() => resolve('wedged'), 2000)) + ]) +} + +function firstPixel(image) { + return Array.from(image.data.subarray(0, 4)) +} + +afterEach(() => vi.unstubAllGlobals()) + +describe('xterm image wasm budget', () => { + it('keeps idle terminals free of wasm decoders', async () => { + const panes = Array.from({ length: 300 }, () => createTerminal()) + try { + // Let any asynchronous decoder instantiation settle. + await new Promise((resolve) => setTimeout(resolve, 100)) + for (const { sixel, iip } of panes) { + expect(sixel._dec).toBeUndefined() + expect(iip._dec._inst).toBeNull() + expect(iip._qoiDec._inst).toBeFalsy() + } + } finally { + for (const { terminal } of panes) { + terminal.dispose() + } + } + }) + + it('returns decoders after each SIXEL and IIP image', async () => { + const painted = stubCanvasGlobals() + const { terminal, addon, sixel, iip } = createTerminal() + let added = 0 + addon.onImageAdded(() => added++) + try { + await write(terminal, SIXEL_RED_REGISTER_1) + expect(painted).toHaveLength(1) + expect(sixel._dec).toBeUndefined() + + await write(terminal, IIP_PNG) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(iip._dec._inst).toBeNull() + expect(added).toBe(2) + } finally { + terminal.dispose() + } + }) + + it('keeps SIXEL color registers across images until a terminal reset', async () => { + const painted = stubCanvasGlobals() + const { terminal } = createTerminal() + try { + await write(terminal, SIXEL_RED_REGISTER_1) + await write(terminal, SIXEL_USE_REGISTER_1) + expect(firstPixel(painted[1])).toEqual([255, 0, 0, 255]) + + await write(terminal, '\x1bc') + await write(terminal, SIXEL_USE_REGISTER_1) + expect(firstPixel(painted[2])).not.toEqual([255, 0, 0, 255]) + } finally { + terminal.dispose() + } + }) + + it('drops images without wedging the parser when wasm memory is exhausted', async () => { + stubCanvasGlobals() + // A pixelLimit no other test uses keeps the shared SIXEL pool empty for this key. + const { terminal, addon } = createTerminal({ pixelLimit: 1234567 }) + const replies = [] + terminal.onData((data) => replies.push(data)) + function exhausted() { + throw new RangeError('WebAssembly.Memory(): could not allocate memory') + } + vi.stubGlobal('WebAssembly', { ...WebAssembly, Memory: exhausted, Instance: exhausted }) + try { + expect(await writeOrWedge(terminal, '\x1b_Ga=T,f=32,s=1,v=1,i=7;AAAA/w==\x1b\\')).toBe( + 'parsed' + ) + expect(await writeOrWedge(terminal, IIP_PNG)).toBe('parsed') + expect(await writeOrWedge(terminal, SIXEL_USE_REGISTER_1)).toBe('parsed') + expect(await writeOrWedge(terminal, 'after')).toBe('parsed') + + expect(addon._storage._images.size).toBe(0) + expect(replies.join('')).toContain('ENOMEM') + expect(terminal.buffer.active.getLine(0).translateToString(true)).toContain('after') + } finally { + terminal.dispose() + } + }) +}) diff --git a/docs/reference/xterm-patch-regeneration.md b/docs/reference/xterm-patch-regeneration.md index d398f10a6bb..3197de33f20 100644 --- a/docs/reference/xterm-patch-regeneration.md +++ b/docs/reference/xterm-patch-regeneration.md @@ -48,6 +48,15 @@ after reset, disable or disposal. `config/scripts/xterm-image-lifecycle-contract exercises those boundaries against the installed addon. Font zoom scales visible tiles without creating enlarged full-image canvases; `config/scripts/xterm-image-resize-contract.test.mjs` checks allocation and tile mapping. +Every wasm memory reserves its guard region inside V8's sandbox, which caps a +renderer at about 124 live memories no matter how much RAM is free. Upstream +gave each terminal a SIXEL decoder at activation and kept IIP decoders after the +first image, so a window with ~120+ terminals ran out. The patch borrows SIXEL +decoders from a small shared pool only while a sequence is open, keeping color +registers on the terminal, and drops IIP decoders after each image. A decoder +that cannot be allocated drops that image; before the patch it threw out of the +parser and left the terminal's write queue stuck. +`config/scripts/xterm-image-wasm-budget-contract.test.mjs` covers both. ## Rules diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 02422ea3f19..8b5c4b890d4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -111,7 +111,7 @@ overrides: patchedDependencies: i18next-cli@1.74.2: 7955b89d3aa229f477408608d331f78c85148a85a85913729f89fac65ad8b207 '@vscode/windows-process-tree@0.8.0': b4be93859cefb159949d9cf05f97fa91a221dff0f793a6f03d02d78ae5b32035 - '@xterm/addon-image@0.10.0-beta.300': 5fc280019957573eefe8daa2969534d6090ddb29c6b5842b8f22e99dc1ce3146 + '@xterm/addon-image@0.10.0-beta.300': e5254a46d6f57bef4a8a19683bfa685afa0ca0127545aea53b54a48104ca3562 '@xterm/addon-ligatures@0.11.0-beta.300': 47405b9994b5acf1b4e90b49250358c1ca03649854d59560e7732b72fe336920 '@xterm/addon-search@0.17.0-beta.300': eee5338dd2621ece46e79c61ec06766cd7fadaf79ffdb24e2a8ab68e97ef31f0 '@xterm/addon-serialize@0.15.0-beta.300': b35533fe252e7e45433150170348889f4e08a6c17f7017ac34ea694d831fec7f @@ -331,7 +331,7 @@ importers: version: 0.12.0-beta.300(@xterm/xterm@6.1.0-beta.303(patch_hash=dd0ccc59cd1ccf99f4d76e5aa2456da165fa0804dce19a833d7638bd07ffa393)) '@xterm/addon-image': specifier: 0.10.0-beta.300 - version: 0.10.0-beta.300(patch_hash=5fc280019957573eefe8daa2969534d6090ddb29c6b5842b8f22e99dc1ce3146)(@xterm/xterm@6.1.0-beta.303(patch_hash=dd0ccc59cd1ccf99f4d76e5aa2456da165fa0804dce19a833d7638bd07ffa393)) + version: 0.10.0-beta.300(patch_hash=e5254a46d6f57bef4a8a19683bfa685afa0ca0127545aea53b54a48104ca3562)(@xterm/xterm@6.1.0-beta.303(patch_hash=dd0ccc59cd1ccf99f4d76e5aa2456da165fa0804dce19a833d7638bd07ffa393)) '@xterm/addon-ligatures': specifier: 0.11.0-beta.300 version: 0.11.0-beta.300(patch_hash=47405b9994b5acf1b4e90b49250358c1ca03649854d59560e7732b72fe336920)(@xterm/xterm@6.1.0-beta.303(patch_hash=dd0ccc59cd1ccf99f4d76e5aa2456da165fa0804dce19a833d7638bd07ffa393)) @@ -10744,7 +10744,7 @@ snapshots: dependencies: '@xterm/xterm': 6.1.0-beta.303(patch_hash=dd0ccc59cd1ccf99f4d76e5aa2456da165fa0804dce19a833d7638bd07ffa393) - '@xterm/addon-image@0.10.0-beta.300(patch_hash=5fc280019957573eefe8daa2969534d6090ddb29c6b5842b8f22e99dc1ce3146)(@xterm/xterm@6.1.0-beta.303(patch_hash=dd0ccc59cd1ccf99f4d76e5aa2456da165fa0804dce19a833d7638bd07ffa393))': + '@xterm/addon-image@0.10.0-beta.300(patch_hash=e5254a46d6f57bef4a8a19683bfa685afa0ca0127545aea53b54a48104ca3562)(@xterm/xterm@6.1.0-beta.303(patch_hash=dd0ccc59cd1ccf99f4d76e5aa2456da165fa0804dce19a833d7638bd07ffa393))': dependencies: '@xterm/xterm': 6.1.0-beta.303(patch_hash=dd0ccc59cd1ccf99f4d76e5aa2456da165fa0804dce19a833d7638bd07ffa393) From 6e1b7e7fa314362a039829b34fb72d96df1be861 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:21:53 -0700 Subject: [PATCH 05/83] test: remove junk tests that assert source text instead of behavior (#23815) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Deletes 101 test files and trims 112 more, all matching documented junk patterns: exact source/import/string greps, copied inventories and export lists, duplicate invocations of a contract another test already owns, typeof-shape checks TypeScript already enforces, and self-comparisons. The largest group read a production `.ts` file and asserted on its text — for example a TaskPage test that required the source to contain `selectedRepos.find((r) => r.id === newIssueRepoId) ?? selectedRepos[0] ?? null`. Any behavior-preserving rename broke it; no behavior change ever did. Production-side follow-through: exports that only these tests imported are de-exported or deleted, stale comments pointing at removed censuses are dropped, and the reliability-gate registry, `cloud/package.json` test lists, and orphaned source-reading helpers are updated so nothing references a deleted file. Two files kept their real coverage and lost only the census scaffolding: `agent-status-producer-census.test.ts` now drives all five producers end to end instead of grepping the source tree, and `config-toml-trust-stale-writes` replaces an export-list parity check. --- cloud/apps/relay/src/assignment-store.ts | 2 +- .../src/cell-inventory-lock-census.test.ts | 335 --------- .../cell-inventory-lock-contention.test.ts | 30 - ...production-cloud-sql-rollout-lock.test.mjs | 28 - .../scripts/push-gateway-workflow.test.mjs | 5 - .../scripts/push-validation-workflow.test.mjs | 48 -- .../relay-asia-admission-workflow.test.mjs | 375 ---------- .../relay-regional-rehome-workflow.test.mjs | 269 ------- .../relay-same-cap-script-census.test.mjs | 108 --- cloud/package.json | 4 +- config/reliability-gates.jsonc | 31 +- .../scripts/bun-profile-change-scope.test.mjs | 4 +- config/scripts/ci-shard-timings.json | 1 - .../cli-main-module-bundle-parity.test.ts | 91 --- ...t-hosted-browser-package-coverage.test.mjs | 7 - config/scripts/computer-e2e-workflow.test.mjs | 286 -------- .../electron-vite-output-contract.test.ts | 10 - .../headless-serve-shutdown-workflow.test.mjs | 171 ----- .../mobile-web-app-route-manifest.test.mjs | 22 +- ...package-electron-runtime-contract.test.mjs | 564 --------------- ...ged-hang-watchdog-worker-contract.test.mjs | 37 - .../scripts/pr-workflow-lint-parity.test.mjs | 86 --- .../scripts/ssh-docker-ci-sharding.test.mjs | 20 - .../terminal-ime-e2e-workflow.test.mjs | 32 - .../verify-dev-channel-packaging.test.mjs | 13 - .../scripts/win-crash-survival-e2e.test.mjs | 36 +- .../windows-process-tree-gyp-path.test.mjs | 32 +- ...ws-pty-native-capability-workflow.test.mjs | 87 --- ...windows-signing-workflow-contract.test.mjs | 498 ------------- .../accounts/mobile-accounts-route.test.ts | 13 - .../mobile-browser-pane-source.test.ts | 27 - .../mobile-agent-icon-assets.test.ts | 11 +- .../files/files-router-seam-census.test.ts | 35 - .../home-host-edit-navigation-source.test.ts | 11 - .../hooks/use-mobile-dictation-source.test.ts | 97 --- .../host-route-href-encoding.test.ts | 76 -- .../MobileWebShellScreen.test.tsx | 18 - .../bridge-client-frame-cap-boundary.test.ts | 16 - .../bridge-client-frame-cap-unit.test.ts | 14 - .../bridge/bridge-envelope.test.ts | 92 +-- ...age-first-paint-through-the-bridge.test.ts | 19 - .../mobile-web-shell-flag-census.test.ts | 207 ------ ...obile-web-shell-router-seam-census.test.ts | 94 --- .../mobile-web-shell-screen-test-harness.tsx | 2 +- .../shell-older-page-paths-census.test.ts | 89 --- .../shell-screen-route-census.test.ts | 278 -------- .../shell-view-surface.test.ts | 44 -- .../desktop-notification-channel.test.ts | 13 - .../notification-route-coordination.test.ts | 17 - .../keyboard-geometry-host-os-census.test.ts | 69 -- .../keyboard-geometry-owner-census.test.ts | 38 - .../microphone-screen-lock-census.test.ts | 104 --- ...ent-send-keyboard-dismissal-wiring.test.ts | 212 ------ .../session/mobile-native-chat-noise.test.ts | 1 + .../mobile-session-last-tab-close.test.ts | 43 -- .../mobile-session-route-parity.test.ts | 669 ------------------ ...ession-route-source-family.test-support.ts | 69 -- .../src/session/mobile-session-route.test.ts | 19 - .../mobile-session-startup-source.test.ts | 295 -------- ...uick-commands-tab-stability-source.test.ts | 67 -- .../session-router-seam-census.test.ts | 79 --- ...rminal-field-submit-binding-wiring.test.ts | 66 -- .../source-control/mobile-pr-create.test.ts | 26 - .../source-control-router-seam-census.test.ts | 44 -- .../mobile-tasks-refactor-parity.test.ts | 158 ----- .../document-parse-time-effects.test.ts | 52 -- .../src/terminal/document/host-seams.test.ts | 35 - .../terminal/terminal-cell-box-census.test.ts | 62 -- .../terminal-foreground-recovery.test.ts | 44 -- .../terminal-input-connection-gate.test.ts | 91 +-- .../terminal-ios-dictation-write-back.test.ts | 23 - .../terminal-ios-ime-keyboard.test.ts | 23 - ...erminal-keyboard-avoidance-webview.test.ts | 40 -- .../terminal-live-input-affordance.test.ts | 73 -- .../terminal/terminal-viewport-refit.test.ts | 194 +---- .../terminal-webview-consumer-census.test.ts | 85 --- .../terminal/terminal-webview-engine.test.ts | 61 -- .../terminal-webview-query-reply.test.ts | 32 - .../terminal/terminal-webview-reflow.test.ts | 62 -- .../terminal-webview-scroll-routing.test.ts | 258 ------- .../terminal-webview-text-zoom.test.ts | 80 --- ...erminal-write-coalescer-boundaries.test.ts | 79 --- .../bridged-parity/c2-page-closure.test.ts | 235 ------ .../bridged-parity/c3-page-closure.test.ts | 222 ------ .../test-support/census-source-files.test.ts | 34 +- .../src/test-support/rpc-recording/README.md | 14 +- .../native-mounting-substitutes.test.ts | 1 - .../operation-module-loader.test.ts | 2 - .../test-support/webview-document-census.ts | 6 +- .../paired-host-writer-census.test.ts | 39 - .../transport/timer-receiver-census.test.ts | 126 ---- .../unchecked-rpc-reader-boundary.test.ts | 5 - mobile/src/worktree/home-resume-card.test.ts | 11 - mobile/tests-typecheck-baseline.txt | 1 - src/cli/cli-command-name-parity.test.ts | 25 - src/cli/dispatch.ts | 3 +- src/cli/handler-group-manifest.test.ts | 30 - .../orchestration-timeout-cli.test.ts | 288 -------- .../handlers/orchestration-timeout.test.ts | 292 -------- src/cli/handlers/orchestration.test.ts | 127 +++- src/cli/registry-parity.test.ts | 46 -- src/cli/registry-parity.ts | 21 - src/cli/runtime-client-deferral.test.ts | 37 +- src/cli/serve-electron-flag-parity.test.ts | 31 +- .../wsl-hook-relay-sentinel.test.ts | 2 - .../session-search-host-registration.test.ts | 31 - ...r-session-registry-import-boundary.test.ts | 12 - .../claude-account-service-api-parity.test.ts | 31 +- .../claude-agent-sdk-import-boundary.test.ts | 110 +-- ...x-trust-grant-main-thread-boundary.test.ts | 60 -- ...=> config-toml-trust-stale-writes.test.ts} | 44 +- .../gpu-crash-diagnostics.test.ts | 28 - .../gpu-crash-fallback-field-sessions.test.ts | 114 +-- .../gpu-fallback-recovered-launch.test.ts | 21 - .../work-item-details-api-parity.test.ts | 37 - ...omation-dispatcher-source-boundary.test.ts | 22 - src/main/ipc/filesystem-watcher-real.test.ts | 9 - .../ipc/github-ipc-channel-parity.test.ts | 110 --- .../pty-spawn-shell-override-parity.test.ts | 26 - .../pi/titlebar-extension-service.test.ts | 4 - .../ports/port-scan-command-client.test.ts | 12 - .../port-scan-command-import-boundary.test.ts | 18 - .../settled-pty-writer-census.test.ts | 94 --- .../providers/ssh-filesystem-provider.test.ts | 12 - ...uit-teardown-agent-browser-daemons.test.ts | 33 - .../minimax/minimax-fetcher.test.ts | 58 +- .../agent-session-launch-env-backfill.test.ts | 89 --- ...gent-startup-input-assembly-census.test.ts | 56 -- ...osted-browser-row-hydration-census.test.ts | 63 -- .../agent-status-producer-census.test.ts | 130 +--- .../rpc/terminal-stream-byte-length.test.ts | 102 --- ...ructured-claude-auth-policy-wiring.test.ts | 24 +- .../ssh/relay-protocol-backpressure.test.ts | 297 -------- src/main/ssh/ssh-system-fallback.test.ts | 8 - src/main/startup/configure-process.test.ts | 35 +- src/main/startup/secure-dns-census.test.ts | 10 - ...updater-test-harness.leaked-timers.test.ts | 123 ---- .../usage/usage-scan-worker-client.test.ts | 13 - src/relay/relay-watcher-event-emitter.test.ts | 9 - .../workspace-view-cross-client-sync.test.tsx | 75 +- .../src/components/AgentStateDot.test.ts | 10 +- .../automation-scoped-list-client.test.ts | 3 +- .../BrowserAnnotationSendMenuContent.test.tsx | 17 - .../BrowserPane.remote-link-routing.test.ts | 25 - .../BrowserPane.render-ipc.test.ts | 19 - ...-client-page-metadata-route-census.test.ts | 43 -- .../browser-guest-paint-retention.ts | 1 - ...rowser-guest-retention-site-census.test.ts | 223 ------ ...nfirmation-dialog-refresh-boundary.test.ts | 22 - ...ture-interaction-writer-boundaries.test.ts | 323 --------- ...github-item-dialog-source-boundary.test.ts | 310 -------- .../repro-8784-ghe-avatar-fallback.test.ts | 85 --- .../linear-issue-workspace-api-parity.test.ts | 49 -- .../linear-issue-workspace-header.test.ts | 30 - ...StructuredSession.transport-probe.test.tsx | 377 ---------- .../native-chat-composer-containment.test.ts | 33 - .../native-chat/native-chat-noise.test.ts | 56 -- ...ourceControl.host-context-boundary.test.ts | 111 --- .../ai-vault-session-refresh.test.ts | 7 - .../components/settings/GeneralPane.test.ts | 31 - ...rktreeDialog.host-context-boundary.test.ts | 34 - .../sidebar/StatusIndicator.test.ts | 10 +- .../sidebar/project-group-header-dom.test.ts | 63 -- .../sidebar/worktree-keyboard-cycle.test.ts | 26 - .../worktree-list/grouping/build-rows.test.ts | 51 -- .../PetStatusSegment.layout.test.ts | 15 - ...urce-session-classification-parity.test.ts | 52 -- ...pace-space-manager-source-boundary.test.ts | 79 --- ...hosted-browser-row-strip-placement.test.ts | 42 -- ...urface.client-hosted-active-state.test.tsx | 20 - .../task-drawer-source-boundary.test.ts | 108 --- .../task-page-github-issue-creation.test.ts | 53 -- .../task-page-source-family.test-support.ts | 39 - .../task-page-source-switch-boundary.test.ts | 99 --- .../task-page-task-creation-drafts.test.ts | 103 --- ...k-page-workspace-composer-boundary.test.ts | 136 ---- ...erminal-pane-listener-order-parity.test.ts | 94 --- ...al-close-confirm-keyboard-vs-mouse.test.ts | 24 - ...inal-provider-snapshot-capability.test.tsx | 17 - ...ktree-jump-palette-sleeping-filter.test.ts | 26 - ...mp-palette-source-context-boundary.test.ts | 37 - ...rktree-jump-palette-source.test-support.ts | 6 - ...ace-session-merge-close-tombstones.test.ts | 13 - ...poserState-host-context-boundaries.test.ts | 593 ---------------- .../useSettingsNavigationMetadata.test.ts | 40 -- ...agent-launch-caller-profile-census.test.ts | 91 --- ...ent-launch-caller-profiles-test-harness.ts | 140 +--- ...agent-launch-routing-caller-census.test.ts | 86 --- .../non-secure-context-crypto.repro.test.ts | 17 +- .../react-commit-cascade-telemetry.test.ts | 2 - ...uctured-agent-startup-label-census.test.ts | 28 - .../workspace-emoji-shortcodes.lazy.test.ts | 9 - ...reation-flow-agent-trust-preflight.test.ts | 32 - ...rktree-status-spinner-launch-agent.test.ts | 12 - ...browser-workspace-tab-close-census.test.ts | 197 ------ .../host-session-mirror-settle-census.test.ts | 256 ------- .../src/runtime/remote-server-parity.test.ts | 44 -- .../runtime-host-contact-parity.test.ts | 70 +- .../store/slices/github-pr-comments.test.ts | 56 -- .../github-work-items-query-bounds.test.ts | 25 - .../store/slices/linear-invalidation.test.ts | 29 - .../slices/repo-identity-reconcile.test.ts | 3 - .../runtime-host-status-entry-parity.test.ts | 56 -- .../web-runtime-client-export-parity.test.ts | 18 - .../child-process-import-boundary.test.ts | 27 - .../emoji-shortcode-catalog.lazy.test.ts | 35 - src/shared/network/manual-address.test.ts | 8 - .../pane-agent-identity-inventory.test.ts | 488 ------------- ...e-agent-identity-surface-inventory.test.ts | 284 -------- src/shared/priority-semaphore.test.ts | 30 - .../runtime-client-export-parity.test.ts | 242 ------- .../run.test.mjs | 11 - 212 files changed, 200 insertions(+), 16827 deletions(-) delete mode 100644 cloud/apps/relay/src/cell-inventory-lock-census.test.ts delete mode 100644 cloud/dev/scripts/push-validation-workflow.test.mjs delete mode 100644 cloud/dev/scripts/relay-asia-admission-workflow.test.mjs delete mode 100644 cloud/dev/scripts/relay-regional-rehome-workflow.test.mjs delete mode 100644 config/scripts/cli-main-module-bundle-parity.test.ts delete mode 100644 config/scripts/packaged-hang-watchdog-worker-contract.test.mjs delete mode 100644 config/scripts/pr-workflow-lint-parity.test.mjs delete mode 100644 config/scripts/windows-pty-native-capability-workflow.test.mjs delete mode 100644 config/scripts/windows-signing-workflow-contract.test.mjs delete mode 100644 mobile/src/browser/mobile-browser-pane-source.test.ts delete mode 100644 mobile/src/files/files-router-seam-census.test.ts delete mode 100644 mobile/src/home-host-edit-navigation-source.test.ts delete mode 100644 mobile/src/hooks/use-mobile-dictation-source.test.ts delete mode 100644 mobile/src/host-screen/host-route-href-encoding.test.ts delete mode 100644 mobile/src/mobile-web-shell/mobile-web-shell-flag-census.test.ts delete mode 100644 mobile/src/mobile-web-shell/mobile-web-shell-router-seam-census.test.ts delete mode 100644 mobile/src/mobile-web-shell/shell-older-page-paths-census.test.ts delete mode 100644 mobile/src/mobile-web-shell/shell-screen-route-census.test.ts delete mode 100644 mobile/src/mobile-web-shell/shell-view-surface.test.ts delete mode 100644 mobile/src/platform/keyboard-geometry-host-os-census.test.ts delete mode 100644 mobile/src/platform/keyboard-geometry-owner-census.test.ts delete mode 100644 mobile/src/platform/microphone-screen-lock-census.test.ts delete mode 100644 mobile/src/session/agent-send-keyboard-dismissal-wiring.test.ts delete mode 100644 mobile/src/session/mobile-session-last-tab-close.test.ts delete mode 100644 mobile/src/session/mobile-session-route-parity.test.ts delete mode 100644 mobile/src/session/mobile-session-route-source-family.test-support.ts delete mode 100644 mobile/src/session/mobile-session-startup-source.test.ts delete mode 100644 mobile/src/session/quick-commands-tab-stability-source.test.ts delete mode 100644 mobile/src/session/session-router-seam-census.test.ts delete mode 100644 mobile/src/session/terminal-field-submit-binding-wiring.test.ts delete mode 100644 mobile/src/source-control/source-control-router-seam-census.test.ts delete mode 100644 mobile/src/tasks/mobile-tasks-refactor-parity.test.ts delete mode 100644 mobile/src/terminal/terminal-cell-box-census.test.ts delete mode 100644 mobile/src/terminal/terminal-ios-dictation-write-back.test.ts delete mode 100644 mobile/src/terminal/terminal-ios-ime-keyboard.test.ts delete mode 100644 mobile/src/terminal/terminal-live-input-affordance.test.ts delete mode 100644 mobile/src/terminal/terminal-webview-consumer-census.test.ts delete mode 100644 mobile/src/terminal/terminal-webview-reflow.test.ts delete mode 100644 mobile/src/terminal/terminal-webview-scroll-routing.test.ts delete mode 100644 mobile/src/test-support/bridged-parity/c2-page-closure.test.ts delete mode 100644 mobile/src/test-support/bridged-parity/c3-page-closure.test.ts delete mode 100644 mobile/src/transport/paired-host-writer-census.test.ts delete mode 100644 mobile/src/transport/timer-receiver-census.test.ts delete mode 100644 src/cli/cli-command-name-parity.test.ts delete mode 100644 src/cli/handlers/orchestration-timeout-cli.test.ts delete mode 100644 src/cli/handlers/orchestration-timeout.test.ts delete mode 100644 src/cli/registry-parity.test.ts delete mode 100644 src/cli/registry-parity.ts delete mode 100644 src/main/browser/browser-session-registry-import-boundary.test.ts delete mode 100644 src/main/codex/codex-trust-grant-main-thread-boundary.test.ts rename src/main/codex/{config-toml-trust-api-parity.test.ts => config-toml-trust-stale-writes.test.ts} (59%) delete mode 100644 src/main/github/work-item-details-api-parity.test.ts delete mode 100644 src/main/headless-automation-dispatcher-source-boundary.test.ts delete mode 100644 src/main/ipc/github-ipc-channel-parity.test.ts delete mode 100644 src/main/ipc/pty/pty-spawn-shell-override-parity.test.ts delete mode 100644 src/main/ports/port-scan-command-import-boundary.test.ts delete mode 100644 src/main/providers/settled-pty-writer-census.test.ts delete mode 100644 src/main/quit-teardown-agent-browser-daemons.test.ts delete mode 100644 src/main/runtime/agent-session-launch-env-backfill.test.ts delete mode 100644 src/main/runtime/agent-startup-input-assembly-census.test.ts delete mode 100644 src/main/runtime/client-hosted-browser-row-hydration-census.test.ts delete mode 100644 src/main/ssh/relay-protocol-backpressure.test.ts delete mode 100644 src/main/updater-test-harness.leaked-timers.test.ts delete mode 100644 src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.remote-link-routing.test.ts delete mode 100644 src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.render-ipc.test.ts delete mode 100644 src/renderer/src/components/browser-pane/browser-client-page-metadata-route-census.test.ts delete mode 100644 src/renderer/src/components/browser-pane/host-guest/browser-guest-retention-site-census.test.ts delete mode 100644 src/renderer/src/components/feature-interaction-writer-boundaries.test.ts delete mode 100644 src/renderer/src/components/github-item-dialog-source-boundary.test.ts delete mode 100644 src/renderer/src/components/linear-issue-workspace-api-parity.test.ts delete mode 100644 src/renderer/src/components/linear-issue-workspace-header.test.ts delete mode 100644 src/renderer/src/components/native-chat/NativeChatStructuredSession.transport-probe.test.tsx delete mode 100644 src/renderer/src/components/native-chat/native-chat-composer-containment.test.ts delete mode 100644 src/renderer/src/components/native-chat/native-chat-noise.test.ts delete mode 100644 src/renderer/src/components/right-sidebar/SourceControl.host-context-boundary.test.ts delete mode 100644 src/renderer/src/components/sidebar/DeleteWorktreeDialog.host-context-boundary.test.ts delete mode 100644 src/renderer/src/components/sidebar/project-group-header-dom.test.ts delete mode 100644 src/renderer/src/components/status-bar/PetStatusSegment.layout.test.ts delete mode 100644 src/renderer/src/components/status-bar/resource-session-classification-parity.test.ts delete mode 100644 src/renderer/src/components/status-bar/workspace-space-manager-source-boundary.test.ts delete mode 100644 src/renderer/src/components/task-drawer-source-boundary.test.ts delete mode 100644 src/renderer/src/components/task-page-github-issue-creation.test.ts delete mode 100644 src/renderer/src/components/task-page-source-family.test-support.ts delete mode 100644 src/renderer/src/components/task-page-source-switch-boundary.test.ts delete mode 100644 src/renderer/src/components/task-page-task-creation-drafts.test.ts delete mode 100644 src/renderer/src/components/task-page-workspace-composer-boundary.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/terminal-pane-listener-order-parity.test.ts delete mode 100644 src/renderer/src/components/worktree-jump-palette-source-context-boundary.test.ts delete mode 100644 src/renderer/src/components/worktree-jump-palette-source.test-support.ts delete mode 100644 src/renderer/src/lib/agent-launch-caller-profile-census.test.ts delete mode 100644 src/renderer/src/lib/agent-launch-routing-caller-census.test.ts delete mode 100644 src/renderer/src/lib/structured-agent-startup-label-census.test.ts delete mode 100644 src/renderer/src/lib/worktree-creation-flow-agent-trust-preflight.test.ts delete mode 100644 src/renderer/src/runtime/browser-workspace-tab-close-census.test.ts delete mode 100644 src/renderer/src/runtime/host-session-mirror-settle-census.test.ts delete mode 100644 src/renderer/src/store/slices/github-work-items-query-bounds.test.ts delete mode 100644 src/renderer/src/store/slices/runtime-host-status-entry-parity.test.ts delete mode 100644 src/renderer/src/web/web-runtime-client-export-parity.test.ts delete mode 100644 src/shared/pane-agent-identity-inventory.test.ts delete mode 100644 src/shared/pane-agent-identity-surface-inventory.test.ts delete mode 100644 src/shared/runtime-client-export-parity.test.ts diff --git a/cloud/apps/relay/src/assignment-store.ts b/cloud/apps/relay/src/assignment-store.ts index 3572a69299c..9a5cd9d4165 100644 --- a/cloud/apps/relay/src/assignment-store.ts +++ b/cloud/apps/relay/src/assignment-store.ts @@ -8482,7 +8482,7 @@ function isDatabaseLockUnavailable(error: unknown): boolean { return error instanceof Error && error.message === 'database_lock_unavailable' } -export function cellInventoryLockOptions(mode: CellInventoryLockMode): RelayLockOptions { +function cellInventoryLockOptions(mode: CellInventoryLockMode): RelayLockOptions { if (mode === 'nowait') return { failIfUnavailable: true, measureHoldMs: true } if (mode === 'pool-default') return { measureHoldMs: true } return { lockTimeoutMs: CELL_INVENTORY_LOCK_TIMEOUT_MS, measureHoldMs: true } diff --git a/cloud/apps/relay/src/cell-inventory-lock-census.test.ts b/cloud/apps/relay/src/cell-inventory-lock-census.test.ts deleted file mode 100644 index e26d8d0551e..00000000000 --- a/cloud/apps/relay/src/cell-inventory-lock-census.test.ts +++ /dev/null @@ -1,335 +0,0 @@ -import { readFileSync } from 'node:fs' -import { describe, expect, it } from 'vitest' -import { cellInventoryLockOptions, type CellInventoryLockMode } from './assignment-store.js' - -// Which entry points can reach a call site. A site a sweep can enter must never -// take the bounded wait: its 55P03 becomes a terminal transaction failure, and -// the incident monitor freezes on a single one. -type Reachability = 'request' | 'sweep' | 'both' | 'orphan' - -// 'caller' is not a CellInventoryLockMode: those sites take the mode threaded -// from `assign`, which is 'request' for a client and 'pool-default' for the -// evacuateDeadCells sweep. -type CensusMode = CellInventoryLockMode | 'caller' - -type CensusEntry = { method: string; mode: CensusMode; reach: Reachability } - -// Every lockCellInventory / lockGeneralCellInventory call site in -// assignment-store.ts, in source order. A new site fails this test until it is -// classified here, which is the point. -const CENSUS: CensusEntry[] = [ - // assignStickyOnce is gone from this list: its retry now locks only the row - // the host is pinned to (lockCellRows), which is what a sticky refresh - // touches. Placement below is the one genuinely fleet-wide decision left. - { method: 'assignOnce', mode: 'caller', reach: 'both' }, - { method: 'assignOnce', mode: 'caller', reach: 'both' }, - { method: 'assignOnce', mode: 'nowait', reach: 'both' }, - { method: 'assignOnce', mode: 'nowait', reach: 'both' }, - { method: 'assignOnce', mode: 'nowait', reach: 'both' }, - { method: 'refreshDrainMigrationLeasesOnce', mode: 'request', reach: 'request' }, - // changeActivity, acquireActivity, activateControl and - // removeSupersededSameCellControls no longer take the inventory: they lock - // only the one or two cell rows they touch, in cell_id order (lockCellRows), - // so they cannot cycle with placement's ordered inventory lock, and the - // 23-row lock there had serialised every reconnect in the fleet behind every - // other one. The control accept path went one step further and takes no cell - // read lock at all: its single conditional write is the last statement before - // COMMIT. - { method: 'startEvacuation', mode: 'request', reach: 'request' }, - { method: 'completeEvacuationFromDeadSourceOnce', mode: 'request', reach: 'request' }, - { method: 'completeEvacuationFromDeadSourceOnce', mode: 'nowait', reach: 'request' }, - { method: 'supersedeRegisteredEvacuationOnce', mode: 'request', reach: 'request' }, - { method: 'supersedeRegisteredEvacuationOnce', mode: 'nowait', reach: 'request' }, - { method: 'prepareRegisteredCellSupersession', mode: 'request', reach: 'request' }, - { method: 'prepareRegisteredCellSupersession', mode: 'request', reach: 'request' }, - { method: 'completeEvacuation', mode: 'nowait', reach: 'both' }, - { method: 'completeEvacuation', mode: 'pool-default', reach: 'both' }, - { method: 'rebalanceDormant', mode: 'request', reach: 'request' }, - // startRegionalRehomeCandidate is gone: the rehome commit reads the inventory - // unlocked and locks only its target row, NOWAIT, as the statement before - // COMMIT (reserveRegionalRehomeTargetRow below). - { method: 'completeRegionalRehomeCandidate', mode: 'nowait', reach: 'sweep' }, - // Both regional-rehome abort sweeps share this rollback; only the 24-hour - // one also disables the durable switch. - { method: 'rollBackStalledRegionalRehomes', mode: 'nowait', reach: 'sweep' }, - { method: 'abortExpiredEvacuations', mode: 'nowait', reach: 'sweep' }, - { method: 'abortExpiredEvacuations', mode: 'nowait', reach: 'sweep' }, - { method: 'releaseExpiredActivityLeases', mode: 'nowait', reach: 'sweep' }, - { method: 'releaseExpiredActivity', mode: 'nowait', reach: 'sweep' } - // reconcileReservationAccounting and leastLoadedCell are gone too: the first - // repairs exactly two cells' counters and now holds only those rows, and the - // second selects from the inventory its single caller has already locked. -] - -// Every inline `FROM relay_cells ... FOR UPDATE` outside the named lock helpers, -// in source order: whole-table locks in reconciliation and sticky placement, -// and single-row locks for a cell the method is already scoped to (heartbeat, -// fence, drain generation, configuration, or a reservation adjust that runs -// under a lock its caller already holds). A new inline lock fails the census -// below until it is listed here; per-connection paths that touch more than one -// cell go through lockCellRows so the order is fixed. -const NAMED_LOCK_HELPERS = ['lockCellInventory', 'lockGeneralCellInventory', 'lockCellRows'] - -const INLINE_CELL_LOCK_SITES = [ - 'reconcileCellsWithOptions', - 'assignStickyOnce', - 'recordCellHeartbeat', - 'attestCellFence', - 'adoptLegacyCellFence', - 'commitLegacyCellFenceAdoption', - 'prepareCellFenceAttempt', - 'attestCellFenceAttempt', - 'attestCellFenceAttempt', - 'configureCell', - 'reserveRegionalRehomeTargetRow', - 'assertDrainCellGeneration', - 'adjustCellReservation' -] - -// The background sweeps, and nothing else. A method reachable from one of these -// can be entered by a sweep tick, whatever else can also enter it. Both lists are -// read from source, so a new sweep step or a new route widens the derivation here -// instead of silently widening what a bounded wait can be entered from. -const SWEEP_ENTRY_FILES = ['./assignment-cleanup-steps.ts', './regional-rehome-worker.ts'] -const REQUEST_ENTRY_FILES = [ - './app.ts', - './relay-server.ts', - './host-session-registry.ts', - './cell-admission-startup.ts' -] - -const DECLARATION = /^ {2}(?:private |public )?(?:static )?(?:async )?([A-Za-z_][\w]*)[(<]/ - -function storeSource(): string[] { - return readFileSync(new URL('./assignment-store.ts', import.meta.url), 'utf8').split('\n') -} - -function entryPoints(files: string[]): string[] { - return files.flatMap((file) => - [ - ...readFileSync(new URL(file, import.meta.url), 'utf8').matchAll( - /assignments\.([A-Za-z_][\w]*)\(/g - ) - ].map((call) => call[1]!) - ) -} - -// Same-class call graph: store methods only ever reach each other through `this.`. -function storeCallGraph(lines: string[]): Map> { - const bounds: { name: string; start: number }[] = [] - lines.forEach((line, index) => { - const declaration = DECLARATION.exec(line) - if (declaration) bounds.push({ name: declaration[1]!, start: index }) - }) - const callees = new Map>() - bounds.forEach((method, index) => { - const end = bounds[index + 1]?.start ?? lines.length - const names = callees.get(method.name) ?? new Set() - for (const call of lines - .slice(method.start, end) - .join('\n') - .matchAll(/this\.([A-Za-z_][\w]*)\s*\(/g)) { - names.add(call[1]!) - } - callees.set(method.name, names) - }) - return callees -} - -function closure(callees: Map>, roots: string[]): Set { - const reached = new Set() - const pending = [...roots] - while (pending.length > 0) { - const name = pending.pop()! - if (reached.has(name)) continue - reached.add(name) - for (const callee of callees.get(name) ?? []) if (!reached.has(callee)) pending.push(callee) - } - return reached -} - -// Why: a hand-written reachability column is a claim, not a check. Derive both -// directions, so a new sweep edge into a bounded site fails here instead of in -// production, and so 'sweep' and 'both' stop being asserted by hand. -function derivedReachability(lines: string[]): (method: string) => Reachability { - const callees = storeCallGraph(lines) - const sweep = closure(callees, entryPoints(SWEEP_ENTRY_FILES)) - const request = closure(callees, entryPoints(REQUEST_ENTRY_FILES)) - return (method) => - sweep.has(method) - ? request.has(method) - ? 'both' - : 'sweep' - : request.has(method) - ? 'request' - : 'orphan' -} - -function readCallSites(): { method: string; mode: CensusMode }[] { - const sites: { method: string; mode: CensusMode }[] = [] - let method = '' - for (const line of storeSource()) { - const declaration = DECLARATION.exec(line) - if (declaration) method = declaration[1]! - if (/private async lock(General)?CellInventory\(/.test(line)) continue - const call = /lock(?:General)?CellInventory\(\s*\w+\s*,\s*(?:'([a-z-]+)'|(\w+))\s*\)/.exec(line) - if (!call) continue - sites.push({ method, mode: (call[1] ?? 'caller') as CensusMode }) - } - return sites -} - - -// Tier 3 and tier 4 of the row lock order documented in assignment-store.ts. A -// transaction that takes relay_cells before this host's reservation rows can -// cycle with one that takes them the other way round, and PostgreSQL resolves -// that as a 40P01 during exactly the drain and rehome waves these paths exist -// to run. The cell row is the one every host on a cell shares, so it is the -// lock that must be taken last, which fixes the direction for everyone else. -const CELL_LOCK_CALL = - /this\.(?:lockCellInventory|lockGeneralCellInventory|lockCellRows|adjustCellReservationAtomically|adjustCellReservation)\(|UPDATE relay_cells/ -const RESERVATION_LOCK_CALL = - /this\.(?:lockControlConnectionReservations|insertControlConnectionReservation|claimControlConnectionReservation|releaseSupersededControlConnectionReservations)\(|(?:UPDATE|INTO|DELETE FROM)\s+relay_control_connection_reservations/ - -// The lock helpers themselves, plus the one reporting query that reads both -// tables without locking either. -const ROW_LOCK_ORDER_EXEMPT = [ - 'lockCellInventory', - 'lockGeneralCellInventory', - 'lockCellRows', - 'lockControlConnectionReservations', - 'adjustCellReservation', - 'adjustCellReservationAtomically', - 'insertControlConnectionReservation', - 'claimControlConnectionReservation', - 'releaseSupersededControlConnectionReservations', - 'cellDeploymentStatus' -] - -function methodSpans(lines: string[]): { name: string; start: number; end: number }[] { - const starts: { name: string; start: number }[] = [] - lines.forEach((line, index) => { - const declaration = DECLARATION.exec(line) - if (declaration) starts.push({ name: declaration[1]!, start: index }) - }) - return starts.map((entry, index) => ({ - ...entry, - end: starts[index + 1]?.start ?? lines.length - })) -} - -function pathsTakingCellsBeforeReservations(lines: string[]): string[] { - const offending: string[] = [] - for (const span of methodSpans(lines)) { - if (ROW_LOCK_ORDER_EXEMPT.includes(span.name)) continue - let cell = Number.POSITIVE_INFINITY - let reservation = Number.POSITIVE_INFINITY - for (let index = span.start; index < span.end; index++) { - const line = lines[index]! - if (CELL_LOCK_CALL.test(line)) cell = Math.min(cell, index) - if (RESERVATION_LOCK_CALL.test(line)) reservation = Math.min(reservation, index) - } - if (cell < reservation && reservation !== Number.POSITIVE_INFINITY) { - offending.push(span.name) - } - } - return offending -} - -describe('cell inventory lock call-site census', () => { - it('classifies every call site exactly as recorded', () => { - expect(readCallSites()).toEqual(CENSUS.map(({ method, mode }) => ({ method, mode }))) - }) - - // Why: the census only sees lockCellInventory calls, so a hand-written - // `relay_cells ... FOR UPDATE` would escape classification entirely. - it('routes every relay_cells row lock through a named lock helper', () => { - const lines = storeSource() - const rawSites: string[] = [] - // Whole statements, not a fixed window: a wide column list or a raw - // FOR UPDATE inside query() must not slip past. - const source = lines.join('\n') - const bounds: { name: string; start: number }[] = [] - lines.forEach((line, index) => { - const declaration = DECLARATION.exec(line) - if (declaration) bounds.push({ name: declaration[1]!, start: index }) - }) - const methodAt = (offset: number): string => { - const lineIndex = source.slice(0, offset).split('\n').length - 1 - let name = '' - for (const bound of bounds) if (bound.start <= lineIndex) name = bound.name - return name - } - const tick = String.fromCharCode(96) - const statementCall = new RegExp( - '\\.(queryLocked|query)\\(\\s*' + tick + '([^' + tick + ']*)' + tick, - 'g' - ) - for (const call of source.matchAll(statementCall)) { - const statement = call[2]! - if (!/\bFROM\s+relay_cells\b/.test(statement)) continue - const locks = call[1] === 'queryLocked' || /\bFOR\s+UPDATE\b/.test(statement) - if (!locks) continue - const method = methodAt(call.index) - if (NAMED_LOCK_HELPERS.includes(method)) continue - rawSites.push(method) - } - expect(rawSites).toEqual(INLINE_CELL_LOCK_SITES) - }) - - it('takes the host reservation rows before the shared cell row everywhere', () => { - expect(pathsTakingCellsBeforeReservations(storeSource())).toEqual([]) - }) - - it('leaves no call site taking the inventory without naming a mode', () => { - const source = readFileSync(new URL('./assignment-store.ts', import.meta.url), 'utf8') - const unclassified = source - .split('\n') - .filter((line) => /lock(?:General)?CellInventory\(\s*\w+\s*\)/.test(line)) - .filter((line) => !line.includes('private async')) - - expect(unclassified).toEqual([]) - }) - - it('derives the same reachability the census claims', () => { - const reachOf = derivedReachability(storeSource()) - - expect(readCallSites().map(({ method }) => reachOf(method))).toEqual( - CENSUS.map((entry) => entry.reach) - ) - }) - - // Why: this is the whole point of the classification. A shorter wait on a - // sweep-reachable site turns contention into a terminal transaction failure - // that counts against the incident gate's relayPostgresRetryExhausted bar. - // Why: the hold distribution is what the 500ms bound will be tuned against, so - // a mode that stops asking for it goes unmeasured in exactly the lane that - // matters. Nothing else in the suite reads the pool-default branch. - it('measures the hold in every lock mode', () => { - const modes: CellInventoryLockMode[] = ['request', 'nowait', 'pool-default'] - - expect(modes.map((mode) => cellInventoryLockOptions(mode).measureHoldMs)).toEqual([ - true, - true, - true - ]) - }) - - it('never puts a sweep-reachable site on the bounded wait', () => { - const reachOf = derivedReachability(storeSource()) - const bounded = readCallSites().filter( - (site) => site.mode === 'request' && ['sweep', 'both'].includes(reachOf(site.method)) - ) - - expect(bounded).toEqual([]) - }) - - it('routes every sweep-only site to NOWAIT so it can skip the tick', () => { - const reachOf = derivedReachability(storeSource()) - const queueing = readCallSites().filter( - (site) => reachOf(site.method) === 'sweep' && site.mode !== 'nowait' - ) - - expect(queueing).toEqual([]) - }) -}) diff --git a/cloud/apps/relay/src/cell-inventory-lock-contention.test.ts b/cloud/apps/relay/src/cell-inventory-lock-contention.test.ts index 44a4b990ea8..1bf3153f3e4 100644 --- a/cloud/apps/relay/src/cell-inventory-lock-contention.test.ts +++ b/cloud/apps/relay/src/cell-inventory-lock-contention.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { afterEach, describe, expect, it, vi } from 'vitest' const fakes = vi.hoisted(() => ({ @@ -78,7 +77,6 @@ describe('bounded cell-inventory lock wait', () => { // Why: a bound at or above the pool default would fence nothing, and one far // below the hold time would convert ordinary contention into terminal failures. it('keeps the request bound strictly inside the pool default', () => { - expect(CELL_INVENTORY_LOCK_TIMEOUT_MS).toBe(500) expect(CELL_INVENTORY_LOCK_TIMEOUT_MS).toBeLessThan(POSTGRES_LOCK_TIMEOUT_MS) }) @@ -361,15 +359,6 @@ describe('bounded cell-inventory lock wait', () => { await database.close() }) - // Why: index.ts boots a server on import, so its wiring can only be read. An - // unspread hold metric is invisible: the flush simply omits the fields. - it('spreads the hold counts into the runtime metrics flush', () => { - const source = readFileSync(new URL('./index.ts', import.meta.url), 'utf8') - const flush = /observability\.start\(\(\) => \(\{([^}]*)\}\)\)/.exec(source) - - expect(flush?.[1]).toContain('...consumeRelayCellInventoryHold(database)') - }) - // Why: 500ms is a first value, not a measurement. Tuning it needs the hold // distribution, which no runtime metric carried. it('reports how long the inventory lock was held to COMMIT', async () => { @@ -492,25 +481,6 @@ describe('background sweeps skip a contended cell inventory', () => { expect(warnings.entries).toEqual([]) await database.close() }) - - it('still aborts the expired evacuation once the inventory is free', async () => { - const database = await openInMemoryRelayDatabase() - const probe = new InventoryLockProbe(database) - let now = 1_000 - const store = new RelayAssignmentStore(probe, () => now) - await store.reconcileCells(CELLS) - const assignment = await store.assign(identity) - await store.activateControl(identity, { - cellId: assignment.cellId, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - await store.startEvacuation(identity, 'cell-b') - now += 24 * 60 * 60_000 - - expect(await store.abortExpiredEvacuations()).toBe(1) - await database.close() - }) }) // Returns each inventory lock the run took, as its bound or 'nowait'. diff --git a/cloud/dev/scripts/production-cloud-sql-rollout-lock.test.mjs b/cloud/dev/scripts/production-cloud-sql-rollout-lock.test.mjs index d79d4f91046..628b09176da 100644 --- a/cloud/dev/scripts/production-cloud-sql-rollout-lock.test.mjs +++ b/cloud/dev/scripts/production-cloud-sql-rollout-lock.test.mjs @@ -1,5 +1,4 @@ import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' import { test } from 'node:test' import { LEASED_WORKFLOWS, @@ -21,7 +20,6 @@ import { revisionMintingScripts, workflowFiles } from './cloud-sql-rollout-lock-census.mjs' -import { relayWorkflowFile } from './relay-repository.mjs' const expectedLease = { production: PRODUCTION_LEASE, staging: STAGING_LEASE, selectable: SELECTABLE_LEASE } const leasedFiles = Object.keys(LEASED_WORKFLOWS) @@ -182,29 +180,3 @@ test('census: no workflow rolls out against the shared instance outside the leas assert.ok(!(file in NOT_A_CLOUD_SQL_CANDIDATE), `${file} cannot be both leased and a non-candidate`) } }) - -// The API and auth deploy scripts share this contract but stay in the private repository. -const serviceCapScripts = ['dev/scripts/deploy-relay-blue-green.mjs'] - -test('budgets tagged Cloud Run candidates outside the service-wide instance cap', () => { - for (const file of serviceCapScripts) { - const script = readFileSync(new URL(`../../${file}`, import.meta.url), 'utf8') - assert.match(script, /'--no-traffic'/, file) - assert.match(script, /'--max'/, file) - } - const budget = readFileSync( - new URL('../../dev/scripts/relay-cloud-sql-connection-budget.mjs', import.meta.url), - 'utf8' - ) - assert.match(budget, /directly addressable tagged revisions outside service-level caps/) - assert.match( - budget, - /apiCandidate: retainedDirectorRollback \+ inputs\.apiInstances \* inputs\.apiPoolMax/ - ) - const director = readWorkflow(relayWorkflowFile('deploy-relay-production-director.yml')) - const capacity = readWorkflow(relayWorkflowFile('deploy-relay-production-capacity-job.yml')) - const asia = readWorkflow(relayWorkflowFile('operate-relay-asia-admission.yml')) - assert.match(director, /--max-instances "\$\{DIRECTOR_MAX_INSTANCES\}"/) - assert.match(capacity, /--max-instances 5/) - assert.match(asia, /--max-instances "\$\{DIRECTOR_MAX_INSTANCES\}"/) -}) diff --git a/cloud/dev/scripts/push-gateway-workflow.test.mjs b/cloud/dev/scripts/push-gateway-workflow.test.mjs index 3ee4fabe410..5a8349c1855 100644 --- a/cloud/dev/scripts/push-gateway-workflow.test.mjs +++ b/cloud/dev/scripts/push-gateway-workflow.test.mjs @@ -309,11 +309,6 @@ test('push credentials cannot assume the shared Relay deploy identity', () => { assert.doesNotMatch(terraform('push-gateway.tf'), /member\s*=\s*local\.relay_github_deploy_service_account_member/) }) -// A latest revision needs a successor even when validation is inert. -test('dedicated database admits three simultaneous revision pools', () => { - assert.match(terraform('push-gateway.tf'), /var\.push_max_instances \* var\.push_database_pool_max \* 3 <= 64/) -}) - test('push has only a dedicated database attachment and a narrowly scoped deployment lease', () => { const service = terraform('push-gateway.tf') const database = terraform('push-dedicated-database.tf') diff --git a/cloud/dev/scripts/push-validation-workflow.test.mjs b/cloud/dev/scripts/push-validation-workflow.test.mjs deleted file mode 100644 index e26769cfeb3..00000000000 --- a/cloud/dev/scripts/push-validation-workflow.test.mjs +++ /dev/null @@ -1,48 +0,0 @@ -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import test from 'node:test' -import { readRelayWorkflow } from './relay-repository.mjs' - -const workflow = readRelayWorkflow('push-deploy.yml') -const position = (name) => { - const index = workflow.indexOf(`- name: ${name}`) - assert.notEqual(index, -1) - return index -} -const capability = position('Require image support for inert validation') -const deploy = position('Deploy the candidate revision with no traffic') -const activation = position('Retire inert validation and activate the verified image') -const shift = position('Shift all traffic to the verified candidate') - -test('the exact build digest must support validation before production boot', () => { - assert.match(workflow, /docker buildx build --push --platform linux\/amd64 --provenance=false --metadata-file/) - assert.match(workflow, /containerimage\.digest/) - assert.doesNotMatch(workflow, /gcloud artifacts docker images describe/) - assert.ok(capability < deploy) - const preflight = workflow.slice(capability, deploy) - assert.match(preflight, /docker run --rm --network none --entrypoint node "\$\{IMAGE\}"/) - assert.match(preflight, /loadPushConfig\(env\)\.mode !== "validation"/) - assert.match(preflight, /validation_mode_not_fail_closed/) -}) - -test('inert validation and credential checks precede deliberate activation of the same digest', () => { - assert.match(workflow.slice(deploy, activation), /--update-env-vars ORCA_PUSH_MODE=validation/) - assert.match(workflow.slice(deploy, activation), /\.mode == "validation"/) - assert.ok(position('Prove the runtime identity can reach FCM') < activation) - const active = workflow.slice(activation, shift) - assert.ok(active.indexOf('gcloud run deploy') < active.indexOf('gcloud run revisions delete')) - assert.match(active, /--image "\$\{IMAGE\}"/) - assert.match(active, /--remove-env-vars ORCA_PUSH_MODE/) - assert.match(active, /\.spec\.containers\[0\]\.image == \$image/) - assert.match(active, /\.spec\.serviceAccountName == \$account/) - assert.match(active, /\.mode == "active"/) - assert.ok(active.indexOf('ACTIVATION_ATTEMPTED=true') < active.indexOf('gcloud run deploy')) - assert.match(workflow, /deletion below must stop its workers/) -}) - -test('production startup connects read-only and gates all background work in validation', () => { - const entry = readFileSync(new URL('../../apps/push/src/index.ts', import.meta.url), 'utf8') - assert.match(entry, /readOnly: config\.mode === 'validation'/) - assert.match(entry, /startPushBackground\(config,/) - assert.doesNotMatch(entry, /worker\.start\(/) -}) diff --git a/cloud/dev/scripts/relay-asia-admission-workflow.test.mjs b/cloud/dev/scripts/relay-asia-admission-workflow.test.mjs deleted file mode 100644 index 8283d43ca44..00000000000 --- a/cloud/dev/scripts/relay-asia-admission-workflow.test.mjs +++ /dev/null @@ -1,375 +0,0 @@ -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import { test } from 'node:test' -import { relayWorkflowUrl } from './relay-repository.mjs' - -const workflow = readFileSync( - relayWorkflowUrl('operate-relay-asia-admission.yml'), - 'utf8' -) -const iam = readFileSync(new URL('../../infra/terraform/relay-github-actions.tf', import.meta.url), 'utf8') -const stagingProof = readFileSync( - relayWorkflowUrl('prove-relay-asia-staging.yml'), - 'utf8' -) -const directorWorkflow = readFileSync( - relayWorkflowUrl('deploy-relay-production-director.yml'), - 'utf8' -) -const terraformReadme = readFileSync( - new URL('../../infra/terraform/README.md', import.meta.url), - 'utf8' -) -const proofIam = readFileSync( - new URL('../../infra/terraform/relay-asia-proof-iam.tf', import.meta.url), - 'utf8' -) -const relayTerraform = readFileSync( - new URL('../../infra/terraform/relay.tf', import.meta.url), - 'utf8' -) -const rolloutEvidence = readFileSync( - new URL('./relay-asia-rollout-evidence.mjs', import.meta.url), - 'utf8' -) -const admissionBudgets = readFileSync( - new URL('../../packages/relay-contract/src/admission-budgets.ts', import.meta.url), - 'utf8' -) - -test('offers the exact audited admission modes under the shared deployment lock', () => { - for (const mode of [ - 'inspect', 'initialize', 'verify', 'register', 'configure', 'promote', 'rollback' - ]) { - assert.match(workflow, new RegExp(`\\b${mode}\\b`)) - } - assert.match(workflow, /production-cloud-sql-rollout/) - assert.match(workflow, /relay-staging-mutation/) - assert.match(workflow, /selector-generation/) - assert.match(workflow, /selector-attempt-id/) -}) - -test('requires exact confirmations and uses the existing admin identity', () => { - assert.match(workflow, /INITIALIZE_ADMISSION_SELECTOR/) - assert.match(workflow, /REGISTER_ASIA_MIGRATION_ONLY/) - assert.match(workflow, /PROMOTE_ASIA_GENERAL/) - assert.match(workflow, /ROLLBACK_ASIA_MIGRATION_ONLY/) - assert.match(workflow, /CONFIGURE_ASIA_DIRECTOR/) - assert.match(workflow, /GCP_RELAY_DEPLOY_SERVICE_ACCOUNT/) - assert.match(workflow, /id_token_audience: \$\{\{ env\.DIRECTOR_ORIGIN \}\}\/v1\/admin\/drain/) - assert.match(iam, /"operate-relay-asia-admission\.yml"/) -}) - -test('discovers generation read-only and explicitly initializes only generation zero', () => { - assert.match(workflow, /leave empty only for inspect/) - assert.match(workflow, /test -z "\$\{EXPECTED_SELECTOR_GENERATION\}"/) - assert.match(workflow, /test "\$\{EXPECTED_SELECTOR_GENERATION\}" = 0/) - assert.match(workflow, /\^\(0\|\[1-9\]\[0-9\]\*\)\$/) - assert.match(workflow, /selector-membership-sha256/) - assert.match(workflow, /\^\[a-f0-9\]\{64\}\$/) - assert.match(workflow, /director-image-digest/) - assert.match(workflow, /\.spec\.containers\[0\]\.image == \$image/) -}) - -test('uploads one sanitized machine-readable admission result', () => { - assert.match(workflow, /sanitize-relay-asia-admission-result\.mjs/) - const upload = /- name: Upload sanitized admission result\n([\s\S]*?)(?=\n - name:)/ - .exec(workflow)?.[1] - assert.ok(upload) - assert.match( - upload, - /if: \$\{\{ inputs\.mode != 'configure' && steps\.admission-operation\.outcome == 'success' \}\}/ - ) - assert.match(upload, /uses: actions\/upload-artifact@v4/) - assert.match( - upload, - /relay-asia-admission-result-\$\{\{ github\.run_id \}\}-\$\{\{ github\.run_attempt \}\}/ - ) - assert.match(upload, /path: \$\{\{ runner\.temp \}\}\/relay-asia-admission-result\/result\.json/) - assert.match(upload, /if-no-files-found: error/) - assert.match(upload, /retention-days: 7/) - assert.ok( - workflow.indexOf('Upload sanitized admission result') > - workflow.indexOf('Upload immutable canary evidence') - ) -}) - -test('binds selector operations and director configuration to reviewed implementations', () => { - assert.match(workflow, /operate-relay-asia-admission\.mjs/) - assert.match(workflow, /prepare-relay-asia-director-cells\.mjs/) - assert.match(workflow, /deploy-relay-blue-green\.mjs/) - assert.match(workflow, /--prune-revisions false/) - assert.doesNotMatch(workflow, /gcloud secrets versions add/) - assert.match(workflow, /orca-cloud-relay-regional-placement-enabled/) - assert.match(workflow, /\.valueSource\.secretKeyRef/) - assert.match(workflow, /jq -er --arg secret "\$\{REGIONAL_PLACEMENT_SECRET\}"/) - assert.doesNotMatch(workflow, /jq -e --arg secret "\$\{REGIONAL_PLACEMENT_SECRET\}"/) - assert.doesNotMatch(workflow, /--regional-placement-enabled/) - assert.doesNotMatch(workflow, /"\$\{\{ inputs\./) - assert.doesNotMatch(workflow, /dns/i) -}) - -test('requires immutable staged evidence and a timed production canary before expansion', () => { - assert.match(workflow, /actions: read/) - assert.match(workflow, /actions\/download-artifact@v4/) - assert.match(workflow, /relay-asia-staging-\$\{EVIDENCE_RUN_ID\}-\$\{EVIDENCE_RUN_ATTEMPT\}/) - assert.match(workflow, /evidence_kind=staging/) - assert.match(workflow, /load-relay-controls\.mjs/) - assert.match(workflow, /--controls 1/) - assert.match(workflow, /--splices 1/) - assert.match(workflow, /--splice-hold-seconds 60/) - assert.match(workflow, /--relay-asia-load-principals 1/) - assert.match(workflow, /--duration-seconds 300/) - assert.match(workflow, /--required-lease-horizons 2/) - assert.match(workflow, /pnpm\/action-setup@v4/) - assert.match(workflow, /Install exact canary dependencies/) - assert.match(workflow, /pnpm install --frozen-lockfile/) - assert.match(workflow, /pnpm --filter @orca-cloud\/relay-contract build/) - assert.ok( - workflow.indexOf('Build the canary Relay contract') < - workflow.indexOf('Run a real five-minute canary control and splice') - ) - assert.match(workflow, /--load-report "\$\{RUNNER_TEMP\}\/relay-asia-canary-load\.json"/) - assert.match(workflow, /"production-gce-c28":"migration-only","production-gce-c29":"migration-only"/) - // C28/C29 promotion downloads C27's canary under exactly this name. - assert.match(workflow, /relay-asia-\$\{\{ steps\.inputs\.outputs\.canary_hostname \}\}-canary-\$\{\{ github\.run_id \}\}-\$\{\{ github\.run_attempt \}\}/) - assert.match(workflow, /echo "canary_hostname=\$\{canary_cell##\*-\}"/) - assert.match(workflow, /id: canary-evidence-upload/) - assert.match(workflow, /Return an unproven canary cell to migration-only/) - assert.match(workflow, /steps\.canary-evidence-upload\.outcome != 'success'/) - assert.match(workflow, /--mode recover-promotion[\s\S]*?--attempt-id "\$\{SELECTOR_ATTEMPT_ID\}"/) - assert.match(workflow, /--attempt-id "\$\{SELECTOR_ATTEMPT_ID\}-rollback"/) - assert.match(workflow, /evidence_kind=c27/) - assert.match(workflow, /orca_relay_runtime_metrics/) - assert.match(workflow, /relay-asia-rollout-evidence\.mjs create-canary \\\n\s+--cell-id "\$\{CANARY_CELL\}"/) - assert.match(workflow, /retention-days: 7/) - assert.match(workflow, /Require the exact director image before promotion/) - assert.match(workflow, /DIRECTOR_ORIGIN.*\/v1\/admin\/runtime-status/) - assert.match(workflow, /\.imageDigest.*IMAGE_DIGEST/) - const provenance = /- name: Verify evidence provenance and rollout binding before authentication\n([\s\S]*?)(?=\n - id: auth)/ - .exec(workflow)?.[1] - assert.ok(provenance) - assert.match(provenance, /\.head_sha \| select\(type == "string" and test\("\^\[a-f0-9\]\{40\}\$"\)\)/) - assert.match(provenance, /--commit-sha "\$\{evidence_commit_sha\}"/) - assert.doesNotMatch(provenance, /--commit-sha "\$\{GITHUB_SHA\}"/) -}) - -test('binds each production promotion wave to its exact evidence and canary', () => { - const cases = /case "\$\{TARGET_CELL_IDS\}" in\n([\s\S]*?)\n\s*esac/.exec(workflow)?.[1] - assert.ok(cases) - const waves = Object.fromEntries( - [...cases.matchAll(/^ {14}([a-z0-9,-]+)\)\n([\s\S]*?);;/gm)].map((match) => [match[1], { - evidence: /evidence_kind=([a-z0-9]+)/.exec(match[2])?.[1] ?? 'none', - canary: /canary_cell=([a-z0-9-]+)/.exec(match[2])?.[1] ?? 'none' - }]) - ) - assert.deepEqual(waves, { - 'production-gce-c27': { evidence: 'staging', canary: 'production-gce-c27' }, - 'production-gce-c28,production-gce-c29': { evidence: 'c27', canary: 'none' }, - 'production-gce-c30': { evidence: 'none', canary: 'production-gce-c30' } - }) - assert.match(cases, /\*\) echo "production promotion wave is not reviewed" >&2; exit 1 ;;/) - assert.match(workflow, /if test "\$\{evidence_kind\}" = none; then\n\s+test -z "\$\{EVIDENCE_RUN_ID\}"/) - assert.doesNotMatch(workflow, /inputs\.cell-ids == /) -}) - -test('runs the timed canary and its automatic rollback for C27 and C30 alike', () => { - const steps = workflow.split(/\n(?= - )/) - const named = (name) => steps.find((step) => step.includes(`name: ${name}`)) - for (const name of [ - 'Install exact canary dependencies', - 'Build the canary Relay contract', - 'Verify the canary cell state and start the timed canary', - 'Run a real five-minute canary control and splice', - 'Collect regional, Relay SQL, and Cloud SQL canary evidence', - 'Upload immutable canary evidence' - ]) { - assert.match(named(name), /if: \$\{\{ steps\.inputs\.outputs\.canary == 'true' \}\}/, name) - } - assert.match( - workflow, - /if: \$\{\{ inputs\.mode == 'configure' \|\| steps\.inputs\.outputs\.canary == 'true' \}\}/ - ) - const rollback = named('Return an unproven canary cell to migration-only') - assert.match( - rollback, - /if: \$\{\{ always\(\) && steps\.inputs\.outputs\.canary == 'true' && steps\.admission-operation\.outcome != 'skipped' && steps\.canary-evidence-upload\.outcome != 'success' \}\}/ - ) - assert.match(rollback, /CANARY_CELL: \$\{\{ steps\.inputs\.outputs\.canary_cell \}\}/) - assert.match(rollback, /--mode recover-promotion \\\n\s+--cell-ids "\$\{CANARY_CELL\}"/) - assert.match(rollback, /--mode rollback \\\n\s+--cell-ids "\$\{CANARY_CELL\}"/) - assert.match(rollback, /'\.states\[\$cell\]' <<< "\$\{result\}"\)" = migration-only/) - const start = named('Verify the canary cell state and start the timed canary') - assert.match(start, /production-gce-c30\)\n\s+verify_cells=production-gce-c30\n\s+expected_states='\{"production-gce-c30":"general"\}'/) - assert.match(start, /test "\$\(jq -cS '\.states' <<< "\$\{result\}"\)" = "\$\(jq -cS '\.' <<< "\$\{expected_states\}"\)"/) - assert.match(named('Run a real five-minute canary control and splice'), /--duration-seconds 300/) -}) - -test('creates staging evidence only after the bounded launch-path load and rollback', () => { - assert.match(stagingProof, /runs-on: \[self-hosted, linux, x64, relay-asia-east2-load\]/) - assert.doesNotMatch(stagingProof, /group: relay-asia-east2-load/) - assert.match(stagingProof, /pnpm\/action-setup@v4/) - assert.match(stagingProof, /pnpm install --frozen-lockfile/) - assert.match(stagingProof, /pnpm --filter @orca-cloud\/relay-contract build/) - assert.match(stagingProof, /run_phase launch 5 5/) - assert.doesNotMatch(stagingProof, /run_phase control|run_phase mixed/) - assert.match(stagingProof, /--aggregate-controls "\$\(\(controls \* 4\)\)"/) - assert.match(stagingProof, /--aggregate-splices "\$\(\(splices \* 4\)\)"/) - assert.match(stagingProof, /--required-lease-horizons 2/) - assert.match(stagingProof, /--splice-ramp-seconds 120/) - assert.match(stagingProof, /--max-generator-rss-growth-mib 512/) - assert.match(stagingProof, /--relay-asia-load-principals 32/) - assert.match(stagingProof, /ulimit -n/) - assert.match(stagingProof, /--region-behavior-probes 1/) - assert.match(stagingProof, /--capacity-cell-origin https:\/\/c4\.relay-staging\.onorca\.dev/) - assert.match(stagingProof, /--rebind-probes 2/) - assert.match(stagingProof, /--skip-rebind-overflow-check/) - assert.doesNotMatch(stagingProof, /--request-unit-invites|--regional-fallback-probes/) - assert.match(stagingProof, /--aggregate-reader-splices.*echo 5/) - assert.match(stagingProof, /--aggregate-reader-bytes.*echo 12582912/) - assert.match(stagingProof, /--phase-barrier-dir "\$\{proof_dir\}\/\$\{phase\}-barrier"/) - assert.match(stagingProof, /--duration-seconds 210/) - assert.match(stagingProof, /trap stop_shards EXIT/) - assert.match(stagingProof, /if ! wait "\$\{pid\}"; then failed=1; break; fi/) - assert.match(stagingProof, /connectionFailuresByReason/) - assert.match(stagingProof, /--launch-report "\$\{proof_dir\}\/launch\.json"/) - assert.match(stagingProof, /id-token: write/) - assert.match(stagingProof, /STAGING_GCP_RELAY_ASIA_PROOF_WORKLOAD_IDENTITY_PROVIDER/) - assert.match(stagingProof, /STAGING_GCP_RELAY_ASIA_PROOF_SERVICE_ACCOUNT/) - assert.doesNotMatch(stagingProof, /STAGING_GCP_DEPLOY_SERVICE_ACCOUNT/) - assert.doesNotMatch(stagingProof, /STAGING_RELAY_LOAD_ACCESS_TOKEN/) - assert.doesNotMatch(stagingProof, /secrets versions access|signing-key-file/) - assert.match(stagingProof, /relay-asia-rollout-evidence\.mjs create-staging/) - assert.match(stagingProof, /Require the exact staging director image before promotion/) - assert.match(stagingProof, /DIRECTOR_ORIGIN.*\/v1\/admin\/runtime-status/) - assert.match(stagingProof, /\.imageDigest.*IMAGE_DIGEST/) - assert.match(stagingProof, /Return staging C4 to migration-only/) - assert.match(stagingProof, /steps\.promote\.outcome != 'skipped'/) - assert.match(stagingProof, /--mode recover-promotion[\s\S]*?--attempt-id "\$\{PROMOTE_ATTEMPT_ID\}"/) - assert.match(stagingProof, /--mode rollback[\s\S]*?--expected-generation "\$\{promoted_generation\}"/) - assert.match(stagingProof, /if: \$\{\{ success\(\) \}\}/) - assert.match( - stagingProof, - /recover:\n if: \$\{\{ always\(\) && github\.ref == 'refs\/heads\/main' \}\}/ - ) - assert.match(stagingProof, /needs: prove/) - assert.match(stagingProof, /Recover staging C4 with a fresh identity/) - assert.equal((stagingProof.match(/google-github-actions\/auth@v2/g) ?? []).length, 2) - assert.equal((stagingProof.match(/--mode recover-promotion/g) ?? []).length, 2) - assert.equal((stagingProof.match(/--mode rollback/g) ?? []).length, 2) -}) - -test('keeps the private runner below its 64-port Cloud NAT allocation', () => { - const profile = /run_phase launch (\d+) (\d+)/.exec(stagingProof) - const controlsPerShard = Number(profile?.[1]) - const splicesPerShard = Number(profile?.[2]) - const rebindProbes = Number(/--rebind-probes (\d+)/.exec(stagingProof)?.[1]) - const runtimeStatusSockets = 1 - assert.ok( - controlsPerShard * 4 + splicesPerShard * 4 * 2 + rebindProbes + runtimeStatusSockets < 64 - ) -}) - -test('paces one-source staging upgrades below the Relay anti-abuse ceiling', () => { - const splicesPerShard = Number(/run_phase launch \d+ (\d+)/.exec(stagingProof)?.[1]) - const rebindProbes = Number(/--rebind-probes (\d+)/.exec(stagingProof)?.[1]) - const spliceRampMs = Number(/--splice-ramp-seconds (\d+)/.exec(stagingProof)?.[1]) * 1000 - const ceiling = Number( - /maxPreAuthAttemptsPerSourcePerMinute: (\d+)/.exec(admissionBudgets)?.[1] - ) - const totalSplices = splicesPerShard * 4 - const attempts = Array.from({ length: totalSplices }, (_, ordinal) => - Math.floor(ordinal * spliceRampMs / (totalSplices - 1)) - ).flatMap((startedAt) => [startedAt, startedAt]) - attempts.push(...Array.from({ length: 4 + rebindProbes }, () => 0)) - const busiestMinute = Math.max(...attempts.map((startedAt) => - attempts.filter((attempt) => attempt >= startedAt && attempt < startedAt + 60_000).length - )) - assert.ok(busiestMinute < ceiling) -}) - -test('reserves rollback time beyond the complete bounded staging proof envelope', () => { - const timeoutMinutes = Number(/timeout-minutes: (\d+)/.exec(stagingProof)?.[1]) - assert.equal(timeoutMinutes, 75) - const spliceRampSeconds = Number(/--splice-ramp-seconds (\d+)/.exec(stagingProof)?.[1]) - const launchSeconds = 180 + spliceRampSeconds + 210 + 60 - const setupEvidenceAndRollbackSeconds = 10 * 60 - const envelopeMinutes = Math.ceil((launchSeconds + setupEvidenceAndRollbackSeconds) / 60) - assert.ok(timeoutMinutes - envelopeMinutes >= 30) - assert.match(stagingProof, /--ramp-seconds 180/) - assert.match(stagingProof, /--duration-seconds 210/) -}) - -test('binds the staging proof to one least-privilege Google identity', () => { - assert.match( - proofIam, - /github_relay_asia_proof_workflow_file = "prove-relay-asia-staging\.yml"/ - ) - assert.match( - proofIam, - /assertion\.workflow_ref == '\$\{prefix\}\$\{local\.github_relay_asia_proof_workflow_file\}@refs\/heads\/main'/ - ) - assert.match(proofIam, /assertion\.environment == 'staging'/) - assert.match(proofIam, /assertion\.event_name == 'workflow_dispatch'/) - assert.match(proofIam, /roles\/logging\.viewer/) - assert.match(proofIam, /roles\/monitoring\.viewer/) - assert.match(rolloutEvidence, /readCloudSqlBackends/) - assert.match(rolloutEvidence, /cloudSql: await readCloudSqlBackends/) - assert.doesNotMatch(proofIam, /compute\.|cloudsql\.|secretmanager\.|roles\/editor|roles\/run\./) -}) - -test('keeps the production US-first switch in durable Secret Manager state', () => { - assert.match(directorWorkflow, /options: \[preserve, enable, disable\]/) - assert.match(directorWorkflow, /default: preserve/) - assert.match(directorWorkflow, /gcloud secrets versions add/) - assert.match(directorWorkflow, /preserve\) desired="\$\{current\}"/) - assert.match(directorWorkflow, /--regional-placement-secret-version "\$\{target_version\}"/) - assert.match(directorWorkflow, /test "\$\{CEILING\}" = "\$\{DIRECTOR_MAX_INSTANCES\}"/) - assert.match(directorWorkflow, /orca-cloud-relay-regional-placement-enabled/) - assert.match(directorWorkflow, /\.valueSource\.secretKeyRef \/\/ \.valueFrom\.secretKeyRef/) - assert.match(directorWorkflow, /\.version \/\/ \.key/) - assert.match(directorWorkflow, /\.secret \/\/ \.name/) - assert.match(workflow, /\.valueSource\.secretKeyRef \/\/ \.valueFrom\.secretKeyRef/) - assert.doesNotMatch(directorWorkflow, /--regional-placement-enabled/) - assert.doesNotMatch(workflow, /inputs\.regional-placement-enabled/) -}) - -test('prunes incompatible production revisions only when explicitly confirmed', () => { - assert.match( - directorWorkflow, - /prune-incompatible-revisions:[\s\S]*?default: false[\s\S]*?type: boolean/ - ) - assert.match(directorWorkflow, /PRUNE_INCOMPATIBLE_RELAY_DIRECTOR_REVISIONS/) - assert.match( - directorWorkflow, - /test "\$\{REGIONAL_PLACEMENT_MODE\}" = preserve[\s\S]*?test "\$\{CONFIRMATION\}" = PRUNE_INCOMPATIBLE_RELAY_DIRECTOR_REVISIONS/ - ) - assert.match( - directorWorkflow, - /--prune-revisions "\$\{PRUNE_INCOMPATIBLE_REVISIONS\}"/ - ) -}) - -test('documents the exact regional-placement secret bootstrap before director rollout', () => { - for (const address of [ - 'google_secret_manager_secret.relay_regional_placement_enabled', - 'google_secret_manager_secret_version.relay_regional_placement_enabled', - 'google_secret_manager_secret_iam_member.relay_regional_placement_runtime_accessor', - 'google_secret_manager_secret_iam_member.relay_regional_placement_deploy_accessor[0]', - 'google_secret_manager_secret_iam_member.relay_regional_placement_deploy_adder[0]', - 'google_secret_manager_secret_iam_member.relay_regional_placement_deploy_viewer[0]' - ]) { - assert.match(terraformReadme, new RegExp(address.replaceAll(/[.[\]]/g, '\\$&'))) - } - assert.match(terraformReadme, /Before the first director deployment/) - assert.match(terraformReadme, /Pass the exact environment tfvars/) - // The Cloudflare records left with the apps root; a -var for a variable this root no longer - // declares is a hard error, so no relay procedure may still tell an operator to pass it. - assert.doesNotMatch(terraformReadme, /manage_artifact_dns/) - assert.match(terraformReadme, /exactly these six additions/) - assert.match(terraformReadme, /version metadata/) - assert.match( - relayTerraform, - /resource "google_secret_manager_secret_iam_member" "relay_regional_placement_deploy_viewer"[\s\S]*?role\s+= "roles\/secretmanager\.viewer"/ - ) -}) diff --git a/cloud/dev/scripts/relay-regional-rehome-workflow.test.mjs b/cloud/dev/scripts/relay-regional-rehome-workflow.test.mjs deleted file mode 100644 index aabf80a65f0..00000000000 --- a/cloud/dev/scripts/relay-regional-rehome-workflow.test.mjs +++ /dev/null @@ -1,269 +0,0 @@ -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import { test } from 'node:test' -import { fileURLToPath } from 'node:url' -import { relayWorkflowUrl } from './relay-repository.mjs' - -function workflow(name) { - return readFileSync( - fileURLToPath(relayWorkflowUrl(name)), - 'utf8' - ) -} - -test('same-cap wrapper is reusable, canary-bound, and sequential', () => { - const wrapper = workflow('deploy-relay-production-same-cap.yml') - const job = workflow('deploy-relay-production-same-cap-job.yml') - assert.match(wrapper, /options: \[verify, canary-apply, batch-apply, rollback\]/) - assert.match(wrapper, /relay-same-cap-canary-\$\{\{ inputs\.canary-run-id \}\}/) - assert.match(wrapper, /needs: \[gate, cell_1\]/) - assert.match(wrapper, /needs: \[gate, cell_2\]/) - assert.match(wrapper, /needs: \[gate, cell_3\]/) - assert.match(job, /on:\n workflow_call:/) - assert.match(job, /c27\|c28\|c29\|c30\)/) - assert.match(job, /EXPECTED_HARD_CAP=3000/) - assert.match(job, /EXPECTED_REGION=asia-east2/) - assert.match(job, /--hard-cap "\$\{EXPECTED_HARD_CAP\}"/) - assert.match(job, /--regional-rehome-protocol "\$\{DESIRED_REHOME_PROTOCOL\}"/) - assert.match(job, /--argjson protocol "\$\{PREDECESSOR_REHOME_PROTOCOL\}"/) - assert.match(job, /runtime predecessor mismatch fields=/) - // A rollback interrupted between apply and restore must be resumable. - assert.match(job, /ROLLBACK_RESUME=true/) - assert.match(job, /test "\$\{LIVE_IMAGE_DIGEST\}" = "\$\{DESIRED_IMAGE_DIGEST\}"/) - // Resume must skip BOTH the drain (no restart will clear the flag) and the - // apply (state already converged), and prove convergence instead. - assert.match( - job, - /Reversibly isolate and drain only the selected cell\n if: \$\{\{ inputs\.mode != 'verify' && env\.ROLLBACK_RESUME != 'true' \}\}/ - ) - assert.match( - job, - /Apply only the selected same-cap template and MIG\n if: \$\{\{ inputs\.mode != 'verify' && env\.ROLLBACK_RESUME != 'true' \}\}/ - ) - assert.match( - job, - /Require converged Terraform state and a stable MIG on resume\n if: \$\{\{ inputs\.mode != 'verify' && env\.ROLLBACK_RESUME == 'true' \}\}/ - ) - assert.match(job, /resume found unconverged resources/) - // A canary or batch cell that failed before its template apply also - // resumes here with template drift from repo changes since its last roll; - // only a plan the reviewed validator approves for the image the cell - // already serves may pass, and resume still applies nothing. - assert.match(job, /requiring reviewed rollback-image drift/) - assert.match( - job, - /--image "\$\{DESIRED_IMAGE\}" \\\n {16}--rollback-image "\$\{DESIRED_IMAGE\}"/ - ) - // The relaxation is only safe if the reviewed validator actually runs on - // the NON-converged branch, in same-cap-cell mode, with the trust config - // the validator requires, restricted to the template-and-MIG change pair. - assert.match( - job, - /if ! terraform -chdir=infra\/terraform show -json[\s\S]{0,220}\| length == 0' >\/dev\/null\n then\n/ - ) - assert.match( - job, - /requiring reviewed rollback-image drift'\n[\s\S]{0,400}?\n {16}--mode same-cap-cell --cell-id "\$\{TARGET_CELL_ID\}" \\\n/ - ) - assert.match( - job, - /Require converged Terraform state and a stable MIG on resume[\s\S]{0,300}CAPACITY_SERVICE_ACCOUNT: \$\{\{ vars\.PRODUCTION_GCP_RELAY_CAPACITY_SERVICE_ACCOUNT \}\}\n {10}DIRECTOR_RUNTIME_SERVICE_ACCOUNT: \$\{\{ vars\.PRODUCTION_GCP_RELAY_DIRECTOR_RUNTIME_SERVICE_ACCOUNT \}\}/ - ) - assert.match( - job, - /--rollback-image "\$\{DESIRED_IMAGE\}" \\\n {16}--capacity-service-account "\$\{CAPACITY_SERVICE_ACCOUNT\}" \\\n {16}--rehome-director-service-account "\$\{DIRECTOR_RUNTIME_SERVICE_ACCOUNT\}"/ - ) - assert.match( - job, - /host-drain \\\n {16}--regional-rehome-protocol "\$\{DESIRED_REHOME_PROTOCOL\}" \\\n {16}"\$\{POOL_ARGUMENTS\[@\]\}"\)"\n {12}echo "\$\{RESUME_REVIEW\}"\n {12}jq -e '\.changes == 2' <<< "\$\{RESUME_REVIEW\}" >\/dev\/null/ - ) - // A resume applies nothing at all, which is what a resume means: the only accepted - // unconverged plan is the template-and-MIG rollback-image drift, and it is left pending. - const resumeStep = job.slice( - job.indexOf('- name: Require converged Terraform state and a stable MIG on resume'), - job.indexOf('- name: Apply only the selected same-cap template and MIG') - ) - assert.equal(resumeStep.split('terraform -chdir=infra/terraform apply').length, 1) - assert.match(job, /resume requires the isolated migration-only cell/) - assert.match(job, /test "\$\{TARGET_INCARNATION\}" = "\$\{SOURCE_INCARNATION\}"/) - assert.match(job, /\(.regionalRehomeProtocol \/\/ 0\) == \$protocol/) - assert.match(job, /\(\.draining == false or \$drainingOk\)/) - // Selector expectations must follow the mutations' returned generations, - // not fixed offsets: isolate is a no-op on a cell a failed canary already - // isolated, and the restore inspect must expect post-restore membership. - assert.match(job, /SELECTOR_GENERATION_AFTER_ISOLATE=\$\{EFFECTIVE_SELECTOR_GENERATION\}/) - assert.match(job, /SELECTOR_GENERATION_AFTER_ISOLATE=\$\{ISOLATE_GENERATION\}/) - assert.match(job, /--expected-selector-generation "\$\{SELECTOR_GENERATION_AFTER_ISOLATE\}"/) - assert.match(job, /--expected-selector-generation "\$\{SELECTOR_GENERATION_AFTER_RESTORE\}"/) - assert.match(job, /--expected-migration-only-cells "\$\{RESTORED_MIGRATION_CELLS\}"/) - assert.match(job, /--expected-general-cells "\$\{RESTORED_GENERAL_CELLS\}"/) - assert.match(job, /FAILSAFE_GENERATION/) - // Later batch waves start after ~16-min predecessor rolls, so BOTH evidence - // age checks must scale by wave or cell_2+ can never pass; the bound's - // per-wave step is the cell job timeout, so the two must move together. - assert.match(job, /--required-migration-policy strict \\\n --wave-index "\$\{WAVE_INDEX\}"/) - // Wave 0 must retry freshness-only failures too: one Cloud Monitoring publish - // lag at the sample instant is not health evidence, and single-shot wave 0 - // failed a whole batch on a series that was fresh again a minute later. - assert.match( - job, - /dry-run\.state\.json" \\\n {14}--wave-index "\$\{WAVE_INDEX\}" \\\n {14}--selector-wave-delta "\$\{SELECTOR_WAVE_DELTA\}" --retry-freshness/ - ) - assert.doesNotMatch(job, /RETRY_ARGS/) - // Break-glass: the override skips the aggregate 15-minute monitor evidence and - // nothing else. The live per-wave recheck still runs on the override path, off - // the dispatch inputs the rehome inspect below verifies against the director. - assert.match( - job, - /if test -n "\$\{GATE_OVERRIDE_CONFIRMATION\}"; then[\s\S]{0,700}?--no-monitor-state \\\n {14}--expected-selector-generation "\$\{EXPECTED_SELECTOR_GENERATION\}" \\\n {14}--selector-membership-file[\s\S]{0,160}?--wave-index "\$\{WAVE_INDEX\}" \\\n {14}--selector-wave-delta "\$\{SELECTOR_WAVE_DELTA\}" --retry-freshness/ - ) - // The override is re-validated here, not trusted from the caller, and it is - // bound to the digest this wave installs. - assert.match( - job, - /test "\$\{GATE_OVERRIDE_CONFIRMATION\}" = \\\n {14}"SKIP_RELAY_MONITOR_GATE \$\{TARGET_IMAGE_DIGEST\}"/ - ) - assert.match(job, /\[\[ "\$\{GATE_OVERRIDE_REASON\}" =~ \^\[\[:print:\]\]\{12,500\}\$ \]\]/) - // Exactly the aggregate-evidence steps are skipped, and only them: every step - // that reads or spends the sealed monitor artifact carries the override guard. - const overrideSkipped = [ - 'Require fresh aggregate monitor evidence reference', - 'Download private aggregate monitor evidence', - 'Verify monitor evidence provenance', - "Download this wave's single-use safety authority", - 'Require safety evidence consumed by this workflow' - ] - for (const name of overrideSkipped) { - assert.match( - job, - new RegExp(`- name: ${name}\\n {8}if: \\$\\{\\{ inputs\\.mode != 'verify' && inputs\\.gate-override-confirmation == '' \\}\\}`) - ) - } - assert.equal( - job.match(/inputs\.gate-override-confirmation == ''/g).length, - overrideSkipped.length - ) - // The wrapper validates the override before anything runs, passes it to every - // cell, seals it into the canary artifact, and prints it in the run summary. - assert.match(wrapper, /--gate-override-reason "\$\{GATE_OVERRIDE_REASON\}" \\\n {12}--gate-override-confirmation "\$\{GATE_OVERRIDE_CONFIRMATION\}"\)/) - // One per cell job in the serial cell_1..cell_10 chain. - assert.equal( - wrapper.match(/gate-override-confirmation: \$\{\{ inputs\.gate-override-confirmation \}\}/g).length, - 10 - ) - assert.match(wrapper, /Aggregate monitor gate overridden \(break-glass\)/) - assert.match(wrapper, /ACTOR: \$\{\{ github\.actor \}\}/) - for (const name of [ - 'Reject previously consumed aggregate safety evidence', - 'Consume aggregate safety evidence for this exact wave' - ]) { - assert.match( - wrapper, - new RegExp(`- name: ${name}\\n {8}if: \\$\\{\\{ inputs\\.mode != 'verify' && inputs\\.gate-override-confirmation == '' \\}\\}`) - ) - } - assert.match(job, /timeout-minutes: 75/) - // Both age gates step by the cell job timeout above; the constant is - // duplicated across the two languages, so pin each copy to it. - for (const source of [ - '../../dev/scripts/relay-monitor-evidence.mjs', - '../../apps/relay-ops/src/incident-live-preflight-cli.ts' - ]) { - const body = readFileSync(fileURLToPath(new URL(source, import.meta.url)), 'utf8') - assert.match(body, /WAVE_PREDECESSOR_TIMEOUT_MS = 75 \* 60_000/) - assert.match(body, /\^\[0-9\]\$/) - } - // Aged-evidence replay via job re-runs is fenced: mutations are - // single-dispatch, so a failed cell needs a fresh gate and monitor run. - assert.match(job, /test "\$\{GITHUB_RUN_ATTEMPT\}" = 1/) - for (const index of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) { - assert.match(wrapper, new RegExp(`wave-index: '${index}'`)) - } - assert.doesNotMatch(job, /EFFECTIVE_SELECTOR_GENERATION \+ 1\)/) - assert.doesNotMatch(job, /EFFECTIVE_SELECTOR_GENERATION \+ 2\)/) - assert.match(job, /\$region == "us-central1" and \$protocol == 0 and [.]region == null/) - assert.match(job, /[.]regionalRehomeProtocol \/\/ 0/) - assert.match(job, /runtime predecessor normalized legacy fields=/) - assert.match(job, /probe-relay-rehome-trust[.]mjs/) - assert.doesNotMatch(job, /service_account: \$\{\{ vars\.PRODUCTION_GCP_RELAY_(?:DIRECTOR_)?RUNTIME_SERVICE_ACCOUNT/) - assert.doesNotMatch(job, /roles\/iam\.serviceAccountTokenCreator/) -}) - -// Why: the same-cap caller defines release_lease itself, and a caller-defined job presents the -// caller as job_workflow_ref, so the pair must admit the caller alongside its reusable job. -test('shared deploy WIF admits the exact same-cap reusable workflow pair and the caller itself', () => { - const terraform = readFileSync( - fileURLToPath(new URL('../../infra/terraform/relay-github-actions.tf', import.meta.url)), - 'utf8' - ) - const providerStart = terraform.indexOf( - 'resource "google_iam_workload_identity_pool_provider" "github"' - ) - const providerEnd = terraform.indexOf('\nresource "', providerStart + 1) - const sharedProvider = terraform.slice(providerStart, providerEnd) - assert.ok(providerStart >= 0 && providerEnd > providerStart) - assert.match(sharedProvider, /local\.relay_github_workflow_conditions\["github"\]/) - // The pairing itself now lives in the clause the provider renders, once per accepted repository. - assert.match( - terraform, - /assertion\.workflow_ref == '\$\{prefix\}\$\{local\.github_production_relay_same_cap_workflow_file\}@refs\/heads\/main' && \(assertion\.job_workflow_ref == '\$\{prefix\}\$\{local\.github_production_relay_same_cap_job_workflow_file\}@refs\/heads\/main' \|\| assertion\.job_workflow_ref == '\$\{prefix\}\$\{local\.github_production_relay_same_cap_workflow_file\}@refs\/heads\/main'\)/ - ) -}) - -test('pause and disable precede optional installation and cloud diagnostics', () => { - const job = workflow('operate-relay-production-rehome-job.yml') - const emergency = job.indexOf('Apply emergency durable pause or disable before diagnostics') - const install = job.indexOf('pnpm install --frozen-lockfile') - const revision = job.indexOf('Verify exact serving and rollback director identities') - assert.ok(emergency > 0) - assert.ok(emergency < install) - assert.ok(emergency < revision) - assert.match(job, /inputs\.mode == 'pause' \|\| inputs\.mode == 'disable'/) - assert.match(job, /Seal 24-hour aggregate region observation evidence/) - assert.match(job, /--freshness=25h --limit=30000/) - assert.match(job, /relay-region-observation-\$\{\{ github\.run_id \}\}-\$\{\{ github\.run_attempt \}\}/) - assert.match(job, /test "\$\{RATE_PER_MINUTE\}" = 10/) -}) - -test('a failed enable independently restores and verifies durable disabled state', () => { - const job = workflow('operate-relay-production-rehome-job.yml') - const enable = job.indexOf('Apply exact durable regional rehome enable') - const evidence = job.indexOf('Read fresh aggregate completion and abort evidence') - const summary = job.indexOf('Publish aggregate control evidence') - const recovery = job.indexOf('Fail closed after an unsuccessful enable run') - assert.ok(enable > 0 && enable < evidence && evidence < summary && summary < recovery) - const recoveryStep = job.slice(recovery) - assert.match( - recoveryStep, - /failure\(\) && inputs\.mode == 'enable' && steps\.google-auth\.outcome == 'success'/ - ) - assert.match(recoveryStep, /--mode recover-enable/) - assert.match(recoveryStep, /--expected-control-generation "\$\{EXPECTED_CONTROL_GENERATION\}"/) - assert.match(recoveryStep, /RECOVER_FAILED_REGIONAL_REHOME_ENABLE/) - assert.match(recoveryStep, /\.control\.enabled == false/) - assert.doesNotMatch(recoveryStep, /gcloud|pnpm/) -}) - -test('director rollout has a strict one-time identity bootstrap', () => { - const workflowBody = workflow('deploy-relay-production-director.yml') - const script = readFileSync( - fileURLToPath(new URL('./deploy-relay-blue-green.mjs', import.meta.url)), - 'utf8' - ) - assert.match(workflowBody, /BOOTSTRAP_RELAY_DIRECTOR_REHOME_IDENTITY/) - assert.match(workflowBody, /--predecessor-runtime-service-account/) - assert.match(workflowBody, /--expected-rehome-generation/) - assert.match(script, /args\.push\('--service-account', config\['runtime-service-account'\]\)/) - assert.match(script, /director predecessor runtime service account does not match/) - const candidateProof = script.indexOf('await verifyRehomeDisabled(candidate.origin)') - const trafficMove = script.indexOf('operations.updateTraffic(config, [`--to-tags=') - assert.ok(candidateProof > 0 && candidateProof < trafficMove) - assert.equal(script.indexOf('verifyRehomeDisabled', trafficMove), -1) -}) - -test('rehome job pipes every control result through tee under pipefail', () => { - const job = workflow('operate-relay-production-rehome-job.yml') - // Without `shell: bash` the step exit code is tee's, so a thrown inspect/apply passes green. - assert.match(job, /defaults:\n run:\n(?: #.*\n)* shell: bash\n/) - assert.ok((job.match(/\| tee "\$\{RUNNER_TEMP\}/g) ?? []).length >= 5) -}) diff --git a/cloud/dev/scripts/relay-same-cap-script-census.test.mjs b/cloud/dev/scripts/relay-same-cap-script-census.test.mjs index 1e023ce0c9d..ff2c265ee72 100644 --- a/cloud/dev/scripts/relay-same-cap-script-census.test.mjs +++ b/cloud/dev/scripts/relay-same-cap-script-census.test.mjs @@ -13,7 +13,6 @@ import { readRelayWorkflow } from './relay-repository.mjs' import { validateCapacityPlan } from './validate-relay-capacity-plan.mjs' const workflow = readRelayWorkflow('deploy-relay-production-same-cap-job.yml') -const capacityWorkflow = readRelayWorkflow('deploy-relay-production-capacity-job.yml') const production = readFileSync( new URL('../../infra/terraform/environments/production.tfvars', import.meta.url), 'utf8' @@ -295,74 +294,10 @@ describe('same-cap roll scripts accept every same-cap cell', () => { assert.equal(resolveCellShape('production-gce-c31').status, 1) }) - it('passes the same-cap allowlist on every canary invocation the job runs', () => { - const invocations = workflow.split('prepare-relay-production-capacity-canary.mjs').slice(1) - assert.equal(invocations.length, 4) - for (const invocation of invocations) { - const lines = invocation.split('\n') - const end = lines.findIndex((line) => !line.endsWith('\\')) - const call = lines.slice(0, end + 1).join(' ') - assert.match(call, /--approved-cells same-cap/) - // The restore call picks its mode from the cell's entry admission class. - assert.match(call, /--mode (isolate|drain|activate|"\$\{RESTORE_MODE\}")/) - } - }) - it('paces the drain it sends to the selected cell', () => { - const drain = workflow.split('--mode drain')[1] ?? '' - assert.match(drain.split('\n').slice(0, 2).join(' '), /--pace-window-ms "\$\{DRAIN_PACE_WINDOW_MS\}"/) - // 5 min is the cell's DRAIN_PACE_WINDOW_MAX_MS; a 2,700-host cell at 2 min overruns the director's sticky lane. - assert.match(workflow, /DRAIN_PACE_WINDOW_MS: '300000'/) - // The transition wait has to outlast the pacing window on top of the leases it waits on. - assert.match(workflow, /--activity restart-safe[\s\S]*?--timeout-ms 1200000/) - }) - it('passes this cell\'s rehome protocol and pool on every plan validation the job runs', () => { - const invocations = workflow.split('validate-relay-capacity-plan.mjs').slice(1) - assert.equal(invocations.length, 2) - for (const invocation of invocations) { - const lines = invocation.split('\n') - const end = lines.findIndex((line) => !line.trimEnd().endsWith('\\')) - const call = lines.slice(0, end + 1).join(' ') - assert.match(call, /--mode same-cap-cell/) - assert.match(call, /--regional-rehome-protocol "\$\{DESIRED_REHOME_PROTOCOL\}"/) - assert.match(call, /"\$\{POOL_ARGUMENTS\[@\]\}"/) - } - // Each of those steps must build the flag from the resolved pool, and only when there is one. - const builders = workflow.split( - 'if test -n "${EXPECTED_DATABASE_POOL_MAX}"; then\n' + - ' POOL_ARGUMENTS=(--database-pool-max "${EXPECTED_DATABASE_POOL_MAX}")' - ) - assert.equal(builders.length, 3) - assert.equal(workflow.split('POOL_ARGUMENTS=()').length, 3) - }) - // One cell's compute path and nothing else: the template and the MIG bound to it. The cell - // backend service stays out because the capacity role has no compute.backendServices.update, - // so naming it fails the apply after the MIG has already rolled. - it('targets exactly this cell template and MIG on every plan the job runs', () => { - const plans = workflow.split('terraform -chdir=infra/terraform plan').slice(1) - assert.equal(plans.length, 2) - for (const plan of plans) { - const lines = plan.split('\n') - const end = lines.findIndex((line) => !line.trimEnd().endsWith('\\')) - const call = lines.slice(0, end + 1).join('\n') - assert.deepEqual( - [...call.matchAll(/-target=([\w.]+)\[\\"\$\{TARGET_CELL_ID\}\\"\]/g)] - .map(([, resource]) => resource), - [ - 'google_compute_instance_template.relay_gce_cell', - 'google_compute_instance_group_manager.relay_gce_cell' - ] - ) - // Any target that is not one of those two, or not scoped to this cell, fails here. - assert.equal(call.split('-target=').length, 3) - } - }) - it('never names a backend service on any plan or apply in the job', () => { - assert.equal(workflow.includes('google_compute_backend_service'), false) - }) it('validates a correct plan for every wave cell at that cell\'s rehome protocol', () => { const trusted = SAME_CAP_CELLS.filter((cell) => REHOME_SOURCE_CELLS.has(cell)) @@ -569,25 +504,6 @@ describe('same-cap roll scripts accept every same-cap cell', () => { ) }) - it('pins the capacity identity on every plan validation the job runs', () => { - const invocations = workflow.split('validate-relay-capacity-plan.mjs').slice(1) - assert.equal(invocations.length, 2) - for (const invocation of invocations) { - const lines = invocation.split('\n') - const end = lines.findIndex((line) => !line.trimEnd().endsWith('\\')) - assert.match( - lines.slice(0, end + 1).join(' '), - /--capacity-service-account "\$\{CAPACITY_SERVICE_ACCOUNT\}"/ - ) - } - // Both steps must read it from the same repository variable the job already requires. - assert.equal( - workflow.split( - 'CAPACITY_SERVICE_ACCOUNT: ${{ vars.PRODUCTION_GCP_RELAY_CAPACITY_SERVICE_ACCOUNT }}' - ).length, - 4 - ) - }) it('decides the predecessor draining rule from the real block, for both classes', () => { // A zero-host cell sheds nothing, and a failed canary's own drain leaves the flag set @@ -777,29 +693,5 @@ describe('same-cap roll scripts accept every same-cap cell', () => { assert.equal(rolls('resume', { changes: 0 }), 'no-replace') assert.equal(rolls('none', { changes: 0 }), 'no-replace') }) - - it('waits on the image a stranded cell actually serves', () => { - const isolate = workflow - .split('name: Reversibly isolate and drain only the selected cell')[1] - .split('\n - id:')[0] - assert.match(isolate, /--expected-image-digests "\$\{PREDECESSOR_IMAGE_DIGEST\}"/) - // A stranded cell has to come back on a new process, which is what clears the drain. - const after = workflow - .split('name: Verify new incarnation, exact image, protocol, and durable safety')[1] - .split('\n - name:')[0] - assert.match(after, /test "\$\{TARGET_INCARNATION\}" != "\$\{SOURCE_INCARNATION\}"/) - assert.match(after, /if test "\$\{ROLLBACK_RESUME\}" = true; then/) - }) - - it('leaves the US-only capacity job on the default allowlist', () => { - assert.doesNotMatch(capacityWorkflow, /--approved-cells/) - }) }) -// Both trusted versions must prove the same authenticated drain boundary. -it('proves rehome trust for protocol 3 on forward and rollback rolls', () => { - const step = workflow.split('name: Prove exact per-host trust and idempotent no-neighbor behavior')[1].split('\n - name:')[0] - assert.match(step, /inputs\.rollback-rehome-protocol != '0'/) - assert.match(step, /inputs\.target-rehome-protocol != '0'/) - assert.match(step, /probe-relay-rehome-trust\.mjs/) -}) diff --git a/cloud/package.json b/cloud/package.json index 0dd2a546699..c029b06d6fa 100644 --- a/cloud/package.json +++ b/cloud/package.json @@ -20,8 +20,8 @@ "load:relay:model": "node dev/scripts/run-relay-load-model.mjs", "load:relay:recovery-gate": "node dev/scripts/run-relay-recovery-wave-gate.mjs", "ops:relay": "pnpm --filter @orca-cloud/relay-ops dev", - "pretest": "node --test dev/scripts/capture-terraform-plan-baseline.test.mjs dev/scripts/operate-relay-asia-admission.test.mjs dev/scripts/prepare-relay-asia-director-cells.test.mjs dev/scripts/prepare-relay-asia-topology-input.test.mjs dev/scripts/production-cloud-sql-rollout-lock.test.mjs dev/scripts/read-relay-serving-regional-placement-version.test.mjs dev/scripts/relay-asia-admission-workflow.test.mjs dev/scripts/relay-asia-rollout-evidence.test.mjs dev/scripts/relay-asia-topology-workflow.test.mjs dev/scripts/relay-cloud-sql-connection-budget.test.mjs dev/scripts/relay-load-reader-evidence.test.mjs dev/scripts/relay-lock-contention-alerts.test.mjs dev/scripts/relay-region-hint-metrics.test.mjs dev/scripts/relay-staging-deploy-identity.test.mjs dev/scripts/sanitize-relay-asia-admission-result.test.mjs dev/scripts/terraform-root-partition.test.mjs dev/scripts/validate-relay-asia-topology-plan.test.mjs ../.github/actions/cloud-sql-rollout-lease/action-contract.test.mjs ../.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs", - "test": "pnpm -r test && node --test dev/scripts/classify-relay-production-capacity-director.test.mjs dev/scripts/classify-relay-staging-bootstrap.test.mjs dev/scripts/deploy-relay-blue-green.test.mjs dev/scripts/deploy-relay-gce-candidate.test.mjs dev/scripts/deploy-relay-gce-multi-target.test.mjs dev/scripts/github-smoke-token.test.mjs dev/scripts/infra.test.mjs dev/scripts/operate-relay-regional-rehome.test.mjs dev/scripts/power-staging-relay.test.mjs dev/scripts/prepare-relay-capacity-canary.test.mjs dev/scripts/prepare-relay-production-capacity-canary.test.mjs dev/scripts/probe-relay-legacy-admission.test.mjs dev/scripts/probe-relay-rehome-trust.test.mjs dev/scripts/production-cell-image-digest-consistency.test.mjs dev/scripts/push-gateway-workflow.test.mjs dev/scripts/push-gateway-recovery.test.mjs dev/scripts/push-validation-workflow.test.mjs dev/scripts/read-relay-production-capacity-identity.test.mjs dev/scripts/relay-admin-endpoint-retry-workflow.test.mjs dev/scripts/relay-admin-transient-retry.test.mjs dev/scripts/relay-admission-selector.test.mjs dev/scripts/relay-gce-terraform-fence.test.mjs dev/scripts/relay-load-connection-failure.test.mjs dev/scripts/relay-load-control-peer.test.mjs dev/scripts/relay-load-director-capacity-gate.test.mjs dev/scripts/relay-load-model.test.mjs dev/scripts/relay-load-phase-barrier.test.mjs dev/scripts/relay-load-placement-boundary.test.mjs dev/scripts/relay-load-profile.test.mjs dev/scripts/relay-load-rebind-boundary.test.mjs dev/scripts/relay-load-region-behavior.test.mjs dev/scripts/relay-load-request-unit-boundary.test.mjs dev/scripts/relay-load-run-lifecycle.test.mjs dev/scripts/relay-monitor-evidence.test.mjs dev/scripts/relay-production-capacity-wave.test.mjs dev/scripts/relay-production-capacity-workflow.test.mjs dev/scripts/relay-production-identity-boundaries.test.mjs dev/scripts/relay-production-same-cap-wave.test.mjs dev/scripts/relay-public-workflow-contract.test.mjs dev/scripts/relay-recovery-wave-gate.test.mjs dev/scripts/relay-region-observation-evidence.test.mjs dev/scripts/relay-regional-rehome-workflow.test.mjs dev/scripts/relay-rehome-aggregate-evidence.test.mjs dev/scripts/relay-repository.test.mjs dev/scripts/relay-same-cap-script-census.test.mjs dev/scripts/relay-same-cap-shadow-gate.test.mjs dev/scripts/relay-staging-c4-refresh-workflow.test.mjs dev/scripts/relay-staging-capacity-identity.test.mjs dev/scripts/staging-relay-apply-guard.test.mjs dev/scripts/validate-relay-capacity-plan.test.mjs dev/scripts/verify-relay-capacity-transition.test.mjs dev/scripts/verify-relay-legacy-bootstrap.test.mjs dev/scripts/workload-identity-attribute-conditions.test.mjs", + "pretest": "node --test dev/scripts/capture-terraform-plan-baseline.test.mjs dev/scripts/operate-relay-asia-admission.test.mjs dev/scripts/prepare-relay-asia-director-cells.test.mjs dev/scripts/prepare-relay-asia-topology-input.test.mjs dev/scripts/production-cloud-sql-rollout-lock.test.mjs dev/scripts/read-relay-serving-regional-placement-version.test.mjs dev/scripts/relay-asia-rollout-evidence.test.mjs dev/scripts/relay-asia-topology-workflow.test.mjs dev/scripts/relay-cloud-sql-connection-budget.test.mjs dev/scripts/relay-load-reader-evidence.test.mjs dev/scripts/relay-lock-contention-alerts.test.mjs dev/scripts/relay-region-hint-metrics.test.mjs dev/scripts/relay-staging-deploy-identity.test.mjs dev/scripts/sanitize-relay-asia-admission-result.test.mjs dev/scripts/terraform-root-partition.test.mjs dev/scripts/validate-relay-asia-topology-plan.test.mjs ../.github/actions/cloud-sql-rollout-lease/action-contract.test.mjs ../.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs", + "test": "pnpm -r test && node --test dev/scripts/classify-relay-production-capacity-director.test.mjs dev/scripts/classify-relay-staging-bootstrap.test.mjs dev/scripts/deploy-relay-blue-green.test.mjs dev/scripts/deploy-relay-gce-candidate.test.mjs dev/scripts/deploy-relay-gce-multi-target.test.mjs dev/scripts/github-smoke-token.test.mjs dev/scripts/infra.test.mjs dev/scripts/operate-relay-regional-rehome.test.mjs dev/scripts/power-staging-relay.test.mjs dev/scripts/prepare-relay-capacity-canary.test.mjs dev/scripts/prepare-relay-production-capacity-canary.test.mjs dev/scripts/probe-relay-legacy-admission.test.mjs dev/scripts/probe-relay-rehome-trust.test.mjs dev/scripts/production-cell-image-digest-consistency.test.mjs dev/scripts/push-gateway-workflow.test.mjs dev/scripts/push-gateway-recovery.test.mjs dev/scripts/read-relay-production-capacity-identity.test.mjs dev/scripts/relay-admin-endpoint-retry-workflow.test.mjs dev/scripts/relay-admin-transient-retry.test.mjs dev/scripts/relay-admission-selector.test.mjs dev/scripts/relay-gce-terraform-fence.test.mjs dev/scripts/relay-load-connection-failure.test.mjs dev/scripts/relay-load-control-peer.test.mjs dev/scripts/relay-load-director-capacity-gate.test.mjs dev/scripts/relay-load-model.test.mjs dev/scripts/relay-load-phase-barrier.test.mjs dev/scripts/relay-load-placement-boundary.test.mjs dev/scripts/relay-load-profile.test.mjs dev/scripts/relay-load-rebind-boundary.test.mjs dev/scripts/relay-load-region-behavior.test.mjs dev/scripts/relay-load-request-unit-boundary.test.mjs dev/scripts/relay-load-run-lifecycle.test.mjs dev/scripts/relay-monitor-evidence.test.mjs dev/scripts/relay-production-capacity-wave.test.mjs dev/scripts/relay-production-capacity-workflow.test.mjs dev/scripts/relay-production-identity-boundaries.test.mjs dev/scripts/relay-production-same-cap-wave.test.mjs dev/scripts/relay-public-workflow-contract.test.mjs dev/scripts/relay-recovery-wave-gate.test.mjs dev/scripts/relay-region-observation-evidence.test.mjs dev/scripts/relay-rehome-aggregate-evidence.test.mjs dev/scripts/relay-repository.test.mjs dev/scripts/relay-same-cap-script-census.test.mjs dev/scripts/relay-same-cap-shadow-gate.test.mjs dev/scripts/relay-staging-c4-refresh-workflow.test.mjs dev/scripts/relay-staging-capacity-identity.test.mjs dev/scripts/staging-relay-apply-guard.test.mjs dev/scripts/validate-relay-capacity-plan.test.mjs dev/scripts/verify-relay-capacity-transition.test.mjs dev/scripts/verify-relay-legacy-bootstrap.test.mjs dev/scripts/workload-identity-attribute-conditions.test.mjs", "typecheck": "pnpm -r typecheck" }, "devDependencies": { diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 4e4443354fa..e3468836373 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -943,7 +943,7 @@ "invariant": "One structured-send operation id causes at most one provider dispatch. A recorded or transport-ambiguous send reuses that id across retry, caller reconnect, client remount, and journal recovery; only a terminal rejection may rotate to a first delivery.", "oracle": "Inject adapter acknowledgement loss, RPC response loss, caller replacement, logical-client close after response, auth recovery with a written request, missing journal submissions, legacy pending rows, stale fences, operation expiry, mobile remount, and durable-journal capacity. Assert one provider dispatch or one operation id for every ambiguous retry, fresh identity only after rejection, and no eviction of ambiguous mobile ids.", "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/agent-session-operation-ledger.test.ts src/shared/structured-agent-session-send-disposition.test.ts src/main/runtime/agent-session-operation-admission.test.ts src/main/native-chat/agent-session-wire/structured-agent-session-refusal-retry.test.ts src/main/native-chat/agent-session-wire/structured-agent-session-send.test.ts src/main/runtime/orchestration/structured-mailbox-pointer-delivery.test.ts src/main/runtime/orchestration/structured-mailbox-pointer-host.test.ts src/main/runtime/orchestration/structured-pointer-operation-id.test.ts src/renderer/src/components/native-chat/use-structured-agent-session-outbox.test.tsx src/renderer/src/components/native-chat/use-structured-agent-session.test.tsx src/renderer/src/components/native-chat/NativeChatStructuredSession.transport-probe.test.tsx src/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsx src/renderer/src/lib/launch-structured-agent-session.test.ts", + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/agent-session-operation-ledger.test.ts src/shared/structured-agent-session-send-disposition.test.ts src/main/runtime/agent-session-operation-admission.test.ts src/main/native-chat/agent-session-wire/structured-agent-session-refusal-retry.test.ts src/main/native-chat/agent-session-wire/structured-agent-session-send.test.ts src/main/runtime/orchestration/structured-mailbox-pointer-delivery.test.ts src/main/runtime/orchestration/structured-mailbox-pointer-host.test.ts src/main/runtime/orchestration/structured-pointer-operation-id.test.ts src/renderer/src/components/native-chat/use-structured-agent-session-outbox.test.tsx src/renderer/src/components/native-chat/use-structured-agent-session.test.tsx src/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsx src/renderer/src/lib/launch-structured-agent-session.test.ts", "ORCA_BACKGROUND_LAUNCH=1 pnpm --dir mobile test ../mobile/src/session/mobile-native-chat-image-attachment.test.ts ../mobile/src/session/use-mobile-native-chat-image-attachments.test.ts ../mobile/src/session/mobile-structured-send-operation-journal.test.ts ../mobile/src/session/mobile-structured-session-operation-retention.test.ts ../mobile/src/session/mobile-structured-send-delivery.test.ts ../mobile/src/session/use-mobile-structured-agent-session-send.test.tsx ../mobile/src/session/use-mobile-structured-agent-session.test.tsx ../mobile/src/transport/mobile-relay-rpc-session.test.ts ../mobile/src/transport/rpc-client-delivery-ambiguity.test.ts ../mobile/src/transport/stable-logical-rpc-client.test.ts" ], "testFiles": [ @@ -957,7 +957,6 @@ "src/main/runtime/orchestration/structured-pointer-operation-id.test.ts", "src/renderer/src/components/native-chat/use-structured-agent-session-outbox.test.tsx", "src/renderer/src/components/native-chat/use-structured-agent-session.test.tsx", - "src/renderer/src/components/native-chat/NativeChatStructuredSession.transport-probe.test.tsx", "src/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsx", "src/renderer/src/lib/launch-structured-agent-session.test.ts", "mobile/src/session/mobile-native-chat-image-attachment.test.ts", @@ -1033,7 +1032,7 @@ "date": "2026-09-12", "runner": "local", "platform": "macos", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/agent-session-operation-ledger.test.ts src/shared/structured-agent-session-send-disposition.test.ts src/main/runtime/agent-session-operation-admission.test.ts src/main/native-chat/agent-session-wire/structured-agent-session-refusal-retry.test.ts src/main/native-chat/agent-session-wire/structured-agent-session-send.test.ts src/main/runtime/orchestration/structured-mailbox-pointer-delivery.test.ts src/main/runtime/orchestration/structured-mailbox-pointer-host.test.ts src/main/runtime/orchestration/structured-pointer-operation-id.test.ts src/renderer/src/components/native-chat/use-structured-agent-session-outbox.test.tsx src/renderer/src/components/native-chat/use-structured-agent-session.test.tsx src/renderer/src/components/native-chat/NativeChatStructuredSession.transport-probe.test.tsx src/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsx src/renderer/src/lib/launch-structured-agent-session.test.ts", + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/agent-session-operation-ledger.test.ts src/shared/structured-agent-session-send-disposition.test.ts src/main/runtime/agent-session-operation-admission.test.ts src/main/native-chat/agent-session-wire/structured-agent-session-refusal-retry.test.ts src/main/native-chat/agent-session-wire/structured-agent-session-send.test.ts src/main/runtime/orchestration/structured-mailbox-pointer-delivery.test.ts src/main/runtime/orchestration/structured-mailbox-pointer-host.test.ts src/main/runtime/orchestration/structured-pointer-operation-id.test.ts src/renderer/src/components/native-chat/use-structured-agent-session-outbox.test.tsx src/renderer/src/components/native-chat/use-structured-agent-session.test.tsx src/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsx src/renderer/src/lib/launch-structured-agent-session.test.ts", "result": "passed", "durationSeconds": 22.1, "summary": "Thirteen focused host, shared, renderer, and orchestration files passed 148 tests." @@ -12353,7 +12352,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty-pending-projection-admissions.test.ts src/main/ipc/ssh-pty-legacy-projection.test.ts src/main/ipc/ssh-pty-model-admission.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime-path-candidate-history.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/orca-runtime-tail-wait-memo.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/providers/ssh-pty-provider.test.ts src/main/providers/ssh-pty-source-delivery-ledger.test.ts src/main/ssh/ssh-pty-retired-source-deliveries.test.ts src/main/ssh/ssh-relay-session.test.ts src/main/ssh/ssh-relay-session-data-delivery.test.ts src/main/ssh/ssh-relay-session-recovery-races.test.ts src/main/ssh/ssh-relay-session-incarnation.test.ts src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts src/main/ssh/ssh-relay-session-terminal-error.test.ts src/main/ssh/ssh-pty-recovery-retention-budget.test.ts src/main/ssh/relay-protocol-backpressure.test.ts src/relay/protocol-backpressure.test.ts src/relay/pty-source-credit-ledger.test.ts src/relay/pty-source-credit-scheduler.test.ts src/relay/relay-pty-source-publication.test.ts src/relay/ssh-pty-source-credit-adapter.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/providers/ssh-pty-provider.test.ts src/main/providers/ssh-pty-source-delivery-ledger.test.ts src/main/ssh/ssh-pty-retired-source-deliveries.test.ts src/main/ssh/ssh-relay-session.test.ts src/main/ssh/ssh-relay-session-data-delivery.test.ts src/main/ssh/ssh-relay-session-recovery-races.test.ts src/main/ssh/ssh-relay-session-incarnation.test.ts src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts src/main/ssh/ssh-relay-session-terminal-error.test.ts src/main/ssh/ssh-pty-recovery-retention-budget.test.ts src/relay/protocol-backpressure.test.ts src/relay/pty-source-credit-ledger.test.ts src/relay/pty-source-credit-scheduler.test.ts src/relay/relay-pty-source-publication.test.ts src/relay/ssh-pty-source-credit-adapter.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh-pty-model-admission.test.ts src/main/ipc/ssh-pty-output-model-migration.test.ts src/main/ssh/ssh-relay-session-model-migration.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/relay/git-response-stream-ownership.test.ts src/relay/pty-handler-output-streaming.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/providers/ssh-pty-notification-routing.test.ts src/main/providers/ssh-pty-provider-agent-session-create-operation.test.ts src/main/providers/ssh-pty-provider-exit-race.test.ts src/main/providers/ssh-pty-provider-reattach-incarnation.test.ts --reporter=dot", @@ -12400,7 +12399,6 @@ "src/main/ssh/ssh-relay-session-terminal-error.test.ts", "src/main/ssh/ssh-pty-recovery-retention-budget.test.ts", "src/main/ssh/ssh-pty-retired-source-deliveries.test.ts", - "src/main/ssh/relay-protocol-backpressure.test.ts", "src/relay/protocol-backpressure.test.ts", "src/relay/git-response-stream-ownership.test.ts", "src/relay/pty-handler-output-streaming.test.ts", @@ -12617,13 +12615,6 @@ "invalid-checkpoint cancellation retains the exact delivery until restore response settlement, then retry mints a fresh activation and emits one live source frame" ] }, - { - "file": "src/main/ssh/relay-protocol-backpressure.test.ts", - "assertions": [ - "main SSH decoder accepts one maximum frame plus 1 MiB partial input and rejects one extra byte", - "a throwing continuation clears retained input, releases one pause epoch, and publishes one typed ownership error" - ] - }, { "file": "src/relay/protocol-backpressure.test.ts", "assertions": [ @@ -12812,7 +12803,7 @@ "date": "2026-07-29", "runner": "local", "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/providers/ssh-pty-provider.test.ts src/main/providers/ssh-pty-source-delivery-ledger.test.ts src/main/ssh/ssh-pty-retired-source-deliveries.test.ts src/main/ssh/ssh-relay-session.test.ts src/main/ssh/ssh-relay-session-data-delivery.test.ts src/main/ssh/ssh-relay-session-recovery-races.test.ts src/main/ssh/ssh-relay-session-incarnation.test.ts src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts src/main/ssh/ssh-relay-session-terminal-error.test.ts src/main/ssh/ssh-pty-recovery-retention-budget.test.ts src/main/ssh/relay-protocol-backpressure.test.ts src/relay/protocol-backpressure.test.ts src/relay/pty-source-credit-ledger.test.ts src/relay/pty-source-credit-scheduler.test.ts src/relay/relay-pty-source-publication.test.ts src/relay/ssh-pty-source-credit-adapter.test.ts --reporter=dot", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/providers/ssh-pty-provider.test.ts src/main/providers/ssh-pty-source-delivery-ledger.test.ts src/main/ssh/ssh-pty-retired-source-deliveries.test.ts src/main/ssh/ssh-relay-session.test.ts src/main/ssh/ssh-relay-session-data-delivery.test.ts src/main/ssh/ssh-relay-session-recovery-races.test.ts src/main/ssh/ssh-relay-session-incarnation.test.ts src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts src/main/ssh/ssh-relay-session-terminal-error.test.ts src/main/ssh/ssh-pty-recovery-retention-budget.test.ts src/relay/protocol-backpressure.test.ts src/relay/pty-source-credit-ledger.test.ts src/relay/pty-source-credit-scheduler.test.ts src/relay/relay-pty-source-publication.test.ts src/relay/ssh-pty-source-credit-adapter.test.ts --reporter=dot", "result": "passed", "durationSeconds": 2.24, "summary": "Sixteen deterministic SSH relay/session/source/decoder files passed 192 tests, including exit-sealed private recovery, retained stale-transfer cancellation authority, exact private-frame proof watermarks, one retirement record across 10,000 same-PTY token rotations, stale-owner fallback, and scheduler rejection isolation; no live topology was exercised." @@ -15501,7 +15492,7 @@ "oracle": "Seed status, dispatch, and worker_done rows across direct-handle and canonical Run recipients in an isolated DB. Compare pointer count, RPC and built-CLI check output, direct SQLite rows, unread/peek/all/type filters, concurrent pollers, fixed Delivery IDs, explicit acknowledgment, restart, filtered check --wait, and coordinator remint. Route a 125-row old-handle backlog, inject a commit without notification, and require startup repair. Exercise duplicate Run/Dispatch owners, stale panes, 50-row pages, cancellation, lifecycle fencing, and absent PTYs. Drop a federation ACK, reconnect/restart v1/v2 peers, and require stable import plus no duplicate read-row wake. Hold a healthy SSH write past five seconds but below the 60-second settlement deadline, then distinguish the three settlement outcomes end to end: only a proven refusal releases the reservation and drains a delivery parked behind the watermark; a dropped in-flight settlement must surface as unverifiable with bytes handed to the transport, preserve the durable write-attempted reservation, and emit no duplicate pointer after restart; a settled write that throws mid-pointer is unverifiable, not a refusal; and an Enter whose settlement is lost stays at enter-attempted so restart emits no second Enter. Install the production PTY controller and verify that it routes settled writes through the owning provider and refuses before any byte when the routed provider cannot settle. Census every production PTY provider class and reject a settlement synthesized from the fire-and-forget write.", "commands": [ "pnpm run build:cli && pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration-message-delivery-identity.test.ts --reporter=dot --testTimeout=5000", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration-mailbox-routing-races.test.ts src/main/runtime/orchestration-mailbox-notification-consistency.test.ts src/main/runtime/orchestration-mailbox-detached-routing.test.ts src/main/runtime/orchestration-mailbox-transport-settlement.test.ts src/main/ipc/pty-controller-ownership-routing.test.ts src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts src/main/runtime/orchestration/orchestration-run-delivery-db.test.ts src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts src/main/runtime/orchestration/formatter.test.ts src/main/providers/ssh-pty-provider.test.ts src/main/providers/ssh-pty-write.test.ts src/main/providers/settled-pty-writer-census.test.ts src/main/runtime/orchestration/mailbox-pointer-stage.test.ts src/main/daemon/client.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration-mailbox-routing-races.test.ts src/main/runtime/orchestration-mailbox-notification-consistency.test.ts src/main/runtime/orchestration-mailbox-detached-routing.test.ts src/main/runtime/orchestration-mailbox-transport-settlement.test.ts src/main/ipc/pty-controller-ownership-routing.test.ts src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts src/main/runtime/orchestration/orchestration-run-delivery-db.test.ts src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts src/main/runtime/orchestration/formatter.test.ts src/main/providers/ssh-pty-provider.test.ts src/main/providers/ssh-pty-write.test.ts src/main/runtime/orchestration/mailbox-pointer-stage.test.ts src/main/daemon/client.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/terminal-send-stale-leaf-liveness.test.ts src/main/runtime/rpc/methods/orchestration/runs/runs.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/federation-sync.test.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts --reporter=dot" ], @@ -15518,7 +15509,6 @@ "src/main/runtime/orchestration/formatter.test.ts", "src/main/providers/ssh-pty-provider.test.ts", "src/main/providers/ssh-pty-write.test.ts", - "src/main/providers/settled-pty-writer-census.test.ts", "src/main/runtime/orchestration/mailbox-pointer-stage.test.ts", "src/main/daemon/client.test.ts", "src/main/daemon/daemon-pty-router.test.ts", @@ -15620,13 +15610,6 @@ "file": "src/main/runtime/orchestration/mailbox-pointer-stage.test.ts", "assertions": ["a refused pointer write drains a delivery parked behind its watermark"] }, - { - "file": "src/main/providers/settled-pty-writer-census.test.ts", - "assertions": [ - "every production IPtyProvider class exposes a settled writer", - "no settled writer synthesizes its settlement from the fire-and-forget write" - ] - }, { "file": "src/main/ipc/pty-controller-ownership-routing.test.ts", "assertions": [ @@ -15666,7 +15649,7 @@ "date": "2026-09-05", "runner": "local", "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration-mailbox-routing-races.test.ts src/main/runtime/orchestration-mailbox-notification-consistency.test.ts src/main/runtime/orchestration-mailbox-detached-routing.test.ts src/main/runtime/orchestration-mailbox-transport-settlement.test.ts src/main/ipc/pty-controller-ownership-routing.test.ts src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts src/main/runtime/orchestration/orchestration-run-delivery-db.test.ts src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts src/main/runtime/orchestration/formatter.test.ts src/main/providers/ssh-pty-provider.test.ts src/main/providers/ssh-pty-write.test.ts src/main/providers/settled-pty-writer-census.test.ts src/main/runtime/orchestration/mailbox-pointer-stage.test.ts src/main/daemon/client.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration-mailbox-routing-races.test.ts src/main/runtime/orchestration-mailbox-notification-consistency.test.ts src/main/runtime/orchestration-mailbox-detached-routing.test.ts src/main/runtime/orchestration-mailbox-transport-settlement.test.ts src/main/ipc/pty-controller-ownership-routing.test.ts src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts src/main/runtime/orchestration/orchestration-run-delivery-db.test.ts src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts src/main/runtime/orchestration/formatter.test.ts src/main/providers/ssh-pty-provider.test.ts src/main/providers/ssh-pty-write.test.ts src/main/runtime/orchestration/mailbox-pointer-stage.test.ts src/main/daemon/client.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts", "result": "passed", "durationSeconds": 4.73, "summary": "267 tests passed after the pointer-write path moved to the three-valued WriteSettlement union. New coverage: a dropped in-flight SSH settlement reaches the stager as unverifiable with bytes handed to the transport, a settled write that throws mid-pointer preserves the write-attempted reservation, an Enter whose settlement is lost stays at enter-attempted with no second Enter after restart, a refusal releases the reservation and drains a delivery parked behind its watermark, the production controller refuses before any byte when the routed provider cannot settle, and a census pins the five production IPtyProvider classes and rejects a settlement synthesized from the fire-and-forget write. Each new assertion was verified red against the pre-fix shape." @@ -15675,7 +15658,7 @@ "date": "2026-08-13", "runner": "local", "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration-mailbox-routing-races.test.ts src/main/runtime/orchestration-mailbox-notification-consistency.test.ts src/main/runtime/orchestration-mailbox-detached-routing.test.ts src/main/runtime/orchestration-mailbox-transport-settlement.test.ts src/main/ipc/pty-controller-ownership-routing.test.ts src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts src/main/runtime/orchestration/orchestration-run-delivery-db.test.ts src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts src/main/runtime/orchestration/formatter.test.ts src/main/providers/ssh-pty-provider.test.ts src/main/providers/ssh-pty-write.test.ts src/main/providers/settled-pty-writer-census.test.ts src/main/runtime/orchestration/mailbox-pointer-stage.test.ts src/main/daemon/client.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration-mailbox-routing-races.test.ts src/main/runtime/orchestration-mailbox-notification-consistency.test.ts src/main/runtime/orchestration-mailbox-detached-routing.test.ts src/main/runtime/orchestration-mailbox-transport-settlement.test.ts src/main/ipc/pty-controller-ownership-routing.test.ts src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts src/main/runtime/orchestration/orchestration-run-delivery-db.test.ts src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts src/main/runtime/orchestration/formatter.test.ts src/main/providers/ssh-pty-provider.test.ts src/main/providers/ssh-pty-write.test.ts src/main/runtime/orchestration/mailbox-pointer-stage.test.ts src/main/daemon/client.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts", "result": "passed", "durationSeconds": 8.22, "summary": "245 tests passed across mailbox identity, durable coordinator-handle migration, insertion-time canonicalization, duplicate-free 51-row ownership branch caps, unrestricted reservation merging, direct and Dispatch pointer suppression, persisted reconciliation, 50-row paging and filtered waits, cross-PTY serialization, lifecycle fencing, bounded daemon and SSH transport settlement, outstanding Deliveries, reminted Dispatch ownership, acknowledgment, cancellation, and bounded pane lookup." diff --git a/config/scripts/bun-profile-change-scope.test.mjs b/config/scripts/bun-profile-change-scope.test.mjs index ef21fed5e34..15258cea96d 100644 --- a/config/scripts/bun-profile-change-scope.test.mjs +++ b/config/scripts/bun-profile-change-scope.test.mjs @@ -119,15 +119,13 @@ describe('the actual Bun build and profile-test dependency graph', () => { expect((await classifyBunProfileChanges([file], async () => inputs)).shouldRun).toBe(true) }) - it('retains all selected tests and uses the same selectors as the Bun runner', () => { + it('retains all selected tests and the selectors the Bun runner uses', () => { const tests = discoverBunProfileTests() expect(tests.length).toBeGreaterThan(80) expect(tests.every((file) => inputs.has(file))).toBe(true) expect( bunProfileTestPaths().every((selector) => tests.some((file) => file.includes(selector))) ).toBe(true) - const runner = readFileSync(new URL('./run-bun-profile-tests.mjs', import.meta.url), 'utf8') - expect(runner).toContain('testArgs.length > 0 ? testArgs : bunProfileTestPaths({ artifact })') }) }) diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 664e8268662..795f6070baf 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -193,7 +193,6 @@ "config/scripts/package-electron-runtime-contract.test.mjs": 447, "config/scripts/package-linux-formats.test.mjs": 208, "config/scripts/packaged-browser-lane-contract.test.mjs": 104, - "config/scripts/packaged-hang-watchdog-worker-contract.test.mjs": 161, "config/scripts/packaged-node-pty-prebuild-prune.test.mjs": 93, "config/scripts/packaged-source-map-prune.test.mjs": 117, "config/scripts/patched-dependencies-frozen-install.test.mjs": 900, diff --git a/config/scripts/cli-main-module-bundle-parity.test.ts b/config/scripts/cli-main-module-bundle-parity.test.ts deleted file mode 100644 index b545579facf..00000000000 --- a/config/scripts/cli-main-module-bundle-parity.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { readFileSync, readdirSync } from 'node:fs' -import { join, matchesGlob, resolve } from 'node:path' -import { createRequire } from 'node:module' -import { describe, expect, it } from 'vitest' -import { electronViteConfig } from '../../electron.vite.config' -import { GUARDED_ENTRY_NAMES } from '../build-plugins/plain-node-entry-guard' - -const REPO_ROOT = resolve(__dirname, '..', '..') -const CLI_ROOT = join(REPO_ROOT, 'src', 'cli') -const packaging = createRequire(import.meta.url)('../electron-builder.config.cjs') - -function listCliSourceFiles(dir: string): string[] { - return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { - const path = join(dir, entry.name) - if (entry.isDirectory()) { - return listCliSourceFiles(path) - } - return entry.isFile() && entry.name.endsWith('.ts') && !entry.name.endsWith('.test.ts') - ? [path] - : [] - }) -} - -// Why: `import type` is erased by tsc, so it needs no emitted module at runtime. -const VALUE_IMPORT_FROM_MAIN = /(? { - const source = readFileSync(file, 'utf-8') - return [ - ...source.matchAll(VALUE_IMPORT_FROM_MAIN), - ...source.matchAll(DYNAMIC_IMPORT_FROM_MAIN) - ].map((match) => ({ - file: file.slice(REPO_ROOT.length + 1), - module: match[1].replace(/\.js$/, '') - })) - }) -} - -function findElectronViteMainEntries(): Record { - const input = electronViteConfig.main?.build?.rollupOptions?.input - if (!input || typeof input !== 'object' || Array.isArray(input)) { - throw new Error('Expected named main-process inputs') - } - return input -} - -describe('CLI imports of main-process modules', () => { - // Why: electron-vite cleans out/main and emits only its declared entries, so a - // `src/main/*` module the CLI imports but the config omits is deleted by the - // build that runs after `build:cli` — keep source-level feedback ahead of the - // final-artifact runtime verifier. - it('has an electron-vite entry for every main module the CLI imports', () => { - const entries = findElectronViteMainEntries() - const missing = findMainImports().filter( - ({ module }) => entries[module] !== join(REPO_ROOT, 'src', 'main', `${module}.ts`) - ) - - expect(missing).toEqual([]) - }) - - it('guards every CLI main module against Electron imports', () => { - const guarded = new Set(GUARDED_ENTRY_NAMES) - expect(findMainImports().filter(({ module }) => !guarded.has(module))).toEqual([]) - }) - - it('unpacks every CLI main entry for plain Node outside Electron', () => { - const missing = findMainImports().filter( - ({ module }) => - !packaging.asarUnpack.some((pattern: string) => - matchesGlob(`out/main/${module}.js`, pattern) - ) - ) - expect(missing).toEqual([]) - }) - - it('finds the imports it is meant to guard', () => { - // Why: a broken matcher would make the guard above vacuously pass. - expect(findMainImports()).toContainEqual({ - file: join('src', 'cli', 'profile-state-location.ts'), - module: 'persistence/profile-state/profile-state-active-location' - }) - expect(findMainImports()).toContainEqual({ - file: join('src', 'cli', 'handlers', 'agent-hooks.ts'), - module: 'orca-profiles/profile-index-store' - }) - expect(findMainImports().length).toBeGreaterThanOrEqual(2) - expect(Object.keys(findElectronViteMainEntries()).length).toBeGreaterThanOrEqual(2) - }) -}) diff --git a/config/scripts/client-hosted-browser-package-coverage.test.mjs b/config/scripts/client-hosted-browser-package-coverage.test.mjs index f7f1ceb5995..204cf162e55 100644 --- a/config/scripts/client-hosted-browser-package-coverage.test.mjs +++ b/config/scripts/client-hosted-browser-package-coverage.test.mjs @@ -19,13 +19,6 @@ describe('client-hosted browser package coverage', () => { expect(steps[boundaries].run).not.toContain(file) }) - it('bundles the WSL browser-network relay with its version stamp', () => { - const relayBuild = readFileSync(join(projectDir, 'config/scripts/build-relay.mjs'), 'utf8') - - expect(relayBuild).toContain("outfile: join(outDir, 'wsl-browser-network-relay.js')") - expect(relayBuild).toContain("join(outDir, '.browser-network-version')") - }) - it('runs client-hosted Electron lifecycle coverage on native package hosts', () => { const prWorkflow = readFileSync(join(projectDir, '.github/workflows/pr.yml'), 'utf8') const parsedWorkflow = parse(prWorkflow) diff --git a/config/scripts/computer-e2e-workflow.test.mjs b/config/scripts/computer-e2e-workflow.test.mjs index fc605bac5bd..3e31ccf5a80 100644 --- a/config/scripts/computer-e2e-workflow.test.mjs +++ b/config/scripts/computer-e2e-workflow.test.mjs @@ -6,197 +6,6 @@ import { parse } from 'yaml' const projectDir = resolve(import.meta.dirname, '../..') describe('computer-use e2e workflow', () => { - it('cancels superseded pull request runs without cancelling scheduled runs', () => { - const workflow = parse( - readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') - ) - - expect(workflow.concurrency).toEqual({ - group: 'computer-e2e-${{ github.event.pull_request.number || github.ref }}', - 'cancel-in-progress': "${{ github.event_name == 'pull_request' }}" - }) - }) - - it('runs computer-use e2e files serially because they share desktop focus', () => { - const config = readFileSync(join(projectDir, 'tests/e2e/vitest.config.ts'), 'utf8') - - expect(config).toContain('fileParallelism: false') - }) - - it('guards e2e source against fragile waits and Windows Calculator drift', () => { - const driver = readFileSync(join(projectDir, 'tests/e2e/helpers/computer-driver.ts'), 'utf8') - const cliDriver = readFileSync( - join(projectDir, 'tests/e2e/helpers/computer-cli-driver.ts'), - 'utf8' - ) - const windowsStoreE2e = readFileSync( - join(projectDir, 'tests/e2e/computer-windows-store.e2e.ts'), - 'utf8' - ) - - expect(driver).not.toContain('await delay(3500)') - expect(driver).toContain("await waitForComputerWindowTitle('gedit', fileName, 15000)") - expect(cliDriver).toContain('ORCA_DEV_USER_DATA_PATH') - expect(cliDriver).toContain('orca-computer-runtime-') - expect(cliDriver).toContain('retryMissingRuntimeMetadata') - expect(cliDriver).toContain('Could not read Orca runtime metadata') - expect(cliDriver).toContain("'serve', '--no-pairing', '--json'") - - expect(windowsStoreE2e).toContain("app.bundleId === 'ApplicationFrameHost'") - expect(windowsStoreE2e).toContain("app.bundleId === 'win32calc'") - expect(windowsStoreE2e).toContain('buttonIndex >= 0') - expect(windowsStoreE2e).toContain('pane(?:\\s|$)/m') - expect(windowsStoreE2e).toContain('String(clickIndex)') - expect(windowsStoreE2e).not.toContain( - "for (const buttonName of ['One', 'Plus', 'Two', 'Equals'])" - ) - }) - - it('triggers on computer-use shared contracts, scripts, and agent skill changes', () => { - const workflow = parse( - readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') - ) - const triggerPaths = workflow.on.pull_request.paths - - expect(triggerPaths).toEqual( - expect.arrayContaining([ - 'config/scripts/computer-e2e-workflow.test.mjs', - 'config/scripts/macos-computer-helper-owner-loss-group-recovery.test.mjs', - 'config/scripts/computer-use-modifier-safety.test.mjs', - 'config/scripts/computer-use-skill-guidance.test.mjs', - 'config/scripts/computer-use-smoke.mjs', - 'config/scripts/computer-use-smoke.test.mjs', - 'skills/computer-use/SKILL.md', - 'src/main/computer/**', - 'src/main/runtime/rpc/dispatcher.ts', - 'src/main/runtime/rpc/errors.ts', - 'src/main/runtime/rpc/methods/computer*.ts', - 'src/shared/computer-use-*.ts', - 'tests/e2e/vitest.config.ts' - ]) - ) - expect(triggerPaths).not.toContain('src/shared/runtime-types.ts') - }) - - it('runs focused computer-use regression tests in the PR native-smoke job', () => { - const workflow = parse( - readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') - ) - const nativeSmokeRuns = workflow.jobs['native-smoke'].steps - .map((step) => step.run) - .filter((run) => typeof run === 'string') - const checkout = workflow.jobs['native-smoke'].steps.find( - (step) => step.uses === 'actions/checkout@v6' - ) - const regressionRun = nativeSmokeRuns.find((run) => run.includes('pnpm vitest run')) - const expectedRegressionFiles = [ - 'config/scripts/macos-computer-helper-owner-loss-group-recovery.test.mjs', - 'config/scripts/macos-computer-helper-owner-loss-processes.test.mjs', - 'config/scripts/computer-use-modifier-safety.test.mjs', - 'config/scripts/computer-use-skill-guidance.test.mjs', - 'config/scripts/computer-use-smoke.test.mjs', - 'src/main/computer/computer-provider-lifecycle.test.ts', - 'src/main/computer/computer-provider-unavailable-message.test.ts', - 'src/main/computer/sidecar-client.test.ts', - 'src/main/computer/macos-native-provider-client.test.ts', - 'src/main/computer/macos-native-provider-socket.test.ts', - 'src/main/computer/macos-computer-use-permissions.test.ts', - 'src/main/computer/macos-computer-use-permission-status.test.ts', - 'src/main/computer/desktop-script-provider-client.test.ts', - 'src/main/computer/desktop-script-provider-cache.test.ts', - 'src/main/computer/desktop-script-provider-actions.test.ts', - 'src/main/computer/desktop-script-provider-cache-lifecycle.test.ts', - 'src/main/computer/desktop-script-provider-errors.test.ts', - 'src/main/computer/desktop-script-provider-action-errors.test.ts', - 'src/shared/computer-use-error-recovery.test.ts', - 'src/shared/computer-use-key-spec.test.ts', - 'src/cli/format.test.ts', - 'src/cli/handlers/computer.test.ts', - 'src/cli/handlers/computer-action-routing.test.ts', - 'src/cli/handlers/computer-action-validation.test.ts', - 'src/cli/handlers/computer-state-formatting.test.ts', - 'src/cli/specs/computer.test.ts', - 'src/cli/index.test.ts', - 'src/main/runtime/rpc/dispatcher-computer-errors.test.ts', - 'src/main/runtime/rpc/errors.test.ts', - 'src/main/runtime/rpc/methods/computer.test.ts', - 'src/main/runtime/rpc/methods/computer-actions.test.ts', - 'src/cli/runtime/envelope-schema.test.ts', - 'src/shared/remote-runtime-client.test.ts' - ] - - expect(checkout.with['persist-credentials']).toBe(false) - expect(regressionRun).toBeTruthy() - for (const file of expectedRegressionFiles) { - expect(regressionRun).toContain(file) - } - }) - - it('keeps Linux native imports available without installing the GUI-only stack in PR smoke', () => { - const workflow = parse( - readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') - ) - const nativeSmokeInstall = workflow.jobs['native-smoke'].steps.find( - (step) => step.if === "runner.os == 'Linux'" - ) - const scheduledLinuxInstall = workflow.jobs.linux.steps.find((step) => - step.run?.includes('apt-get install') - ) - - expect(nativeSmokeInstall.run).toContain('python3') - expect(nativeSmokeInstall.run).toContain('python3-gi') - expect(nativeSmokeInstall.run).toContain('gir1.2-atspi-2.0') - expect(nativeSmokeInstall.run).toContain('at-spi2-core') - expect(nativeSmokeInstall.run).not.toContain('gedit') - expect(nativeSmokeInstall.run).not.toContain('xvfb') - expect(nativeSmokeInstall.run).not.toContain('xdotool') - expect(scheduledLinuxInstall.run).toContain('gedit') - expect(scheduledLinuxInstall.run).toContain('xvfb') - expect(scheduledLinuxInstall.run).toContain('xdotool') - }) - - it('builds and tests the macOS helper on every trigger without hosted TCC e2e', () => { - const workflow = parse( - readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') - ) - const job = workflow.jobs['mac-native-owner-smoke'] - const runs = job.steps.map((step) => step.run).filter((run) => typeof run === 'string') - const checkout = job.steps.find((step) => step.uses === 'actions/checkout@v6') - const install = job.steps.find( - (step) => step.uses === './.github/actions/install-node-dependencies' - ) - - expect(job.if).toBeUndefined() - expect(job['runs-on']).toBe('macos-15') - expect(checkout.with['persist-credentials']).toBe(false) - expect(install.with['native-runtime']).toBe('electron') - expect(runs).toContain('pnpm bench:macos-computer-helper-owner-loss --expect reaped --trials 1') - const cleanupRun = runs.find((run) => - run.includes('config/scripts/macos-computer-helper-owner-loss-processes.test.mjs') - ) - expect(cleanupRun).toContain( - 'config/scripts/macos-computer-helper-owner-loss-group-recovery.test.mjs' - ) - expect(runs).toContain('pnpm verify:computer-native') - expect( - runs.find((run) => run.includes('config/scripts/build-native-for-platform.test.mjs')) - ).toContain('--config config/vitest.config.ts') - expect(runs.join('\n')).not.toContain('test:e2e:computer') - expect(workflow.jobs.mac).toBeUndefined() - expect(workflow.on.pull_request.paths).toEqual( - expect.arrayContaining([ - 'config/scripts/build-native-for-platform.mjs', - 'config/scripts/build-native-for-platform.test.mjs', - 'config/scripts/macos-computer-helper-owner-loss-benchmark.mjs', - 'config/scripts/macos-computer-helper-owner-loss-group-recovery.test.mjs', - 'config/scripts/macos-computer-helper-owner-loss-metrics.mjs', - 'config/scripts/macos-computer-helper-owner-loss-processes.mjs', - 'config/scripts/macos-computer-helper-owner-loss-processes.test.mjs', - 'config/scripts/macos-computer-helper-owner-loss-trial-cleanup.mjs' - ]) - ) - }) - it('uses the cached Electron dependency path for scheduled Linux and Windows e2e', () => { const workflow = parse( readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') @@ -220,29 +29,6 @@ describe('computer-use e2e workflow', () => { } }) - it('runs deterministic macOS owner-loss benchmark cleanup coverage', () => { - const benchmark = readFileSync( - join(projectDir, 'config/scripts/macos-computer-helper-owner-loss-benchmark.mjs'), - 'utf8' - ) - const cleanup = readFileSync( - join(projectDir, 'config/scripts/macos-computer-helper-owner-loss-trial-cleanup.mjs'), - 'utf8' - ) - - expect(benchmark).toContain('spawnBenchmarkProcess(executable, [launcherDir]') - expect(benchmark).toContain("stdio: ['ignore', stdoutDescriptor, stderrDescriptor]") - expect(benchmark).toContain('cleanupOwnerLossTrial({') - const parseIndex = benchmark.indexOf('parseBenchmarkTrialResult(serializedResult)') - const cleanupIndex = benchmark.indexOf('cleanupOwnerLossTrial({') - expect(parseIndex).toBeGreaterThanOrEqual(0) - expect(cleanupIndex).toBeGreaterThanOrEqual(0) - expect(parseIndex).toBeLessThan(cleanupIndex) - expect(benchmark).toContain('trialCleanupSha256: artifactSha256(trialCleanupPath)') - expect(cleanup).toContain('killRecordedAndMatchingProcesses(options.recordPath') - expect(cleanup).toContain("signalValidatedProcessGroup(options.pid, options.marker, 'SIGKILL'") - }) - it('boots the built daemon under plain Node in the PR native-smoke job after the main build', () => { const workflow = parse( readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') @@ -279,34 +65,6 @@ describe('computer-use e2e workflow', () => { ) }) - it('re-runs the native-smoke job when the daemon bundle graph changes', () => { - const workflow = parse( - readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') - ) - const triggerPaths = workflow.on.pull_request.paths - - expect(triggerPaths).toEqual( - expect.arrayContaining([ - 'config/scripts/daemon-boot-smoke.mjs', - 'config/scripts/windows-daemon-workspace-close-repro.mjs', - 'electron.vite.config.ts', - 'config/build-plugins/**', - 'src/main/daemon/**' - ]) - ) - }) - - it('does not run computer-use e2e in PR smoke jobs', () => { - const workflow = parse( - readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') - ) - const nativeSmokeRuns = workflow.jobs['native-smoke'].steps - .map((step) => step.run) - .filter((run) => typeof run === 'string') - - expect(nativeSmokeRuns.join('\n')).not.toContain('test:e2e:computer') - }) - it('builds Electron main output before every computer-use e2e run', () => { const workflow = parse( readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') @@ -352,48 +110,4 @@ describe('computer-use e2e workflow', () => { expect(allRuns.join('\n')).toContain('test:e2e:computer') expect(allRuns.join('\n')).not.toContain('test:e2e:computer -- --reporter') }) - - it('runs Linux e2e on schedule without advertising hosted macOS TCC coverage', () => { - const workflow = parse( - readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') - ) - const triggerPaths = workflow.on.pull_request.paths - const linuxRuns = workflow.jobs.linux.steps - .map((step) => step.run) - .filter((run) => typeof run === 'string') - - expect(triggerPaths).toEqual( - expect.arrayContaining([ - 'tests/e2e/computer-linux.e2e.ts', - 'tests/e2e/helpers/computer-cli-driver.ts', - 'tests/e2e/helpers/computer-driver.ts' - ]) - ) - expect(triggerPaths).not.toContain('tests/e2e/computer-mac.e2e.ts') - expect(triggerPaths).not.toContain('tests/e2e/computer-mac-safari.e2e.ts') - expect(workflow.jobs.mac).toBeUndefined() - expect(linuxRuns).toContain( - 'xvfb-run --auto-servernum dbus-run-session -- pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-linux.e2e.ts' - ) - }) - - it('runs every Windows computer-use e2e file in the scheduled Windows job', () => { - const workflow = parse( - readFileSync(join(projectDir, '.github/workflows/computer-e2e.yml'), 'utf8') - ) - const triggerPaths = workflow.on.pull_request.paths - const windowsRuns = workflow.jobs.windows.steps - .map((step) => step.run) - .filter((run) => typeof run === 'string') - - expect(triggerPaths).toEqual( - expect.arrayContaining([ - 'tests/e2e/computer-windows.e2e.ts', - 'tests/e2e/computer-windows-store.e2e.ts' - ]) - ) - expect(windowsRuns).toContain( - 'pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-windows.e2e.ts tests/e2e/computer-windows-store.e2e.ts' - ) - }) }) diff --git a/config/scripts/electron-vite-output-contract.test.ts b/config/scripts/electron-vite-output-contract.test.ts index 958e461ffd9..da6d45c8a23 100644 --- a/config/scripts/electron-vite-output-contract.test.ts +++ b/config/scripts/electron-vite-output-contract.test.ts @@ -20,9 +20,6 @@ import { createRequire } from 'node:module' import { electronViteConfig } from '../../electron.vite.config' import { BOOTSTRAP_FATAL_EXIT_GUARD_KEY } from '../../src/main/startup/bootstrap-fatal-exit-guard' -const targetConfig = readFileSync('config/electron-vite-target.config.cts', 'utf8') -const devRunner = readFileSync('config/scripts/run-electron-vite-dev.mjs', 'utf8') - type BootstrapProcessMock = EventEmitter & { env: Record pid: number @@ -253,11 +250,6 @@ describe('Electron Vite output contract', () => { ) }) - it('rejects prototype properties as build targets', () => { - // Own-property check only: an inherited key like `constructor` must not select a build target. - expect(targetConfig).toContain('Object.hasOwn(configByTarget, target)') - }) - it('gives the dev terminal daemon helper the TCC identity watched by Orca', () => { // Asserted on the values rather than the source text: the ids moved into // dev-electron-bundle-identity.mjs so every dev bundle signs to one cdhash. @@ -265,7 +257,5 @@ describe('Electron Vite output contract', () => { expect(getDevHelperPlistPatches()).toEqual([ { key: 'CFBundleIdentifier', value: DEV_HELPER_BUNDLE_ID } ]) - expect(devRunner).toContain("'Electron Helper.app',") - expect(devRunner).toContain('setPlistValue(helperPlistPath, key, value)') }) }) diff --git a/config/scripts/headless-serve-shutdown-workflow.test.mjs b/config/scripts/headless-serve-shutdown-workflow.test.mjs index 77b92b1d0c3..d9de91f28da 100644 --- a/config/scripts/headless-serve-shutdown-workflow.test.mjs +++ b/config/scripts/headless-serve-shutdown-workflow.test.mjs @@ -4,53 +4,8 @@ import { parse } from 'yaml' import { describe, expect, it } from 'vitest' const workflow = parse(readFileSync('.github/workflows/pr.yml', 'utf8')) -const headlessLinuxGuide = readFileSync('docs/reference/headless-linux-server.md', 'utf8') -const signalCase = readFileSync('config/docker/headless-serve-shutdown/run-signal-case.sh', 'utf8') -const shutdownDockerRunner = readFileSync( - 'config/scripts/run-headless-serve-shutdown-docker.mjs', - 'utf8' -) -const shutdownDockerfile = readFileSync('config/docker/headless-serve-shutdown/Dockerfile', 'utf8') -const desktopStartupOracle = readFileSync( - 'config/docker/headless-serve-shutdown/run-appimage-desktop-startup-case.sh', - 'utf8' -) -const headlessLinuxProse = headlessLinuxGuide.replace(/\s+/g, ' ') - -function readSystemdUnitBlocks(doc, unitName) { - const escapedUnitName = unitName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') - return [...doc.matchAll(new RegExp(`^# /etc/systemd/system/${escapedUnitName}$`, 'gm'))].map( - (match) => { - const start = match.index + match[0].length - const end = doc.indexOf('```', start) - const nextUnitHeaderOffset = doc.slice(start).search(/^# \/etc\/systemd\/system\/.+$/m) - const nextUnitHeader = nextUnitHeaderOffset === -1 ? -1 : start + nextUnitHeaderOffset - if (end === -1 || (nextUnitHeader !== -1 && end > nextUnitHeader)) { - throw new Error(`Missing closing code fence for ${unitName}`) - } - return doc.slice(start, end) - } - ) -} describe('headless serve shutdown PR gate', () => { - it('reads only exact, closed systemd unit blocks', () => { - expect( - readSystemdUnitBlocks('# /etc/systemd/system/orca-serveXservice\n```', 'orca-serve.service') - ).toEqual([]) - expect(() => - readSystemdUnitBlocks('# /etc/systemd/system/orca-serve.service\n', 'orca-serve.service') - ).toThrow('Missing closing code fence for orca-serve.service') - expect(() => - readSystemdUnitBlocks( - '# /etc/systemd/system/orca-serve.service\n' + - 'KillMode=mixed\n' + - '# /etc/systemd/system/other.service\n```', - 'orca-serve.service' - ) - ).toThrow('Missing closing code fence for orca-serve.service') - }) - it('packages Linux artifacts before running the Docker signal oracle', () => { const steps = workflow.jobs.package.steps const packageStep = steps.find((step) => step.name === 'Package unpacked app') @@ -72,130 +27,4 @@ describe('headless serve shutdown PR gate', () => { steps.filter((step) => step.run?.includes('run-headless-serve-shutdown-docker.mjs')) ).toHaveLength(1) }) - - it('keeps readiness polling finite and leak-free', () => { - expect(signalCase).toContain('read_ready_line()') - expect(signalCase).toContain("sed -u -n 's/^[^{]*//p'") - expect(signalCase).toContain('startup_timeout_seconds=${ORCA_STARTUP_TIMEOUT_SECONDS:-180}') - expect(signalCase).toContain('startup_deadline=$((SECONDS + startup_timeout_seconds))') - expect(signalCase).toContain('while (( SECONDS < startup_deadline )); do') - expect(signalCase).toContain('kill -0 "$app_pid" 2>/dev/null || break') - expect(signalCase).toContain( - "jq's `inputs` waits for EOF even when wrapped in `first`, so a tail -F" - ) - expect(signalCase).not.toContain('tail --pid=') - }) - - it('gives owned shutdown state a bounded cleanup grace', () => { - expect(signalCase).toContain('for shutdown_poll in {0..50}; do') - expect(signalCase).toContain('[[ -z "$listener_after" && -z "$owned_residue" ]]') - expect(signalCase).toContain('((${#survivors[@]} == 0))') - expect(signalCase).toContain('((shutdown_poll < 50)) && sleep 0.1') - }) - - it('checks that a serving-electron signal target owns the ready socket', () => { - const ssRecord = - 'LISTEN 0 128 127.0.0.1:41235 0.0.0.0:* users:(("orca-ide",pid=23,fd=7),("orca-ide",pid=25,fd=8))' - expect([...ssRecord.matchAll(/pid=([0-9]+)/g)].map((match) => match[1])).toEqual(['23', '25']) - expect(signalCase).toContain( - 'listener_before_pids=$(grep -oE \'pid=[0-9]+\' <<<"$listener_before" | cut -d= -f2 || true)' - ) - expect(signalCase).toContain('signal_target_pid=$(head -n1 <<<"$listener_before_pids")') - expect(signalCase).toContain('outside the entrypoint process tree') - }) - - it('runs the original AppImage desktop startup oracle before extraction and signals', () => { - expect(shutdownDockerfile).toContain( - 'COPY run-appimage-desktop-startup-case.sh /usr/local/bin/run-appimage-desktop-startup-case' - ) - const startupCall = shutdownDockerRunner.indexOf( - 'runDesktopStartupOracle({ image, appImage, platform })' - ) - const extractionCall = shutdownDockerRunner.indexOf( - "'timeout --kill-after=10s 120s /input/orca.AppImage --appimage-extract" - ) - const signalLoop = shutdownDockerRunner.indexOf("for (const signal of ['INT', 'TERM'])") - expect(startupCall).toBeGreaterThan(-1) - expect(extractionCall).toBeGreaterThan(startupCall) - expect(signalLoop).toBeGreaterThan(startupCall) - expect(shutdownDockerRunner).toContain("'/usr/local/bin/run-appimage-desktop-startup-case'") - }) - - it('preserves startup logs when the launcher exits before its marker', () => { - expect(desktopStartupOracle).toContain('signal_process_group TERM || true') - expect(desktopStartupOracle).toContain('signal_process_group KILL || true') - expect(desktopStartupOracle).toContain('cat "$stdout_log" >&2 2>/dev/null || true') - expect(desktopStartupOracle).toContain('cat "$stderr_log" >&2 2>/dev/null || true') - expect(desktopStartupOracle).toContain( - 'FAIL: desktop launcher exited before ${reason} (status=${observed_status})' - ) - expect(desktopStartupOracle).toContain('ORCA_STARTUP_STATE_DIR_CLEANUP=1') - expect(desktopStartupOracle).toContain( - '[[ "$state_dir" =~ ^/tmp/orca-appimage-startup\\.[^/]+$ ]] || return 0' - ) - }) - - it('requires the bound AppImage to be executable before launch and extraction', () => { - expect(desktopStartupOracle).toContain( - '[[ -x "$appimage" ]] || { echo "FAIL: AppImage is not executable: $appimage" >&2; exit 1; }' - ) - expect(shutdownDockerRunner).toContain( - '\'test -r /input/orca.AppImage && test -x /input/orca.AppImage || { echo "FAIL: AppImage bind must be readable and executable" >&2; exit 1; }\'' - ) - }) - - it('gives the original AppImage enough bounded extraction space', () => { - expect(shutdownDockerRunner).toContain("'/tmp:rw,nosuid,nodev,exec,size=1g'") - }) - - it('keeps owned Xvfb alive during the documented systemd graceful stop', () => { - const serveUnits = readSystemdUnitBlocks(headlessLinuxGuide, 'orca-serve.service') - const ownedXvfbUnits = serveUnits.filter((unit) => !/^Environment=DISPLAY=/m.test(unit)) - const managedXvfbUnits = serveUnits.filter((unit) => /^Environment=DISPLAY=/m.test(unit)) - - expect(ownedXvfbUnits).toHaveLength(1) - expect(ownedXvfbUnits[0]).toMatch(/^ExecStart=.*orca-linux\.AppImage serve.*$/m) - expect(ownedXvfbUnits[0]).toMatch(/^KillMode=mixed$/m) - expect(managedXvfbUnits).toHaveLength(1) - expect(managedXvfbUnits[0]).toMatch(/^KillMode=mixed$/m) - }) - - it('distinguishes persisted state from live work during a service restart', () => { - expect(headlessLinuxProse).toContain( - 'The detached terminal daemon is preserved by a different mechanism: it is launched through `systemd-run --user --scope`' - ) - expect(headlessLinuxProse).toContain( - 'These guarantees preserve live processes only when the daemon is in its own' - ) - expect(headlessLinuxProse).toContain( - 'The unscoped fallback remains destructive: a service restart kills every terminal' - ) - expect(headlessLinuxProse).toContain( - 'Treat a stop as destructive unless `health.terminalDaemon.cgroupUnit` names an `orca-daemon-*.scope` on that host' - ) - expect(headlessLinuxProse).toContain( - 'A separately paired runtime is outside that boundary; local execution and SSH hosts reached through this runtime are not. An affected or unknown omission, missing scope, failed request or lost connection is `unverifiable`' - ) - expect(headlessLinuxGuide).toContain( - 'sudo -Hu orca /home/orca/.local/bin/orca-ide terminal list --json' - ) - expect(headlessLinuxGuide).not.toContain('sudo -Hu orca orca-ide terminal list --json') - expect(headlessLinuxGuide).not.toContain('Two facts make this safe and predictable') - }) - - it('uses the registered CLI name from ordinary Linux shells', () => { - const commandRule = - 'The registered Linux CLI command is `orca-ide`, not `orca`, to avoid shadowing the GNOME Orca screen reader.' - const substitutionRule = - "From an ordinary shell outside that service user's managed environment, substitute `orca-ide` for `orca` in commands below." - const censusCommand = '`sudo -Hu orca /home/orca/.local/bin/orca-ide terminal list --json`' - - expect(headlessLinuxProse).toContain(commandRule) - expect(headlessLinuxProse).toContain(substitutionRule) - expect(headlessLinuxProse).toContain(censusCommand) - expect(headlessLinuxGuide).toContain('best-effort dispatcher at `$HOME/.local/bin/orca`') - expect(headlessLinuxProse.indexOf(substitutionRule)).toBeLessThan( - headlessLinuxProse.indexOf(censusCommand) - ) - }) }) diff --git a/config/scripts/mobile-web-app-route-manifest.test.mjs b/config/scripts/mobile-web-app-route-manifest.test.mjs index b4c29d8d9d8..1cbf256bd7a 100644 --- a/config/scripts/mobile-web-app-route-manifest.test.mjs +++ b/config/scripts/mobile-web-app-route-manifest.test.mjs @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -250,23 +250,3 @@ describe('the synthesized RequireContext', () => { expect(() => context('constructor')).toThrow('no route module') }) }) - -describe('the web entry', () => { - it('leaves the suspense boundary to expo-router', async () => { - const entry = await readFile(join(projectDir, 'mobile', 'web-entry', 'index.tsx'), 'utf8') - // A second boundary around the whole tree catches nothing the router has not already caught, - // and would only make the fallback ambiguous about which layer suspended. - expect(entry).not.toContain('Suspense') - }) - - itBundling('because the router already wraps every screen in one', async () => { - // The premise of the test above, read off the copy that is bundled: getQualifiedRouteComponent - // wraps each screen itself, which is what makes the lazy route manifest safe without a - // boundary of our own. - const useScreens = await readFile( - join(projectDir, 'mobile', 'node_modules', 'expo-router', 'build', 'useScreens.js'), - 'utf8' - ) - expect(useScreens).toContain(' { } it('keeps the native Windows registry addon optional and platform-gated', () => { - const rebuildScript = readProject('config/scripts/rebuild-native-deps.mjs') - const ensureScript = readProject('config/scripts/ensure-native-runtime.mjs') expect(packageJson.optionalDependencies['@orca/windows-registry']).toBe('workspace:*') // Why: allowBuilds stops pnpm running node-gyp at install time -- the root // Windows-only rebuild owns this addon so it is built against the right runtime ABI. expect(pnpmWorkspace.allowBuilds['@orca/windows-registry']).toBe(false) - // Why assert the guard and the member separately: the list now carries more - // than one addon, so pinning the whole literal only tested its formatting. - expect(rebuildScript).toContain("rebuildPlatform === 'win32'") - expect(rebuildScript).toContain("'@orca/windows-registry'") - expect(ensureScript).toContain("process.platform === 'win32'") - expect(ensureScript).toContain("'@orca/windows-registry'") if (windowsAddonsInstalled) { expect(packageTargets.win32).toEqual( expect.arrayContaining([ @@ -55,20 +46,10 @@ describe('Electron runtime package contract', () => { }) it('keeps the native Windows process-table addon optional and platform-gated', () => { - const rebuildScript = readFileSync( - join(projectDir, 'config/scripts/rebuild-native-deps.mjs'), - 'utf8' - ) - const ensureScript = readFileSync( - join(projectDir, 'config/scripts/ensure-native-runtime.mjs'), - 'utf8' - ) expect(packageJson.optionalDependencies['@vscode/windows-process-tree']).toBe('0.8.0') // Why: same rule as the registry addon -- allowBuilds stops pnpm running node-gyp at // install time so the Windows-only rebuild owns it with the right runtime ABI. expect(pnpmWorkspace.allowBuilds['@vscode/windows-process-tree']).toBe(false) - expect(rebuildScript).toContain("'@vscode/windows-process-tree'") - expect(ensureScript).toContain("'@vscode/windows-process-tree'") // Why pin the patch: the upstream binding.gyp requires Spectre-mitigated // libraries our build agents do not carry, and the enumeration stops after // 1024 processes -- on a busy host that silently hides the very descendants @@ -92,195 +73,6 @@ describe('Electron runtime package contract', () => { } }) - it('guards package scripts that launch Electron tooling', () => { - const scripts = packageJson.scripts - const guardedScripts = [ - 'start', - 'dev', - 'dev-stable-name', - 'build:unpack', - 'build:win', - 'build:mac', - 'build:mac:release', - 'build:linux', - 'test:e2e', - 'test:e2e:terminal-rendering-golden', - 'test:e2e:posix-profile-index-golden', - 'test:e2e:terminal-rendering-release-evidence', - 'test:e2e:headful' - ] - - for (const scriptName of guardedScripts) { - expect(scripts[scriptName], scriptName).toContain('pnpm run ensure:electron-runtime &&') - } - }) - - it('keeps Windows and Linux package builds off macOS native helper builds', () => { - const scripts = packageJson.scripts - - expect(scripts['build:desktop']).not.toContain('build:computer-macos') - expect(scripts['build:desktop']).not.toContain('build:keyboard-layout-macos') - expect(scripts['build:win']).toContain('pnpm run build:desktop') - expect(scripts['build:win']).not.toContain('pnpm run build ') - expect(scripts['build:win']).not.toContain('build:computer-macos') - expect(scripts['build:win']).not.toContain('build:keyboard-layout-macos') - expect(scripts['build:linux']).toContain('pnpm run build:desktop') - expect(scripts['build:linux']).not.toContain('pnpm run build ') - expect(scripts['build:linux']).not.toContain('build:computer-macos') - expect(scripts['build:linux']).not.toContain('build:keyboard-layout-macos') - expect(scripts['build:mac']).toContain('pnpm run build:computer-macos') - expect(scripts['build:mac']).toContain('pnpm run build:keyboard-layout-macos') - expect(scripts['build:release']).toContain('pnpm run build:native') - expect(scripts['build:release']).not.toContain('build:computer-macos') - }) - - it('runs the web build through the heap-sized Vite wrapper', () => { - expect(packageJson.scripts['build:web']).toContain('node config/scripts/run-vite-web-build.mjs') - expect(packageJson.scripts['build:web']).toContain('node config/scripts/verify-web-build.mjs') - }) - - it('guards release publishing before electron-builder runs', () => { - const releaseWorkflow = readFileSync( - join(projectDir, '.github/workflows/release-cut.yml'), - 'utf8' - ) - const parsedWorkflow = parse(releaseWorkflow) - const macWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/release-mac-build.yml'), 'utf8') - ) - const releaseCommands = new Map( - parsedWorkflow.jobs.build.strategy.matrix.include.map(({ platform, release_command }) => [ - platform, - release_command - ]) - ) - const macReleaseCommand = macWorkflow.jobs['build-mac'].steps.find( - (step) => step.name === 'Publish release artifacts (macOS)' - ).with.command - - expect([...releaseCommands.keys()].sort()).toEqual(['linux-arm64', 'linux-x64', 'win']) - for (const command of [...releaseCommands.values(), macReleaseCommand]) { - expect(command).toContain('node config/scripts/ensure-native-runtime.mjs --runtime=electron') - expect(command).toContain('electron-builder') - expect(command.indexOf('ensure-native-runtime')).toBeLessThan( - command.indexOf('electron-builder') - ) - } - expect(macReleaseCommand).toContain(' && ORCA_MAC_RELEASE=1 ') - expect(releaseCommands.get('linux-x64')).toContain(' && pnpm exec electron-builder ') - expect(releaseCommands.get('linux-x64')).toContain('--linux AppImage deb rpm --x64') - expect(releaseCommands.get('linux-arm64')).toContain('ORCA_LINUX_ARM64_RELEASE=1') - expect(releaseCommands.get('linux-arm64')).toContain('--linux AppImage deb rpm --arm64') - expect(releaseCommands.get('win')).toContain( - '; if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }; pnpm exec electron-builder ' - ) - }) - - it('blocks Linux and macOS release packaging on watcher process fault recovery', () => { - const releaseWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/release-cut.yml'), 'utf8') - ) - const macWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/release-mac-build.yml'), 'utf8') - ) - const assertFaultGate = (steps, publishStepName, expectedCondition) => { - const names = steps.map((step) => step.name) - const gate = steps.find((step) => step.name === 'Gate runtime file-watcher process isolation') - - expect(gate.if).toBe(expectedCondition) - expect(gate['continue-on-error']).toBeUndefined() - expect(gate.run).toContain('node config/scripts/runtime-file-watcher-fault-harness.mjs') - expect(gate.run).toContain('ELECTRON_RUN_AS_NODE=1 pnpm exec electron') - expect(names.indexOf('Build app')).toBeLessThan(names.indexOf(gate.name)) - expect(names.indexOf(gate.name)).toBeLessThan(names.indexOf(publishStepName)) - } - - assertFaultGate( - releaseWorkflow.jobs.build.steps, - 'Publish release artifacts (Linux)', - "runner.os == 'Linux'" - ) - assertFaultGate( - macWorkflow.jobs['build-mac'].steps, - 'Publish release artifacts (macOS)', - undefined - ) - }) - - it('packages and release-gates the SSH relay watcher child', () => { - const relayBuild = readFileSync(join(projectDir, 'config/scripts/build-relay.mjs'), 'utf8') - const builderConfig = readFileSync( - join(projectDir, 'config/electron-builder.config.cjs'), - 'utf8' - ) - const remoteCommands = readFileSync( - join(projectDir, 'src/main/ssh/ssh-remote-commands.ts'), - 'utf8' - ) - const releaseWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/release-cut.yml'), 'utf8') - ) - const macWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/release-mac-build.yml'), 'utf8') - ) - - expect(relayBuild).toContain("'parcel-watcher-process-entry.ts'") - expect(relayBuild).toContain("outfile: join(outDir, 'relay-watcher.js')") - expect(relayBuild).toContain("outfile: join(outDir, 'relay-ai-vault-service.js')") - expect(builderConfig).toContain("from: 'out/relay'") - - // Hashing and remote install probing are manifest-driven, so the contract - // is that both companions are declared once and that both sites read it. - expect(relayArtifactFilenames(true)).toContain('relay-watcher.js') - expect(relayArtifactFilenames(true)).toContain('relay-ai-vault-service.js') - expect(relayBuild).toContain('relayArtifactFilenames(') - expect(remoteCommands).toContain('relayArtifactFilenames(') - - const assertRelayGate = (steps, publishStepName) => { - const names = steps.map((step) => step.name) - const gate = steps.find((step) => step.name === 'Gate SSH relay watcher process isolation') - expect(gate['continue-on-error']).toBeUndefined() - expect(gate.run).toContain('node config/scripts/relay-watcher-fault-harness.mjs') - expect(names.indexOf('Build app')).toBeLessThan(names.indexOf(gate.name)) - expect(names.indexOf(gate.name)).toBeLessThan(names.indexOf(publishStepName)) - } - - assertRelayGate(releaseWorkflow.jobs.build.steps, 'Publish release artifacts (Linux)') - assertRelayGate(macWorkflow.jobs['build-mac'].steps, 'Publish release artifacts (macOS)') - const releaseNames = releaseWorkflow.jobs.build.steps.map((step) => step.name) - expect(releaseNames.indexOf('Gate SSH relay watcher process isolation')).toBeLessThan( - releaseNames.indexOf('Build Windows release artifacts') - ) - }) - - it('packages and verifies the Windows SSH node-pty console-list fallback', () => { - const relayBuild = readFileSync(join(projectDir, 'config/scripts/build-relay.mjs'), 'utf8') - const relayDeploy = readFileSync(join(projectDir, 'src/main/ssh/ssh-relay-deploy.ts'), 'utf8') - const patchAsset = readFileSync( - join(projectDir, 'config/relay-assets/node-pty-1.1.0-console-list-agent-patch.cjs'), - 'utf8' - ) - - expect(relayBuild).toContain('copyFileSync(') - expect(relayBuild).toContain('hash.update(readFileSync') - expect(relayBuild).toContain('node-pty-1.1.0-console-list-agent-patch.cjs') - expect(relayDeploy).toContain('assertPatchedNodePtyConsoleListAgent') - expect(relayDeploy.match(/\$\{windowsNodePtyPatchCommand\(nodePath\)\}/g)).toHaveLength(2) - expect(patchAsset).toContain('consoleProcessList = [shellPid];') - expect(patchAsset).toContain('packageJson.version !== EXPECTED_NODE_PTY_VERSION') - }) - - it('pins the Windows release builder to the VS 2022 runner image', () => { - const releaseWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/release-cut.yml'), 'utf8') - ) - const windowsReleaseEntry = releaseWorkflow.jobs.build.strategy.matrix.include.find( - ({ platform }) => platform === 'win' - ) - - expect(windowsReleaseEntry.os).toBe('windows-2022') - }) - it('keeps release-cut signing provenance on GitHub-hosted runners', () => { const releaseWorkflow = parse( readFileSync(join(projectDir, '.github/workflows/release-cut.yml'), 'utf8') @@ -306,360 +98,4 @@ describe('Electron runtime package contract', () => { expect(releaseWorkflow.jobs['publish-release'].needs).toContain('build') expect(releaseWorkflow.jobs['publish-release'].needs).toContain('build-mac') }) - - it('runs the macOS release build in an isolated Blacksmith workflow', () => { - const releaseMacWorkflowText = readFileSync( - join(projectDir, '.github/workflows/release-mac-build.yml'), - 'utf8' - ) - const releaseMacWorkflow = parse(releaseMacWorkflowText) - const buildMacJob = releaseMacWorkflow.jobs['build-mac'] - const checkoutStep = buildMacJob.steps.find((step) => step.name === 'Checkout') - const publishStep = buildMacJob.steps.find( - (step) => step.name === 'Publish release artifacts (macOS)' - ) - - expect(releaseMacWorkflow['run-name']).toBe( - 'Mac release build ${{ inputs.tag }} (${{ inputs.release_run_id }})' - ) - expect(releaseMacWorkflow.on.workflow_dispatch.inputs.tag.required).toBe(true) - expect(releaseMacWorkflow.on.workflow_dispatch.inputs.release_run_id.required).toBe(true) - expect(buildMacJob['runs-on']).toBe('blacksmith-6vcpu-macos-15') - expect(checkoutStep.with.ref).toBe('refs/tags/${{ inputs.tag }}') - expect(publishStep.with.command).toContain('ORCA_MAC_RELEASE=1') - expect(publishStep.with.command).toContain('electron-builder') - expect(publishStep.with.command).toContain('--mac --publish always') - expect(releaseMacWorkflowText).not.toContain('signpath/') - expect(releaseMacWorkflowText).not.toContain('SIGNPATH_') - }) - - it('publishes both Linux release matrix entries', () => { - const releaseWorkflow = readFileSync( - join(projectDir, '.github/workflows/release-cut.yml'), - 'utf8' - ) - const parsedWorkflow = parse(releaseWorkflow) - const publishLinuxStep = parsedWorkflow.jobs.build.steps.find( - (step) => step.name === 'Publish release artifacts (Linux)' - ) - - expect(publishLinuxStep.if).toContain("matrix.platform == 'linux-x64'") - expect(publishLinuxStep.if).toContain("matrix.platform == 'linux-arm64'") - expect(publishLinuxStep.with.command).toBe('${{ matrix.release_command }}') - }) - - it('keeps Linux postinstall repairing Chromium sandbox permissions', () => { - const afterInstallScript = readFileSync( - join(projectDir, 'resources/linux/packaging/after-install.sh'), - 'utf8' - ) - - expect(afterInstallScript).toContain('chrome-sandbox') - expect(afterInstallScript).toContain('chmod 4755 "$sandbox"') - expect(afterInstallScript).not.toContain('chmod 0755 "$sandbox"') - expect(afterInstallScript).toContain('is_owned_link()') - expect(afterInstallScript).toContain('readlink -f -- "$link"') - expect(afterInstallScript).toContain('[ ! -e "$link" ] && [ ! -L "$link" ]') - expect(afterInstallScript).not.toContain('[ ! -e "$link" ] || [ -L "$link" ]') - }) - - it('advances only the skill release ledger in a taggable release-cut commit', () => { - const releaseWorkflow = readFileSync( - join(projectDir, '.github/workflows/release-cut.yml'), - 'utf8' - ) - const parsedWorkflow = parse(releaseWorkflow) - const checkoutStep = parsedWorkflow.jobs.cut.steps.find((step) => step.name === 'Checkout ref') - const bumpStep = parsedWorkflow.jobs.cut.steps.find( - (step) => step.name === 'Bump package.json and tag' - ) - - const bumpIndex = bumpStep.run.indexOf( - 'npm version "$VERSION" --no-git-tag-version --allow-same-version' - ) - const generateIndex = bumpStep.run.indexOf( - 'node config/scripts/generate-skill-bundle-manifest.mjs --release "$VERSION"' - ) - const commands = bumpStep.run.replace(/^\s*#.*$/gm, '') - // Unanchored: a `git add` chained after `&&` stages just as effectively. - const stagedPaths = [...commands.matchAll(/\bgit add (.+)$/gm)].flatMap((match) => - match[1].trim().split(/\s+/) - ) - // Quotes trimmed and deduped: the index guard names the row a second time. - const mentioned = new Set(commands.match(/resources[/\\]skills[^\s'"]*/g)) - expect(checkoutStep.with['fetch-depth']).toBe(0) - expect(bumpIndex).toBeGreaterThanOrEqual(0) - // Why: the cut is the only point that advances the release ledger, so this - // tag's revision is never rebuilt later — it appends that row, nothing else. - expect(generateIndex).toBeGreaterThan(bumpIndex) - expect(bumpStep.run.indexOf('git add package.json')).toBeGreaterThan(generateIndex) - expect(stagedPaths).toEqual(['package.json', 'resources/skills/release-mapping.json']) - // Every distinct mention must be staged, so a copy, a redirect, or a path - // held in a variable cannot reach the content-addressed artifacts. Matched - // without a trailing slash so `dir="resources/skills"` still counts. - expect([...mentioned]).toEqual(stagedPaths.slice(1)) - // Regeneration is banned job-wide by the generator suite. Here: `-a`, `-am`, - // and `--all` sweep unstaged artifacts in; `--allow-empty` below must not. - expect(commands).not.toMatch(/\bcommit\b[^\n]*(?:\s-[a-z]*a[a-z]*\b|\s--all\b)/) - expect(bumpStep.run).toContain('git diff --cached --quiet') - expect(bumpStep.run).toContain('git commit --allow-empty -m "$commit_message"') - }) - - it('keeps release-cut RC retries monotonic across stale attempts', () => { - const releaseWorkflow = readFileSync( - join(projectDir, '.github/workflows/release-cut.yml'), - 'utf8' - ) - const parsedWorkflow = parse(releaseWorkflow) - const versionStep = parsedWorkflow.jobs.cut.steps.find( - (step) => step.name === 'Compute next version' - ) - - expect(versionStep.run).toContain('node config/scripts/release-rc-history.mjs "$1"') - expect(versionStep.run).toContain('tag_matches_current_ref') - expect(versionStep.run).toContain('cutting the next version instead of reusing stale artifacts') - expect(versionStep.run).toContain('git rev-parse "$existing_rc_tag"') - }) - - it('bumps separate Homebrew casks for stable and RC desktop tags', () => { - const releaseWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/release-cut.yml'), 'utf8') - ) - const homebrewWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/homebrew-bump.yml'), 'utf8') - ) - - expect(releaseWorkflow.jobs['homebrew-bump'].if).toContain( - "startsWith(needs.cut.outputs.tag, 'v')" - ) - expect(releaseWorkflow.jobs['homebrew-bump'].if).not.toContain('-rc.') - expect(releaseWorkflow.jobs['homebrew-bump-published-rc-draft'].with.tag).toBe( - '${{ needs.cut.outputs.latest_published_rc_tag }}' - ) - - const resolveCaskStep = homebrewWorkflow.jobs['bump-cask'].steps.find( - (step) => step.name === 'Resolve cask target' - ) - const renderStep = homebrewWorkflow.jobs['bump-cask'].steps.find( - (step) => step.name === 'Render updated cask file' - ) - const copyStep = homebrewWorkflow.jobs['bump-cask'].steps.find( - (step) => step.name === 'Copy cask into tap and open PR' - ) - - expect(resolveCaskStep.run).toContain('token="orca@rc"') - expect(resolveCaskStep.run).toContain('token="orca"') - expect(renderStep.env.CASK_PATH).toBe('${{ steps.cask.outputs.path }}') - expect(copyStep.run).toContain('cp "$CASK_PATH" "tap/$CASK_PATH"') - expect(copyStep.run).toContain('git add "$CASK_PATH"') - }) - - it('installs the Electron package binary in the shared unit-test workflow', () => { - const unitTestWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/unit-tests.yml'), 'utf8') - ) - const installStep = unitTestWorkflow.jobs.test.steps.find( - (step) => step.name === 'Install Electron package binary for tests' - ) - - expect(installStep.run).toBe('node config/scripts/install-electron-package-binary.mjs') - }) - - it('smokes the packaged CLI from outside the checkout in PR checks', () => { - const prWorkflow = readFileSync(join(projectDir, '.github/workflows/pr.yml'), 'utf8') - const parsedWorkflow = parse(prWorkflow) - const smokeStep = parsedWorkflow.jobs.package.steps.find( - (step) => step.name === 'Smoke packaged CLI' - ) - - expect(smokeStep.run).toBe( - 'node config/scripts/smoke-packaged-cli.mjs --app-dir=dist/linux-unpacked' - ) - }) - - it('keeps terminal scale perf wired to the report budget gate', () => { - const packageScripts = packageJson.scripts - const terminalPerfWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/terminal-perf.yml'), 'utf8') - ) - const steps = terminalPerfWorkflow.jobs['terminal-perf'].steps - const runStep = steps.find((step) => step.name === 'Run terminal scale perf report gate') - const uploadStep = steps.find((step) => step.name === 'Upload terminal perf report') - - expect(packageScripts['test:e2e:terminal-perf:scale:report']).toContain( - 'run-terminal-scale-perf-report-gate.mjs' - ) - expect(runStep.run).toContain('pnpm run test:e2e:terminal-perf:scale:report') - expect(runStep.run).toContain('xvfb-run --auto-servernum') - const manualProfileKnobs = [ - ['ORCA_TERMINAL_PERF_FRAME_COUNT', 'frame_count', 'ORCA_E2E_OPENCODE_FRAME_COUNT'], - [ - 'ORCA_TERMINAL_PERF_FRAME_INTERVAL_MS', - 'frame_interval_ms', - 'ORCA_E2E_OPENCODE_FRAME_INTERVAL_MS' - ], - [ - 'ORCA_TERMINAL_PERF_PRESSURE_OUTPUT_CHARS', - 'pressure_output_chars', - 'ORCA_E2E_OPENCODE_PRESSURE_OUTPUT_CHARS' - ], - ['ORCA_TERMINAL_PERF_SCALE_PANES', 'scale_panes', 'ORCA_E2E_OPENCODE_SCALE_PANES'], - [ - 'ORCA_TERMINAL_PERF_SCALE_CROSS_WORKSPACE_PANES', - 'scale_cross_workspace_panes', - 'ORCA_E2E_OPENCODE_SCALE_CROSS_WORKSPACE_PANES' - ], - [ - 'ORCA_TERMINAL_PERF_SCALE_PRESSURE_PANES', - 'scale_pressure_panes', - 'ORCA_E2E_OPENCODE_SCALE_PRESSURE_PANES' - ], - [ - 'ORCA_TERMINAL_PERF_SCALE_HIDDEN_PRESSURE_PANES', - 'scale_hidden_pressure_panes', - 'ORCA_E2E_OPENCODE_SCALE_HIDDEN_PRESSURE_PANES' - ] - ] - for (const [workflowEnv, inputName, runnerEnv] of manualProfileKnobs) { - expect(runStep.env[workflowEnv]).toBe(`\${{ inputs.${inputName} }}`) - expect(runStep.run).toContain(runnerEnv) - } - expect(uploadStep.uses).toBe('actions/upload-artifact@v7') - expect(uploadStep.with.path).toBe('${{ env.ORCA_E2E_TERMINAL_PERF_REPORT_PATH }}') - }) - - it('keeps platform golden regressions in the manual and release workflows', () => { - const packageScripts = packageJson.scripts - const goldenWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/golden-e2e-experiment.yml'), 'utf8') - ) - const releaseWorkflow = parse( - readFileSync(join(projectDir, '.github/workflows/release-cut.yml'), 'utf8') - ) - const steps = goldenWorkflow.jobs['golden-e2e'].steps - const goldenPlatformLabels = new Map([ - ['linux', 'Linux'], - ['mac', 'macOS'], - ['windows', 'Windows'] - ]) - const goldenMatrix = goldenWorkflow.jobs['golden-e2e'].strategy.matrix.include - const goldenPlatforms = goldenMatrix.map(({ platform }) => platform).sort() - const goldenRunSteps = new Map( - goldenPlatforms.map((platform) => { - const label = goldenPlatformLabels.get(platform) - - expect(label, platform).toBeDefined() - - return [platform, steps.find((step) => step.name === `Run golden E2E tests on ${label}`)] - }) - ) - const releaseGoldenJob = releaseWorkflow.jobs['terminal-rendering-golden'] - const releaseGoldenMatrix = releaseGoldenJob.strategy.matrix.include - const releaseEvidenceJob = releaseWorkflow.jobs['terminal-rendering-release-evidence'] - const releaseBuildNeeds = releaseWorkflow.jobs.build.needs - const publishReleaseNeeds = releaseWorkflow.jobs['publish-release'].needs - // Why: Windows release evidence is temporarily paused for CI runner PTY readiness. - const releaseEvidencePlatforms = ['linux', 'mac'] - - expect(packageScripts['test:e2e:terminal-rendering-golden']).toContain( - '@terminal-rendering-golden' - ) - expect(packageScripts['test:e2e:terminal-rendering-golden']).toContain( - 'terminal-raw-emoji-table-scroll-restore.spec.ts' - ) - expect(packageScripts['test:e2e:terminal-rendering-golden']).toContain( - 'terminal-webgl-atlas-budget.spec.ts' - ) - expect(packageScripts['test:e2e:terminal-rendering-golden']).not.toContain( - 'terminal-long-table-scroll-restore.spec.ts' - ) - const goldenCommand = packageScripts['test:e2e:terminal-rendering-golden'] - expect(goldenCommand).toContain('--project electron-headless') - expect(goldenCommand).toContain('--project electron-headful') - expect(packageScripts['test:e2e:windows-fresh-startup-golden']).toContain( - 'golden-windows-fresh-startup.spec.ts' - ) - expect(packageScripts['test:e2e:windows-fresh-startup-golden']).toContain( - '@windows-fresh-startup-golden' - ) - expect(packageScripts['test:e2e:posix-profile-index-golden']).toContain( - 'golden-posix-profile-index-fsync.spec.ts' - ) - expect(packageScripts['test:e2e:posix-profile-index-golden']).toContain( - 'golden-posix-fresh-startup.spec.ts' - ) - expect(packageScripts['test:e2e:posix-profile-index-golden']).toContain( - '@posix-profile-index-golden' - ) - expect(packageScripts['test:e2e:terminal-rendering-release-evidence']).toContain( - 'terminal-opencode-emoji-table-rendering.spec.ts' - ) - expect(packageScripts['test:e2e:terminal-rendering-release-evidence']).toContain( - 'terminal-long-table-scroll-restore.spec.ts' - ) - expect(goldenMatrix).toEqual([ - { os: 'ubuntu-latest', platform: 'linux' }, - { os: 'macos-15', platform: 'mac' }, - { os: 'windows-2022', platform: 'windows' } - ]) - expect(goldenRunSteps.get('linux')?.run).toContain( - 'pnpm run test:e2e:terminal-rendering-golden' - ) - expect(goldenRunSteps.get('linux')?.run).toContain( - 'pnpm run --if-present test:e2e:posix-profile-index-golden' - ) - expect(goldenRunSteps.get('mac')?.run).toContain('pnpm run test:e2e:terminal-rendering-golden') - expect(goldenRunSteps.get('mac')?.run).toContain( - 'pnpm run --if-present test:e2e:posix-profile-index-golden' - ) - expect(goldenRunSteps.get('windows')).toMatchObject({ - if: "runner.os == 'Windows'", - shell: 'pwsh' - }) - expect(goldenRunSteps.get('windows').run).toContain( - 'pnpm run --if-present test:e2e:windows-fresh-startup-golden' - ) - expect(goldenWorkflow.on.pull_request).toBeUndefined() - expect(goldenWorkflow.on.workflow_dispatch).toBeDefined() - expect(releaseBuildNeeds).not.toContain('terminal-rendering-golden') - expect(releaseBuildNeeds).not.toContain('terminal-rendering-release-evidence') - expect(publishReleaseNeeds).toContain('terminal-rendering-golden') - expect(publishReleaseNeeds).toContain('build') - expect(publishReleaseNeeds).not.toContain('terminal-rendering-release-evidence') - expect(releaseGoldenJob['continue-on-error']).toBeUndefined() - expect(releaseGoldenMatrix).toEqual(goldenMatrix) - const releaseLinuxRunStep = releaseGoldenJob.steps.find( - (step) => step.name === 'Run terminal rendering golden on Linux' - ) - expect(releaseLinuxRunStep.run).toContain('pnpm run test:e2e:terminal-rendering-golden') - expect(releaseLinuxRunStep.run).toContain( - 'pnpm run --if-present test:e2e:posix-profile-index-golden' - ) - const releaseMacRunStep = releaseGoldenJob.steps.find( - (step) => step.name === 'Run terminal rendering golden on macOS' - ) - expect(releaseMacRunStep.run).toContain('pnpm run test:e2e:terminal-rendering-golden') - expect(releaseMacRunStep.run).toContain( - 'pnpm run --if-present test:e2e:posix-profile-index-golden' - ) - const releaseWindowsRunStep = releaseGoldenJob.steps.find( - (step) => step.name === 'Run fresh-startup golden on Windows' - ) - expect(releaseWindowsRunStep).toMatchObject({ - if: "runner.os == 'Windows'", - shell: 'pwsh' - }) - expect(releaseWindowsRunStep.run).toContain( - 'pnpm run --if-present test:e2e:windows-fresh-startup-golden' - ) - expect(releaseWindowsRunStep.run).not.toContain('test:e2e:workspace-session-golden') - expect(releaseWindowsRunStep.run).not.toContain('test:e2e:source-control-golden') - expect(releaseEvidenceJob['continue-on-error']).toBe(true) - expect( - releaseEvidenceJob.strategy.matrix.include.map(({ platform }) => platform).sort() - ).toEqual(releaseEvidencePlatforms) - expect(releaseEvidenceJob.steps.map((step) => step.run ?? '')).toContain( - 'xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-release-evidence' - ) - }) }) diff --git a/config/scripts/packaged-hang-watchdog-worker-contract.test.mjs b/config/scripts/packaged-hang-watchdog-worker-contract.test.mjs deleted file mode 100644 index a4998760b67..00000000000 --- a/config/scripts/packaged-hang-watchdog-worker-contract.test.mjs +++ /dev/null @@ -1,37 +0,0 @@ -import { readFileSync } from 'node:fs' -import { parse } from 'yaml' -import { describe, expect, it } from 'vitest' - -describe('packaged hang watchdog worker contract', () => { - it('boots the worker from app.asar in PR checks', () => { - const workflow = parse(readFileSync('.github/workflows/pr.yml', 'utf8')) - const smokeSource = readFileSync( - 'config/scripts/smoke-packaged-hang-watchdog-worker.mjs', - 'utf8' - ) - const smokeStep = workflow.jobs.package.steps.find( - (step) => step.name === 'Smoke packaged hang watchdog worker' - ) - - expect(smokeStep.run).toBe( - 'xvfb-run --auto-servernum node config/scripts/smoke-packaged-hang-watchdog-worker.mjs --app-dir=dist/linux-unpacked' - ) - expect(smokeSource).toContain( - "process.platform === 'linux' ? ['--no-sandbox', launcherDir] : [launcherDir]" - ) - expect(smokeSource).toContain('const LAUNCH_TIMEOUT_MS = 30_000') - expect(smokeSource).toContain('timeout: LAUNCH_TIMEOUT_MS') - }) - - // Why: Electron ignores process.exitCode, so the gate needs app.exit plus a stdout assertion. - it('fails the smoke when the packaged worker never reports success', () => { - const smokeSource = readFileSync( - 'config/scripts/smoke-packaged-hang-watchdog-worker.mjs', - 'utf8' - ) - - expect(smokeSource).toContain('app.exit(1)') - expect(smokeSource).not.toContain('app.quit()') - expect(smokeSource).toContain('if (!result.stdout.includes(SUCCESS_LINE))') - }) -}) diff --git a/config/scripts/pr-workflow-lint-parity.test.mjs b/config/scripts/pr-workflow-lint-parity.test.mjs deleted file mode 100644 index 648714f244c..00000000000 --- a/config/scripts/pr-workflow-lint-parity.test.mjs +++ /dev/null @@ -1,86 +0,0 @@ -import { readFileSync } from 'node:fs' -import { parse } from 'yaml' -import { describe, expect, it } from 'vitest' - -// Why: pr.yml re-lists the `lint` chain as individual steps so a single failure -// does not mask the rest and oxlint keeps its `--format github` annotations. -// Hand-maintained mirrors drift (#10601: three verifiers never ran on PRs), so -// this gate fails the moment a `lint` step has no counterpart in pr.yml. - -// Flags that only change reporting, so they must not split two otherwise identical commands. -const REPORTING_FLAGS_WITH_VALUE = new Set(['--format', '--reporter']) -const REPORTING_FLAGS = new Set(['--quiet']) -const PACKAGE_RUNNER_TOKENS = new Set(['pnpm', 'npm', 'yarn', 'npx', 'run', 'exec', 'node']) - -function splitCommandChain(command) { - return command - .split(/\n|&&|;/) - .map((part) => part.trim()) - .filter(Boolean) -} - -function canonicalize(command) { - const tokens = command.split(/\s+/) - const canonical = [] - - for (let index = 0; index < tokens.length; index += 1) { - const token = tokens[index] - if (canonical.length === 0 && PACKAGE_RUNNER_TOKENS.has(token)) { - continue - } - if (REPORTING_FLAGS.has(token)) { - continue - } - if (REPORTING_FLAGS_WITH_VALUE.has(token)) { - index += 1 - continue - } - canonical.push(token) - } - - return canonical.join(' ') -} - -/** Expands `pnpm run x` indirection until every entry is a real binary invocation. */ -function resolveLeafCommands(command, scripts, seen = new Set()) { - const leaves = [] - - for (const part of splitCommandChain(command)) { - const scriptName = part.match(/^(?:pnpm|npm|yarn)(?:\s+run)?\s+([\w:-]+)$/)?.[1] - if (scriptName && scripts[scriptName] && !seen.has(scriptName)) { - leaves.push( - ...resolveLeafCommands(scripts[scriptName], scripts, new Set([...seen, scriptName])) - ) - continue - } - leaves.push(canonicalize(part)) - } - - return leaves -} - -describe('PR workflow lint parity', () => { - it('runs every `pnpm lint` step on pull requests', () => { - const { scripts } = JSON.parse(readFileSync('package.json', 'utf8')) - const workflow = parse(readFileSync('.github/workflows/pr.yml', 'utf8')) - - // Scan every job: which one hosts the lint steps is an organizational - // detail that has already been renamed once (verify -> static_analysis). - const workflowCommands = new Set( - Object.values(workflow.jobs) - .flatMap((job) => job.steps ?? []) - .filter((step) => typeof step.run === 'string') - .flatMap((step) => resolveLeafCommands(step.run, scripts)) - ) - - const missing = resolveLeafCommands(scripts.lint, scripts).filter( - (leaf) => !workflowCommands.has(leaf) - ) - - expect( - missing, - `.github/workflows/pr.yml is missing lint steps: ${missing.join(', ')}. ` + - 'Add a step for each one so PR CI matches `pnpm lint`.' - ).toEqual([]) - }) -}) diff --git a/config/scripts/ssh-docker-ci-sharding.test.mjs b/config/scripts/ssh-docker-ci-sharding.test.mjs index c3b015727d6..403c059e92c 100644 --- a/config/scripts/ssh-docker-ci-sharding.test.mjs +++ b/config/scripts/ssh-docker-ci-sharding.test.mjs @@ -37,26 +37,6 @@ it('gives every removed SSH spec a dedicated owner even for test-only edits', () ]) }) -it('runs all four isolated shards and the special SSH suites exactly once', () => { - expect(job.strategy.matrix.shard).toEqual([1, 2, 3, 4]) - expect(job.strategy['fail-fast']).toBe(false) - const remaining = job.steps.find((step) => step.name === 'Run remaining Docker SSH E2E') - expect(remaining.run).toContain('pnpm run test:e2e:ssh-docker --shard=${{ matrix.shard }}/4') - expect(remaining.if).toBe('always()') - expect(remaining['continue-on-error']).toBeUndefined() - expect(readRunner(runners[0])).toContain("'--workers=1'") - expect(job.steps.find((step) => step.name === 'Run Docker SSH watcher isolation E2E').if).toBe( - 'matrix.shard == 1' - ) - expect( - job.steps.find( - (step) => step.name === 'Run Docker SSH terminal parking + startup readiness E2E' - ).if - ).toBe('always() && matrix.shard == 1') - const upload = job.steps.find((step) => step.uses === 'actions/upload-artifact@v7') - expect(upload.with.name).toContain('${{ matrix.shard }}') -}) - it('native Playwright shards preserve every SSH test and project exactly once', async () => { const cli = join(dirname(require.resolve('playwright/package.json')), 'cli.js') const env = { diff --git a/config/scripts/terminal-ime-e2e-workflow.test.mjs b/config/scripts/terminal-ime-e2e-workflow.test.mjs index 162a6d08ace..cb12839a2af 100644 --- a/config/scripts/terminal-ime-e2e-workflow.test.mjs +++ b/config/scripts/terminal-ime-e2e-workflow.test.mjs @@ -45,29 +45,6 @@ describe('terminal IME e2e workflow', () => { expect(nativeIndex).toBeGreaterThan(deterministicIndex) }) - it('keeps IBus lifecycle scoped to owned processes', () => { - const runner = readFileSync( - join(projectDir, 'config/scripts/run-terminal-ibus-hangul-e2e.mjs'), - 'utf8' - ) - - expect(runner).toContain( - "['--xim', '--verbose', '--panel=disable', '--emoji-extension=disable']" - ) - expect(runner).toContain("spawn('xfwm4', ['--compositor=off']") - expect(runner).toContain("['initial-input-mode', 'hangul']") - expect(runner).toContain("['hangul-keyboard', '2']") - expect(runner).toContain("process.kill(-processGroupId, 'SIGTERM')") - expect(runner).toContain("process.kill(-processGroupId, 'SIGKILL')") - expect(runner).toContain('const killDeadline = Date.now() + processKillTimeoutMs') - expect(runner).toMatch( - /'test:e2e:headful',\s*'--workers=1',\s*'tests\/e2e\/terminal-ibus-hangul-native\.spec\.ts'/ - ) - expect(runner).not.toContain("'--replace'") - expect(runner).not.toContain('killall') - expect(runner).not.toContain('pkill') - }) - it('runs native Wayland independently with CJK fonts and retained evidence', () => { const job = workflow.jobs['linux-wayland'] expect(job.needs).toBeUndefined() @@ -82,13 +59,4 @@ describe('terminal IME e2e workflow', () => { expect(upload.if).toBe('always()') expect(upload.with.name).toBe('terminal-wayland-ime-evidence') }) - - it('bounds blocking native input commands', () => { - const nativeSpec = readFileSync( - join(projectDir, 'tests/e2e/terminal-ibus-hangul-native.spec.ts'), - 'utf8' - ) - - expect(nativeSpec.match(/timeout: NATIVE_COMMAND_TIMEOUT_MS/g)).toHaveLength(3) - }) }) diff --git a/config/scripts/verify-dev-channel-packaging.test.mjs b/config/scripts/verify-dev-channel-packaging.test.mjs index dfde5d461d2..ceef8f76174 100644 --- a/config/scripts/verify-dev-channel-packaging.test.mjs +++ b/config/scripts/verify-dev-channel-packaging.test.mjs @@ -53,19 +53,6 @@ describe('electron-builder dev-channel identity', () => { expect(config.win.verifyUpdateCodeSignature).toBe(false) }) - // Why on every channel: the hook is the only handle electron-builder gives on - // the NSIS uninstaller, and it signs nothing — it relays the file to and from - // the CI SignPath request. Carrying it must not drag a publisherName onto a - // dev build, which is the failure the split above exists to prevent. - it('carries the uninstaller sign hook without changing publisherName semantics', () => { - for (const env of [{}, WIN_ADHOC_ENV]) { - const config = loadConfigWithEnv(env) - expect(typeof config.win.signtoolOptions.sign).toBe('function') - } - expect(loadConfigWithEnv({}).win.signtoolOptions.publisherName).toBe('SignPath Foundation') - expect(loadConfigWithEnv(WIN_ADHOC_ENV).win.signtoolOptions.publisherName).toBeUndefined() - }) - it.each([ ['hourly', { ORCA_WIN_HOURLY: '1' }, 'orca-hourly'], ['daily', { ORCA_WIN_DAILY: '1' }, 'orca-daily'], diff --git a/config/scripts/win-crash-survival-e2e.test.mjs b/config/scripts/win-crash-survival-e2e.test.mjs index 40a2e1bb483..9c772eb01eb 100644 --- a/config/scripts/win-crash-survival-e2e.test.mjs +++ b/config/scripts/win-crash-survival-e2e.test.mjs @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { describe, expect, it, vi } from 'vitest' import { parseArgs } from '../../tests/tools/win-crash-survival-e2e/cli-args.mjs' import { buildCrashAssertions } from '../../tests/tools/win-crash-survival-e2e/crash-assertions.mjs' @@ -13,26 +12,6 @@ import { closeApp, resolveElectronMainPid } from '../../tests/tools/win-update-e import { isPidAlive } from '../../tests/tools/win-update-e2e/daemon-processes.mjs' describe('win-crash-survival-e2e proof contracts', () => { - it('keeps the packaged proof manually dispatchable without a PR trigger', () => { - const workflow = readFileSync('.github/workflows/win-crash-survival-e2e.yml', 'utf8') - expect(workflow).not.toMatch(/^ pull_request:/m) - expect(workflow).toMatch(/^ workflow_dispatch:/m) - expect(workflow).not.toMatch(/^ push:/m) - expect(workflow).toContain('--expect "$env:EXPECT"') - expect(workflow).toContain('exit $LASTEXITCODE') - expect(workflow).toContain("'!config/**/*.test.*'") - expect(workflow).toContain("'!src/**/*.test.*'") - expect(workflow).toContain("'!src/**/*.bench.*'") - expect(workflow).toContain("'!config/reliability-gates.jsonc'") - expect(workflow).toContain("'resources/**'") - expect(workflow).toContain('cache: pnpm') - expect(workflow.indexOf('- name: Setup Node.js')).toBeGreaterThan( - workflow.indexOf('- name: Setup pnpm') - ) - expect(workflow).toContain("if: steps.cache-installer.outputs.cache-hit != 'true'") - expect(workflow).toContain('crash-survival-electron-builder-') - }) - it('requires the full survival oracle, including daemon identity and reattach', () => { const base = { profile: 'survival', @@ -58,15 +37,6 @@ describe('win-crash-survival-e2e proof contracts', () => { ).toBe(false) }) - it('scans for FailFast only after the post-crash input probe', () => { - const harness = readFileSync('tests/tools/win-crash-survival-e2e/run.mjs', 'utf8') - const scanIndex = harness.indexOf('const { events: failFastEvents }') - const probeIndex = harness.indexOf('reattachProven = await proveReattachedShell') - expect(scanIndex).not.toBe(-1) - expect(probeIndex).not.toBe(-1) - expect(scanIndex).toBeGreaterThan(probeIndex) - }) - it('fails closed when the Windows event log query fails', () => { let command = '' expect(() => @@ -162,11 +132,7 @@ describe('win-crash-survival-e2e proof contracts', () => { expect(reattachSentinelMatches('1660|canary|extra', 'canary', 1660)).toBe(false) }) - it('requires the real packaged main for the crash proof but permits fallback cleanup', async () => { - const harness = readFileSync('tests/tools/win-crash-survival-e2e/run.mjs', 'utf8') - expect(harness).toContain( - 'resolveElectronMainPid(session.app, { allowLauncherFallback: false })' - ) + it('resolves the real packaged main but permits fallback cleanup', async () => { expect( await resolveElectronMainPid({ evaluate: async () => 222, diff --git a/config/scripts/windows-process-tree-gyp-path.test.mjs b/config/scripts/windows-process-tree-gyp-path.test.mjs index f1d3742e583..0f8a651e12f 100644 --- a/config/scripts/windows-process-tree-gyp-path.test.mjs +++ b/config/scripts/windows-process-tree-gyp-path.test.mjs @@ -1,43 +1,13 @@ import { execFileSync } from 'node:child_process' -import { existsSync, readFileSync } from 'node:fs' +import { existsSync } from 'node:fs' import { isAbsolute, join, resolve } from 'node:path' import { describe, expect, it } from 'vitest' const projectDir = resolve(import.meta.dirname, '../..') -const PATCH = readFileSync( - join(projectDir, 'config/patches/@vscode__windows-process-tree@0.8.0.patch'), - 'utf8' -) const PACKAGE_DIR = join(projectDir, 'node_modules', '@vscode', 'windows-process-tree') const RESOLVED_GYP = "require.resolve('node-addon-api/node_addon_api.gyp')" describe('windows-process-tree node-addon-api gyp path', () => { - it('stages headers without a pnpm-sensitive gyp dependency', () => { - expect(PATCH).not.toContain('+ "../../node-addon-api') - expect(PATCH).toContain('+ "include_dirs": ["deps/node-addon-api"],') - expect(PATCH).toContain('+ "defines": ["NAPI_CPP_EXCEPTIONS", "_HAS_EXCEPTIONS=1"],') - const buildScript = readFileSync( - join(projectDir, 'config/scripts/build-windows-process-tree-relay-addon.mjs'), - 'utf8' - ) - expect(buildScript).toContain('stageWindowsProcessTreeNodeAddonApiHeaders(PACKAGE_DIR)') - expect(buildScript).toContain('Repaired un-applied pnpm patch hunks before build.') - const rebuildHelper = readFileSync( - join(projectDir, 'config/scripts/windows-process-tree-gyp-rebuild.mjs'), - 'utf8' - ) - expect(rebuildHelper).toContain("createRequire(join(packageDir, 'package.json'))") - expect(rebuildHelper).toContain("resolve('node-addon-api/package.json')") - expect(rebuildHelper).toContain("'napi.h'") - expect(rebuildHelper).toContain("'napi-inl.h'") - expect(rebuildHelper).toContain("'napi-inl.deprecated.h'") - const rebuildScript = readFileSync( - join(projectDir, 'config/scripts/rebuild-native-deps.mjs'), - 'utf8' - ) - expect(rebuildScript).toContain('stageWindowsProcessTreeNodeAddonApiHeaders()') - }) - // The installed Windows dependency is exercised by the Windows CI lane. it.runIf(process.platform === 'win32')( 'resolves node_addon_api.gyp to a real file from the package directory', diff --git a/config/scripts/windows-pty-native-capability-workflow.test.mjs b/config/scripts/windows-pty-native-capability-workflow.test.mjs deleted file mode 100644 index e7b18363aeb..00000000000 --- a/config/scripts/windows-pty-native-capability-workflow.test.mjs +++ /dev/null @@ -1,87 +0,0 @@ -import { readFileSync } from 'node:fs' -import { describe, expect, it } from 'vitest' -import { parse } from 'yaml' - -const workflow = parse(readFileSync('.github/workflows/pr.yml', 'utf8')) -const packageJson = JSON.parse(readFileSync('package.json', 'utf8')) - -describe('packaged Windows PTY native capability routing', () => { - it('runs the packaged executable immediately after the unpacked app is built', () => { - const job = workflow.jobs.package_windows - const packageIndex = job.steps.findIndex((step) => step.name === 'Package unpacked app') - const smokeIndex = job.steps.findIndex( - (step) => step.name === 'Smoke packaged Windows PTY native capability' - ) - const smoke = job.steps[smokeIndex] - - expect(job['runs-on']).toBe('windows-2022') - expect(smokeIndex).toBe(packageIndex + 1) - expect(smoke.run).toBe( - 'pnpm run smoke:windows-pty-native-capability -- --exe=dist/win-unpacked/Orca.exe' - ) - expect(smoke.if).toBeUndefined() - expect(smoke['continue-on-error']).toBeUndefined() - expect(packageJson.scripts['smoke:windows-pty-native-capability']).toBe( - 'node tests/tools/windows-pty-native-capability-smoke/run.mjs' - ) - }) - - it('keeps patched source rebuild, release build, runtime reuse, and aggregate routing intact', () => { - const job = workflow.jobs.package_windows - const install = job.steps.find( - (step) => step.uses === './.github/actions/install-node-dependencies' - ) - const nodeCacheSave = job.steps.find( - (step) => step.name === 'Save compiled Node native modules' - ) - const electronCache = job.steps.find( - (step) => step.name === 'Restore compiled Electron native modules' - ) - const build = job.steps.find((step) => step.name === 'Build package inputs') - const prepare = job.steps.find((step) => step.name === 'Prepare Electron native runtime') - const packageStep = job.steps.find((step) => step.name === 'Package unpacked app') - const verify = workflow.jobs.verify.steps.find( - (step) => step.name === 'Require successful checks' - ) - const ensureNativeRuntime = readFileSync('config/scripts/ensure-native-runtime.mjs', 'utf8') - - expect(install.with['native-runtime']).toBe('node') - expect(install.with['persist-native-cache']).toBe('false') - expect(nodeCacheSave.uses).toBe('actions/cache/save@v5') - expect(nodeCacheSave.with.key).toContain('-node-node') - expect(electronCache.with.key).toContain('-electron-node') - for (const cache of [nodeCacheSave, electronCache]) { - expect(cache.with.key).toContain('.github/actions/install-node-dependencies/action.yml') - expect(cache.with.key).toContain('config/scripts/ensure-native-runtime.mjs') - expect(cache.with.key).toContain('config/scripts/rebuild-native-deps.mjs') - } - expect(ensureNativeRuntime).toContain("runPnpm(['exec', 'node-gyp', 'rebuild']") - expect(ensureNativeRuntime).toContain("resolve(moduleDir, 'scripts', 'post-install.js')") - expect(build.run).toBe('pnpm run build:release:parallel') - expect(prepare.run).toBe('node config/scripts/ensure-native-runtime.mjs --runtime=electron') - expect(packageStep.env.ORCA_REUSE_PREPARED_NATIVE_RUNTIME).toBe('1') - expect(workflow.jobs.verify.needs).toContain('package_windows') - expect(verify.env.PACKAGE_WINDOWS).toBe('${{ needs.package_windows.result }}') - expect(verify.run).toContain('"$PACKAGE_WINDOWS"') - }) - - it('keeps the native probe event-based, scoped, and runnable in packaged Node mode', () => { - const driver = readFileSync('tests/tools/windows-pty-native-capability-smoke/run.mjs', 'utf8') - const probe = readFileSync( - 'tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.cjs', - 'utf8' - ) - const source = `${driver}\n${probe}` - - expect(driver).toContain("ELECTRON_RUN_AS_NODE: '1'") - expect(source).not.toMatch(/\b(?:sleep|tasklist|taskkill)\b/i) - expect(source).not.toContain('maxRetries') - expect(source).not.toContain('retryDelay') - expect(source).not.toContain("from 'node:child_process'") - expect(source).not.toContain("require('node:child_process')") - expect(probe).toContain("'System32', 'wscript.exe'") - expect(probe).toContain('real-orca-detached-launcher.vbs') - expect(probe).not.toMatch(/cmd\.exe|start "" \/b/i) - expect(probe).toContain('native.terminateJob(target._pty, target.pid)') - }) -}) diff --git a/config/scripts/windows-signing-workflow-contract.test.mjs b/config/scripts/windows-signing-workflow-contract.test.mjs deleted file mode 100644 index 98d0d5e8e88..00000000000 --- a/config/scripts/windows-signing-workflow-contract.test.mjs +++ /dev/null @@ -1,498 +0,0 @@ -import { readFileSync } from 'node:fs' -import { createRequire } from 'node:module' -import { join, resolve } from 'node:path' -import { describe, expect, it } from 'vitest' -import { parse } from 'yaml' - -const projectDir = resolve(import.meta.dirname, '../..') - -const readWorkflow = (relativePath) => parse(readFileSync(join(projectDir, relativePath), 'utf8')) - -describe('Windows signing workflow contract', () => { - it('preflights SignPath module install before Windows signing side effects', () => { - const parsedWorkflow = readWorkflow('.github/workflows/release-cut.yml') - const steps = parsedWorkflow.jobs.build.steps - const stepNames = steps.map((step) => step.name) - const installStepIndexes = stepNames.flatMap((name, index) => - name === 'Install SignPath PowerShell module' ? [index] : [] - ) - const buildIndex = stepNames.indexOf('Build Windows release artifacts') - const verifyNodePtyIndex = stepNames.indexOf('Verify Windows node-pty ConPTY runtime') - const uploadIndex = stepNames.indexOf('Upload unsigned Windows installer for SignPath') - const downloadIndex = stepNames.indexOf('Download signed Windows installer from SignPath') - - expect(verifyNodePtyIndex).toBe(buildIndex + 1) - expect(installStepIndexes).toEqual([verifyNodePtyIndex + 1]) - expect(installStepIndexes[0]).toBeLessThan(uploadIndex) - - expect(steps[verifyNodePtyIndex].run).toContain( - 'dist/win-unpacked/resources/node_modules/node-pty/build/Release' - ) - expect(steps[verifyNodePtyIndex].run).toContain('conpty/conpty.dll') - - const uploadThroughDownloadScript = steps - .slice(uploadIndex, downloadIndex + 1) - .map((step) => step.run ?? '') - .join('\n') - - expect(uploadThroughDownloadScript).not.toContain('Install-Module -Name SignPath') - - const installStep = steps[installStepIndexes[0]] - - expect(installStep.if).toBe("matrix.platform == 'win' && github.run_attempt == 1") - expect(installStep.uses).toBe('./.github/actions/install-signpath-module') - expect(installStep.run).toBeUndefined() - - const installAction = readWorkflow('.github/actions/install-signpath-module/action.yml') - const actionStep = installAction.runs.steps[0] - const installRun = actionStep.run - const sleepSeconds = [...installRun.matchAll(/Start-Sleep -Seconds (\d+)/g)].map( - ([, seconds]) => seconds - ) - - expect(installAction.runs.using).toBe('composite') - expect(actionStep.shell).toBe('pwsh') - expect(installRun).toContain( - 'if ($null -eq (Get-PSRepository -Name PSGallery -ErrorAction SilentlyContinue))' - ) - expect(installRun).toContain('Register-PSRepository -Default -InstallationPolicy Trusted') - expect(installRun).toContain('Set-PSRepository -Name PSGallery -InstallationPolicy Trusted') - expect(installRun).toMatch(/\$env:PSModulePath -split \[System\.IO\.Path\]::PathSeparator/) - expect(installRun).toContain( - "$signPathModulePath = Join-Path -Path $currentUserModuleRoot -ChildPath 'SignPath'" - ) - expect(installRun).toMatch(/for \(\$attempt = 1; \$attempt -le 3; \$attempt\+\+\)/) - expect(sleepSeconds).toContain('15') - expect(sleepSeconds).toContain('30') - expect(installRun).toContain( - 'Install-Module -Name SignPath -Repository PSGallery -MinimumVersion 4.0.0 -MaximumVersion 4.999.999 -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop' - ) - expect(installRun).toContain('Import-Module SignPath -ErrorAction Stop') - expect(installRun).toContain( - 'Get-Command -Name Get-SignedArtifact -Module SignPath -ErrorAction Stop' - ) - expect(installRun).toContain('Remove-Item -LiteralPath $signPathModulePath -Recurse -Force') - expect(installRun).not.toContain('SignPath*') - expect(installRun).not.toMatch(/throw\s+\$_/) - }) - - it('falls back to a hash-pinned SignPath nupkg when the gallery API is down', () => { - const installAction = readWorkflow('.github/actions/install-signpath-module/action.yml') - const installRun = installAction.runs.steps[0].run - - // Why: the gallery API 403s during Azure Front Door incidents while its CDN - // stays up, so a pinned nupkg is the fallback. The hash pin is the only - // integrity check on that route — losing it would let any payload install. - const { 'fallback-version': version, 'fallback-sha256': sha256 } = installAction.inputs - expect(version.default).toMatch(/^4\.\d+\.\d+$/) - expect(sha256.default).toMatch(/^[0-9a-f]{64}$/) - expect(installRun).toContain('Get-FileHash -LiteralPath $nupkg -Algorithm SHA256') - expect(installRun).toContain('$actualHash -ne $expectedHash.ToUpperInvariant()') - expect(installRun).toContain('throw "SHA-256 mismatch for $source') - expect(installRun).toContain( - 'https://cdn.powershellgallery.com/packages/signpath.$version.nupkg' - ) - - // The module only resolves by name when the folder matches its ModuleVersion. - expect(installRun).toContain( - '$versionRoot = Join-Path -Path $signPathModulePath -ChildPath $version' - ) - // The fallback only runs after the gallery route is exhausted, and still - // fails the job when neither route produced a usable module. - expect(installRun.indexOf('$installed = $true')).toBeLessThan( - installRun.indexOf('if (-not $installed)') - ) - expect(installRun).toContain('throw "Unable to install the SignPath PowerShell module') - }) - - it('still installs SignPath when the cut ref predates the composite action', () => { - const parsedWorkflow = readWorkflow('.github/workflows/release-cut.yml') - const steps = parsedWorkflow.jobs.build.steps - const stepNames = steps.map((step) => step.name) - const checkoutIndex = stepNames.indexOf('Checkout') - const restoreIndex = stepNames.indexOf('Restore composite actions from the workflow ref') - const installIndex = stepNames.indexOf('Install SignPath PowerShell module') - - // Why: the build job checks out the cut tag, which for a hotfix cut from an - // older ref can predate `.github/actions/install-signpath-module`; without - // this restore the `uses: ./…` step dies on a missing action.yml. - expect(restoreIndex).toBeGreaterThan(checkoutIndex) - expect(restoreIndex).toBeLessThan(installIndex) - - const restoreStep = steps[restoreIndex] - const restoreRun = restoreStep.run - - expect(restoreStep.env.WORKFLOW_SHA).toBe('${{ github.workflow_sha }}') - expect(restoreRun).toContain('.github/actions/install-signpath-module/action.yml') - expect(restoreRun).toContain('git fetch --no-tags --depth=1 origin "$WORKFLOW_SHA"') - expect(restoreRun).toContain('git checkout "$WORKFLOW_SHA" -- .github/actions') - - // Why: restoring the action must not turn signing into a soft dependency — - // a missing module still has to fail the Windows job, and the CDN fallback - // still has to reject an unexpected payload. - expect(steps[installIndex]['continue-on-error']).toBeUndefined() - expect(restoreStep['continue-on-error']).toBeUndefined() - - const installRun = readWorkflow('.github/actions/install-signpath-module/action.yml').runs - .steps[0].run - - expect(installRun).toContain('$actualHash -ne $expectedHash.ToUpperInvariant()') - expect(installRun).toContain('throw "SHA-256 mismatch for $source') - }) - - it('never recreates Windows signing requests on a workflow rerun', () => { - const parsedWorkflow = readWorkflow('.github/workflows/release-cut.yml') - const steps = parsedWorkflow.jobs.build.steps - const stepNames = steps.map((step) => step.name) - const skipStep = steps.find((step) => step.name === 'Skip Windows artifact rebuild on rerun') - - expect(skipStep?.if).toBe("matrix.platform == 'win' && github.run_attempt != 1") - expect(skipStep?.run).toContain('Existing signed release assets must be reused') - - const signingStepNames = [ - 'Build Windows release artifacts', - 'Stage unsigned inner PE files for signing', - 'Upload unsigned inner binaries for SignPath', - 'Submit inner binaries signing request', - 'Download signed inner binaries from SignPath', - 'Upload unsigned Windows installer for SignPath', - 'Submit Windows installer signing request', - 'Download signed Windows installer from SignPath', - 'Stage signed Windows release assets', - 'Publish signed Windows release artifacts' - ] - - for (const stepName of signingStepNames) { - const step = steps[stepNames.indexOf(stepName)] - expect(step?.if, stepName).toContain('github.run_attempt == 1') - } - }) - - it('shares one SignPath module install path between release and rehearsal', () => { - const rehearsalWorkflow = readWorkflow('.github/workflows/windows-signing-rehearsal.yml') - const stepNames = rehearsalWorkflow.jobs.rehearse.steps.map((step) => step.name) - const installIndex = stepNames.indexOf('Install SignPath PowerShell module') - - // Why: the rehearsal exists to prove the real signing flow, so it must - // install the module exactly the way the release job does. - expect(rehearsalWorkflow.jobs.rehearse.steps[installIndex].uses).toBe( - './.github/actions/install-signpath-module' - ) - expect(rehearsalWorkflow.jobs.rehearse.steps[installIndex].run).toBeUndefined() - expect(installIndex).toBeLessThan( - stepNames.indexOf('Download signed inner binaries from SignPath') - ) - }) - - it('requires Windows inner binary signatures before publishing', () => { - const parsedWorkflow = readWorkflow('.github/workflows/release-cut.yml') - const steps = parsedWorkflow.jobs.build.steps - const stepNames = steps.map((step) => step.name) - const outerVerifyIndex = stepNames.indexOf('Verify signed Windows installer') - const innerVerifyIndex = stepNames.indexOf('Verify Windows inner binary signatures') - const evidenceIndex = stepNames.indexOf('Upload Windows inner signing evidence') - const publishIndex = stepNames.indexOf('Publish signed Windows release artifacts') - - expect(outerVerifyIndex).toBeGreaterThan(-1) - expect(innerVerifyIndex).toBe(outerVerifyIndex + 1) - expect(stepNames[innerVerifyIndex + 1]).toBe('Notify Slack when Windows signing fails') - expect(evidenceIndex).toBe(innerVerifyIndex + 2) - expect(publishIndex).toBe(evidenceIndex + 1) - - expect(steps[innerVerifyIndex].env.ORCA_WINDOWS_INNER_SIGNATURE_REQUIRED).toBe('true') - expect(steps[innerVerifyIndex].run).toContain("@('Orca.exe', 'resources\\bin\\orca.exe')") - expect(stepNames).not.toContain('Roll back to original installer after failed rebuild') - - const innerChainStepNames = [ - 'Stage unsigned inner PE files for signing', - 'Upload unsigned inner binaries for SignPath', - 'Submit inner binaries signing request', - 'Download signed inner binaries from SignPath', - 'Restore signed inner binaries into unpacked app', - 'Restore signed uninstaller for the installer rebuild', - 'Replace cached elevate.exe with the signed copy', - 'Rebuild NSIS installer from signed unpacked app' - ] - for (const stepName of innerChainStepNames) { - const step = steps[stepNames.indexOf(stepName)] - expect(step, stepName).toBeDefined() - expect(step['continue-on-error'], stepName).toBeUndefined() - } - }) -}) - -// Why these exist: the NSIS uninstaller is generated inside electron-builder's -// uninstaller pass and deleted immediately after being embedded, so the only way -// CI can sign it is the export/import relay through win.signtoolOptions.sign. -// Every link is asserted here the way Orca.exe and conpty_console_list.node are. -describe('Windows NSIS uninstaller signing', () => { - const releaseSteps = () => readWorkflow('.github/workflows/release-cut.yml').jobs.build.steps - const stepNamed = (steps, name) => steps.find((step) => step.name === name) - - const EXPORT_ENV = 'ORCA_WIN_UNINSTALLER_EXPORT_PATH' - const SIGNED_ENV = 'ORCA_WIN_UNINSTALLER_SIGNED_PATH' - - it('exports the uninstaller from the first Windows build', () => { - const build = stepNamed(releaseSteps(), 'Build Windows release artifacts') - - expect(build.env[EXPORT_ENV]).toContain('uninstaller-signing') - expect(build.env[EXPORT_ENV]).toContain('orca-uninstaller.exe') - }) - - // Why this is a test and not a comment: `files` in the electron-builder config - // is all-negation, so app-builder packs whatever is left in the checkout root. - // These steps retry, and a retried attempt would pack an unsigned .exe into - // app.asar — the very defect this chain removes. Every relay path must live - // outside the checkout. - it('keeps every relay path out of the packed checkout', () => { - const relayEnvValues = [ - ...releaseSteps(), - ...readWorkflow('.github/workflows/windows-signing-rehearsal.yml').jobs.rehearse.steps - ].flatMap((step) => [step.env?.[EXPORT_ENV], step.env?.[SIGNED_ENV]].filter(Boolean)) - - expect(relayEnvValues.length).toBe(4) - for (const value of relayEnvValues) { - expect(value).toContain('runner.temp') - expect(value).not.toContain('github.workspace') - } - - const relayScripts = [ - ...releaseSteps(), - ...readWorkflow('.github/workflows/windows-signing-rehearsal.yml').jobs.rehearse.steps - ] - .map((step) => step.run ?? '') - .filter((run) => run.includes('uninstaller-signing')) - - expect(relayScripts.length).toBeGreaterThan(0) - for (const run of relayScripts) { - // Why count occurrences rather than assert `toContain` once: a step - // carrying two relay paths could root the first in RUNNER_TEMP and leave - // the second bare-relative — which resolves against the checkout, and is - // exactly the shape of the defect this test exists to catch. - const mentions = run.match(/uninstaller-signing/g) ?? [] - const rooted = run.match(/Join-Path \$env:RUNNER_TEMP 'uninstaller-signing/g) ?? [] - - expect(rooted.length, run).toBe(mentions.length) - expect(run).not.toContain('$env:GITHUB_WORKSPACE') - } - }) - - it('stages the uninstaller into the same request as the inner binaries', () => { - const stage = stepNamed(releaseSteps(), 'Stage unsigned inner PE files for signing') - - expect(stage.run).toContain('uninstaller-signing\\unsigned\\orca-uninstaller.exe') - expect(stage.run).toContain('uninstaller\\orca-uninstaller.exe') - // No third SignPath request: exactly two submissions, as budgeted for the - // 1h + 4h approval waits inside the 360-minute job cap. - const submissions = releaseSteps().filter( - (step) => step.uses === 'signpath/github-action-submit-signing-request@v2' - ) - expect(submissions).toHaveLength(2) - }) - - it('keeps the uninstaller out of the inner-binary copy-back list', () => { - const stage = stepNamed(releaseSteps(), 'Stage unsigned inner PE files for signing') - const restoreInner = stepNamed( - releaseSteps(), - 'Restore signed inner binaries into unpacked app' - ) - - expect(stage.run).not.toMatch(/\$list\.Add\(['"]uninstaller/) - expect(restoreInner.run).not.toContain('orca-uninstaller.exe') - }) - - it('blocks publication when the exported uninstaller is missing', () => { - const stage = stepNamed(releaseSteps(), 'Stage unsigned inner PE files for signing') - const uninstallerBlock = stage.run.slice(stage.run.indexOf('$exportedUninstaller')) - - expect(uninstallerBlock).toContain('throw "No exported NSIS uninstaller') - expect(uninstallerBlock).not.toContain('catch') - expect(uninstallerBlock).toMatch(/Copy-Item[^\r\n]*-ErrorAction Stop/) - }) - - it('restores exact artifact paths rather than suffix-matching another executable', () => { - for (const [name, path] of [ - ['Restore signed inner binaries into unpacked app', '$relative'], - [ - 'Restore signed uninstaller for the installer rebuild', - "'uninstaller\\orca-uninstaller.exe'" - ] - ]) { - const restore = stepNamed(releaseSteps(), name) - expect(restore.run).toContain(`(Join-Path 'signed-inner' ${path})`) - expect(restore.run).toContain(`(Join-Path 'signed-inner/signing-stage' ${path})`) - expect(restore.run).toContain('if (@($candidates).Count -ne 1)') - expect(restore.run).not.toContain('Select-Object -First 1') - expect(restore.run).not.toContain('-like "*$relative"') - const rehearsal = readWorkflow('.github/workflows/windows-signing-rehearsal.yml') - const rehearseRestore = stepNamed(rehearsal.jobs.rehearse.steps, name) - expect(rehearseRestore.run).toBe(restore.run) - expect(restore.env.SIGNING_POLICY).toBe('release-signing') - expect(rehearseRestore.env.SIGNING_POLICY).toBe( - "${{ inputs.signing-policy-slug || 'test-signing' }}" - ) - expect(restore.run).toContain("$requireValid = $env:SIGNING_POLICY -ne 'test-signing'") - expect(restore.run).toContain( - "if ($null -eq $signature.SignerCertificate -or ($requireValid -and ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notlike '*CN=SignPath Foundation*')))" - ) - } - }) - - it('requires the CLI signature at its electron-builder extraResources destination', () => { - const require = createRequire(import.meta.url) - const config = require('../electron-builder.config.cjs') - const cli = config.win.extraResources.find((resource) => resource.to === 'bin/orca.exe') - expect(cli).toBeDefined() - const payloadPath = `resources/${cli.to}`.replaceAll('/', '\\') - const rehearsal = readWorkflow('.github/workflows/windows-signing-rehearsal.yml') - for (const gate of [ - stepNamed(releaseSteps(), 'Verify Windows inner binary signatures'), - stepNamed(rehearsal.jobs.rehearse.steps, 'Verify signatures end to end') - ]) { - expect(gate.run).toContain(`foreach ($requiredTarget in @('Orca.exe', '${payloadPath}'))`) - expect(gate.run).toContain( - 'if ($targets -notcontains $requiredTarget) { $targets += $requiredTarget }' - ) - expect(gate.run).toContain('foreach ($relative in $targets)') - } - }) - - it('waits for approval even when the notification fails', () => { - const steps = releaseSteps() - const notify = stepNamed( - steps, - 'Notify Slack that inner-binary signing is waiting for approval' - ) - const download = stepNamed(steps, 'Download signed inner binaries from SignPath') - expect(notify['continue-on-error']).toBe(true) - expect(download.if).not.toContain('notify-inner-signing') - expect(download.if).toContain("steps.submit-inner-signing.outcome == 'success'") - }) - - it('re-injects the signed uninstaller into the rebuilt installer', () => { - const steps = releaseSteps() - const restore = stepNamed(steps, 'Restore signed uninstaller for the installer rebuild') - const rebuild = stepNamed(steps, 'Rebuild NSIS installer from signed unpacked app') - const names = steps.map((step) => step.name) - - expect(restore.if).toContain('github.run_attempt == 1') - expect(restore.if).toContain("steps.restore-signed-inner.outcome == 'success'") - expect(restore.run).toContain('orca-uninstaller.exe') - expect(names.indexOf(restore.name)).toBeLessThan(names.indexOf(rebuild.name)) - expect(rebuild.env[SIGNED_ENV]).toContain('uninstaller-signing') - // Default success() gating blocks the rebuild after a failed restore. - expect(rebuild.if).not.toContain('restore-signed-uninstaller') - }) - - // NSIS hides the uninstaller in a compressed data section the bundled 7za - // cannot read, so the gate proves it from the sign hook's digest receipt - // instead of extracting it — and only when the relay actually ran. - it('reports the embedded uninstaller in the inner-binary evidence gate', () => { - const gate = stepNamed(releaseSteps(), 'Verify Windows inner binary signatures') - - expect(gate.env.UNINSTALLER_SIGNING_COMPLETED).toBe( - "${{ steps.restore-signed-uninstaller.outcome == 'success' }}" - ) - expect(gate.run).toContain('.embedded-sha256') - expect(gate.run).toContain("$failures.Add('The NSIS uninstaller signing did not complete.')") - expect(gate.run).toContain("$env:UNINSTALLER_SIGNING_COMPLETED -eq 'true'") - expect(gate.run).toContain('not signed by SignPath Foundation: Uninstall Orca.exe') - // The uninstaller must not join the 7z payload loop, which cannot see it. - expect(gate.run).not.toContain("$targets += 'Uninstall Orca.exe'") - }) - - it('rehearses the uninstaller leg end to end', () => { - const steps = readWorkflow('.github/workflows/windows-signing-rehearsal.yml').jobs.rehearse - .steps - const names = steps.map((step) => step.name) - const pack = stepNamed(steps, 'Package Windows app and export the NSIS uninstaller') - const rebuild = stepNamed(steps, 'Build NSIS installer from signed unpacked app') - const verify = stepNamed(steps, 'Verify signatures end to end') - - // --dir never produces an uninstaller, so the rehearsal has to build the - // installer the way release-cut's first Windows pass does. - expect(pack.run).toContain('--win --publish never') - expect(pack.run).not.toContain('--dir') - expect(pack.env[EXPORT_ENV]).toContain('orca-uninstaller.exe') - expect(names).toContain('Restore signed uninstaller for the installer rebuild') - expect(rebuild.env[SIGNED_ENV]).toContain('orca-uninstaller.exe') - expect(verify.run).toContain('.embedded-sha256') - // The receipt only proves the import leg ran. The rehearsal is where the - // shipped uninstaller itself gets checked — the release job cannot install - // onto the runner it publishes from. - expect(verify.run).toContain('shipped: Uninstall Orca.exe') - expect(verify.run).toContain('-tnsis') - expect(verify.run).toContain("-ArgumentList '/S'") - }) - - // This workflow is the merge gate, so it must not be able to fail on its own - // artefact: 7-Zip's NSIS handler is unreliable enough that its output has to - // be corroborated before a signature verdict is drawn from it. - it('never lets an unreliable extract fail the rehearsal', () => { - const steps = readWorkflow('.github/workflows/windows-signing-rehearsal.yml').jobs.rehearse - .steps - const verify = stepNamed(steps, 'Verify signatures end to end') - - // The 7-Zip route is only trusted when it reproduces the relayed bytes; - // otherwise it falls through to the install route rather than failing. - expect(verify.run).toContain( - 'Write-Host "7-Zip\'s NSIS output did not match the relayed digest; falling back to a silent install."' - ) - expect(verify.run).toMatch(/\$installedUninstaller = \$null\r?\n\s*\}/) - - // The comparison that is not tautological: a file NSIS wrote out, against - // the digest the sign hook recorded. - expect(verify.run).toContain('$shippedDigest -ne $expectedDigest') - expect(verify.run).toContain('the uninstaller the installer ships is not the relayed one') - - // An installer that prompts must not hang to the 360-minute job cap, and - // the app it launches must not outlive the step holding install-dir handles. - expect(verify.run).toContain('-PassThru') - expect(verify.run).toContain('$installerProcess.WaitForExit(300000)') - expect(verify.run).toContain('the silent install did not exit within 5 minutes') - expect(verify.run).toMatch(/for \(\$attempt = 0; \$attempt -lt 20; \$attempt\+\+\)/) - expect(verify.run).toContain("Get-Process -Name 'orca-terminal-daemon'") - }) - - // resources\elevate.exe is downgraded to advisory because app-builder-lib's - // CopyElevateHelper clobbers it on every nsis pack — a pre-existing defect - // that predates the uninstaller relay and is being tracked separately. The - // escape hatch it needed is the kind that quietly grows until the gate - // asserts nothing, so pin it to exactly that one file. - it('confines the advisory escape hatch to elevate.exe', () => { - const steps = readWorkflow('.github/workflows/windows-signing-rehearsal.yml').jobs.rehearse - .steps - const verify = stepNamed(steps, 'Verify signatures end to end') - const advisoryCalls = verify.run - .split('\n') - .filter((line) => line.includes('-Advisory') && line.includes('Test-Signature')) - - expect(advisoryCalls).toHaveLength(1) - expect(advisoryCalls[0]).toContain('installed: $relative') - expect(verify.run).toContain("if ($relative -eq 'resources\\elevate.exe')") - - // Both uninstaller verdicts stay fatal — the whole point of the gate. - for (const call of ['relayed: orca-uninstaller.exe', 'shipped: Uninstall Orca.exe']) { - const line = verify.run - .split('\n') - .find((it) => it.includes(`Test-Signature`) && it.includes(call)) - expect(line, call).toBeDefined() - expect(line, call).not.toContain('-Advisory') - } - - // An advisory must still reach the evidence artifact, or downgrading it - // becomes indistinguishable from deleting the check. - expect(verify.run).toContain('ADVISORY (known pre-existing') - expect(verify.run).toContain('$script:advisories.Add($problem)') - }) - - it('wires the electron-builder sign hook that the relay depends on', () => { - const require = createRequire(import.meta.url) - const configPath = resolve(projectDir, 'config/electron-builder.config.cjs') - delete require.cache[require.resolve(configPath)] - const config = require(configPath) - - expect(typeof config.win.signtoolOptions.sign).toBe('function') - delete require.cache[require.resolve(configPath)] - }) -}) diff --git a/mobile/src/accounts/mobile-accounts-route.test.ts b/mobile/src/accounts/mobile-accounts-route.test.ts index 0b25d44d3f0..2a77c8a2b3a 100644 --- a/mobile/src/accounts/mobile-accounts-route.test.ts +++ b/mobile/src/accounts/mobile-accounts-route.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { describe, expect, it, vi } from 'vitest' import { mobileAccountsRouteTarget } from './mobile-accounts-route' import { @@ -7,12 +6,6 @@ import { type HostStackNavigationState } from '../navigation/host-stack-navigation' -const homeSource = readFileSync(new URL('../home/MobileHomeScreen.tsx', import.meta.url), 'utf8') -const accountCardsSource = readFileSync( - new URL('../home/MobileHomeAccountUsageCards.tsx', import.meta.url), - 'utf8' -) - function navigationHarness(initialState: HostStackNavigationState) { const stateListeners = new Set<() => void>() let state = initialState @@ -85,10 +78,4 @@ describe('mobile accounts route', () => { payload: mobileAccountsRouteTarget('host/one') }) }) - - it('opens the home account-usage card through the cold-navigator-safe transition', () => { - expect(homeSource).toContain('onOpenAccounts={openMobileAccounts}') - expect(accountCardsSource).toContain('props.onOpen(host.id)') - expect(accountCardsSource).not.toContain('/accounts`') - }) }) diff --git a/mobile/src/browser/mobile-browser-pane-source.test.ts b/mobile/src/browser/mobile-browser-pane-source.test.ts deleted file mode 100644 index 69cd5af5391..00000000000 --- a/mobile/src/browser/mobile-browser-pane-source.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { readFileSync } from 'node:fs' -import { describe, expect, it } from 'vitest' - -const source = readFileSync(new URL('./MobileBrowserPane.tsx', import.meta.url), 'utf8') - -function sliceBetween(startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('MobileBrowserPane source invariants', () => { - it('mirrors handler refs in a layout effect instead of during render', () => { - const mirrorBlock = sliceBetween( - 'useLayoutEffect(() => {', - ' useEffect(() => {\n lastZoomResetUrlRef.current' - ) - - expect(mirrorBlock).toContain('frameMetadataRef.current = frameMetadata') - expect(mirrorBlock).toContain('layoutRef.current = layout') - expect(mirrorBlock).toContain('dialogRef.current = dialog') - expect(mirrorBlock).toContain('zoomRef.current = zoom') - expect(mirrorBlock).toContain('}, [dialog, frameMetadata, layout, zoom])') - }) -}) diff --git a/mobile/src/components/mobile-agent-icon-assets.test.ts b/mobile/src/components/mobile-agent-icon-assets.test.ts index f4f6325d806..7020d4b4977 100644 --- a/mobile/src/components/mobile-agent-icon-assets.test.ts +++ b/mobile/src/components/mobile-agent-icon-assets.test.ts @@ -1,4 +1,4 @@ -import { existsSync, readFileSync } from 'node:fs' +import { existsSync } from 'node:fs' import path from 'node:path' import { describe, expect, it } from 'vitest' import type { TuiAgent } from '../../../src/shared/tui-agent' @@ -17,7 +17,6 @@ const GLYPH_AGENT_IDS = new Set([ const dirname = import.meta.dirname const assetsDir = path.resolve(dirname, '../../../src/shared/agent-icons') -const assetsModuleSource = readFileSync(path.join(dirname, 'mobile-agent-icon-assets.ts'), 'utf8') // Why: these agents previously loaded from Google's favicon service, which is // unreachable in some regions/offline (#8451). Every one that lacks a glyph @@ -34,12 +33,4 @@ describe('mobile bundled agent icons', () => { ) } }) - - it('wires every favicon-path agent into the bundled asset map', () => { - for (const id of agentsNeedingBundledIcon) { - expect(assetsModuleSource, `${id} not mapped in mobile-agent-icon-assets.ts`).toContain( - `agent-icons/${id}.png` - ) - } - }) }) diff --git a/mobile/src/files/files-router-seam-census.test.ts b/mobile/src/files/files-router-seam-census.test.ts deleted file mode 100644 index 360b040b2df..00000000000 --- a/mobile/src/files/files-router-seam-census.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - callsRouteHandoff, - importsExpoRouterValue, - parse, - productFiles -} from '../navigation/router-seam-census.test-support' - -const FILES_ROOT = import.meta.dirname - -/** - * Which modules here hold a router, so the census cannot pass by seeing nothing. - * - * The walk and the two rules are the seam's, shared with every other domain that runs them; what - * stays here is this domain's own evidence: which of its modules are meant to hold a router. - */ -const ROUTER_HOLDERS = ['MobileFilePreviewScreen.tsx', 'MobileFileExplorerPanel.tsx'] - -describe('the files domain reaches the router through the handoff seam', () => { - const files = productFiles(FILES_ROOT) - - it('walks the modules it is written against', () => { - expect(files).toEqual(expect.arrayContaining(ROUTER_HOLDERS)) - }) - - it('imports no router from expo-router, which the page cannot hand a route back through', () => { - expect(files.filter((name) => importsExpoRouterValue(parse(FILES_ROOT, name)))).toEqual([]) - }) - - it('takes the router from useRouteHandoff at every screen that holds one', () => { - expect(files.filter((name) => callsRouteHandoff(parse(FILES_ROOT, name))).sort()).toEqual( - [...ROUTER_HOLDERS].sort() - ) - }) -}) diff --git a/mobile/src/home-host-edit-navigation-source.test.ts b/mobile/src/home-host-edit-navigation-source.test.ts deleted file mode 100644 index 617dd030c8a..00000000000 --- a/mobile/src/home-host-edit-navigation-source.test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { readFileSync } from 'node:fs' -import { describe, expect, it } from 'vitest' - -const homeSource = readFileSync(new URL('./home/MobileHomeScreen.tsx', import.meta.url), 'utf8') - -describe('Home host edit navigation wiring', () => { - it('uses the cold-navigator-safe edit transition', () => { - expect(homeSource).toMatch(/const openMobileHostEdit = useOpenMobileHostEdit\(\)/) - expect(homeSource).toMatch(/onEdit:\s*openMobileHostEdit/) - }) -}) diff --git a/mobile/src/hooks/use-mobile-dictation-source.test.ts b/mobile/src/hooks/use-mobile-dictation-source.test.ts deleted file mode 100644 index aedc0543bce..00000000000 --- a/mobile/src/hooks/use-mobile-dictation-source.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { readFileSync } from 'node:fs' -import { describe, expect, it } from 'vitest' - -const source = readFileSync(new URL('./use-mobile-dictation.ts', import.meta.url), 'utf8') -const nativeCaptureSource = readFileSync( - new URL('../platform/dictation-capture.ts', import.meta.url), - 'utf8' -) - -function sliceSource(sourceText: string, startPattern: string, endPattern: string): string { - const start = sourceText.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = sourceText.indexOf(endPattern, start) - expect(end).toBeGreaterThan(start) - return sourceText.slice(start, end) -} - -function sliceBetween(startPattern: string, endPattern: string): string { - return sliceSource(source, startPattern, endPattern) -} - -describe('useMobileDictation source invariants', () => { - it('publishes live option refs from committed renders before passive Effects flush', () => { - const refDeclarations = sliceBetween( - 'const clientRef = useRef(client)', - 'useLayoutEffect(() => {' - ) - expect(refDeclarations).not.toContain('.current =') - - const mirrorEffect = sliceBetween('useLayoutEffect(() => {', 'const reportError =') - expect(mirrorEffect).toContain('clientRef.current = client') - expect(mirrorEffect).toContain('enabledRef.current = enabled') - expect(mirrorEffect).toContain('onTranscriptRef.current = onTranscript') - expect(mirrorEffect).toContain('onErrorRef.current = onError') - expect(mirrorEffect).toContain('}, [client, enabled, onTranscript, onError])') - }) - - it('carries audio the capture dropped into the same refusal the budget raises', () => { - const chunkHandler = sliceBetween('const sub = capture.onChunk(', 'return () => sub.remove()') - expect(chunkHandler).toContain('if (chunk.droppedBytes > 0)') - expect(chunkHandler).toContain('MOBILE_DICTATION_CONNECTION_SLOW_ERROR_MESSAGE') - // Only the page can drop: the seam's native half is where the microphone is. - expect(nativeCaptureSource).toContain('droppedBytes: 0') - }) - - it('resets pending audio bytes whenever pending chunk tracking is cleared', () => { - const pendingChunkClears = source.match(/pendingChunksRef\.current\.clear\(\)/g) ?? [] - const pendingAudioResets = source.match(/pendingAudioBudgetRef\.current\.reset\(\)/g) ?? [] - - expect(pendingAudioResets).toHaveLength(pendingChunkClears.length) - }) - - it('closes the capture on every path that ends a dictation', () => { - const closeAudio = sliceBetween( - 'const closeDictationAudio = useCallback(', - 'const failActiveDictation =' - ) - expect(closeAudio).toContain('capture.end()') - const cleanupSlices = [ - sliceBetween('const failActiveDictation = useCallback(', 'useEffect(() => {'), - sliceBetween('const abandonDictation = useCallback(', 'const cancel ='), - sliceBetween('return () => {\n const dictationId = activeIdRef.current', ' return {') - ] - for (const cleanupSlice of cleanupSlices) { - expect(cleanupSlice).toContain('closeDictationAudio()') - } - // The capture hands over its tail before the pending sends are taken, or the finish overtakes - // the last chunk. `mobile-dictation-stop-tail.test.tsx` drives the order this pins. - const stopBody = sliceBetween( - 'const stop = useCallback(async () => {', - 'const abandonDictation =' - ) - expect(stopBody.indexOf('capture.end()')).toBeLessThan( - stopBody.indexOf('await Promise.allSettled') - ) - }) - - it('routes an audio interruption through cancel and a disable through the reporting abort', () => { - const interruptionEffect = sliceBetween('capture.onInterruption(', 'return () => sub.remove()') - const disabledEffect = sliceBetween( - 'useEffect(() => {\n if (!enabled) {', - ' }, [abandonDictation, enabled])' - ) - - expect(interruptionEffect).toContain('void cancel()') - // A disable is not the user's cancel, so it carries the reason the composer shows; the user's - // own cancel is the one end that passes none. `mobile-dictation-input-closed-mid-start.test.tsx` - // drives both halves. - expect(disabledEffect).toContain( - 'void abandonDictation(MOBILE_DICTATION_INPUT_CLOSED_ERROR_MESSAGE)' - ) - expect(source).toContain('const cancel = useCallback(() => abandonDictation(null)') - // Which interruptions end a capture is one predicate both seams read, so a page cannot cancel - // on a kind the device ignores. `dictation-capture.test.ts` drives the rule itself. - expect(nativeCaptureSource).toContain('bridgeAudioInterruptionEndsCapture(event.data)') - }) -}) diff --git a/mobile/src/host-screen/host-route-href-encoding.test.ts b/mobile/src/host-screen/host-route-href-encoding.test.ts deleted file mode 100644 index c1ced2afe90..00000000000 --- a/mobile/src/host-screen/host-route-href-encoding.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -/** - * Every host-route target the host page builds, and whether its host id survives being one segment. - * - * `useLocalSearchParams` and the persisted host store both answer the decoded id, and the store - * admits any non-empty string, so an id carrying `/`, `?`, `#` or whitespace stops being the single - * segment `matchesRoutePattern` reads it as the moment it is interpolated raw. Inside the shell's - * page that decides where a tap goes: the handoff matches the pathname against the shell's - * `pageRoutes` before it chooses between this document and the native stack. - * - * A census rather than six assertions, because the failure is a habit and not a bug: each of these - * sites was written by copying the one next to it, and the seventh will be too. - */ -const MOBILE_ROOT = join(import.meta.dirname, '..', '..') - -/** The files that build a target from the host list and its row sheet. */ -const HOST_PAGE_SOURCES = [ - 'src/host-screen/host-screen-header.tsx', - 'src/host-screen/host-screen-overlays.tsx', - 'src/host-screen/use-host-worktree-actions.ts', - 'src/agent-history/worktree-navigation-actions.ts' -] - -/** - * The two `/h/${...}` reads that are not targets. - * - * Both compare against a pathname the router answers rather than building a link, so encoding them - * would change what a comparison matches instead of what a tap opens. They are listed by the text - * that makes them comparisons, so a line that stopped being one stops being exempt. - */ -const COMPARISONS = ['pathname === `/h/${hostId}`'] - -const HOST_SEGMENT = /`\/h\/\$\{([^}]*)\}/g - -function hostInterpolations(source: string): string[] { - return [...source.matchAll(HOST_SEGMENT)].map((match) => match[1] ?? '') -} - -describe('every host-route target the host page builds', () => { - it('reaches the census, so the assertion below cannot pass on an empty list', () => { - const found = HOST_PAGE_SOURCES.flatMap((path) => - hostInterpolations(readFileSync(join(MOBILE_ROOT, path), 'utf8')) - ) - expect(found.length).toBeGreaterThanOrEqual(6) - }) - - it('encodes the host id, at every site', () => { - const raw: string[] = [] - for (const path of HOST_PAGE_SOURCES) { - const source = readFileSync(join(MOBILE_ROOT, path), 'utf8') - const exempt = COMPARISONS.filter((text) => source.includes(text)).length - const unencoded = hostInterpolations(source).filter( - (expression) => !expression.includes('encodeURIComponent') - ) - // The comparisons are subtracted rather than matched away, so a file that lost its comparison - // and gained a raw target does not come out even. - if (unencoded.length > exempt) { - raw.push(`${path}: ${unencoded.length - exempt} raw`) - } - } - expect(raw).toEqual([]) - }) - - it('keeps the pathname comparisons out of the count for a stated reason, not by accident', () => { - const source = readFileSync( - join(MOBILE_ROOT, 'src/host-screen/use-host-worktree-actions.ts'), - 'utf8' - ) - // Present, so the exemption above is answering something real; and a comparison, so the - // exemption is not quietly covering a target. - expect(source).toContain(COMPARISONS[0]) - }) -}) diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx index a93f503bd63..64220f80c11 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx @@ -28,7 +28,6 @@ import { act, create } from 'react-test-renderer' import { bridgeId, clientFrame, createFakeRpcClient } from './bridge-host-test-fakes' import { byName, - DEFAULT_ROUTE_GRANTS, trackRenderedScreen, NativeFallback, SCREEN_BUILD_ID as BUILD_ID, @@ -150,7 +149,6 @@ describe('the hybrid shell screen', () => { const tree = await renderScreen(readyState('session-one')) const view = byName(tree, 'ShellViewProbe')[0] expect(view.props.bridgeEnabled).toBe(true) - expect(typeof view.props.onBridgeMessage).toBe('function') // Delivered with no client behind it: there is no host to answer, and nothing throws. await act(async () => { view.props.onBridgeMessage({ nativeEvent: { json: '{"v":1,"type":"ready"}' } }) @@ -634,22 +632,6 @@ describe('a refused update is said beside the page, not in front of it', () => { }) }) -/** - * Last in the file on purpose: it is the case the block above would have poisoned. - * - * Those cases grant the screencast lane and install a client, and before the shared setup reset - * them both, whatever ran next inherited a route granted a lane it never asked for. Deleting the - * reset fails here and nowhere else, because nothing else runs after a case that mutates them. - */ -describe('what one case mutates does not reach the next', () => { - it('starts from the shared route grants and no client', () => { - expect({ grants: dependencies.routeGrants, client: dependencies.client }).toEqual({ - grants: DEFAULT_ROUTE_GRANTS, - client: null - }) - }) -}) - /** * What is on screen between the generation being mounted and the page having a frame. * diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-frame-cap-boundary.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-frame-cap-boundary.test.ts index 1901b5f368c..b29219f178e 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-frame-cap-boundary.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-frame-cap-boundary.test.ts @@ -1,6 +1,4 @@ import { describe, expect, it } from 'vitest' -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { BRIDGE_MAX_MESSAGE_BYTES, parseBridgeMessage } from './bridge-caps' import { createFakeBridgePortPair } from './bridge-port-pair-test-harness' @@ -95,18 +93,4 @@ describe('the page frame cap at its boundary', () => { expect(read.ok).toBe(false) expect(read.ok ? null : read.refusal).toBe('oversized') }) - - it('reaches the cap through the shared predicate and spells it nowhere else', () => { - // The census half. A copy of the bound inside the client is a second spelling that can only - // drift from the one the reader applies, and it would pass every case above on the day it was - // written. `isBridgeFrameWithinCap` is the one thing both sides call. - const client = readFileSync(join(import.meta.dirname, 'bridge-rpc-client.ts'), 'utf8') - expect(client).toContain('isBridgeFrameWithinCap(') - expect(client).not.toContain('BRIDGE_MAX_MESSAGE_BYTES') - // And the predicate is the reader's own, not a lookalike beside it: the module that parses - // inbound frames is the module that exports it. - const caps = readFileSync(join(import.meta.dirname, 'bridge-caps.ts'), 'utf8') - expect(caps).toContain('export function isBridgeFrameWithinCap') - expect(caps).toContain('if (!isBridgeFrameWithinCap(raw))') - }) }) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-frame-cap-unit.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-frame-cap-unit.test.ts index f4ab3eb9bd3..351810c682a 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-frame-cap-unit.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-frame-cap-unit.test.ts @@ -1,6 +1,4 @@ import { describe, expect, it } from 'vitest' -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { BRIDGE_MAX_MESSAGE_BYTES, parseBridgeMessage, utf8ByteLength } from './bridge-caps' import { createFakeBridgePortPair } from './bridge-port-pair-test-harness' @@ -28,18 +26,6 @@ const WIDE_CHARACTER = '漢' const WIDE_CHARACTER_COUNT = 250_000 describe('what the frame cap counts', () => { - it('is the unit both shells count, read from their own sources', () => { - const shell = join(import.meta.dirname, '..', '..', '..', 'modules', 'orca-mobile-web-shell') - const swift = readFileSync(join(shell, 'ios', 'MobileWebShellView.swift'), 'utf8') - const kotlin = readFileSync( - join(shell, 'android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt'), - 'utf8' - ) - // The inbound gate on each platform, by the expression it measures with. - expect(swift).toContain('bridgeGate.accepts(byteCount: json.utf8.count)') - expect(kotlin).toContain('bridgeGate.accepts(json.toByteArray(Charsets.UTF_8).size)') - }) - it('refuses a frame under the cap in code units and over it in bytes', async () => { const pad = WIDE_CHARACTER.repeat(WIDE_CHARACTER_COUNT) // The precondition, without which this is just another oversized frame: a sender reading diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts index 4542949ac32..a1abc7c2d3c 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts @@ -1,14 +1,9 @@ import { describe, expect, it } from 'vitest' import { BrowserScreencastOpcode, - type BrowserScreencastFormat, type BrowserScreencastFrame } from '../../transport/browser-screencast-protocol' import { isRpcResponse } from '../../transport/rpc-response-shape' -import type { ConnectionState, ForegroundNudgeReason, RpcResponse } from '../../transport/types' -import type { SendRequestOptions } from '../../transport/unvalidated-rpc-request-port' -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' import { BRIDGE_MAX_MESSAGE_BYTES, BRIDGE_MAX_METHOD_CHARS, @@ -23,16 +18,12 @@ import { } from './bridge-caps' import { BRIDGE_HAPTICS_KINDS, BRIDGE_HAPTICS_NOTIFY } from './bridge-haptics-notify' import { - BRIDGE_BINARY_FORMATS, - BRIDGE_CONNECTION_STATES, BRIDGE_FAULT_GRANT, - BRIDGE_FOREGROUND_NUDGE_REASONS, BRIDGE_NAVIGATE_BACK_NOTIFY, BRIDGE_PROTOCOL_VERSION, readBridgeClientMessage, readBridgeHostMessage, - type BridgeHostMessage, - type BridgeReplyPayload + type BridgeHostMessage } from './bridge-envelope' import { BRIDGE_BACK_CLAIM_NOTIFY } from './bridge-page-back' import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' @@ -592,86 +583,7 @@ describe('the reply reader is the native acceptance predicate', () => { }) }) -describe('type pins', () => { - it('pins the protocol version both sides send', () => { - expect(BRIDGE_PROTOCOL_VERSION).toBe(1) - }) - - it('closes the connection states over the transport union', () => { - const asTransport = (value: (typeof BRIDGE_CONNECTION_STATES)[number]): ConnectionState => value - const asBridge = (value: ConnectionState): (typeof BRIDGE_CONNECTION_STATES)[number] => value - expect(BRIDGE_CONNECTION_STATES.map(asTransport).map(asBridge)).toEqual([ - ...BRIDGE_CONNECTION_STATES - ]) - }) - - it('closes the foreground reasons over the transport union', () => { - const asTransport = ( - value: (typeof BRIDGE_FOREGROUND_NUDGE_REASONS)[number] - ): ForegroundNudgeReason => value - const asBridge = ( - value: ForegroundNudgeReason - ): (typeof BRIDGE_FOREGROUND_NUDGE_REASONS)[number] => value - expect(BRIDGE_FOREGROUND_NUDGE_REASONS.map(asTransport).map(asBridge)).toEqual([ - ...BRIDGE_FOREGROUND_NUDGE_REASONS - ]) - }) - - it('resolves a reply payload to the transport envelope the page hands its callers', () => { - const asRpcResponse = (value: BridgeReplyPayload): RpcResponse => value - const read = readHost(client({ type: 'reply', id: ID, payload: SUCCESS_PAYLOAD })) - const payload = - read.ok && read.message.type === 'reply' && 'payload' in read.message - ? asRpcResponse(read.message.payload) - : null - expect(payload).toEqual(SUCCESS_PAYLOAD) - }) - - it('accepts every option the raw sender declares', () => { - // Both directions: the literal has to satisfy the type, and the type has to have no key the - // literal is missing, so a new option fails to compile until the schema learns it. - const optionKeys: Record = { - timeoutMs: true, - budgetSpansConnect: true, - failWhenDisconnected: true - } - const options: SendRequestOptions = { - timeoutMs: 1000, - budgetSpansConnect: true, - failWhenDisconnected: true - } - expect(Object.keys(optionKeys).toSorted()).toEqual(Object.keys(options).toSorted()) - expect(readClient(client({ type: 'request', id: ID, method: 'm', options })).ok).toBe(true) - }) - - it('bounds the viewport exactly where the desktop terminal contract does', () => { - // A viewport the page sends is replayed on resubscribe by every stream naming that terminal, - // the native screens' included. One the desktop refuses there would kill a stream the page - // never opened, so the two bounds have to be the same number. - // - // Read rather than imported: mobile may not pull a contract *value* into its bundle, and the - // boundary test that enforces that scans this file too. - const contract = readFileSync( - fileURLToPath( - new URL('../../../../src/shared/rpc-contract/terminal-unary-params.ts', import.meta.url) - ), - 'utf8' - ) - const start = contract.indexOf('export const TerminalViewport') - expect(start).toBeGreaterThan(-1) - const declaration = contract.slice(start, contract.indexOf('})', start)) - expect(declaration).toContain(`cols: z.number().int().min(1).max(${BRIDGE_MAX_VIEWPORT_COLS})`) - expect(declaration).toContain(`rows: z.number().int().min(1).max(${BRIDGE_MAX_VIEWPORT_ROWS})`) - }) - - it('closes the binary formats over the screencast protocol', () => { - const asProtocol = (value: (typeof BRIDGE_BINARY_FORMATS)[number]): BrowserScreencastFormat => - value - const asBridge = (value: BrowserScreencastFormat): (typeof BRIDGE_BINARY_FORMATS)[number] => - value - expect(BRIDGE_BINARY_FORMATS.map(asProtocol).map(asBridge)).toEqual([...BRIDGE_BINARY_FORMATS]) - }) - +describe('the screencast frame reader', () => { it('refuses a screencast metadata field that is not a finite number', () => { const keys = [ 'offsetTop', diff --git a/mobile/src/mobile-web-shell/bridge/page-first-paint-through-the-bridge.test.ts b/mobile/src/mobile-web-shell/bridge/page-first-paint-through-the-bridge.test.ts index c4962ebe16c..46faf5f38c1 100644 --- a/mobile/src/mobile-web-shell/bridge/page-first-paint-through-the-bridge.test.ts +++ b/mobile/src/mobile-web-shell/bridge/page-first-paint-through-the-bridge.test.ts @@ -3,8 +3,6 @@ * what is worth proving is that the page's post reaches the shell's cover over a real frame. */ import { describe, expect, it } from 'vitest' -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { createFakeRpcClient } from '../bridge-host-test-fakes' import { createFakeBridgePortPair } from './bridge-port-pair-test-harness' import { createRouteScreenPaintReporter } from './page-first-paint' @@ -33,23 +31,6 @@ describe('the page telling the shell it has a frame', () => { expect(pair.pagePaintCount()).toBe(1) }) - it('is reported by the page entry, from the effect that runs after the tree commits', () => { - // The one call site, pinned: every test above drives the client directly, so a deleted line in - // the entry would leave a shell covering a page that has painted and will never say so. - const entry = readFileSync( - join(import.meta.dirname, '..', '..', '..', 'web-entry', 'index.tsx'), - 'utf8' - ) - expect(entry).toContain('createRouteScreenPaintReporter(') - expect(entry).toContain('client.notifyPagePainted()') - // Handed to the route screen rather than called from the wrapper's own effect, which commits - // while the route's chunk is still arriving and the body is empty. - expect(entry).toContain('RouteScreenPaintProvider') - expect(entry).not.toMatch( - /stampPageMountState\(target, 'mounted'\)\s*\n\s*reportRouteScreenPaint/ - ) - }) - it('costs the shell nothing to hear: no request, no subscription, no reply', async () => { const rpc = createFakeRpcClient() const pair = createFakeBridgePortPair({ rpc }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-flag-census.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-flag-census.test.ts deleted file mode 100644 index fd23a133375..00000000000 --- a/mobile/src/mobile-web-shell/mobile-web-shell-flag-census.test.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join, relative } from 'node:path' -import { describe, expect, it } from 'vitest' -import { censusSourceFiles } from '../test-support/census-source-files' - -/** - * The hybrid shell flag is the whole of what keeps this feature dark in a native build, so who - * touches it is a product invariant rather than a convention. A second reader is how a dark feature - * stops being dark: a launch-time sweep, a prefetch or a menu item that consults the flag would run - * in a native store build the moment anything flipped it, and none of those would fail a type - * check. - * - * The build-kind fact is the same shape of invariant one level up. `EXPO_PUBLIC_MOBILE_SHELL` is - * what a release workflow sets to build the OTA binary, and a second module spelling it would be a - * second answer to "is this the page's build" that no type check would catch either. - */ -const MOBILE_ROOT = join(import.meta.dirname, '..', '..') -const FLAG_KEY = 'orca:mobileWebShellEnabled' -/** The inlined form. Prose may name the variable; this is the spelling that reads it. */ -const BUILD_SWITCH_READ = 'process.env.EXPO_PUBLIC_' -/** The other spelling Expo's plugin inlines, which is how the rule above would be evaded. */ -const BUILD_SWITCH_BRACKET_READ = "process.env['EXPO_PUBLIC_" -const DEFINITION = 'src/storage/preferences.ts' -/** The one product reader, which only the shared switch decision asks. */ -const FLAG_HOOK = 'src/mobile-web-shell/use-mobile-web-shell-enabled.ts' -/** The one caller of that hook: every route asks this instead, so its list is the whole census. */ -const DECISION = 'src/mobile-web-shell/shell-switch-decision.ts' -const ROUTE = 'app/h/[hostId]/web.tsx' -const HOST_ROUTE = 'app/h/[hostId]/index.tsx' -const AGENT_HISTORY_ROUTE = 'app/h/[hostId]/agent-history/[worktreeId].tsx' -const TASKS_ROUTE = 'app/h/[hostId]/tasks.tsx' -const FILES_ROUTE = 'app/h/[hostId]/files/[worktreeId].tsx' -const FILES_PREVIEW_ROUTE = 'app/h/[hostId]/files/preview/[worktreeId].tsx' -const SOURCE_CONTROL_ROUTE = 'app/h/[hostId]/source-control/[worktreeId].tsx' -const REVIEW_ROUTE = 'app/h/[hostId]/review/[worktreeId].tsx' -const SESSION_ROUTE = 'app/h/[hostId]/session/[worktreeId].tsx' -/** The one switch with no native screen behind it; its route file only re-exports this body. */ -const CATCH_ALL_ROUTE = 'src/mobile-web-shell/catch-all-page-route.tsx' -/** What a switch paints while the decision is `pending`, and the third thing every switch names. */ -const PENDING_SCREEN = 'src/mobile-web-shell/ShellSwitchPendingScreen.tsx' -/** One entry per screen the flag can switch to the page, which is what a review reads. */ -const SWITCHED_ROUTES = [ - HOST_ROUTE, - AGENT_HISTORY_ROUTE, - TASKS_ROUTE, - FILES_ROUTE, - FILES_PREVIEW_ROUTE, - SOURCE_CONTROL_ROUTE, - REVIEW_ROUTE, - SESSION_ROUTE, - CATCH_ALL_ROUTE -] -const DEVELOPER_ROW = 'src/diagnostics/mobile-web-shell-dev-row.tsx' -/** The one screen that decides whether that row mounts, which is a build-kind question. */ -const TROUBLESHOOT_ROUTE = 'app/troubleshoot.tsx' -/** Every tree that ships in the app bundle, with the floor each must clear. `modules` is two files, - * but it is where the native view lives and so the easiest place for a second reader to hide. */ -const TREES = { src: 200, app: 10, modules: 1 } -const SHELL_VIEW = 'modules/orca-mobile-web-shell/src/index.ts' - -function sourceFiles(directory: string): string[] { - return censusSourceFiles(join(MOBILE_ROOT, directory)) - .map((path) => relative(MOBILE_ROOT, path)) - .filter((path) => /\.tsx?$/.test(path) && !path.includes('.test.')) -} - -const SOURCES = Object.keys(TREES) - .flatMap((tree) => sourceFiles(tree)) - .map((path) => ({ - path: path.split('\\').join('/'), - text: readFileSync(join(MOBILE_ROOT, path), 'utf8') - })) - -function filesContaining(needle: string): string[] { - return SOURCES.filter((file) => file.text.includes(needle)) - .map((file) => file.path) - .sort() -} - -/** - * The same matches with the line each was read off, as the failure message for the rules below. - * - * A census that answers only with paths tells a reader which file is wrong and nothing about what - * in it is: the needles here are identifiers, and a file can name one in an import, a call or a - * comment. The snippet is what turns "this list moved" into the edit that moved it. - */ -function matchesOf(needle: string): string { - // Sorted by path then by line number, not as text: `:59:` sorts before `:4:` as a string, which - // reads as a file whose matches are out of order. - return [...SOURCES] - .sort((left, right) => left.path.localeCompare(right.path)) - .flatMap((file) => - file.text - .split('\n') - .flatMap((line, index) => - line.includes(needle) ? [`${file.path}:${index + 1}: ${line.trim()}`] : [] - ) - ) - .join('\n') -} - -describe('who touches the hybrid shell flag', () => { - it('reaches every shipped tree, so the absence assertions below cannot pass vacuously', () => { - const paths = SOURCES.map((file) => file.path) - expect(paths).toContain(DEFINITION) - expect(paths).toContain(FLAG_HOOK) - expect(paths).toContain(DECISION) - expect(paths).toContain(PENDING_SCREEN) - expect(paths).toContain(ROUTE) - for (const route of SWITCHED_ROUTES) { - expect(paths).toContain(route) - } - expect(paths).toContain(DEVELOPER_ROW) - expect(paths).toContain(TROUBLESHOOT_ROUTE) - expect(paths).toContain(SHELL_VIEW) - const trees = Object.keys(TREES) - for (const [tree, floor] of Object.entries(TREES)) { - expect(paths.filter((path) => path.startsWith(`${tree}/`)).length).toBeGreaterThan(floor) - } - expect(paths.filter((path) => !trees.some((tree) => path.startsWith(`${tree}/`)))).toEqual([]) - }) - - it('keeps the storage key itself in one module', () => { - expect(filesContaining(FLAG_KEY)).toEqual([DEFINITION]) - }) - - it('reads the build-time switch in one module', () => { - // `babel-preset-expo` inlines an `EXPO_PUBLIC_*` variable only where it is spelled as a - // literal member expression of `process.env`, so a second read is a second literal to keep in - // step with the workflow input — and a value copied out into a binding is not rewritten at - // all, which reads `undefined` on a device and answers native in a build that is not. - // - // Prose is not a read: the docblocks that name the variable are how a reader finds this - // module, and pinning them would make every wording change a census failure. - expect(filesContaining(BUILD_SWITCH_READ), matchesOf(BUILD_SWITCH_READ)).toEqual([DEFINITION]) - expect( - filesContaining(BUILD_SWITCH_BRACKET_READ), - matchesOf(BUILD_SWITCH_BRACKET_READ) - ).toEqual([]) - }) - - it('answers the build kind through one named function, asked by the flag and the row label', () => { - expect(filesContaining('mobileShellBuildKind'), matchesOf('mobileShellBuildKind')).toEqual( - [DEFINITION, DEVELOPER_ROW].sort() - ) - }) - - it('is read by one hook and by the developer row that writes it, and nowhere else', () => { - expect(filesContaining('loadMobileWebShellEnabled')).toEqual( - [DEFINITION, DEVELOPER_ROW, FLAG_HOOK].sort() - ) - }) - - it('is read by the shared switch decision and by nothing else', () => { - // The narrowest this has ever been, and the reason the rule below is total: a route cannot - // hold a private opinion about the flag — including about the window where it is still `null` - // — without reading it, and this is the only place that reads it. - expect( - filesContaining('useMobileWebShellEnabled'), - matchesOf('useMobileWebShellEnabled') - ).toEqual([DECISION, FLAG_HOOK].sort()) - }) - - it('reaches the switched routes through that decision and no others', () => { - // Each switched route is a screen the flag decides the renderer of, and one more is one more - // place a dark feature could turn itself on. The list grows once per domain series, in the PR - // that switches the route file to MobileWebShellScreen, and never as a side effect of anything - // else. A switched route is inert until MOBILE_WEB_PAGE_ROUTES lists it as well, so an entry - // here can land a PR ahead of that one. - expect(filesContaining('useShellSwitchDecision'), matchesOf('useShellSwitchDecision')).toEqual( - [DECISION, ROUTE, ...SWITCHED_ROUTES].sort() - ) - }) - - it('gives every one of them the same neutral state to paint while the flag is unresolved', () => { - // The rule a sixth switch would otherwise regress past. Reading the flag through the decision - // is not on its own enough: a switch that ignored `pending` and fell through to its native - // screen would satisfy the rule above and still flash native in front of a flag-on user. This - // one says every switch names the neutral screen, which is existence rather than shape — where - // it names it is the route test's business, and `shell-switch-null-flag.test.tsx` drives all - // nine through the states themselves. - expect( - filesContaining('ShellSwitchPendingScreen'), - matchesOf('ShellSwitchPendingScreen') - ).toEqual([PENDING_SCREEN, ROUTE, ...SWITCHED_ROUTES].sort()) - }) - - it('fences the build kind in one place, which the read, the hook and the row gate ask', () => { - // The test that makes a native store build unable to turn the flag on: `__DEV__`, or a binary - // built with the switch set to `ota`. The hook starts its state on it so a native release - // build never reaches the neutral state, which is the same answer `loadMobileWebShellEnabled` - // gives one render later — and two spellings of one build-kind test are two things to keep - // true, where this feature's darkness rests on exactly one. - // - // The Troubleshoot route asks the same question to decide whether to mount the toggle, which - // is the one place a user can switch an OTA build back to the native screens. Asking it rather - // than re-deriving it is why that row and the flag can never disagree about the build. - expect( - filesContaining('mobileWebShellFlagCanBeOn'), - matchesOf('mobileWebShellFlagCanBeOn') - ).toEqual([DEFINITION, FLAG_HOOK, TROUBLESHOOT_ROUTE].sort()) - }) - - it('is written only by the developer row', () => { - expect(filesContaining('saveMobileWebShellEnabled')).toEqual([DEFINITION, DEVELOPER_ROW].sort()) - }) -}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-router-seam-census.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-router-seam-census.test.ts deleted file mode 100644 index e7d8b6c00d3..00000000000 --- a/mobile/src/mobile-web-shell/mobile-web-shell-router-seam-census.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - callsRouteHandoff, - expoRouterValueImports, - parse, - productFiles -} from '../navigation/router-seam-census.test-support' - -const SHELL_ROOT = import.meta.dirname - -/** - * The tree that is both halves of the handoff, which is why it needs its own census. - * - * Every other domain here is page code: a screen the shell may serve, where expo-router's own - * router posts no `navigate` and a target outside the page paints Unmatched over it. This tree is - * different — it holds the app end of the seam as well, so the rule cannot be "no router" and has - * to name which modules are the app end. - * - * It is also the tree where the gap showed: `PageRouteUnavailableScreen` shipped with a bare - * `useRouter` and nothing caught it, because the three landed censuses walk `src/session`, - * `src/files` and `src/source-control` and this tree had none. - */ - -/** - * The two modules that ARE the app end of the handoff, and so hold expo-router's own router. - * - * `MobileWebShellScreen` is what hosts the page; its `router.push` is the `onNavigate` the page's - * `navigate` notify arrives at, so routing it through the seam would hand the page's target back to - * the page. `useShellStackPop` is the same for `onNavigateBack`: it pops the native stack the shell - * was pushed onto. Neither has a `.web.*` sibling and neither can run inside the page — the page has - * no shell within it — so neither is a screen the seam exists for. - */ -const SHELL_SIDE_ROUTER_HOLDERS = ['MobileWebShellScreen.tsx', 'use-shell-stack-pop.ts'] - -/** - * The screens here that render on the page and therefore must reach the router through the seam. - * - * One today. `PageRouteUnavailableScreen` is rendered by the catch-all on the device and by its - * `.web.tsx` sibling inside the page, so a bare replace there navigates within the WebView to a - * route the page does not carry instead of leaving it. - */ -const ROUTER_HOLDERS = ['PageRouteUnavailableScreen.tsx'] - -/** - * The expo-router names this tree may import outside those two, and why none is a router. - * - * `useLocalSearchParams` reads the params of the route already mounted and `usePathname` reads - * which route that is. Neither takes a target, so neither can put a screen in front of the page. - * - * A closed list rather than a ban on `useRouter`, for the reason the session census gives: - * expo-router also exports a module-singleton `router` that navigates from a plain function, and a - * rule written against the one spelling would read that as clean. - */ -const NON_NAVIGATING_ROUTER_NAMES = ['useLocalSearchParams', 'usePathname'] - -describe('the mobile-web-shell tree reaches the router through the handoff seam', () => { - const files = productFiles(SHELL_ROOT) - - it('walks the modules it is written against, so the empty list below means something', () => { - expect(files).toEqual(expect.arrayContaining(SHELL_SIDE_ROUTER_HOLDERS)) - expect(files).toEqual(expect.arrayContaining(ROUTER_HOLDERS)) - // The whole tree, not the five files that touch a router: a walk that collapsed to those would - // report an empty finding list for a domain it never read. - expect(files.length).toBeGreaterThan(60) - }) - - it('imports nothing from expo-router that can navigate, outside the two that are the seam', () => { - const offenders = files - .filter((name) => !SHELL_SIDE_ROUTER_HOLDERS.includes(name)) - .map((name) => ({ - name, - imported: expoRouterValueImports(parse(SHELL_ROOT, name)).filter( - (imported) => !NON_NAVIGATING_ROUTER_NAMES.includes(imported) - ) - })) - .filter((entry) => entry.imported.length > 0) - .map((entry) => `${entry.name} (${entry.imported.join(', ')})`) - expect(offenders).toEqual([]) - }) - - it('takes the router from useRouteHandoff at every screen the page renders', () => { - expect(files.filter((name) => callsRouteHandoff(parse(SHELL_ROOT, name))).sort()).toEqual( - [...ROUTER_HOLDERS].sort() - ) - }) - - it('still holds a real router at the app end, which is what the exemption is for', () => { - // The completeness half: the rule above also passes over a tree whose two seam modules stopped - // navigating at all, which is what it would read as if someone moved them and left this list. - for (const name of SHELL_SIDE_ROUTER_HOLDERS) { - expect(expoRouterValueImports(parse(SHELL_ROOT, name)), name).toContain('useRouter') - } - }) -}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx index 2abeff8fd96..a1b81f1bdc4 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx @@ -68,7 +68,7 @@ export const SCREEN_SNAPSHOT = { host: { id: 'host-1', name: 'Host One', endpoint: 'ws://host-1', lastConnected: 3 } } -export const DEFAULT_ROUTE_GRANTS: readonly string[] = [ +const DEFAULT_ROUTE_GRANTS: readonly string[] = [ 'navigate', 'storage', 'externalLink', diff --git a/mobile/src/mobile-web-shell/shell-older-page-paths-census.test.ts b/mobile/src/mobile-web-shell/shell-older-page-paths-census.test.ts deleted file mode 100644 index a1d40ccf49a..00000000000 --- a/mobile/src/mobile-web-shell/shell-older-page-paths-census.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -/** - * The shell serves no page older than its floor (`MOBILE_WEB_PAGE_VERSION_FLOOR`), so it keeps no - * path for one: no negotiated `accepts`/`reports`, and no WebView resized for the keyboard. The - * retired names are listed so a reintroduction goes red. - */ -import { readFileSync } from 'node:fs' -import { join, relative } from 'node:path' -import { describe, expect, it } from 'vitest' -import { censusSourceFiles } from '../test-support/census-source-files' - -const MOBILE_DIR = join(import.meta.dirname, '..', '..') -const SHELL_DIR = import.meta.dirname -const RETIRED = new RegExp( - [ - 'softwareKeyboardWindowInset', - 'viewShortenedBy', - 'pageReadsKeyboardInset', - 'shellPageReadsKeyboardInset', - 'shellKeyboardGeometry', - 'BRIDGE_KEYBOARD_INSET_ACCEPT', - 'BRIDGE_ROUTE_UPDATE_ACCEPT', - 'BRIDGE_SAFE_AREA_ACCEPT', - 'BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT', - 'BRIDGE_SHELL_ACCEPTS', - 'BRIDGE_MAX_PAGE_ACCEPTS', - 'pageReportsPaint', - 'pageOwnsSafeArea', - 'shellPageOwnsSafeArea', - 'shellAccepts', - 'PageReadyDeclaration', - "'keyboard-inset'", - "'route-update'", - "'safe-area-insets'", - "'page-client-identity'" - ].join('|') -) -/** The negotiated fields themselves, in code: a `ready` or `init` declaring what it takes or reports. */ -const NEGOTIATED_FIELD = /\.(accepts|reports)\b|\b(accepts|reports)\??:/ -const COMMENT = /^\s*(\/\/|\*|\/\*)/ -const KEYBOARD_SIZES_VIEW = /\b(padding|margin)?(Bottom|bottom|height|Height)\s*:[^,}\n]*keyboard/i - -/** Lines that bring back a path for an older page, or size the view from the keyboard. */ -export function olderPagePaths(source: string, inShell: boolean): number[] { - return source - .split('\n') - .flatMap((line, index) => - RETIRED.test(line) || - (inShell && - ((NEGOTIATED_FIELD.test(line) && !COMMENT.test(line)) || KEYBOARD_SIZES_VIEW.test(line))) - ? [index + 1] - : [] - ) -} - -function sources(dir: string): string[] { - return censusSourceFiles(dir).filter( - (file) => /\.tsx?$/.test(file) && !/\.test\.tsx?$/.test(file) - ) -} - -describe('the shell and a page older than its floor', () => { - it('finds the lines it is looking for', () => { - expect(olderPagePaths('style={{ paddingBottom: keyboardInset }}', true)).toEqual([1]) - expect(olderPagePaths("accepts.includes('keyboard-inset')", false)).toEqual([1]) - expect(olderPagePaths('if (accepts.includes(BRIDGE_SAFE_AREA_ACCEPT)) {', false)).toEqual([1]) - expect(olderPagePaths(' accepts: z.array(z.string()).optional(),', true)).toEqual([1]) - expect(olderPagePaths('return message.reports ?? []', true)).toEqual([1]) - expect(olderPagePaths('session.pageOwnsSafeArea', false)).toEqual([1]) - expect( - olderPagePaths('{ paddingTop: insets.top, paddingBottom: insets.bottom }', true) - ).toEqual([]) - expect(olderPagePaths('publishKeyboardInset(keyboardInset)', true)).toEqual([]) - // The field rule is the shell's code: elsewhere, and in prose, `accepts` is an ordinary word. - expect(olderPagePaths('gate.accepts(byteCount)', false)).toEqual([]) - expect(olderPagePaths(' // the answer is what the caller reports: a page', true)).toEqual([]) - }) - - it('keeps no path for one anywhere in the app or the page entry', () => { - const offenders = [ - ...sources(join(MOBILE_DIR, 'src')), - ...sources(join(MOBILE_DIR, 'web-entry')) - ].flatMap((file) => - olderPagePaths(readFileSync(file, 'utf8'), file.startsWith(SHELL_DIR)).map( - (line) => `${relative(MOBILE_DIR, file)}:${line}` - ) - ) - expect(offenders).toEqual([]) - }) -}) diff --git a/mobile/src/mobile-web-shell/shell-screen-route-census.test.ts b/mobile/src/mobile-web-shell/shell-screen-route-census.test.ts deleted file mode 100644 index 1626e376966..00000000000 --- a/mobile/src/mobile-web-shell/shell-screen-route-census.test.ts +++ /dev/null @@ -1,278 +0,0 @@ -import { existsSync, readdirSync, readFileSync } from 'node:fs' -import { dirname, join, resolve } from 'node:path' -import ts from 'typescript-api' -import { describe, expect, it } from 'vitest' - -const HOST_ROUTES = join(import.meta.dirname, '..', '..', 'app', 'h', '[hostId]') -const PAGE_ROUTE_REGISTRY = join( - import.meta.dirname, - '..', - '..', - '..', - 'config', - 'scripts', - 'mobile-web-page-routes.mjs' -) - -/** - * Every switch that hands a route to the shell asks whether the route is one the page can be - * given, and asks it in one place. - * - * A route the schema refuses is dropped to `null` by `bridge-host.ts` and reaches the phone as an - * `init` naming no screen, which the page answers with "Update Orca to open this workspace" — a - * failure screen in place of the native screen sitting right behind the switch. Three routes had - * each grown their own copy of the call and two had none at all, which is the state this census - * ends: the predicate is `shellScreenRoute`, and a switch that spells it itself has a second - * spelling of a rule that can only drift from the one the page reads. - * - * The walk is over the route tree rather than a list, so a route added later is held to this - * without anyone remembering to add it here. - */ -function hostRouteFiles(directory: string = HOST_ROUTES, prefix = ''): string[] { - return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { - const name = prefix === '' ? entry.name : `${prefix}/${entry.name}` - if (entry.isDirectory()) { - return hostRouteFiles(join(directory, entry.name), name) - } - return entry.name.endsWith('.tsx') && !entry.name.includes('.test.') ? [name] : [] - }) -} - -/** - * A route file's body: the file itself, or the module its default export comes from. - * - * `[...page].tsx` is the reason: expo-router 55 reads a file's platform from the first dot of its - * stripped name, so a catch-all cannot carry a `.web.tsx` sibling under `app/` without registering - * a second route, and its body lives under `src/` where the stem is plain. Following the export - * keeps the walk derived from the tree rather than from a list beside it. - * - * Fails closed, which is the half that matters. A shape this cannot resolve is a file whose body - * it never read, and an unread body is exactly where a switch that skips `shellScreenRoute` would - * sit — so an unknown shape is named by the census rather than quietly treated as a non-switch. - */ -type RouteBody = - | { readonly kind: 'source'; readonly text: string } - | { readonly kind: 'unresolved'; readonly why: string } - -/** The module specifier a file's default export comes from, or null when the body is local. */ -function defaultExportSource(parsed: ts.SourceFile): string | null | undefined { - const importedFrom = new Map() - for (const statement of parsed.statements) { - if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) { - const clause = statement.importClause - if (clause?.name !== undefined) { - importedFrom.set(clause.name.text, statement.moduleSpecifier.text) - } - const bindings = clause?.namedBindings - if (bindings !== undefined && ts.isNamedImports(bindings)) { - for (const element of bindings.elements) { - importedFrom.set(element.name.text, statement.moduleSpecifier.text) - } - } - } - } - for (const statement of parsed.statements) { - // `export { default } from 'x'`, and `export { Body as default } from 'x'`. - if ( - ts.isExportDeclaration(statement) && - statement.moduleSpecifier !== undefined && - ts.isStringLiteral(statement.moduleSpecifier) && - statement.exportClause !== undefined && - ts.isNamedExports(statement.exportClause) && - statement.exportClause.elements.some((element) => element.name.text === 'default') - ) { - return statement.moduleSpecifier.text - } - if (ts.isExportAssignment(statement) && statement.isExportEquals !== true) { - // `export default Body` where `Body` came from an import: the body is over there. Any other - // expression — a function, a class, a local — is this file's own. - return ts.isIdentifier(statement.expression) - ? (importedFrom.get(statement.expression.text) ?? null) - : null - } - // `export default function …` / `export default class …`: the body is here. - if ( - (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && - statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword) === - true - ) { - return null - } - } - return undefined -} - -function bodyOf(name: string): RouteBody { - const routeFile = join(HOST_ROUTES, name) - const source = readFileSync(routeFile, 'utf8') - const specifier = defaultExportSource(parse(source)) - if (specifier === undefined) { - return { kind: 'unresolved', why: 'no default export this census recognises' } - } - if (specifier === null) { - return { kind: 'source', text: source } - } - if (!specifier.startsWith('.')) { - return { kind: 'unresolved', why: `default export comes from the package "${specifier}"` } - } - const base = resolve(dirname(routeFile), specifier) - for (const extension of ['.tsx', '.ts']) { - if (existsSync(`${base}${extension}`)) { - return { kind: 'source', text: readFileSync(`${base}${extension}`, 'utf8') } - } - } - return { kind: 'unresolved', why: `no module at "${specifier}"` } -} - -/** The body text, for the rules below; an unresolved shape is caught by its own case first. */ -function read(name: string): string { - const body = bodyOf(name) - return body.kind === 'source' ? body.text : '' -} - -/** - * The one switch that hands over a route the rule refuses, on purpose. - * - * `web.tsx` is `__DEV__`-only and its fallback is `Redirect href="/h/"`, not a native - * screen. Adopting the guard there sends a `..` deep link through that redirect to the host route, - * which this PR keeps native, so the developer lands on the host list with nothing said about why - * the page did not open. Handed over instead, the same id reaches the bridge and comes back as the - * host's own failure screen, which is the better verdict for a route whose whole purpose is to - * open the page deliberately; `mobile-web-shell-route.test.tsx` pins that by name. - * - * Exempted here rather than silently unwalked, so the exception is read when it changes. - */ -const HANDS_OVER_UNJUDGED = ['web.tsx'] - -const parse = (source: string): ts.SourceFile => - ts.createSourceFile('route.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX) - -function importsNames(parsed: ts.SourceFile, module: string): string[] { - return parsed.statements.flatMap((statement) => { - if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) { - return [] - } - if (!statement.moduleSpecifier.text.endsWith(module)) { - return [] - } - const bindings = statement.importClause?.namedBindings - return bindings !== undefined && ts.isNamedImports(bindings) - ? bindings.elements.map((element) => element.name.text) - : [] - }) -} - -/** - * A switch is a route file that imports the shell screen. - * - * The import rather than ` { - if ( - ts.isCallExpression(node) && - ts.isIdentifier(node.expression) && - node.expression.text === name - ) { - called = true - } - ts.forEachChild(node, visit) - } - ts.forEachChild(parsed, visit) - return called -} - -describe('the switches that hand a route to the shell', () => { - const switches = hostRouteFiles().filter((name) => mountsShell(parse(read(name)))) - - it('walks the directory every registered route lives under', () => { - // The root above is written out rather than derived, so this is what ties it to the manifest: - // a page route outside `/h/[hostId]` would be a switch this census never reads. - const pathnames = [ - ...readFileSync(PAGE_ROUTE_REGISTRY, 'utf8').matchAll(/pathname: '([^']+)'/g) - ].map((match) => match[1]) - expect(pathnames.length).toBeGreaterThan(0) - expect(pathnames.filter((pathname) => !pathname.startsWith('/h/[hostId]'))).toEqual([]) - }) - - /** - * Every route file's body was read, so `switches` is a census and not a sample. - * - * A shape this cannot resolve is a body it never opened, and every rule below would read that - * file as "not a switch" — the one answer a census must never give by default. - */ - it('resolves every route file to a body, naming any shape it cannot', () => { - expect( - hostRouteFiles() - .map((name) => ({ name, body: bodyOf(name) })) - .filter((entry) => entry.body.kind === 'unresolved') - .map((entry) => `${entry.name}: ${entry.body.kind === 'unresolved' ? entry.body.why : ''}`) - ).toEqual([]) - }) - - it('walks the route tree and finds them, so the rules below cannot pass vacuously', () => { - expect(switches.sort()).toEqual([ - '[...page].tsx', - 'agent-history/[worktreeId].tsx', - 'files/[worktreeId].tsx', - 'files/preview/[worktreeId].tsx', - 'index.tsx', - 'review/[worktreeId].tsx', - 'session/[worktreeId].tsx', - 'source-control/[worktreeId].tsx', - 'tasks.tsx', - 'web.tsx' - ]) - }) - - it('asks shellScreenRoute whether the route is one the page can be given', () => { - // Imports it *and* calls it: an import the call no longer reaches is a switch that stopped - // asking while still looking like one. - expect( - switches - .filter((name) => !HANDS_OVER_UNJUDGED.includes(name)) - .filter((name) => { - const parsed = parse(read(name)) - return ( - !importsNames(parsed, 'shell-screen-route').includes('shellScreenRoute') || - !callsName(parsed, 'shellScreenRoute') - ) - }) - ).toEqual([]) - }) - - it('reads the call rather than the import, on a fixture that has only the import', () => { - // The rule the case above cannot show against the tree, every switch there calling what it - // imports: an import with no call is named. - const importOnly = parse( - "import { shellScreenRoute } from '../../../src/mobile-web-shell/shell-screen-route'\n" + - "import { MobileWebShellScreen } from '../../../src/mobile-web-shell/MobileWebShellScreen'\n" + - 'export default function Route() {\n return \n}\n' - ) - expect(mountsShell(importOnly)).toBe(true) - expect(importsNames(importOnly, 'shell-screen-route')).toContain('shellScreenRoute') - expect(callsName(importOnly, 'shellScreenRoute')).toBe(false) - }) - - it('spells the rule nowhere else, so the page and the app cannot disagree about it', () => { - // The copies this census ends. `shellScreenRoute` is the one caller of the schema outside the - // bridge, and a switch that reaches for it again is writing the second spelling back. - expect(switches.filter((name) => read(name).includes('BridgeInitRouteSchema'))).toEqual([]) - // And the exemption names a switch that exists, so it cannot outlive the file it excuses. - expect(switches).toEqual(expect.arrayContaining(HANDS_OVER_UNJUDGED)) - }) -}) diff --git a/mobile/src/mobile-web-shell/shell-view-surface.test.ts b/mobile/src/mobile-web-shell/shell-view-surface.test.ts deleted file mode 100644 index 7d8817147ca..00000000000 --- a/mobile/src/mobile-web-shell/shell-view-surface.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { colors } from '../theme/mobile-theme' - -/** - * What the WebView paints before its document does, read off both shells. - * - * Neither can be proven from a JVM or a Swift unit test: it is a property of a live view. What is - * checkable is that neither shell gives the view a surface of its own, which is what makes the - * frame behind it — the screen's own, in the app's own colours — the thing on screen. - * - * The two defaults differ and both are wrong. Android's WebView paints nothing under a transparent - * background, which is fine; a WKWebView is opaque by default and paints white, so a dark app - * opening a page flashed white for the whole of the page's boot. - */ -const SHELL = join(import.meta.dirname, '..', '..', 'modules', 'orca-mobile-web-shell') - -function source(relative: string): string { - return readFileSync(join(SHELL, relative), 'utf8') -} - -describe('what a mounted view paints before the page does', () => { - it('gives the Android view no surface of its own', () => { - const kotlin = source( - 'android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt' - ) - expect(kotlin).toContain('view.setBackgroundColor(Color.TRANSPARENT)') - }) - - it('gives the iOS view none either, which is not its default', () => { - const swift = source('ios/MobileWebShellView.swift') - expect(swift).toContain('webView.isOpaque = false') - expect(swift).toContain('webView.backgroundColor = .clear') - expect(swift).toContain('webView.scrollView.backgroundColor = .clear') - }) - - it('leaves the app surface as the one colour behind a page, and it is not black', () => { - // What shows through both: the screen's own root, which is where the token is read. - const screen = readFileSync(join(import.meta.dirname, 'MobileWebShellScreen.tsx'), 'utf8') - expect(screen).toContain('backgroundColor: colors.bgBase') - expect(colors.bgBase).not.toBe('#000000') - }) -}) diff --git a/mobile/src/notifications/desktop-notification-channel.test.ts b/mobile/src/notifications/desktop-notification-channel.test.ts index 95ff41ebe35..283f3f668d4 100644 --- a/mobile/src/notifications/desktop-notification-channel.test.ts +++ b/mobile/src/notifications/desktop-notification-channel.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { beforeEach, describe, expect, it, vi } from 'vitest' import * as Notifications from 'expo-notifications' import { Platform } from 'react-native' @@ -48,15 +47,3 @@ describe('ensureDesktopNotificationChannel', () => { await expect(ensureDesktopNotificationChannel()).rejects.toThrow('no channels') }) }) - -describe('app boot', () => { - it('creates the channel at startup, not only once a socket subscribes', () => { - // A background push can be the first thing to target 'orca-desktop', and Android - // drops a notification whose channel does not exist. Asserted against the source - // because vitest only collects src/, so app/_layout.tsx has no runtime coverage. - const layout = readFileSync(new URL('../../app/_layout.tsx', import.meta.url), 'utf8') - - expect(layout).toContain("from '../src/notifications/desktop-notification-channel'") - expect(layout).toMatch(/^void ensureDesktopNotificationChannel\(\)\.catch\(/m) - }) -}) diff --git a/mobile/src/notifications/notification-route-coordination.test.ts b/mobile/src/notifications/notification-route-coordination.test.ts index 6f1b8a4aeec..a55d3809f5f 100644 --- a/mobile/src/notifications/notification-route-coordination.test.ts +++ b/mobile/src/notifications/notification-route-coordination.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { describe, expect, it, vi } from 'vitest' import { getNotificationNavigationTarget } from './notification-routing' import { @@ -7,8 +6,6 @@ import { type HostStackNavigationState } from '../navigation/host-stack-navigation' -const rootLayoutSource = readFileSync(new URL('../../app/_layout.tsx', import.meta.url), 'utf8') - function navigationHarness(initialState: HostStackNavigationState | undefined) { const stateListeners = new Set<() => void>() let state = initialState @@ -100,20 +97,6 @@ describe('notification route coordination', () => { it('leaves a host-only notification as a shallow push with nothing to coordinate', () => { expect(getNotificationNavigationTarget({ hostId: 'host-1' })?.sessionTarget).toBeNull() }) - - it('routes notification taps through the coordinated transition, not a bare push', () => { - const start = rootLayoutSource.indexOf('// ─── Notification tap routing ───') - const end = rootLayoutSource.indexOf('// ─── End notification tap routing ───', start) - - // Assert the markers first: a renamed banner would otherwise slice garbage and report a - // missing call instead of the real cause. - expect(start).toBeGreaterThanOrEqual(0) - expect(end).toBeGreaterThan(start) - - const notificationEffect = rootLayoutSource.slice(start, end) - expect(notificationEffect).toContain('openNotificationRoute(target)') - expect(notificationEffect).not.toContain('router.push(') - }) }) it('reuses the current workspace screen and targets the notification pane without pushing', () => { diff --git a/mobile/src/platform/keyboard-geometry-host-os-census.test.ts b/mobile/src/platform/keyboard-geometry-host-os-census.test.ts deleted file mode 100644 index 81b7259395d..00000000000 --- a/mobile/src/platform/keyboard-geometry-host-os-census.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Keyboard and inset arithmetic branches on the host OS, never on `Platform.OS`. - * - * The page runs as `web` while the keyboard it lifts over is the phone's, reported in that OS's own - * terms (iOS counts the home indicator). A `Platform.OS === 'ios'` there takes the Android branch on - * an iPhone page: measured on the iPhone 17 simulator, the terminal lifted 34 pt past native. - */ -import { readFileSync } from 'node:fs' -import { relative } from 'node:path' -import { fileURLToPath } from 'node:url' -import { describe, expect, it } from 'vitest' -import { censusSourceFiles } from '../test-support/census-source-files' - -const MOBILE_DIR = fileURLToPath(new URL('../../', import.meta.url)) -const GEOMETRY = - /keyboardHeight|keyboardLift|keyboardInset|bottomInset|insets\.bottom|KeyboardAvoidingView|keyboard(Will|Did)(Show|Hide)/ - -const KEYBOARD_READ = - /keyboardHeight|keyboardLift|keyboardInset|useKeyboardOcclusion|useSoftKeyboard/ -const KEYBOARD_IMPORT = /from '[^']*(keyboard|inset)[^']*'/i -const KEYBOARD_FILE = /(keyboard|inset|drawer|lift)[^/]*$/i -const COMMENT = /^\s*(\/\/|\*|\/\*)/ - -/** - * `Platform.OS` reads near keyboard or inset arithmetic, or anywhere in a file that reads the keyboard, - * imports a keyboard/inset module or is named for one: a live-input reopen flag four lines from its - * keyboard height escaped the proximity rule alone. Comments are not reads. - */ -export function platformReadsInGeometry(source: string, file = ''): number[] { - const lines = source.split('\n') - const wholeFile = - KEYBOARD_READ.test(source) || KEYBOARD_IMPORT.test(source) || KEYBOARD_FILE.test(file) - return lines.flatMap((line, index) => - line.includes('Platform.OS') && - !COMMENT.test(line) && - (wholeFile || - lines.slice(Math.max(0, index - 2), index + 3).some((near) => GEOMETRY.test(near))) - ? [index + 1] - : [] - ) -} - -function files(): string[] { - return ['src', 'app'].flatMap((dir) => - censusSourceFiles(fileURLToPath(new URL(`../../${dir}/`, import.meta.url))).filter( - (file) => /\.tsx?$/.test(file) && !/\.test\.tsx?$/.test(file) && !file.endsWith('host-os.ts') - ) - ) -} - -describe('keyboard and inset arithmetic', () => { - it('finds the reads it is looking for', () => { - expect( - platformReadsInGeometry("const lift = Platform.OS === 'ios' ? keyboardHeight - 1 : 0") - ).toEqual([1]) - expect( - platformReadsInGeometry("keyboardType={Platform.OS === 'ios' ? 'url' : 'default'}") - ).toEqual([]) - }) - - it('reads the host OS, never Platform.OS', () => { - const offenders = files().flatMap((file) => - platformReadsInGeometry(readFileSync(file, 'utf8'), file).map( - (line) => `${relative(MOBILE_DIR, file)}:${line}` - ) - ) - expect(offenders).toEqual([]) - }) -}) diff --git a/mobile/src/platform/keyboard-geometry-owner-census.test.ts b/mobile/src/platform/keyboard-geometry-owner-census.test.ts deleted file mode 100644 index b3bee07b5f4..00000000000 --- a/mobile/src/platform/keyboard-geometry-owner-census.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Who may ask React Native's `Keyboard` for geometry: the keyboard seam, and one named exception. - * - * react-native-web's `Keyboard` has no `metrics` and an `addListener` that never fires, so a page - * screen that asks it directly either throws (a fill sheet crashed the page on `metrics()`) or waits - * forever. The seam has a web sibling that answers from the window instead; everything else reads it. - */ -import { readFileSync } from 'node:fs' -import { relative } from 'node:path' -import { fileURLToPath } from 'node:url' -import { describe, expect, it } from 'vitest' -import { censusSourceFiles } from '../test-support/census-source-files' - -const MOBILE_DIR = fileURLToPath(new URL('../../', import.meta.url)) -const SRC_DIR = fileURLToPath(new URL('../', import.meta.url)) - -const SEAM = 'src/platform/keyboard-occlusion.ts' -/** A one-shot "open after the keyboard hides" with a timer fallback; on the page, where the event - * never fires, the timer is what opens the sheet, so it cannot wait forever. */ -const TAB_SHEET_AFTER_HIDE = 'src/session/use-mobile-session-terminal-send-actions.ts' - -const asksKeyboard = (line: string): boolean => - line.includes('Keyboard.metrics(') || line.includes('Keyboard.addListener(') - -function callers(): string[] { - return censusSourceFiles(SRC_DIR) - .filter((file) => /\.tsx?$/.test(file) && !/\.test\.tsx?$/.test(file)) - .filter((file) => readFileSync(file, 'utf8').split('\n').some(asksKeyboard)) - .map((file) => relative(MOBILE_DIR, file)) - .sort() -} - -describe("React Native's Keyboard geometry", () => { - it('is read only by the keyboard seam and the tab sheet that waits for a hide', () => { - // Also the presence precondition: the seam itself must match, or the matcher is broken. - expect(callers()).toEqual([SEAM, TAB_SHEET_AFTER_HIDE].sort()) - }) -}) diff --git a/mobile/src/platform/microphone-screen-lock-census.test.ts b/mobile/src/platform/microphone-screen-lock-census.test.ts deleted file mode 100644 index 992918930e4..00000000000 --- a/mobile/src/platform/microphone-screen-lock-census.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Who may name the screen: one module, and nothing on the page. - * - * The screen a dictation holds awake is a property of the microphone, so the device module that - * opens the mic takes it and gives it back. Everything above that — the composer's five states, the - * pending-audio budget, where a transcript is routed — has no business naming it, and the page has - * no way to: the verb it used to ask through is gone, along with the tag pools, the timeouts and - * the foreground re-acquire that existed to keep the page's idea of the screen and the device's - * agreeing. - * - * A census rather than a rule in a reviewer's head, because the seam grew back twice from exactly - * the shape this forbids: a page that can ask for a wake tag acquires the bookkeeping to track what - * it asked for. Existence, not shape — any import of the package, and any mention of the verb's - * name at all, from any file but the one owner. - */ -import { readFileSync, readdirSync } from 'node:fs' -import { relative, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { describe, expect, it } from 'vitest' - -const MOBILE_DIR = fileURLToPath(new URL('../../', import.meta.url)) - -/** The one module that may hold the screen: the device calls the microphone's capture makes. */ -const SCREEN_LOCK_OWNER = 'src/platform/native-audio-device.ts' - -/** This file names both things it forbids, so it reads every file but itself. */ -const CENSUS = 'src/platform/microphone-screen-lock-census.test.ts' - -const KEEP_AWAKE_PACKAGE = 'expo-keep-awake' - -/** Built rather than written, so the census does not contain the word it bans. */ -const RETIRED_VERB_WORD = `wake${'lock'}` - -function sourceFiles(): string[] { - const found: string[] = [] - const walk = (dir: string): void => { - for (const entry of readdirSync(dir, { withFileTypes: true })) { - const full = join(dir, entry.name) - if (entry.isDirectory()) { - walk(full) - continue - } - if (entry.name.endsWith('.ts') || entry.name.endsWith('.tsx')) { - found.push(relative(MOBILE_DIR, full)) - } - } - } - for (const root of ['src', 'app']) { - walk(join(MOBILE_DIR, root)) - } - return found.sort() -} - -/** The line, not just the file: a census that answers "somewhere in 1,400 files" is one a reader - * has to re-run by hand before they can act on it. */ -function hits(match: (line: string) => boolean, skip: readonly string[]): string[] { - const found: string[] = [] - for (const file of sourceFiles()) { - if (skip.includes(file)) { - continue - } - const lines = readFileSync(join(MOBILE_DIR, file), 'utf8').split('\n') - for (const [index, line] of lines.entries()) { - if (match(line)) { - found.push(`${file}:${index + 1}: ${line.trim()}`) - } - } - } - return found -} - -/** An import of the package, which is a module that can hold the screen. A test's `vi.mock` of it - * is not one: the mock exists because the graph reaches the owner, which is the rule holding. */ -const importsKeepAwake = (line: string): boolean => - line.includes(`from '${KEEP_AWAKE_PACKAGE}'`) || line.includes(`require('${KEEP_AWAKE_PACKAGE}')`) - -const namesRetiredVerb = (line: string): boolean => - line.toLowerCase().includes(RETIRED_VERB_WORD.toLowerCase()) - -describe('the one module that may hold the screen awake', () => { - it('is the only one that imports the keep-awake package', () => { - expect(hits(importsKeepAwake, [SCREEN_LOCK_OWNER, CENSUS])).toEqual([]) - }) - - it('does import it, so the absence above is the rule holding and not the match missing', () => { - // The presence precondition every absence needs: the matcher finds the one file that should - // match, so a typo in the package name fails here rather than passing everywhere. - expect(hits(importsKeepAwake, [CENSUS]).map((hit) => hit.split(':')[0])).toEqual([ - SCREEN_LOCK_OWNER - ]) - }) - - it('leaves no page-facing name for the screen anywhere in the app', () => { - // The retired verb, in any casing: a grant row, a schema, a server, a tag, a mock or a comment - // pointing at a seam that no longer exists. - expect(hits(namesRetiredVerb, [CENSUS])).toEqual([]) - }) - - it('reads a tree big enough for those absences to mean something', () => { - // A walk that found nothing would pass all three rules above by having nothing to judge. - expect(sourceFiles().length).toBeGreaterThan(900) - expect(sourceFiles()).toContain(SCREEN_LOCK_OWNER) - }) -}) diff --git a/mobile/src/session/agent-send-keyboard-dismissal-wiring.test.ts b/mobile/src/session/agent-send-keyboard-dismissal-wiring.test.ts deleted file mode 100644 index 03b5398939d..00000000000 --- a/mobile/src/session/agent-send-keyboard-dismissal-wiring.test.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readMobileSessionRouteSource } from './mobile-session-route-source-family.test-support' - -const runtimeSource = readMobileSessionRouteSource('./use-mobile-session-terminal-runtime.ts') -const nativeChatSource = readMobileSessionRouteSource( - './use-mobile-session-native-chat-dictation.ts' -) -const sendActionsSource = readMobileSessionRouteSource( - './use-mobile-session-terminal-send-actions.ts' -) -const commandDockSource = readMobileSessionRouteSource('./MobileSessionCommandDock.tsx') -const tabApplicationSource = readMobileSessionRouteSource('./use-mobile-session-tab-application.ts') -const terminalListSource = readMobileSessionRouteSource('./use-mobile-session-terminal-list.ts') -const startupSource = readMobileSessionRouteSource('./use-mobile-session-startup.ts') -const bufferedDraftHookSource = readMobileSessionRouteSource( - '../terminal/use-buffered-terminal-drafts.ts' -) -const keyboardDismissalHookSource = readMobileSessionRouteSource( - './use-agent-send-keyboard-dismissal.ts' -) - -function sourceSlice(source: string, anchorStart: string, anchorEnd: string): string { - const start = source.indexOf(anchorStart) - expect(start).toBeGreaterThanOrEqual(0) - // Why: a duplicated start anchor would silently slice the wrong region. - expect(source.indexOf(anchorStart, start + 1)).toBe(-1) - const end = source.indexOf(anchorEnd, start) - expect(end).toBeGreaterThan(start) - return source.slice(start, end + anchorEnd.length) -} - -describe('terminal send keyboard dismissal wiring', () => { - it('gates the dismissal on the agent-session predicate', () => { - const slice = sourceSlice( - sendActionsSource, - 'const dismissKeyboardAfterAgentSend = useAgentSendKeyboardDismissal(', - 'getSendCompletionGeneration\n )' - ) - expect(slice).toContain('dismissSoftwareKeyboard') - expect(keyboardDismissalHookSource).toContain( - 'shouldDismissKeyboardAfterTerminalSend(origin.tab, accepted)' - ) - expect(keyboardDismissalHookSource).toContain( - 'origin.generation === getSendCompletionGeneration()' - ) - expect(keyboardDismissalHookSource).toContain('dismissSoftwareKeyboard()') - expect(keyboardDismissalHookSource).toContain('return useCallback(') - expect(sendActionsSource).toContain( - "import { useAgentSendKeyboardDismissal } from './use-agent-send-keyboard-dismissal'" - ) - }) - - it('invalidates pending terminal sends when the focused input surface changes', () => { - const slice = sourceSlice( - nativeChatSource, - 'const getSendCompletionGeneration = useMobileSendCompletionGeneration({', - '})' - ) - expect(nativeChatSource).toContain( - 'const routeKey = nativeChatScopeKey ?? `${hostId}\\0${worktreeId}`' - ) - expect(slice).toContain( - 'surfaceKey: JSON.stringify([routeKey, activeHandle, showNativeChat, liveInputEnabled])' - ) - }) - - it('dismisses after the live input submits, which is the only Enter path', () => { - // terminal-live-input.ts deliberately keeps Enter off the key map, so - // submitLiveInput is the single send seam for the live field. - const slice = sourceSlice( - sendActionsSource, - 'const submitLiveInput = useCallback(() => {', - 'useTerminalTextFieldSubmitBinding(liveInputRef, submitLiveInput)' - ) - expect(slice).toContain('const submit = handleLiveInputSubmit()') - expect(slice).toContain('generation: getSendCompletionGeneration()') - expect(slice).toContain('interaction: getLiveInteractionGeneration()') - expect(slice).toContain('sendOrigin.interaction === getLiveInteractionGeneration()') - expect(slice).toContain('dismissKeyboardAfterAgentSend(') - }) - - it('gives the live field both Enter paths and neither blur', () => { - // The page reaches submitLiveInput through the ref binding, because react-native-web withholds - // onSubmitEditing under an open composition; native reaches it through the editor action. - const slice = sourceSlice( - commandDockSource, - 'ref={bindLiveInputField}', - 'importantForAutofill="no"' - ) - expect(slice).toContain('onSubmitEditing={submitLiveInput}') - // Explicit dismissal replaces RN's blur, which stays off so a shell send - // does not drop focus. - expect(slice).toContain('blurOnSubmit={false}') - }) - - it('dismisses the buffered command send only once the write is accepted', () => { - const slice = sourceSlice( - sendActionsSource, - 'async function handleSend() {', - 'async function handleAccessoryKey(' - ) - const acceptedAt = slice.indexOf( - 'const accepted = terminalInputSend.interpret(response) === true' - ) - const restoreAt = slice.indexOf('restoreRejectedDraft()', acceptedAt) - const dismissAt = slice.indexOf('dismissKeyboardAfterAgentSend(') - const responseAt = slice.indexOf('const response = await terminalInputSend.request(') - const catchAt = slice.indexOf('} catch {') - expect(dismissAt).toBeGreaterThan(0) - expect(responseAt).toBeGreaterThan(0) - expect(acceptedAt).toBeGreaterThan(responseAt) - expect(restoreAt).toBeGreaterThan(acceptedAt) - expect(dismissAt).toBeGreaterThan(responseAt) - expect(slice).toContain( - 'const draftUnchanged =\n accepted && bufferedTerminalDraftState.settleBufferedTerminalDraftSend(bufferedDraftSend)' - ) - expect(slice).toContain('dismissKeyboardAfterAgentSend(sendOrigin, accepted && draftUnchanged)') - expect(catchAt).toBeGreaterThan(0) - // Both resolved rejections and transport failures restore the raw draft. - expect(dismissAt).toBeLessThan(catchAt) - expect(slice.slice(catchAt)).not.toContain('dismissKeyboardAfterAgentSend(') - expect(slice.slice(catchAt)).toContain('restoreRejectedDraft()') - }) - - it('keeps buffered Return focused until accepted-agent dismissal runs', () => { - const slice = sourceSlice( - commandDockSource, - 'ref={bindCommandField}', - 'onSubmitEditing={() => void handleSend()}' - ) - expect(slice).toContain('blurOnSubmit={false}') - }) - - it('restores a rejected buffered draft by origin without generation fencing', () => { - const sendSlice = sourceSlice( - sendActionsSource, - 'async function handleSend() {', - 'async function handleAccessoryKey(' - ) - const originAt = sendSlice.indexOf('handle: activeHandle') - const requestAt = sendSlice.indexOf('await terminalInputSend.request(') - const restoreSlice = sourceSlice( - sendActionsSource, - 'const bufferedDraftSend = bufferedTerminalDraftState.beginBufferedTerminalDraftSend(', - 'bufferedTerminalDraftState.restoreRejectedDraft(bufferedDraftSend)' - ) - expect(originAt).toBeGreaterThan(0) - expect(originAt).toBeLessThan(requestAt) - expect(restoreSlice).toContain('activeHandle,\n draft') - expect(bufferedDraftHookSource).not.toContain('getSendCompletionGeneration()') - expect(bufferedDraftHookSource).toContain( - 'restoreRejectedBufferedTerminalDraft(current, send.token.handle, send.draft)' - ) - expect(sendSlice.match(/restoreRejectedDraft\(\)/g)).toHaveLength(2) - expect(keyboardDismissalHookSource).toContain( - 'origin.generation === getSendCompletionGeneration()' - ) - }) - - it('keeps buffered draft callbacks scoped to terminal surfaces and prunes ended tabs', () => { - expect(bufferedDraftHookSource).toContain('const handle = activeHandleRef.current') - expect(bufferedDraftHookSource).toContain('invalidateBufferedTerminalDraftRestoration(') - expect(bufferedDraftHookSource).toContain( - 'setDrafts((current) => updateBufferedTerminalDraft(current, handle, value))' - ) - expect(bufferedDraftHookSource).toContain('pruneBufferedTerminalDraftRestorations(') - expect(runtimeSource).toContain('useRef(bufferedTerminalDraftState.reconcileTerminalTabs)') - expect(tabApplicationSource).toContain( - 'reconcileBufferedDraftsRef.current(currentSessionTabs, nextTabs, {' - ) - const routeResetSlice = sourceSlice( - startupSource, - '// Why: Expo reuses this screen across worktrees;', - 'clearDelayedActionTimers()\n }' - ) - expect(routeResetSlice).toContain('bufferedTerminalDraftState.resetDrafts()') - expect(routeResetSlice).toContain('bufferedTerminalDraftState.clearPendingRestorations()') - }) - - it('bounds buffered drafts on the terminal.list sweep, against the retained set', () => { - // The drafts record and the pending-restoration map both live as long as the - // session screen does; this one call is the only thing that bounds either. - const slice = sourceSlice( - terminalListSource, - 'const liveHandles = new Set(result.terminals.map((terminal) => terminal.handle))', - 'setTerminalKeyboardMetrics((prev) => pruneTerminalKeyboardMetrics(prev, shouldPrune))' - ) - expect(slice).toContain('const retainedHandles = resolveRetainedTerminalHandles(pruneContext)') - expect(slice).toContain('bufferedTerminalDraftState.pruneDrafts(retainedHandles)') - // Not the raw list: terminal.list omits a chat-covered handle while the desktop - // graph reloads, so sweeping drafts against it erases text the user still holds. - expect(slice).not.toContain('pruneDrafts(liveHandles)') - expect(slice.match(/pruneDrafts\(/g)).toHaveLength(1) - expect(bufferedDraftHookSource).toContain( - 'setDrafts((current) => pruneBufferedTerminalDrafts(current, retainedMappedHandles))' - ) - expect(bufferedDraftHookSource).toContain( - 'pruneBufferedTerminalDraftRestorations(pendingRestorationsRef.current, retainedMappedHandles)' - ) - }) - - it('leaves the accessory shortcut keys alone, Enter included', () => { - // Why: the accessory bar sits on top of the keyboard — dismissing would - // pull away the very row the user is tapping. - const slice = sourceSlice( - sendActionsSource, - 'async function handleAccessoryKey(', - 'const sendLiveTerminalInput = useCallback(' - ) - expect(slice).not.toContain('dismissKeyboardAfterAgentSend') - }) -}) diff --git a/mobile/src/session/mobile-native-chat-noise.test.ts b/mobile/src/session/mobile-native-chat-noise.test.ts index 0369a609135..dcda3f3dace 100644 --- a/mobile/src/session/mobile-native-chat-noise.test.ts +++ b/mobile/src/session/mobile-native-chat-noise.test.ts @@ -44,6 +44,7 @@ describe('isNoiseMessage', () => { it('keeps assistant and tool turns', () => { expect(isNoiseMessage(msg('assistant', ' in prose'))).toBe(false) + expect(isNoiseMessage(msg('system', 'Conversation interrupted'))).toBe(false) }) it('keeps a user turn that carries tool results', () => { diff --git a/mobile/src/session/mobile-session-last-tab-close.test.ts b/mobile/src/session/mobile-session-last-tab-close.test.ts deleted file mode 100644 index a15a62b1535..00000000000 --- a/mobile/src/session/mobile-session-last-tab-close.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readMobileSessionRouteSourceFamily } from './mobile-session-route-source-family.test-support' - -const sessionRouteSource = readMobileSessionRouteSourceFamily() - -describe('mobile session last-tab close', () => { - it('preserves terminal identity while an empty snapshot may be transient', () => { - const start = sessionRouteSource.indexOf('const applySessionTabs = useCallback') - const end = sessionRouteSource.indexOf('const readMarkdownTab', start) - const block = sessionRouteSource.slice(start, end) - - expect(block).toContain('} else if (active) {') - expect(block).toContain('retainMissingSurfaces: result.tabs.length === 0') - }) - - it('clears stale active identity when closing leaves no tabs', () => { - const start = sessionRouteSource.indexOf('async function handleCloseSessionTab') - const end = sessionRouteSource.indexOf('const bulkCloseActions', start) - const block = sessionRouteSource.slice(start, end) - - expect(block).toContain( - 'activeSessionTabIdRef.current === tab.id || remainingTabs.length === 0' - ) - expect(block).toContain('activeSessionTabIdRef.current = null') - expect(block).toContain('activeHandleRef.current = null') - expect(block).toContain( - 'reconcileBufferedDraftsRef.current(sessionTabsRef.current, remainingTabs)' - ) - }) - - it('ignores a pending terminal handle when the host requests follow navigation', () => { - const start = sessionRouteSource.indexOf('const applySessionTabs = useCallback') - const end = sessionRouteSource.indexOf('const readMarkdownTab', start) - const block = sessionRouteSource.slice(start, end) - - const followsHost = block.indexOf("const followsHost = result.navigationIntent === 'follow'") - const pendingHandle = block.indexOf('const pendingActiveTerminalHandle = followsHost') - - expect(followsHost).toBeGreaterThanOrEqual(0) - expect(pendingHandle).toBeGreaterThan(followsHost) - expect(block.slice(pendingHandle, pendingHandle + 150)).toContain('? null') - }) -}) diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts deleted file mode 100644 index 7c0ac36e453..00000000000 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ /dev/null @@ -1,669 +0,0 @@ -import { createHash } from 'node:crypto' -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import ts from 'typescript-api' -import { describe, expect, it } from 'vitest' -import { MOBILE_SESSION_ROUTE_SOURCE_FILES } from './mobile-session-route-source-family.test-support' - -const SESSION_FILES = MOBILE_SESSION_ROUTE_SOURCE_FILES -/** The function the route mounts, which C7.7 moved out of the route file and into a component. */ -const ROOT_COMPONENT = 'MobileSessionRouteScreen' -const LOGIC_EXPANSION_NAMES = new Set([ - 'useMobileSessionController', - 'useMobileSessionFoundation', - 'useMobileSessionScreenState', - 'useMobileSessionTerminalRuntime', - 'useMobileSessionFeedbackCapabilities', - 'useMobileSessionNativeChatDictation', - 'useMobileSessionTerminalSubscriptionFoundation', - 'useMobileSessionTerminalSubscription', - 'useMobileSessionTerminalStreamDisplay', - 'useMobileSessionTerminalList', - 'useMobileSessionTabApplication', - 'useMobileSessionDocumentReaders', - 'useMobileSessionDiffComments', - 'useMobileSessionMarkdownActions', - 'useMobileSessionTabReconciliation', - 'useMobileSessionLifecycle', - 'useMobileSessionKeyboardState', - 'useMobileSessionStartup', - 'useMobileSessionPreferenceFocus', - 'useMobileSessionTabSwitching', - 'useMobileSessionTerminalWebview', - 'useMobileSessionTerminalSendActions', - 'useMobileSessionFileActions', - 'useMobileSessionTerminalInput', - 'useMobileSessionAccessorySelection', - 'useMobileSessionAttachments', - 'useMobileSessionTerminalCreateActions', - 'useMobileSessionContentCreateActions', - 'useMobileSessionCloseActions', - 'useMobileSessionBulkClose', - 'useMobileSessionPresentation', - 'useMobileSessionPanelRouteActions' -]) -const SURFACE_EXPANSION_NAMES = new Set([ - 'MobileSessionSurface', - 'MobileSessionHeader', - 'MobileSessionContentRow', - 'MobileSessionActiveContent', - 'MobileSessionCommandDock', - 'MobileSessionSheets' -]) -const CONTENT_COMPONENT_NAMES = ['MarkdownReader', 'DiffLineRow', 'FileReader'] as const -const HOST_COMPONENT_NAMES = new Set([ - 'ActivityIndicator', - 'Animated.View', - 'FlatList', - 'Image', - 'Pressable', - 'SafeAreaView', - 'ScrollView', - 'Text', - 'TextInput', - 'View' -]) - -// Refreshed by C7.2: five clipboard hooks joined the expanded route, which is the whole of the +5 — -// a writer in the diff-note, Markdown and selection actions, a reader in the selection actions and -// the attachment probe. The screen's other four clipboard sites (the terminal's paste, the sheets, -// the quick-command row, the diff-review send) sit outside the walk from `MobileSessionRouteScreen` -// and so do not move this pin. The copy-path sheet also gained the failure toast the other two had. -// Refreshed for `reportDictationFailure`, the whole of that +1: the composer's two dictation -// failure handlers were one policy written twice, and only `onError`'s copy knew about the setup -// sheet, so a refused start showed the desktop's own `voice_dictation_disabled` as a toast. -// -// Refreshed again for the page's keyboard: the screen's own `Keyboard.addListener` pair became the -// `useSoftKeyboard` seam, because react-native-web never fires those events and the live input row -// laid itself out under the IME. +2 hooks (the seam, and the one effect split into a visibility one -// and a height one), +1 effect, -2 registrations and -2 removals for the listener pair, and -6 -// strings: the four event names and the two `'ios'` guards that chose between them. Re-recorded -// against the merged tree, since neither side's hash covers the other's change. -// -// Refreshed for the terminal fields' submit seam: react-native-web withholds `onSubmitEditing` -// when the Enter keydown reports an open composition, which is a soft keyboard's normal mid-word -// state, so both of the dock's fields also bind the page's own line-break signal. +4 hooks and +2 -// callbacks in the send actions — `submitLiveInput` and `submitBufferedDraft`, each with a -// `useTerminalTextFieldSubmitBinding` beside it — and both fields moved their ref, the live one -// its submit handler too. -// Moved once more, -1 hook and -1 callback: `submitBufferedDraft` stopped being a `useCallback`. -// Memoizing it on `[]` froze the per-render `handleSend` it reads, whose guard needs a `client` -// and an `activeHandle` the first render does not have, so the page's line-break submit could -// never pass it. Found by pullfrog on #22300. -// Moved, count unchanged, when the Markdown actions' Back `useEffect` became `useBackClaim`, the -// seam that also claims the key on the page while a draft is dirty. -// Refreshed when the first subscribe began sizing itself from the document's reported cell box: -// the first-subscribe mark ref and `measureViewportOnce` are gone (hooks 282 → 280, callbacks 79 → 78). -// Again when xterm became the only cell measurer: `useTerminalCellBoxRefit` is gone, the frame's -// width ref and `handleTerminalFrameLayout` subscribe a known box on layout (hooks 282, callbacks 79), -// and the pane's `onCellBoxChange` goes to the viewport refit. -// Again when one frame ref replaced the height ref, width ref and width state (hooks 280). -// Again when one `notifyTerminalFrame` took the frame's layout (hooks 281, callbacks 80). -const HEAD_MAIN_HOOK_SHA256 = '004b011722b17ac82c96f0b3c8e303d39b2431a216424e9b86a1ee6a4896f23e' -// Moved when the prompt-cancel flag became one structured-session host support object (main). -// Re-recorded against the merged tree. Again when the frame-layout and cell-box-change callbacks -// named the refs they read in their dependency lists (react-doctor). -// Again when the frame's width and height became one `terminalFrameRef`. -// Again when the frame's layout moved into `notifyTerminalFrame`. -const HEAD_HOOK_BINDING_SHA256 = 'c1bcb859202aaf8d612d3023cb4d895719da513879c61b01545a249a0bda662b' -// Moved when `notifyTerminalFrame` joined and `handleTerminalFrameLayout` became `subscribeIntendedActiveTerminal`. -const HEAD_CALLBACK_IDENTITY_SHA256 = - '9c966301b373c11b27359ef1388c593b638c7f6831186d5c5321553504183e07' -// Pins that no callback body in the route changed unnoticed. Body text, not behaviour: the sends -// and repo reads inside them now name their `RpcOperation` instead of the raw `sendRequest` port. -// Refreshed in step 6 for the gesture flush, whose `terminal.send` became `terminalInputSend` and -// whose accepted-check became that operation's own verdict, then again when that check was spelled -// `=== true` to match the other four sites reading the same verdict. Refreshed in step 7 for the -// reply casts the checked readers made unnecessary — the markdown tab doc, the worktree record's -// `diffComments` and the browser tab's page id are typed by their schemas now. Refreshed once more -// on the merge, for the display-mode toggle whose send became `terminalDisplayModeSet`. Refreshed -// for the files domain's step 7, which retired the markdown disk fallback's `{ content, truncated, -// byteLength }` cast: the preview reader checks the content and salvages the flag, so `readMarkdownTab` -// reads `fallback.value` directly. The dictation-mode refresh is main's own body again — it forwards -// whatever mode the reply carried, so an absent one leaves the mic as inert as main left it. -// Refreshed on the merge of C7.2 and C7.3, which moved this pin from both sides: the terminal -// subscribe now carries the snapshot byte budget its transport imposes, nothing on a phone and the -// frame cap inside the shell's page, and the Markdown copy action gained the failure branch that -// answers a refused write. Re-recorded against the merged tree, since neither side's hash covers -// the other's body. The hook and string counts are C7.2's and stand. -// Refreshed once more for the two dictation failure handlers, which now both call -// `reportDictationFailure` instead of each choosing between the setup sheet and a toast. -// Moved when the metrics handler compared every field, the row pitch included (main). -// Again when the subscribe waited for web-ready and `handleTerminalWebReady` lost `documentHasInit`. -// Again when the subscribe's inits began carrying the laid-out terminal frame, and its resize too. -// Again when those grids read the one frame ref. -// Again when the subscribe sized its viewport inline instead of through a helper. -// Again when the document took the hold rule and the subscribe stopped holding its grid. -// Again when an init took one options object. -// Again when the frame's layout became one `notifyTerminalFrame`. -// Again when the init option took the message's name, `initialData`. -// Again when the document readers mapped refusal codes through one function and kept truncation. -const HEAD_CALLBACK_BODY_SHA256 = 'ff818790399c8532ead38d047d072caf715070b21311538932da2dc811312b06' -// Refreshed for the startup effect: both `worktree.activate` sends became `worktreeActivate`, and -// the sleeping-agent check reads that operation's verdict instead of the reply envelope. Refreshed -// again when the reporter took the reply and interpreted it itself, retiring the hand-built -// refusal the timer site passed when it had no reply at all. Refreshed once more for the -// last-visited-worktree effect, whose bare store write became the one writer of that key, so the -// hybrid shell's page mirror sees it as it is written rather than one `init` later. Refreshed for -// the diff-comments effect, which now catches the loader's rejection. Count unchanged. -// Moved again by the keyboard seam above, which is the +1 effect. -// -1 effect for the Markdown actions' Back registration, which is `useBackClaim`'s own now. -// Moved by the capability probe setting that host support object. -const HEAD_EFFECT_SHA256 = '9b045a547ed269acf95db16cc87e33a9035a20c6888fd30e0363e58bb6b7d883' -const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581' -// Same pin for the 12 bodies that sit in nested functions rather than callbacks, moved by the same -// rewrite of those send and read expressions. Count unchanged. Refreshed again in step 6 for -// `handleClearTerminal`, whose send became `terminalBufferClear`, in step 7 for the browser tab -// create, whose `{ browserPageId?: string }` cast its schema now carries, and once more for -// `handleCreateTerminal`, whose send became `sessionTabCreateTerminal` and whose `response.ok` -// branch became that operation's own throw-the-host-message acceptance. Refreshed for negotiated -// optimistic placement, which defers to legacy host snapshots when ownership paths disagree. -const HEAD_NESTED_FUNCTION_SHA256 = - '923b5ea7fe3330cbd98213b72736bf1f653115ddb5492cb8eb8306d8ca4f28e8' -// -1 registration and -1 removal: the Markdown actions' `BackHandler` pair is `useBackClaim`'s. -const HEAD_NATIVE_REGISTRATION_SHA256 = - '87d4599f475575131d4d5daa20f0dac579ca6c829353cbb654206ea6965dadae' -const HEAD_NATIVE_REMOVAL_SHA256 = - '089bebbc1e4f2e68c5dbaf189bb605d8d5bb247ef5ca52b9db08cc2661afc097' -const HEAD_TIMER_CREATION_SHA256 = - '1a31b625e2174c3db77272249843196d2b6b06ab1e654a96d8f7858e3082e66b' -const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f34234541a2065ec3d1a8cd116' -// Six method literals fewer than before step 6: `terminal.send` and `terminal.clearBuffer` went -// first, then `worktree.activate` twice, `session.tabs.createTerminal` and -// `terminal.setDisplayMode`. Each is now fixed at its operation's definition instead of being -// spelled at the call site. Two literals more across C7.2, both of them the toast a refused write -// now shows: "Couldn't copy path" when the sheets moved onto the clipboard seam, taking the count -// from 532 to 533, and "Couldn't copy" when the Markdown copy action gained the failure branch the -// other copy paths already had, taking it to 534. -// -// Two more across C7.7, 534 -> 536: `'web'`, the platform guard the Markdown actions' -// `BackHandler` registration gained so it stops logging on the page, and `"button"`, the -// accessibility role the header's Back control gained so the page serves it by name. Neither is a -// behaviour change on a phone. The same `'web'` moves the effect hash, and `"button"` the host-JSX -// hash. The effect hash moved a second time and back: the diff-notes loader's uncaught rejection -// was caught and then reverted, because the fix moves `matrix-session.diff-notes-worktree.show-1` -// and a golden is a review event — so this hash is the one the uncaught `void` call produces. -// -// 536 -> 530 for the keyboard seam above: the four event names and the two `'ios'` guards left -// with the listener pair. -// -// The host-JSX hash moved for the header's reconnect tap, which now also checks the re-dial exists: -// the page's provider hands out none. Nothing a phone renders or does changed. -// -// 530 -> 529: `'hardwareBackPress'` left with the Markdown actions' registration for `useBackClaim`. -// -// 529 -> 530, and the host-JSX hash: `key="terminal-frame"`, so the page's frame mounts with its -// onLayout rather than reusing the loading View. Native measured 47 rows before and after: its -// frame reported either way, and its window is its frame, so both measure paths agree there. -// -// 531 -> 530, and the host-JSX and style hashes: the key left, and one `contentFrame` View wraps -// every branch and carries the frame's onLayout, so the page's frame mounts with it. The page measured -// 47 rows before and after; native was measured only on main's bundle (47), and the wrapper is a -// flex:1 View around the same flex:1 frame, so its box is the frame's. -// Count unchanged: `'frame-not-laid-out'`, the gate awaiting the frame's first layout, replaced `'measuring-viewport'`. -// 530 -> 532, and the host-JSX hash: the tab bar and the accessory bar take a ref that gives the -// page `keyboardShouldPersistTaps` ('handled', 'always'), which react-native-web ignores. Natively -// the ref is undefined. 532 -> 531: the live input's reopen flag reads the host OS, not an 'android' literal. -// 531 -> 529: the markdown status line moved to `markdownReaderStatusText`. -const HEAD_RUNTIME_STRING_SHA256 = - '4ab2f316f60c234480615136c02273675543f24d653eb76a62b76f6bc986d985' -// Moved by both of the dock's fields: their refs, and the live one's submit handler, are the seam's now; -// their keyboard type and remount key read the host OS. -// Moved again when the terminal frame kept its laid-out width unrounded, for every fit. -// Again when the frame's onLayout wrote one frame ref and notified a new width imperatively. -// Again when the frame's first laid-out layout alone subscribes a held-back document. -// Again when the frame's onLayout made one `notifyTerminalFrame` call. -const HEAD_HOST_JSX_SHA256 = 'f71b1ee495f67a6e389abf597948ffdff1f9a4a10cde6abefd2611ea4dd94245' -const HEAD_LEAF_JSX_SHA256 = '62eb05c6e2ac0be6d553a141fc8aa1641fcb0c678777d5d539f490aab8648417' -const HEAD_STYLE_REFERENCE_SHA256 = - '56a005a1f65b30c11092e3422caef67810e1ec50f66fdd06471c370138b1eeb6' -const HEAD_IDENTITY_FIELD_SHA256 = - '91146853930a34dd1f3d80e5c97fbacd7cf19fb93dd26fe8fc6f29169622f9d6' -const HEAD_NAVIGATION_SHA256 = '9d96f5dad7de555d6553eac39c0fab00efad507470fd562cb9beaa32db16f512' -// Moved when structured-session features became one helper call; the capability strings it reads -// are pinned by that helper's own test. -const HEAD_CAPABILITY_SHA256 = 'ec1159d6e726383bf7121e9c642657fee5b4ebec049cb44ba132a303bb9a61e2' - -type Definition = { declaration: ts.FunctionDeclaration; sourceFile: ts.SourceFile } -type HookFacts = { - bindings: string[] - callbackBodies: string[] - callbacks: string[] - effects: string[] - hooks: string[] -} - -const printer = ts.createPrinter({ removeComments: true }) -const sourceFiles = new Map() - -function parse(relativePath: string): ts.SourceFile { - const cached = sourceFiles.get(relativePath) - if (cached) { - return cached - } - const filePath = fileURLToPath(new URL(relativePath, import.meta.url)) - const sourceFile = ts.createSourceFile( - relativePath, - readFileSync(filePath, 'utf8'), - ts.ScriptTarget.Latest, - true, - relativePath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS - ) - sourceFiles.set(relativePath, sourceFile) - return sourceFile -} - -function canonical(node: ts.Node, sourceFile: ts.SourceFile): string { - return printer.printNode(ts.EmitHint.Unspecified, node, sourceFile).replace(/\s+/g, '') -} - -function hash(values: readonly string[]): string { - return createHash('sha256').update(values.join('\n')).digest('hex') -} - -function readDefinitions(): Map { - const definitions = new Map() - for (const relativePath of SESSION_FILES) { - const sourceFile = parse(relativePath) - const visit = (node: ts.Node): void => { - if (ts.isFunctionDeclaration(node) && node.name) { - definitions.set(node.name.text, { declaration: node, sourceFile }) - } - ts.forEachChild(node, visit) - } - visit(sourceFile) - } - return definitions -} - -function visitLogicalFunction( - name: string, - definitions: ReadonlyMap, - onNode: (node: ts.Node, sourceFile: ts.SourceFile) => void, - active = new Set() -): void { - const definition = definitions.get(name) - if (!definition?.declaration.body) { - throw new Error(`Missing session function: ${name}`) - } - if (active.has(name)) { - throw new Error(`Recursive session function: ${name}`) - } - const nextActive = new Set(active).add(name) - const visit = (node: ts.Node): void => { - if ( - ts.isCallExpression(node) && - ts.isIdentifier(node.expression) && - LOGIC_EXPANSION_NAMES.has(node.expression.text) - ) { - visitLogicalFunction(node.expression.text, definitions, onNode, nextActive) - return - } - onNode(node, definition.sourceFile) - ts.forEachChild(node, visit) - } - visit(definition.declaration.body) -} - -function readHookFacts(name: string, definitions: ReadonlyMap): HookFacts { - const facts: HookFacts = { - bindings: [], - callbackBodies: [], - callbacks: [], - effects: [], - hooks: [] - } - visitLogicalFunction(name, definitions, (node, sourceFile) => { - if ( - !ts.isCallExpression(node) || - !ts.isIdentifier(node.expression) || - !/^use[A-Z]/.test(node.expression.text) - ) { - return - } - const hookName = node.expression.text - facts.hooks.push(hookName) - const owner = ts.isVariableDeclaration(node.parent) - ? node.parent.name.getText(sourceFile) - : ts.isExpressionStatement(node.parent) - ? '' - : ts.isCallExpression(node.parent) && ts.isIdentifier(node.parent.expression) - ? `` - : '' - const lastArgument = node.arguments.at(-1) - const dependencies = - lastArgument && ts.isArrayLiteralExpression(lastArgument) - ? canonical(lastArgument, sourceFile) - : '' - facts.bindings.push(`${hookName}|${owner}|${dependencies}`) - if (hookName === 'useCallback') { - facts.callbacks.push(`${owner}|${dependencies}`) - facts.callbackBodies.push( - `${owner}|${canonical(node.arguments[0], sourceFile)}|${dependencies}` - ) - } - if (hookName === 'useEffect') { - facts.effects.push(`${canonical(node.arguments[0], sourceFile)}|${dependencies}`) - } - }) - return facts -} - -function readNestedFunctions(definitions: ReadonlyMap): string[] { - const functions: string[] = [] - const visitDefinition = (name: string, active: ReadonlySet): void => { - const definition = definitions.get(name) - if (!definition?.declaration.body || active.has(name)) { - throw new Error(`Invalid nested-function stage: ${name}`) - } - const nextActive = new Set(active).add(name) - const visit = (node: ts.Node): void => { - if ( - ts.isCallExpression(node) && - ts.isIdentifier(node.expression) && - LOGIC_EXPANSION_NAMES.has(node.expression.text) - ) { - visitDefinition(node.expression.text, nextActive) - return - } - if (ts.isFunctionDeclaration(node) && node.name) { - functions.push(`${node.name.text}|${canonical(node, definition.sourceFile)}`) - return - } - ts.forEachChild(node, visit) - } - visit(definition.declaration.body) - } - visitDefinition(ROOT_COMPONENT, new Set()) - return functions -} - -function readNativeAndTimerFacts(definitions: ReadonlyMap): { - cleanups: string[] - creations: string[] - registrations: string[] - removals: string[] -} { - const registrations: string[] = [] - const removals: string[] = [] - const creations: string[] = [] - const cleanups: string[] = [] - const collect = (node: ts.Node, sourceFile: ts.SourceFile): void => { - if (!ts.isCallExpression(node)) { - return - } - if (ts.isPropertyAccessExpression(node.expression)) { - const receiver = node.expression.expression.getText(sourceFile) - const method = node.expression.name.text - if ( - ['BackHandler', 'AppState', 'Keyboard'].includes(receiver) && - ['addEventListener', 'addListener'].includes(method) - ) { - registrations.push(canonical(node, sourceFile)) - } - if (method === 'remove') { - removals.push(canonical(node, sourceFile)) - } - } - if (ts.isIdentifier(node.expression)) { - if (['setTimeout', 'setInterval', 'requestAnimationFrame'].includes(node.expression.text)) { - creations.push(canonical(node, sourceFile)) - } - if ( - ['clearTimeout', 'clearInterval', 'cancelAnimationFrame'].includes(node.expression.text) - ) { - cleanups.push(canonical(node, sourceFile)) - } - } - } - visitLogicalFunction('FileReader', definitions, collect) - visitLogicalFunction(ROOT_COMPONENT, definitions, collect) - return { cleanups, creations, registrations, removals } -} - -function isRuntimeNode(node: ts.Node): boolean { - for (let parent = node.parent; parent; parent = parent.parent) { - if ( - ts.isImportDeclaration(parent) || - ts.isExportDeclaration(parent) || - ts.isImportTypeNode(parent) || - ts.isTypeNode(parent) - ) { - return false - } - } - return true -} - -function readRuntimeStrings(): string[] { - const values: string[] = [] - for (const relativePath of SESSION_FILES) { - const visit = (node: ts.Node): void => { - if (isRuntimeNode(node)) { - if ( - ts.isStringLiteral(node) || - ts.isNoSubstitutionTemplateLiteral(node) || - ts.isTemplateHead(node) || - ts.isTemplateMiddle(node) || - ts.isTemplateTail(node) - ) { - values.push(node.text) - } - if (ts.isJsxText(node) && node.text.trim()) { - values.push(node.text.replace(/\s+/g, ' ').trim()) - } - } - ts.forEachChild(node, visit) - } - visit(parse(relativePath)) - } - return values.sort() -} - -function readJsxFacts(definitions: ReadonlyMap): { - host: string[] - leaf: string[] - styleReferences: string[] -} { - const host: string[] = [] - const leaf: string[] = [] - const active = new Set() - const visitDefinition = (name: string): void => { - const definition = definitions.get(name) - if (!definition?.declaration.body || active.has(name)) { - throw new Error(`Invalid JSX stage: ${name}`) - } - active.add(name) - const visit = (node: ts.Node): void => { - if ( - ts.isCallExpression(node) && - ts.isIdentifier(node.expression) && - LOGIC_EXPANSION_NAMES.has(node.expression.text) - ) { - visitDefinition(node.expression.text) - return - } - if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) { - const opening = ts.isJsxElement(node) ? node.openingElement : node - const tagName = opening.tagName.getText(definition.sourceFile) - if (SURFACE_EXPANSION_NAMES.has(tagName)) { - visitDefinition(tagName) - return - } - const attributes = opening.attributes.properties - .map((attribute) => { - if (ts.isJsxSpreadAttribute(attribute)) { - return `...${canonical(attribute.expression, definition.sourceFile)}` - } - const attributeName = attribute.name.getText(definition.sourceFile) - if (!attribute.initializer) { - return attributeName - } - if (ts.isStringLiteral(attribute.initializer)) { - return `${attributeName}=${JSON.stringify(attribute.initializer.text)}` - } - return `${attributeName}=${ - attribute.initializer.expression - ? canonical(attribute.initializer.expression, definition.sourceFile) - : '' - }` - }) - .join(',') - ;(HOST_COMPONENT_NAMES.has(tagName) ? host : leaf).push(`${tagName}|${attributes}`) - for (const attribute of opening.attributes.properties) { - ts.forEachChild(attribute, visit) - } - if (ts.isJsxElement(node)) { - for (const child of node.children) { - visit(child) - } - } - return - } - if (ts.isJsxFragment(node)) { - for (const child of node.children) { - visit(child) - } - return - } - ts.forEachChild(node, visit) - } - visit(definition.declaration.body) - active.delete(name) - } - for (const name of CONTENT_COMPONENT_NAMES) { - visitDefinition(name) - } - visitDefinition(ROOT_COMPONENT) - const styleReferences: string[] = [] - for (const record of [...host, ...leaf]) { - for (const match of record.matchAll(/styles\.([A-Za-z0-9_]+)/g)) { - styleReferences.push(match[1]) - } - } - return { host, leaf, styleReferences } -} - -function readCompatibilityFacts(definitions: ReadonlyMap): { - capabilities: string[] - identityFields: string[] - navigation: string[] -} { - const capabilities: string[] = [] - const identityFields: string[] = [] - const navigation: string[] = [] - visitLogicalFunction(ROOT_COMPONENT, definitions, (node, sourceFile) => { - if (!isRuntimeNode(node)) { - return - } - if (ts.isPropertyAssignment(node)) { - const name = node.name.getText(sourceFile) - if (['notifyClients', 'deviceToken', 'clientId'].includes(name)) { - identityFields.push(`${name}|${canonical(node.initializer, sourceFile)}`) - } - if ( - name === 'client' && - ts.isObjectLiteralExpression(node.initializer) && - node.initializer.properties.some( - (property) => property.name?.getText(sourceFile) === 'id' - ) && - node.initializer.properties.some( - (property) => property.name?.getText(sourceFile) === 'type' - ) - ) { - identityFields.push(`client|${canonical(node.initializer, sourceFile)}`) - } - } - if (!ts.isCallExpression(node)) { - return - } - if ( - ts.isPropertyAccessExpression(node.expression) && - node.expression.expression.getText(sourceFile) === 'router' && - ['push', 'replace', 'back'].includes(node.expression.name.text) - ) { - navigation.push(canonical(node, sourceFile)) - } - const callName = ts.isIdentifier(node.expression) - ? node.expression.text - : ts.isPropertyAccessExpression(node.expression) - ? node.expression.name.text - : '' - const callText = canonical(node, sourceFile) - if ( - [ - 'startRuntimeCapabilityProbe', - 'supportsMobileQuickCommands', - 'structuredAgentSessionHostSupport' - ].includes(callName) || - (callName === 'includes' && callText.includes('capabilities.includes')) - ) { - capabilities.push(callText) - } - }) - return { capabilities, identityFields, navigation } -} - -describe('mobile session route extraction parity', () => { - it('preserves hooks, callbacks, effects, and nested action bodies', () => { - const definitions = readDefinitions() - const main = readHookFacts(ROOT_COMPONENT, definitions) - const contentBindings = CONTENT_COMPONENT_NAMES.flatMap( - (name) => readHookFacts(name, definitions).bindings - ) - expect(main.hooks).toHaveLength(281) - expect(hash(main.hooks)).toBe(HEAD_MAIN_HOOK_SHA256) - expect(hash(main.bindings)).toBe(HEAD_HOOK_BINDING_SHA256) - expect(main.callbacks).toHaveLength(80) - expect(hash(main.callbacks)).toBe(HEAD_CALLBACK_IDENTITY_SHA256) - expect(hash(main.callbackBodies)).toBe(HEAD_CALLBACK_BODY_SHA256) - expect(main.effects).toHaveLength(24) - expect(hash(main.effects)).toBe(HEAD_EFFECT_SHA256) - expect(contentBindings).toHaveLength(14) - expect(hash(contentBindings)).toBe(HEAD_CONTENT_HOOK_SHA256) - const nestedFunctions = readNestedFunctions(definitions) - expect(nestedFunctions).toHaveLength(12) - expect(hash(nestedFunctions)).toBe(HEAD_NESTED_FUNCTION_SHA256) - }) - - it('preserves native listeners, timers, identity payloads, and compatibility gates', () => { - const definitions = readDefinitions() - const native = readNativeAndTimerFacts(definitions) - expect(native.registrations).toHaveLength(4) - expect(hash(native.registrations)).toBe(HEAD_NATIVE_REGISTRATION_SHA256) - expect(native.removals).toHaveLength(6) - expect(hash(native.removals)).toBe(HEAD_NATIVE_REMOVAL_SHA256) - expect(native.creations.filter((fact) => fact.startsWith('setTimeout'))).toHaveLength(7) - expect(native.creations.filter((fact) => fact.startsWith('setInterval'))).toHaveLength(1) - expect( - native.creations.filter((fact) => fact.startsWith('requestAnimationFrame')) - ).toHaveLength(1) - expect(hash(native.creations)).toBe(HEAD_TIMER_CREATION_SHA256) - expect(native.cleanups.filter((fact) => fact.startsWith('clearTimeout'))).toHaveLength(11) - expect(native.cleanups.filter((fact) => fact.startsWith('clearInterval'))).toHaveLength(1) - expect(native.cleanups.filter((fact) => fact.startsWith('cancelAnimationFrame'))).toHaveLength( - 1 - ) - expect(hash(native.cleanups)).toBe(HEAD_TIMER_CLEANUP_SHA256) - const compatibility = readCompatibilityFacts(definitions) - expect(compatibility.identityFields).toHaveLength(14) - expect(hash(compatibility.identityFields)).toBe(HEAD_IDENTITY_FIELD_SHA256) - expect(compatibility.navigation).toHaveLength(6) - expect(hash(compatibility.navigation)).toBe(HEAD_NAVIGATION_SHA256) - expect(compatibility.capabilities).toHaveLength(6) - expect(hash(compatibility.capabilities)).toBe(HEAD_CAPABILITY_SHA256) - }) - - it('preserves runtime strings, styles, and the expanded JSX tree', () => { - const strings = readRuntimeStrings() - expect(strings).toHaveLength(529) - expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) - const jsx = readJsxFacts(readDefinitions()) - expect(jsx.host).toHaveLength(125) - expect(hash(jsx.host)).toBe(HEAD_HOST_JSX_SHA256) - expect(jsx.leaf).toHaveLength(61) - expect(hash(jsx.leaf)).toBe(HEAD_LEAF_JSX_SHA256) - expect(jsx.styleReferences).toHaveLength(173) - expect(hash(jsx.styleReferences)).toBe(HEAD_STYLE_REFERENCE_SHA256) - }) -}) diff --git a/mobile/src/session/mobile-session-route-source-family.test-support.ts b/mobile/src/session/mobile-session-route-source-family.test-support.ts deleted file mode 100644 index 23ae6fb348e..00000000000 --- a/mobile/src/session/mobile-session-route-source-family.test-support.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' - -/** - * The session screen as one source family, rooted at the component the route mounts. - * - * `MobileSessionRouteScreen.tsx` and not the route file: C7.7 made that file a flag switch, whose - * business is which of the two screens to render and not what the session screen does. Walking it - * would pin the switch's own params and literals into an extraction parity hash that is about the - * screen, and the root function this family is read from is the one that calls the controller. - */ -export const MOBILE_SESSION_ROUTE_SOURCE_FILES = [ - './MobileSessionRouteScreen.tsx', - './use-mobile-session-controller.ts', - './use-mobile-session-foundation.ts', - './use-mobile-session-screen-state.ts', - './use-mobile-session-terminal-runtime.ts', - './use-mobile-session-feedback-capabilities.ts', - './use-mobile-session-native-chat-dictation.ts', - './use-mobile-session-terminal-subscription-foundation.ts', - './use-mobile-session-terminal-subscription.ts', - './use-mobile-session-terminal-stream-display.ts', - './use-mobile-session-terminal-list.ts', - './use-mobile-session-tab-application.ts', - './use-mobile-session-document-readers.ts', - './use-mobile-session-diff-comments.ts', - './use-mobile-session-markdown-actions.ts', - './use-mobile-session-tab-reconciliation.ts', - './use-mobile-session-lifecycle.ts', - './use-mobile-session-keyboard-state.ts', - './use-mobile-session-startup.ts', - './use-mobile-session-preference-focus.ts', - './use-mobile-session-tab-switching.ts', - './use-mobile-session-terminal-webview.ts', - './use-mobile-session-terminal-send-actions.ts', - './use-mobile-session-file-actions.ts', - './use-mobile-session-terminal-input.ts', - './use-mobile-session-accessory-selection.ts', - './use-mobile-session-attachments.ts', - './use-mobile-session-terminal-create-actions.ts', - './use-mobile-session-content-create-actions.ts', - './use-mobile-session-close-actions.ts', - './use-mobile-session-bulk-close.ts', - './use-mobile-session-presentation.ts', - './use-mobile-session-panel-route-actions.tsx', - './MobileSessionMarkdownReader.tsx', - './MobileSessionDiffLineRow.tsx', - './MobileSessionFileReader.tsx', - './MobileSessionSurface.tsx', - './MobileSessionHeader.tsx', - './MobileSessionContentRow.tsx', - './MobileSessionActiveContent.tsx', - './MobileSessionCommandDock.tsx', - './MobileSessionSheets.tsx' -] as const - -export function readMobileSessionRouteSource(relativePath: string): string { - return readFileSync(fileURLToPath(new URL(relativePath, import.meta.url)), 'utf8') -} - -export function readMobileSessionRouteSourceFamily( - relativePaths: readonly string[] = MOBILE_SESSION_ROUTE_SOURCE_FILES -): string { - return relativePaths - .map( - (relativePath) => `// Source: ${relativePath}\n${readMobileSessionRouteSource(relativePath)}` - ) - .join('\n') -} diff --git a/mobile/src/session/mobile-session-route.test.ts b/mobile/src/session/mobile-session-route.test.ts index 33872e0271f..4cd040a061a 100644 --- a/mobile/src/session/mobile-session-route.test.ts +++ b/mobile/src/session/mobile-session-route.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { describe, expect, it, vi } from 'vitest' import { mobileSessionRouteTarget } from './mobile-session-route' import { @@ -7,8 +6,6 @@ import { type HostStackNavigationState } from '../navigation/host-stack-navigation' -const homeSource = readFileSync(new URL('../home/MobileHomeScreen.tsx', import.meta.url), 'utf8') - function navigationHarness(initialState: HostStackNavigationState) { const stateListeners = new Set<() => void>() let state = initialState @@ -95,20 +92,4 @@ describe('mobile session route', () => { payload: target }) }) - - it('routes the home Resume card through the cold-navigator-safe transition', () => { - expect(homeSource).toContain('onOpenResume={openResume}') - - // The tap handler itself must go through the coordinated transition; its only - // direct push is the shallow noticed host-index route for a proven-missing target. - const handlerStart = homeSource.indexOf('const openResume = useCallback(') - const handlerEnd = homeSource.indexOf('[data.router, openMobileSession]', handlerStart) - expect(handlerStart).toBeGreaterThanOrEqual(0) - expect(handlerEnd).toBeGreaterThan(handlerStart) - - const openResume = homeSource.slice(handlerStart, handlerEnd) - expect(openResume).toContain('openMobileSession({') - expect(openResume.match(/router\.push\(/g)).toHaveLength(1) - expect(openResume).toContain('data.router.push(hostRouteWithNotice(') - }) }) diff --git a/mobile/src/session/mobile-session-startup-source.test.ts b/mobile/src/session/mobile-session-startup-source.test.ts deleted file mode 100644 index b457164beed..00000000000 --- a/mobile/src/session/mobile-session-startup-source.test.ts +++ /dev/null @@ -1,295 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - readMobileSessionRouteSource, - readMobileSessionRouteSourceFamily -} from './mobile-session-route-source-family.test-support' - -const source = readMobileSessionRouteSourceFamily() -const startupSource = readMobileSessionRouteSource('./use-mobile-session-startup.ts') -const tabReconciliationSource = readMobileSessionRouteSource( - './use-mobile-session-tab-reconciliation.ts' -) -const bulkCloseSource = readMobileSessionRouteSource('./use-mobile-session-bulk-close.ts') -const presentationSource = readMobileSessionRouteSource('./use-mobile-session-presentation.ts') -const tabSwitchingSource = readMobileSessionRouteSource('./use-mobile-session-tab-switching.ts') -const sheetsSource = readMobileSessionRouteSource('./MobileSessionSheets.tsx') -const reconciliationHookSource = readMobileSessionRouteSource( - './use-mobile-session-tabs-reconciliation.ts' -) -const terminalInventoryRecoverySource = readMobileSessionRouteSource( - './use-mobile-terminal-inventory-recovery.ts' -) -const terminalSubscriptionSource = readMobileSessionRouteSource( - './use-mobile-session-terminal-subscription.ts' -) -const terminalListSource = readMobileSessionRouteSource('./use-mobile-session-terminal-list.ts') -const tabReconciliationOwnerSource = readMobileSessionRouteSource( - './use-mobile-session-tab-reconciliation.ts' -) -const autoCreateHookSource = readMobileSessionRouteSource( - './use-initial-session-terminal-autocreate.ts' -) -const foundationSource = readMobileSessionRouteSource('./use-mobile-session-foundation.ts') -const terminalRuntimeSource = readMobileSessionRouteSource( - './use-mobile-session-terminal-runtime.ts' -) -const terminalSubscriptionSourceForIdentity = readMobileSessionRouteSource( - './use-mobile-session-terminal-subscription.ts' -) -const lifecycleSource = readMobileSessionRouteSource('./use-mobile-session-lifecycle.ts') - -function sliceBetween(startPattern: string, endPattern: string, targetSource = source): string { - const start = targetSource.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = targetSource.indexOf(endPattern, start) - expect(end).toBeGreaterThan(start) - return targetSource.slice(start, end) -} - -describe('mobile session startup', () => { - it('auto-creates one terminal for a newly created empty session', () => { - expect(source).toContain('useWorktreeSessionTabsLoaded(worktreeId)') - expect(source).toContain( - 'initialSessionAutoCreateRef.current = createInitialSessionAutoCreateState()' - ) - - const autoCreateCall = sliceBetween( - 'useInitialSessionTerminalAutoCreate({', - 'const connectionVerdict =', - presentationSource - ) - expect(autoCreateCall).toContain('stateRef: initialSessionAutoCreateRef') - expect(autoCreateCall).toContain( - 'consumeCreationRoute: () => router.setParams({ created: undefined })' - ) - expect(autoCreateCall).toContain("newlyCreatedWorkspace: created === '1'") - expect(autoCreateCall).toContain('visibleTabCount: visibleTabs.length') - expect(autoCreateCall).toContain('createTerminal: () => void handleCreateTerminal()') - - expect(autoCreateHookSource).toContain('shouldAutoCreateInitialSessionTerminal({') - expect(autoCreateHookSource).toContain('stateRef.current.autoCreatedForWorktree === worktreeId') - expect(autoCreateHookSource).toContain('stateRef.current.autoCreatedForWorktree = worktreeId') - expect(autoCreateHookSource).toContain("connState === 'connected'") - expect(autoCreateHookSource).toContain('(visibleTabCount > 0 || activeHandle !== null)') - // Why: both callbacks are re-created every render, so the effect must reach them - // through useEffectEvent rather than deps or a render-time ref write. - expect(autoCreateHookSource).toContain('useEffectEvent(args.consumeCreationRoute)') - expect(autoCreateHookSource).toContain('useEffectEvent(args.createTerminal)') - expect(autoCreateHookSource).toContain('consumeCreationRoute()') - expect(autoCreateHookSource).toContain('createTerminal()') - }) - - it('arms the auto-create only until the route has published a tab (#9717)', () => { - // Emptiness after a populated list is a close, not a cold hydrate. - expect(source).toContain( - 'initialSessionAutoCreateRef.current.sawSessionTabs ||= nextTabs.length > 0' - ) - - const autoCreateCall = sliceBetween( - 'useInitialSessionTerminalAutoCreate({', - 'const connectionVerdict =', - presentationSource - ) - expect(autoCreateCall).toContain('stateRef: initialSessionAutoCreateRef') - expect(autoCreateHookSource).toContain('sawSessionTabs: stateRef.current.sawSessionTabs') - }) - - it('delegates stream ownership while retaining degraded polling and a certified sweep', () => { - expect(source).toContain('useMobileSessionTabsReconciliation<') - expect(source).toContain('const applicationRevision = ++appliedSessionTabsRevisionRef.current') - expect(source).toContain('getApplicationRevision: getSessionTabsApplicationRevision') - expect(source).not.toContain("client.subscribe(\n 'session.tabs.subscribe'") - expect(reconciliationHookSource).toContain("client.subscribe(\n 'session.tabs.subscribe'") - expect(reconciliationHookSource).toContain("if (AppState.currentState !== 'active')") - expect(reconciliationHookSource).toContain('suspendTerminalInventoryRecovery(true)') - expect(reconciliationHookSource).toContain('controller.poll()') - expect(reconciliationHookSource).toContain('tabsRequest !== null') - expect(reconciliationHookSource).toContain('void refreshTerminalInventory()') - expect(reconciliationHookSource).toContain("AppState.addEventListener('change'") - expect(reconciliationHookSource).toContain('const interval = setInterval(') - expect(reconciliationHookSource).toContain('RECONCILIATION_INTERVAL_MS = 2000') - expect(terminalInventoryRecoverySource).toContain('CERTIFIED_TERMINAL_SWEEP_MS = 60_000') - expect(reconciliationHookSource).toContain('controller.setReconciliationActive(false)') - expect(reconciliationHookSource).toContain('clearInterval(interval)') - expect(reconciliationHookSource).toContain('appStateSubscription.remove()') - }) - - it('binds terminal identity to the shared client before subscription effects run', () => { - expect(foundationSource).toContain('const { client, clientId, state: connState }') - expect(foundationSource).toContain(' clientId,') - expect(terminalRuntimeSource).toContain('useRef(clientId)') - expect(terminalRuntimeSource).toContain('deviceTokenRef.current = clientId') - expect(terminalRuntimeSource).toContain('inputGate.canSend && clientId !== null') - expect(terminalSubscriptionSourceForIdentity).toContain('if (clientId === null)') - expect(terminalSubscriptionSourceForIdentity).toContain( - "client: { id: clientId, type: 'mobile' as const }" - ) - expect(lifecycleSource).not.toContain('deviceTokenRef.current = host.deviceToken') - }) - - it('confirms terminal stream teardown with a committed inventory-recovery bridge', () => { - expect(terminalSubscriptionSource).toContain( - "if (data.type === 'end' || data.type === 'error')" - ) - expect(terminalSubscriptionSource).toContain('signalTerminalInventoryRecovery()') - expect(terminalInventoryRecoverySource).toContain('actionRef.current = recoveryAction') - expect(terminalInventoryRecoverySource).toContain('pendingSignalScopeRef.current = scopeKey') - expect(terminalInventoryRecoverySource).toContain( - 'committedScope !== null && committedScope !== scopeKey' - ) - expect(terminalListSource).toContain('return terminalInventoryRequest.activate()') - expect(terminalListSource).toContain('if (!isCurrent() || !response.accepted)') - expect(terminalInventoryRecoverySource).toContain( - 'TERMINAL_INVENTORY_CONFIRMATION_DELAY_MS = 750' - ) - expect(terminalInventoryRecoverySource).toContain( - 'refreshTerminalInventory({ allowEmptyLoaded: true })' - ) - }) - - it('loads session tabs without waiting for desktop activation', () => { - const startupEffect = sliceBetween( - 'void (async () => {', - 'return () => {\n disposed = true', - startupSource - ) - - // Both sends migrated to the typed `worktreeActivate` operation in step 6; what these pin is - // unchanged — the plain activation is fired and not awaited, and it goes out before the tab load. - expect(startupEffect).toContain('void worktreeActivate\n .request(client, {') - expect(startupEffect).toContain("if (client && created !== '1' && !isFloatingWorkspaceRoute)") - expect(startupEffect).toContain("if (client && created === '1' && !isFloatingWorkspaceRoute)") - expect(startupEffect).toContain('notifyClients: false') - expect(startupEffect).toContain("navigation: 'caller'") - expect(startupEffect).not.toContain('await worktreeActivate\n .request(client, {') - expect(startupEffect.indexOf('worktreeActivate\n .request(client, {')).toBeLessThan( - startupEffect.indexOf('await ensureSessionTabs()') - ) - expect(startupEffect).toContain('headlessActivationNeedsHostRenderer(activation.value)') - expect(startupEffect).toContain("showToast('Open Orca on the host to wake sleeping agents.'") - }) - - it('fails runtime capability gates closed before probing a replacement client', () => { - const capabilityEffect = sliceBetween( - 'const hostQueryReplyInputSupportedRef = useRef(false)', - 'return {\n consumeAcceptedSessionTabs', - tabReconciliationSource - ) - const probeStart = capabilityEffect.indexOf('startRuntimeCapabilityProbe(client,') - - expect(probeStart).toBeGreaterThanOrEqual(0) - for (const reset of [ - 'setBrowserScreencastSupported(null)', - 'setAgentSessionHistorySupported(null)', - 'setQuickCommandsSupported(null)', - 'setShowQuickCommands(false)', - 'hostQueryReplyInputSupportedRef.current = false' - ]) { - const resetIndex = capabilityEffect.lastIndexOf(reset) - expect(resetIndex).toBeGreaterThanOrEqual(0) - expect(resetIndex).toBeLessThan(probeStart) - } - }) - - it('activates an already-selected pending terminal tab after hydration', () => { - expect(source).toContain( - 'const pendingTerminalActivationAttemptRef = useRef(null)' - ) - expect(source).toContain('pendingTerminalActivationAttemptRef.current = null') - - const pendingActivationEffect = sliceBetween( - "if (!client || connState !== 'connected' || !activePendingTerminalTab) {", - 'return {\n bulkCloseActions', - bulkCloseSource - ) - expect(pendingActivationEffect).toContain( - 'pendingTerminalActivationAttemptRef.current === activationKey' - ) - expect(pendingActivationEffect).toContain('activateMobileSessionTab(client,') - expect(pendingActivationEffect).toContain('tabId: activePendingTerminalTab.id') - expect(pendingActivationEffect).toContain('leafId: activePendingTerminalTab.leafId') - expect(pendingActivationEffect).toContain('notifyClients: false') - expect(pendingActivationEffect).toContain("navigation: 'caller'") - expect(pendingActivationEffect).toContain( - 'applySessionTabs((response as RpcSuccess).result as SessionTabsResult)' - ) - expect(pendingActivationEffect).toContain('scheduleDelayedAction(() => void fetchSessionTabs()') - }) - - it('keeps ready terminal taps local while publishing caller selection', () => { - const readyTerminalSwitch = sliceBetween( - 'const switchTab = useCallback(', - 'const switchSessionTab = useCallback(', - tabSwitchingSource - ) - - expect(readyTerminalSwitch).not.toContain('focusMobileTerminal(client, handle)') - expect(readyTerminalSwitch).toContain('activateMobileSessionTab(client,') - expect(readyTerminalSwitch).toContain('notifyClients: false') - expect(readyTerminalSwitch).toContain("navigation: 'caller'") - }) - - it('keeps background and pending session-tab activation local to the phone', () => { - const activationRequests = source.split('activateMobileSessionTab(client,').slice(1) - - expect(activationRequests).toHaveLength(4) - for (const request of activationRequests) { - expect(request.slice(0, request.indexOf('})'))).toContain('notifyClients: false') - expect(request.slice(0, request.indexOf('})'))).toContain("navigation: 'caller'") - } - }) - - it('keeps dynamic agent rows above fixed New Tab actions', () => { - const newTabActions = sliceBetween( - 'title="New Tab"', - 'onClose={() => setShowCreateTabDrawer', - sheetsSource - ) - - expect(newTabActions.indexOf('...createTabAgentActions')).toBeLessThan( - newTabActions.indexOf("label: 'Terminal'") - ) - expect(newTabActions.indexOf("label: 'Terminal'")).toBeLessThan( - newTabActions.indexOf("label: 'Browser'") - ) - expect(newTabActions.indexOf("label: 'Browser'")).toBeLessThan( - newTabActions.indexOf("label: 'Markdown Note'") - ) - }) - - it('wires pending-handle recovery through its bounded context (STA-4256)', () => { - const applySessionTabs = sliceBetween( - 'const applySessionTabs = useCallback(', - 'const consumeAcceptedSessionTabs = useCallback(' - ) - const recoveryContext = sliceBetween( - 'const pendingTerminalRecoveryContextCache = useMemo(', - 'const sessionTabsFetchReporting', - tabReconciliationOwnerSource - ) - - const tabsRefWrite = 'sessionTabsRef.current = nextTabs' - const tabsStateWrite = 'setSessionTabs((prev)' - const activeRefWrite = 'activeSessionTabIdRef.current = active?.id ?? null' - const activeStateWrite = 'setActiveSessionTabId(active?.id ?? null)' - for (const write of [tabsRefWrite, tabsStateWrite, activeRefWrite, activeStateWrite]) { - expect(applySessionTabs).toContain(write) - } - expect(applySessionTabs.indexOf(tabsRefWrite)).toBeLessThan( - applySessionTabs.indexOf(tabsStateWrite) - ) - expect(applySessionTabs.indexOf(activeRefWrite)).toBeLessThan( - applySessionTabs.indexOf(activeStateWrite) - ) - expect(recoveryContext).toContain('() => new PendingTerminalHandleRecoveryContextCache()') - expect(recoveryContext).toContain('sessionTabsRef.current,') - expect(recoveryContext).toContain('activeSessionTabIdRef.current') - expect(recoveryContext).toContain( - 'const pendingTerminalRecoveryContextKey = getPendingTerminalRecoveryContextKey()' - ) - expect(source).toContain('hasRecoveryNeed: hasSessionTabsRecoveryNeed') - expect(source).toContain('getPendingTerminalRecoveryContextKey,') - expect(source).toContain('onPendingTerminalRecoveryParked: setParkedPendingTerminalContext') - expect(source).toContain('retryPendingTerminalRecovery()') - }) -}) diff --git a/mobile/src/session/quick-commands-tab-stability-source.test.ts b/mobile/src/session/quick-commands-tab-stability-source.test.ts deleted file mode 100644 index 9c744a5f982..00000000000 --- a/mobile/src/session/quick-commands-tab-stability-source.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import ts from 'typescript' -import { describe, expect, it } from 'vitest' -import { readMobileSessionRouteSource } from './mobile-session-route-source-family.test-support' - -const sourcePath = './MobileSessionHeader.tsx' -const source = readMobileSessionRouteSource(sourcePath) -const sheetsSource = readMobileSessionRouteSource('./MobileSessionSheets.tsx') -const sourceFile = ts.createSourceFile( - sourcePath, - source, - ts.ScriptTarget.Latest, - true, - ts.ScriptKind.TSX -) - -function findQuickCommandsTabButtons(): ts.JsxSelfClosingElement[] { - const matches: ts.JsxSelfClosingElement[] = [] - - function visit(node: ts.Node): void { - if ( - ts.isJsxSelfClosingElement(node) && - node.tagName.getText(sourceFile) === 'QuickCommandsTabButton' - ) { - matches.push(node) - } - ts.forEachChild(node, visit) - } - - visit(sourceFile) - return matches -} - -function getQuickCommandsTabSource(): string { - const start = source.indexOf('accessibilityLabel="New tab"') - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf('', start) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('quick-commands tab stability', () => { - it('keeps the button mounted while preserving the capability gate', () => { - const tabSource = getQuickCommandsTabSource() - const buttons = findQuickCommandsTabButtons() - - expect(buttons).toHaveLength(1) - const tabBar = buttons[0].parent - expect(ts.isJsxElement(tabBar)).toBe(true) - if (!ts.isJsxElement(tabBar)) { - return - } - expect(tabBar.openingElement.tagName.getText(sourceFile)).toBe('View') - const style = tabBar.openingElement.attributes.properties.find( - (attribute): attribute is ts.JsxAttribute => - ts.isJsxAttribute(attribute) && attribute.name.getText(sourceFile) === 'style' - ) - expect(style?.initializer?.getText(sourceFile)).toBe('{styles.tabBar}') - expect(tabSource).toContain('if (quickCommandsSupported === true)') - expect(tabSource).toContain('setShowQuickCommands(true)') - expect(tabSource).toContain('Desktop update required for quick commands') - expect(tabSource).toContain('Checking desktop capabilities — try again in a moment') - }) - - it('only presents the sheet after support is confirmed', () => { - expect(sheetsSource).toContain('visible={showQuickCommands && quickCommandsSupported === true}') - }) -}) diff --git a/mobile/src/session/session-router-seam-census.test.ts b/mobile/src/session/session-router-seam-census.test.ts deleted file mode 100644 index 9f73a5434ca..00000000000 --- a/mobile/src/session/session-router-seam-census.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - callsRouteHandoff, - expoRouterValueImports, - parse, - productFiles -} from '../navigation/router-seam-census.test-support' - -const SESSION_ROOT = import.meta.dirname - -/** - * Which modules here hold a router, so the census cannot pass by seeing nothing. - * - * Four, and each for a different target. The foundation hook bounces a deleted workspace back to - * its host; the file-tap handlers push a preview route from a terminal link or a chat path; the - * notification hook consumes a pane tap by rewriting this route's own params; the review route - * body replaces to the session screen and pops the stack behind it. Only the first two and the - * last can leave the page, which is the whole reason the third is in the list anyway — a - * `setParams` on expo-router's router and a `setParams` on the handoff's are the same call, and - * listing it here is what stops someone later giving it back its own `useRouter` because "it never - * navigates". - */ -const ROUTER_HOLDERS = [ - 'MobileDiffReviewRouteScreen.tsx', - 'use-mobile-file-tap-handlers.ts', - 'use-mobile-session-foundation.ts', - 'use-notification-pane-navigation.ts' -] - -/** - * The expo-router names this domain may still import, and why each one is not a router. - * - * `useFocusEffect` reads whether this screen is the focused one in the document's own stack and - * `useLocalSearchParams` reads the params of the route already mounted. Neither takes a target, so - * neither can put a screen in front of the page; both are the page's own router answering about the - * page's own route, which is exactly what it is for. - * - * A closed list rather than a ban on `useRouter`: the hazard is anything that navigates, and - * expo-router exports a module-singleton `router` that does it from a plain function. A rule written - * against the one spelling would have read that as clean. - */ -const NON_NAVIGATING_ROUTER_NAMES = ['useFocusEffect', 'useLocalSearchParams'] - -describe('the session domain reaches the router through the handoff seam', () => { - const files = productFiles(SESSION_ROOT) - - it('walks the modules it is written against', () => { - expect(files).toEqual(expect.arrayContaining(ROUTER_HOLDERS)) - expect(files.length).toBeGreaterThan(200) - }) - - it('imports nothing from expo-router that can navigate', () => { - const offenders = files - .map((name) => ({ - name, - imported: expoRouterValueImports(parse(SESSION_ROOT, name)).filter( - (imported) => !NON_NAVIGATING_ROUTER_NAMES.includes(imported) - ) - })) - .filter((entry) => entry.imported.length > 0) - .map((entry) => `${entry.name} (${entry.imported.join(', ')})`) - expect(offenders).toEqual([]) - }) - - it('takes the router from useRouteHandoff at every screen that holds one', () => { - expect(files.filter((name) => callsRouteHandoff(parse(SESSION_ROOT, name))).sort()).toEqual( - [...ROUTER_HOLDERS].sort() - ) - }) - - it('still reaches expo-router for the two names that answer about its own route', () => { - // The completeness half: the rule above also passes over a domain that imports nothing at all, - // which is what it would read as if someone moved these hooks and left the list behind. - const imported = new Set( - files.flatMap((name) => expoRouterValueImports(parse(SESSION_ROOT, name))) - ) - expect([...imported].sort()).toEqual([...NON_NAVIGATING_ROUTER_NAMES].sort()) - }) -}) diff --git a/mobile/src/session/terminal-field-submit-binding-wiring.test.ts b/mobile/src/session/terminal-field-submit-binding-wiring.test.ts deleted file mode 100644 index 25a4761af85..00000000000 --- a/mobile/src/session/terminal-field-submit-binding-wiring.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readMobileSessionRouteSource } from './mobile-session-route-source-family.test-support' - -const sendActionsSource = readMobileSessionRouteSource( - './use-mobile-session-terminal-send-actions.ts' -) - -const BINDING_CALL = 'useTerminalTextFieldSubmitBinding(' - -/** The handler each field hands its submit binding, in source order. */ -function readBoundSubmitNames(source: string): string[] { - const names: string[] = [] - let at = source.indexOf(BINDING_CALL) - while (at >= 0) { - const args = source.slice(at + BINDING_CALL.length, source.indexOf(')', at)) - const handler = args.split(',')[1]?.trim() - if (handler) { - names.push(handler) - } - at = source.indexOf(BINDING_CALL, at + 1) - } - return names -} - -/** - * The rule: a handler bound through `useTerminalTextFieldSubmitBinding` must not be frozen on an - * empty dependency list. - * - * `handleSend` is a per-render function whose guard reads `client`, `activeHandle` and `canSend`, - * all absent on the first render, so a submit memoized on `[]` is one closure for the life of the - * component and the field's line-break submit can never pass that guard. The field's own - * `onSubmitEditing` prop keeps working, which is what hid it. - * - * Why a source rule and not a render: every check that mounts its own submit writes the identity - * under test itself, so the render rig's probe route could catch neither the defect nor the fix. - * `terminal-field-submit-binding-send.test.tsx` reads the behaviour instead and catches spellings - * this cannot; this one is the cheap guard beside it. - */ -describe('the submit handlers the terminal fields bind', () => { - it('names one handler per bound field', () => { - expect(readBoundSubmitNames(sendActionsSource)).toEqual([ - 'submitLiveInput', - 'submitBufferedDraft' - ]) - }) - - it('freezes none of them on an empty dependency list', () => { - for (const name of readBoundSubmitNames(sendActionsSource)) { - const declaredAt = sendActionsSource.indexOf(`const ${name} = `) - expect(declaredAt).toBeGreaterThanOrEqual(0) - const boundAt = sendActionsSource.indexOf(`${BINDING_CALL}`, declaredAt) - expect(boundAt).toBeGreaterThan(declaredAt) - expect(sendActionsSource.slice(declaredAt, boundAt)).not.toContain('}, [])') - } - }) - - // The other half of the rule: a handler that is memoized must name what it reads, so the closure - // moves when the send guard's inputs do. - it('gives the live input submit the dependencies its closure reads', () => { - const declaredAt = sendActionsSource.indexOf('const submitLiveInput = ') - const boundAt = sendActionsSource.indexOf(BINDING_CALL, declaredAt) - const slice = sendActionsSource.slice(declaredAt, boundAt) - expect(slice).toContain('handleLiveInputSubmit') - expect(slice).toContain('activeSessionTab') - }) -}) diff --git a/mobile/src/source-control/mobile-pr-create.test.ts b/mobile/src/source-control/mobile-pr-create.test.ts index d52f4861fd4..4935d514f36 100644 --- a/mobile/src/source-control/mobile-pr-create.test.ts +++ b/mobile/src/source-control/mobile-pr-create.test.ts @@ -158,32 +158,6 @@ describe('mobile create form gating parity', () => { ) }) - it('desktop gate hard-blocks on positive unresolved review evidence', () => { - // Mobile lacks review-lookup signals, so it fails closed on ambiguity: the - // shared desktop gate must return false even when eligibility looks ready. - expect( - shouldOpenChecksPanelCreateComposer({ - activeReview: null, - isFolder: false, - branch: 'feature/x', - hostedReviewCreation: eligibility({ canCreate: true }), - reviewLookup: 'positive_unresolved' - }) - ).toBe(false) - }) - - it('desktop gate hard-blocks during a hard refresh error', () => { - expect( - shouldOpenChecksPanelCreateComposer({ - activeReview: null, - isFolder: false, - branch: 'feature/x', - hostedReviewCreation: eligibility({ canCreate: true }), - hasHardRefreshError: true - }) - ).toBe(false) - }) - it('fails closed on an unavailable review lookup even when eligibility looks ready', () => { // The existing-review lookup could not prove there is no PR; mobile has no // review-lookup signal of its own, so create must be blocked. diff --git a/mobile/src/source-control/source-control-router-seam-census.test.ts b/mobile/src/source-control/source-control-router-seam-census.test.ts deleted file mode 100644 index e34d4ad93d8..00000000000 --- a/mobile/src/source-control/source-control-router-seam-census.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - callsRouteHandoff, - importsExpoRouterValue, - parse, - productFiles -} from '../navigation/router-seam-census.test-support' - -const SOURCE_CONTROL_ROOT = import.meta.dirname - -/** - * Which modules here hold a router, so the census cannot pass by seeing nothing. - * - * One holder, not one per screen: the hub's router is taken once in the openers hook and passed - * down through the state hook to the runners and the panel. So this domain's whole reach into the - * router is that single call, and the rules below say so rather than counting screens. - * - * `use-mobile-source-control-runners.ts` is the case a value/type rule is written for: it named - * expo-router only to write `ReturnType`, which is a value import in a type - * position and keeps the module in the graph. `RouteHandoff` is the seam's own name for that type. - */ -const ROUTER_HOLDERS = ['use-mobile-source-control-openers.ts'] - -describe('the source-control domain reaches the router through the handoff seam', () => { - const files = productFiles(SOURCE_CONTROL_ROOT) - - it('walks the modules it is written against', () => { - expect(files).toEqual(expect.arrayContaining(ROUTER_HOLDERS)) - expect(files).toContain('use-mobile-source-control-runners.ts') - expect(files).toContain('MobileSourceControlPanel.tsx') - }) - - it('imports no router from expo-router, which the page cannot hand a route back through', () => { - expect( - files.filter((name) => importsExpoRouterValue(parse(SOURCE_CONTROL_ROOT, name))) - ).toEqual([]) - }) - - it('takes the router from useRouteHandoff at every screen that holds one', () => { - expect( - files.filter((name) => callsRouteHandoff(parse(SOURCE_CONTROL_ROOT, name))).sort() - ).toEqual([...ROUTER_HOLDERS].sort()) - }) -}) diff --git a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts deleted file mode 100644 index 4eb61e3f1da..00000000000 --- a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { createHash } from 'node:crypto' -import { describe, expect, it } from 'vitest' -import { - readFlattenedMobileTasksHookSignatures, - readMobileTasksSemanticSource, - readMobileTasksStyleSource -} from './mobile-tasks-source-family.test-support' -import { readFlattenedMobileTasksRenderTokens } from './mobile-tasks-render-parity.test-support' -import { - readFlattenedMobileTasksCoreStatements, - readMobileTasksDeclarationSignatures -} from './mobile-tasks-execution-parity.test-support' - -const hash = (parts: string[] | string): string => - createHash('sha256') - .update(Array.isArray(parts) ? parts.join('\n') : parts) - .digest('hex') - -// Bound requests change source signatures the same way bound provider, workspace-creation and -// settings requests did: the method string and the envelope read leave the screen and an operation -// name arrives. The behaviour they used to pin is pinned by the recordings in -// mobile/rpc-foundation/goldens instead, which did not move. -// -// The screen-holdout migration takes the last two sends out of this family — the filter sheet's -// linear.selectWorkspace and the screen-root hook's repo.list. Hook, statement, declaration, render -// and style counts are all unchanged, and `semantics` is a pure deletion of four lines, none in: -// two `rpc:` call signatures and the two method literals they carried. The render-token hash moves -// because the picker's handler now names an operation instead of the client. -// -// Step 7's first half moves four of the six again, and moves nothing else. Checked readers on the -// item and list operations delete the reply casts these consumers carried, plus the three shape -// tests the reader now answers for: both `Array.isArray(payload)` guards on the checks read and the -// `typeof count === 'number'` fallback on the item count. Hook, statement, declaration and render -// counts are unchanged, and the render-token hash does not move at all — nothing this family sees -// changed inside a JSX tree. `semantics` is a pure deletion of ten lines. -// -// Round-1 review moves four, and names what each one is. The reaction reader stops matching -// `content` against an arm set mobile invented and forwards it, so `DetailComment` loses the eight -// phantom arms and `COMMENT_REACTION_EMOJI` stops being keyed by them: that is ten string literals -// gone and the `?? ''` fallback's one added, the whole of `semantics`' 3,290 -> 3,281. The eight -// alias-only bindings the deleted casts left behind (`const result = created` and its seven -// siblings) are inlined, which moves the hook and statement hashes without moving their counts. -// Only those eight: the Linear arm of task creation keeps its own `result`, which is a declaration -// with a name rather than an alias for one. -// No `rpc:` signature and no `jsx:` signature moves, the render-token hash does not move, and -// counts stay at 350 hooks, 417 statements and 194 declarations. -// -// The `gitlab.todos` fixture correction moves the same three hashes once more and no others: the -// to-do row is checked now, so the reader's cast is gone from the list-loading hook and the row -// type it forwarded is declared by what the reader proves. Counts are unchanged again, and -// `semantics` does not move, because no RPC call, runtime string or JSX host signature does. -// -// Round 2 moves two, and only because one member widens. `GitHubDetailFile.viewerViewedState` is -// `string` rather than the host's three arms, because the reader forwards it now: that is the -// declaration hash and the three arm literals, `semantics` 3,281 -> 3,278. `status` keeps its arms -// and moves nothing, because its only consumer sends it back as a param the host validates against -// the same set. Hook, statement and render hashes do not move; nothing executable changed. -// -// Step 7's tasks-2 half moves the hook, statement, declaration and semantic hashes once more, for -// the board, runtime, search, workspace-source and workspace-create operations, and moves no count: -// hooks stay at 350, statements at 417, declarations at 194. `semantics` is a pure deletion of four -// lines, 3,278 -> 3,274, and all four are the literals inside the one inline cast type this half -// deletes in use-mobile-tasks-project-detail-loading.tsx — `'DISMISSED'`, `'VIEWED'`, `'UNVIEWED'` -// and the `['status']` index into GitHubDetailFile. No method literal and no `rpc:` call signature -// moves. -// -// The hook and statement hashes also move for comment text alone: `normalized` reads a statement's -// full span, so a comment nested inside one is hashed with it. They move once more when the two -// halves are deduplicated: the project pane's five collection casts and the assignee list's are -// deleted where the entity schemas from the item half now type those rows. -// -// Round 2 of tasks-2 moves the hook and statement hashes a last time, and only those two. One -// statement changes: the Linear list cast (`found as LinearIssue[]`) becomes `found`, because the -// nine members linearIssueRowSchema requires make the value assignable to the mobile alias without -// it. The rest is comment text nested inside statements — three `SAFETY:` lines rewritten to argue -// from the schemas that landed instead of the fixtures round 1 deleted. Counts are unchanged at 350 -// hooks and 417 statements; the declaration, semantic, render and style hashes do not move, which -// is the evidence that deleting the cast changed no type and no call. -// -// The pullfrog pass on the same round moved both once more, again by comment text alone: the -// GitHub search `SAFETY:` line now separates the two members the schema requires (`items`, -// `labels`) from the eight it only types. No statement, type or call changed; counts hold. -// C2.1 swaps the workspace-creation push onto `hostNewWorktreeSessionRoute`, which already built -// this href with both segments encoded. Three of the family move and nothing else does: the hook -// list, because the handler's statements changed shape; the statement hash, for the same reason; -// and `semantics`, which is a pure deletion of two lines — the `URLSearchParams` construction and -// the raw `/h/${hostId}/session/...` template it fed. No RPC call, method literal or JSX host -// signature changed, and the render and style hashes did not move. - -// C2.1 swaps the two clipboard writes onto the platform seam, so the comment-review hook gains one -// hook call and one statement. Two of the family move: the hook list and the statement hash, each -// by one entry. `semantics` does not — no RPC call, method literal or JSX host signature changed — -// and the render and style hashes hold. - -// C2.8 names the status bar's Back control for the shell, which has no native chrome behind it to -// announce one. `accessibilityRole="button"` and `accessibilityLabel="Back"` on that one Pressable -// move the two hashes a JSX prop must move, and only those two. `semantics` 3,272 -> 3,274: the -// element's host signature widens (`jsx:Pressable:style,onPress` -> the same plus the two props) -// and the two new runtime strings `"button"` and `"Back"` arrive. The render-token stream gains -// the eight tokens those two attributes are, 35,195 -> 35,203. No RPC call signature and no method -// literal moves, and the hook, statement, declaration and style hashes do not move at all, which -// is the evidence that nothing executable changed. -// -// The same commit gives that control the `hitSlop={8}` its four siblings carry, so its touch -// target is no longer the glyph alone. One more line of `semantics` changes and no line is added -// or removed — the host signature gains `hitSlop` — so the count holds at 3,274 and only the hash -// moves. The render-token stream gains the four tokens that one attribute is, 35,203 -> 35,207. -// Nothing else in the family moves. - -const SCREEN_RPC_SCREEN_HOOKS = '0f66df2141117dfec2f8a0adb3f598312e6fda8e80833a365a645796f5ab48c3' -const PRE_REFACTOR_DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' -const SCREEN_RPC_STATEMENTS = 'dd8f33cb3cf96f5c39abac397cb77e35f59079291033a1866ead462b041ab979' -// Saved Linear selections now accept unknown persisted values; reconciliation tests cover them. -const MAIN_REBASED_DECLARATIONS = 'ec77d34712c7c4ab19ac6a4d57878f32d22aba790d2420cc14c2c0f000d120e9' -const SCREEN_RPC_SEMANTICS = 'e07a63387d57106483ee703ec6c19dea593e0eca5c651758f42bcb36254850b7' -// StatusDot's spacing moved to the tasks title row as `gap: spacing.sm`; same 8 px. -const PRE_REFACTOR_STYLES = '11504e9f655d4d45deb25d942158a0ee99a1f98007ad1630bb03e1bdfe1e73de' -const SCREEN_RPC_RENDER_TREE = '086742f95f1e87fb89d8c67ffd9f7a229799ae05115f9f4bcc1a925e56dcc8bb' - -describe('Mobile Tasks refactor parity', () => { - it('preserves recursively flattened hook and dependency order', () => { - const screenHooks = readFlattenedMobileTasksHookSignatures('MobileTasksScreen') - expect(screenHooks).toHaveLength(351) - expect(hash(screenHooks)).toBe(SCREEN_RPC_SCREEN_HOOKS) - - const diffHooks = readFlattenedMobileTasksHookSignatures('GitHubPrFileDiff') - expect(diffHooks).toHaveLength(3) - expect(hash(diffHooks)).toBe(PRE_REFACTOR_DIFF_HOOKS) - }) - - it('preserves every screen statement in execution order', () => { - const statements = readFlattenedMobileTasksCoreStatements() - expect(statements).toHaveLength(418) - expect(hash(statements)).toBe(SCREEN_RPC_STATEMENTS) - }) - - it('preserves every moved top-level declaration', () => { - const declarations = readMobileTasksDeclarationSignatures() - expect(declarations).toHaveLength(194) - expect(hash(declarations)).toBe(MAIN_REBASED_DECLARATIONS) - }) - - it('preserves RPC calls, runtime strings, and JSX host signatures', () => { - const semantics = readMobileTasksSemanticSource() - expect(semantics.split('\n')).toHaveLength(3_274) - expect(hash(semantics)).toBe(SCREEN_RPC_SEMANTICS) - }) - - it('preserves render expressions and event handlers in tree order', () => { - const tokens = readFlattenedMobileTasksRenderTokens() - expect(tokens).toHaveLength(35_207) - expect(hash(tokens)).toBe(SCREEN_RPC_RENDER_TREE) - }) - - it('preserves every StyleSheet property and value', () => { - expect(hash(readMobileTasksStyleSource())).toBe(PRE_REFACTOR_STYLES) - }) -}) diff --git a/mobile/src/terminal/document/document-parse-time-effects.test.ts b/mobile/src/terminal/document/document-parse-time-effects.test.ts index 0acddfb78b3..86b8433ed14 100644 --- a/mobile/src/terminal/document/document-parse-time-effects.test.ts +++ b/mobile/src/terminal/document/document-parse-time-effects.test.ts @@ -1,13 +1,9 @@ -import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' import { - DECLARATION_KINDS, documentModuleNames, documentModuleSource, exportedLifecycleFunctions, - parseModule, parseTimeEffects, - readsTheDocument, sequenceCalls, topLevelDeclarationsReachAnElement } from '../../test-support/webview-document-census' @@ -71,43 +67,6 @@ describe('the document modules at parse time', () => { } }) - it('would report a planted element read, which the statement filter cannot see', () => { - // The second reader has its own precondition. A `const` initialised from the document is a - // declaration by shape and a parse-time element read by effect — the exact form that survived - // a remount holding the first mount's node — and the statement-kind filter waves it through. - const planted = - "import { scope } from './document-scope'\n" + - "const indicator = document.getElementById('scroll-indicator')\n" + - 'export function n() {\n return indicator ?? scope.term\n}\n' - expect(parseTimeEffects('planted', planted)).toEqual([ - "planted: indicator = document.getElementById('scroll-indicator')" - ]) - // And the element reader the case above spends on every module: the same plant, seen by it. - expect(topLevelDeclarationsReachAnElement('planted', planted)).toBe(true) - // And the other direction, because a reader that flagged every initialiser would agree with - // the empty list above only by refusing everything: a plain literal is not work. - const inert = - "import { scope } from './document-scope'\n" + - 'const options = { capture: true, passive: false }\n' + - 'export function n() {\n return options.capture && scope.term !== null\n}\n' - expect(parseTimeEffects('inert', inert)).toEqual([]) - }) - - it('would report one, so the empty list above is a measurement', () => { - // The precondition. A walk that matched nothing would agree with an empty expectation just as - // happily, so the same reader is aimed at a module that does have a top-level effect: this - // test file itself, whose `describe` call is exactly the shape the rule refuses. - const source = readFileSync( - new URL('./document-parse-time-effects.test.ts', import.meta.url), - 'utf8' - ) - const running = parseModule('probe', source).body.filter( - (statement) => !DECLARATION_KINDS.has(statement.type) - ) - expect(running.length).toBeGreaterThan(0) - expect(readsTheDocument({ type: 'Identifier', name: 'document' })).toBe(true) - }) - it('start and stop: the sequence calls every one there is, and undoes them in reverse', () => { // Moving an effect out is only correct if something calls it, and a count cannot say that: a // module could export a start nobody runs and the count would agree as soon as the literal @@ -120,9 +79,6 @@ describe('the document modules at parse time', () => { MODULES.filter((name) => name !== THE_SEQUENCE).flatMap((name) => exportedLifecycleFunctions(moduleSource(name), keyword, 'TerminalDocumentScope') ) - expect(moduleSource('selection-overlay')).toContain( - 'export function stopSelectionOverlay(scope: TerminalDocumentScope) {\n stopEdgeScroll(scope)' - ) const started = sequenceCallsTo('startTerminalDocument') // `cancelDocumentFrames` is the frame registry's undo rather than a module's stop, and it is @@ -145,12 +101,4 @@ describe('the document modules at parse time', () => { ) expect(sequenceCallsTo('stopTerminalDocument').at(-1)).toBe('cancelDocumentFrames') }) - - it('would name a start the sequence forgot, which is what the comparison above is for', () => { - // The precondition, planted rather than argued: a module that exports a start nobody calls is - // the failure the set comparison exists to catch, and the reader has to say its name. - const planted = sequenceCallsTo('startTerminalDocument') - expect(planted).not.toContain('startReflow') - expect([...planted, 'startReflow'].sort()).not.toEqual(planted.slice().sort()) - }) }) diff --git a/mobile/src/terminal/document/host-seams.test.ts b/mobile/src/terminal/document/host-seams.test.ts index 17d709ddc42..c000062acf0 100644 --- a/mobile/src/terminal/document/host-seams.test.ts +++ b/mobile/src/terminal/document/host-seams.test.ts @@ -7,7 +7,6 @@ import { notify } from './host-notify' import { flog } from './viewport-transform' import { attachWebglAddon } from './webgl-recovery' import type { TerminalDocumentHost, TerminalViewportChange } from './document-host-seams' -import { documentSourceText } from './document-module-source.test-support' /** * The host seams the page sets, and the window reads and writes they default to. @@ -324,38 +323,4 @@ describe("the document's viewport", () => { window.dispatchEvent(new Event('resize')) expect(scope.panX).toBe(0) }) - - it('is read through the seam everywhere, never off the window directly', () => { - // The default in `document-host-seams.ts` is the one window read, so the census runs over - // every other module; a raw read elsewhere sizes a page terminal to the whole page. - const raw = documentSourceText() - .split('\n') - .filter((line) => /window\.inner(Height|Width)|\binner(Height|Width)\b/.test(line)) - expect(raw).toEqual([ - ' return { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight }' - ]) - }) - - it('maps a client point into the grid only through viewportPoint', () => { - // On the page the host's origin is not the window's, so a client coordinate used against - // anything but another client coordinate lands rows low. Differences of two need no origin. - const arithmetic = documentSourceText() - .split('\n') - .filter((line) => !/^\s*(\*|\/\/)/.test(line)) - .filter((line) => /client[XY]\s*[-+*/<>]|[-+*/<>]=?\s*[\w.[\]]*client[XY]\b/.test(line)) - .map((line) => line.trim()) - .sort() - expect(arithmetic).toEqual([ - 'const dx = Math.abs(e.clientX - gesture.startX)', - 'const dx = Math.abs(mt.clientX - scope.tapCandidate.x)', - 'const dx = Math.abs(t.clientX - scope.longPressOrigin.x)', - 'const dx = a.clientX - b.clientX,', - 'const dy = Math.abs(e.clientY - gesture.startY)', - 'const dy = Math.abs(mt.clientY - scope.tapCandidate.y)', - 'const dy = Math.abs(t.clientY - scope.longPressOrigin.y)', - 'dy = a.clientY - b.clientY', - 'return viewportPoint(scope, (a.clientX + b.clientX) / 2, (a.clientY + b.clientY) / 2)', - 'return { x: clientX - frame.left, y: clientY - frame.top }' - ]) - }) }) diff --git a/mobile/src/terminal/terminal-cell-box-census.test.ts b/mobile/src/terminal/terminal-cell-box-census.test.ts deleted file mode 100644 index ea0e9ece12c..00000000000 --- a/mobile/src/terminal/terminal-cell-box-census.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { readFileSync } from 'node:fs' -import { relative } from 'node:path' -import { fileURLToPath } from 'node:url' -import { describe, expect, it } from 'vitest' -import { censusSourceFiles } from '../test-support/census-source-files' - -const SOURCE_ROOT = fileURLToPath(new URL('..', import.meta.url)) - -// xterm is the only measurer of the cell box. These are the ways to measure a glyph without it, -// matched by technique rather than by name, so a rename cannot hide one. xterm's own code is the -// generated engine, which the walk leaves out. -const GLYPH_MEASUREMENT: [string, RegExp][] = [ - ['canvas text metrics', /\bmeasureText\s*\(/], - ['offscreen canvas', /\bOffscreenCanvas\b/], - ['font bounding box', /\b(font|actual)BoundingBox(Ascent|Descent|Left|Right)\b/] -] -// A probe span: a created span, a run of one glyph, and its laid-out width, all in one file. -const PROBE_SPAN = [ - /createElement\(\s*['"`]span['"`]\s*\)/, - /['"`][A-Za-z0-9]['"`]\s*\.repeat\s*\(/, - /\b(offsetWidth|getBoundingClientRect)\b/ -] - -function productSources(): { path: string; text: string }[] { - return censusSourceFiles(SOURCE_ROOT) - .map((path) => ({ path, name: relative(SOURCE_ROOT, path).replaceAll('\\', '/') })) - .filter(({ name }) => /\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name)) - .map(({ path, name }) => ({ path: name, text: readFileSync(path, 'utf8') })) -} - -function glyphMeasurements(text: string): string[] { - const found = GLYPH_MEASUREMENT.filter(([, pattern]) => pattern.test(text)).map(([kind]) => kind) - return PROBE_SPAN.every((pattern) => pattern.test(text)) ? [...found, 'probe span'] : found -} - -describe('the cell box has one measurer', () => { - it('walks the product sources, including the document that reports the box', () => { - const paths = productSources().map((source) => source.path) - expect(paths).toContain('terminal/document/laid-out-cell-box.ts') - expect(paths).toContain('terminal/document/terminal-init.ts') - }) - - it('recognises each technique it fences', () => { - expect(glyphMeasurements("ctx.measureText('W')")).toEqual(['canvas text metrics']) - expect(glyphMeasurements('new OffscreenCanvas(1, 1)')).toEqual(['offscreen canvas']) - expect(glyphMeasurements('m.fontBoundingBoxAscent + m.fontBoundingBoxDescent')).toEqual([ - 'font bounding box' - ]) - expect( - glyphMeasurements( - "const s = document.createElement('span'); s.textContent = 'W'.repeat(32); s.offsetWidth" - ) - ).toEqual(['probe span']) - }) - - it('has no file under mobile/src measure a glyph outside xterm', () => { - const found = productSources().flatMap(({ path, text }) => - glyphMeasurements(text).map((kind) => `${path}: ${kind}`) - ) - expect(found).toEqual([]) - }) -}) diff --git a/mobile/src/terminal/terminal-foreground-recovery.test.ts b/mobile/src/terminal/terminal-foreground-recovery.test.ts index abf1bd01045..50fcda6ec52 100644 --- a/mobile/src/terminal/terminal-foreground-recovery.test.ts +++ b/mobile/src/terminal/terminal-foreground-recovery.test.ts @@ -2,23 +2,12 @@ import type { RefObject } from 'react' import { describe, expect, it, vi } from 'vitest' import type { ConnectionState } from '../transport/types' import type { TerminalWebViewHandle } from './TerminalWebView' -import { readMobileSessionRouteSource } from '../session/mobile-session-route-source-family.test-support' import { TERMINAL_FOREGROUND_RECOVERY_DELAY_MS, recoverActiveTerminalAfterForeground, shouldRecoverTerminalOnAppStateChange } from './terminal-foreground-recovery' -const lifecycleSource = readMobileSessionRouteSource('../session/use-mobile-session-lifecycle.ts') - -function sliceSessionSource(startPattern: string, endPattern: string): string { - const start = lifecycleSource.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = lifecycleSource.indexOf(endPattern, start) - expect(end).toBeGreaterThan(start) - return lifecycleSource.slice(start, end) -} - type RecoveryHarness = { activeHandleRef: RefObject terminalRefs: RefObject> @@ -139,37 +128,4 @@ describe('terminal foreground recovery', () => { expect(harness.subscribeToTerminal).not.toHaveBeenCalled() }) - - it('is wired to AppState foregrounding in the session screen', () => { - const foregroundPredicate = sliceSessionSource( - 'const shouldRecover = shouldRecoverTerminalOnAppStateChange(', - 'previousAppState = nextAppState' - ) - - expect(lifecycleSource).toContain('shouldRecoverTerminalOnAppStateChange') - expect(foregroundPredicate).toContain('Platform.OS') - expect(lifecycleSource).toContain('recoverActiveTerminalAfterForeground({') - expect(lifecycleSource).toContain("AppState.addEventListener('change'") - const readinessInvalidation = lifecycleSource.indexOf( - 'terminalRef.prepareForForegroundRecovery()' - ) - const replay = lifecycleSource.indexOf('recoverActiveTerminalAfterForeground({') - expect(readinessInvalidation).toBeGreaterThanOrEqual(0) - expect(replay).toBeGreaterThan(readinessInvalidation) - }) - - it('re-runs a deferred recovery once the session screen reconnects', () => { - // Why: resume usually lands mid-reconnect; the session screen must retry - // recovery on the connState→connected transition or blanked panes stay - // stale until a manual tab switch. - expect(lifecycleSource).toContain( - "pendingForegroundRecoveryRef.current = outcome === 'deferred'" - ) - const reconnectRetry = sliceSessionSource( - "if (connState !== 'connected' || !pendingForegroundRecoveryRef.current)", - 'recoverActiveTerminalAfterForeground({' - ) - expect(reconnectRetry).toContain('pendingForegroundRecoveryRef.current = false') - expect(reconnectRetry).toContain("AppState.currentState !== 'active'") - }) }) diff --git a/mobile/src/terminal/terminal-input-connection-gate.test.ts b/mobile/src/terminal/terminal-input-connection-gate.test.ts index 4d55c31bcf4..747f0eaab4c 100644 --- a/mobile/src/terminal/terminal-input-connection-gate.test.ts +++ b/mobile/src/terminal/terminal-input-connection-gate.test.ts @@ -1,28 +1,6 @@ import { describe, expect, it } from 'vitest' import { resolveMobileTerminalInputGate } from './terminal-input-connection-gate' import { buildTerminalSendParams, TERMINAL_INPUT_SEND_OPTIONS } from './terminal-send-request' -import { readMobileSessionRouteSource } from '../session/mobile-session-route-source-family.test-support' - -const runtimeSource = readMobileSessionRouteSource( - '../session/use-mobile-session-terminal-runtime.ts' -) -const sendActionsSource = readMobileSessionRouteSource( - '../session/use-mobile-session-terminal-send-actions.ts' -) -const terminalInputSource = readMobileSessionRouteSource( - '../session/use-mobile-session-terminal-input.ts' -) -const commandDockSource = readMobileSessionRouteSource('../session/MobileSessionCommandDock.tsx') - -function sourceSlice(source: string, anchorStart: string, anchorEnd: string): string { - const start = source.indexOf(anchorStart) - expect(start).toBeGreaterThanOrEqual(0) - // Why: a duplicated start anchor would silently slice the wrong region. - expect(source.indexOf(anchorStart, start + 1)).toBe(-1) - const end = source.indexOf(anchorEnd, start) - expect(end).toBeGreaterThan(start) - return source.slice(start, end + anchorEnd.length) -} describe('terminal input connection gate', () => { it('Given a live connection on a terminal tab Then composing and sending are both allowed', () => { @@ -83,74 +61,9 @@ describe('terminal input connection gate', () => { }) }) -describe('session route offline-compose wiring', () => { - it('derives both gates from the shared resolver', () => { - expect(runtimeSource).toContain('resolveMobileTerminalInputGate({') - }) - - it('keeps the buffered command box editable offline while the live capture stays send-gated', () => { - const bufferedInput = sourceSlice( - commandDockSource, - 'ref={bindCommandField}', - 'onSubmitEditing={() => void handleSend()}' - ) - expect(bufferedInput).toContain('editable={canCompose}') - - const liveCapture = sourceSlice( - commandDockSource, - 'ref={bindLiveInputField}', - 'importantForAutofill="no"' - ) - expect(liveCapture).toContain('editable={canSend}') - }) - - it('keeps the send button connection-gated so held text cannot fire into a dead link', () => { - const sendButton = sourceSlice( - commandDockSource, - 'styles.sendButton,', - 'accessibilityLabel="Send command"' - ) - expect(sendButton).toContain('disabled={!canSend}') - }) - - it('holds composed text when the return key submits offline', () => { - const handleSend = sourceSlice( - sendActionsSource, - 'async function handleSend()', - 'sendingRef.current = true' - ) - expect(handleSend).toContain('!canSend') - }) - - it('keeps the live/buffered mode toggle reachable offline', () => { - const modeToggle = sourceSlice( - commandDockSource, - 'liveInputEnabled && styles.accessoryKeyActive', - 'onPress={toggleLiveInput}' - ) - expect(modeToggle).toContain('disabled={!canCompose}') - }) - - it('tells the live-input commit hook about connection loss so stale mirror state resets', () => { - const hookCall = sourceSlice( - runtimeSource, - 'useTerminalLiveInputCommit({', - 'setLiveInputCapture' - ) - expect(hookCall).toContain("connected: connState === 'connected'") - }) - +describe('terminal send request shape', () => { it('keeps every keystroke-grade terminal send now-or-never so nothing replays after reconnect', () => { - // Live mirror, buffered send, and gesture arrows must all opt out of the - // connect wait — a parked send replays stale bytes into the PTY. Accessory - // keys get the same option inside terminal-live-accessory-raw-send.ts. - expect(sendActionsSource).toContain('TERMINAL_INPUT_SEND_OPTIONS') - expect(terminalInputSource).toContain('TERMINAL_INPUT_SEND_OPTIONS') - const optionUses = [sendActionsSource, terminalInputSource].flatMap( - (source) => source.match(/TERMINAL_INPUT_SEND_OPTIONS/g) ?? [] - ).length - // Two owner imports plus one buffered, one live, and one gesture send. - expect(optionUses).toBe(5) + // A parked send replays stale bytes into the PTY once the socket comes back. expect(TERMINAL_INPUT_SEND_OPTIONS).toEqual({ failWhenDisconnected: true }) }) diff --git a/mobile/src/terminal/terminal-ios-dictation-write-back.test.ts b/mobile/src/terminal/terminal-ios-dictation-write-back.test.ts deleted file mode 100644 index 9929f09c37d..00000000000 --- a/mobile/src/terminal/terminal-ios-dictation-write-back.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readMobileSessionRouteSource } from '../session/mobile-session-route-source-family.test-support' - -const commandDockSource = readMobileSessionRouteSource('../session/MobileSessionCommandDock.tsx') -const sendActionsSource = readMobileSessionRouteSource( - '../session/use-mobile-session-terminal-send-actions.ts' -) - -// Why: iOS terminates an active keyboard-dictation (and IME) session whenever -// JS writes a value into the focused field that differs from the native text -// (RN applies it via setTextAndSelection / _setAttributedString). Terminal -// inputs therefore must echo the raw field text in their controlled value and -// apply dash normalization only on the send/mirror path. See stablyai/orca#7925. -describe('terminal iOS dictation write-back', () => { - it('does not write normalized text back into the buffered command input value', () => { - expect(commandDockSource).toContain('onChangeText={bufferedTerminalDraftState.setInput}') - expect(commandDockSource).not.toContain('setInput((previousText) => normalizeTerminalTextInput') - }) - - it('still normalizes the buffered command text at send time', () => { - expect(sendActionsSource).toContain('normalizeTerminalTextInput(draft)') - }) -}) diff --git a/mobile/src/terminal/terminal-ios-ime-keyboard.test.ts b/mobile/src/terminal/terminal-ios-ime-keyboard.test.ts deleted file mode 100644 index 573dcf04bbf..00000000000 --- a/mobile/src/terminal/terminal-ios-ime-keyboard.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readMobileSessionRouteSource } from '../session/mobile-session-route-source-family.test-support' - -const commandDockSource = readMobileSessionRouteSource('../session/MobileSessionCommandDock.tsx') - -describe('terminal iOS IME keyboard', () => { - it('does not force terminal inputs onto the ASCII-only iOS keyboard', () => { - expect(commandDockSource).not.toContain("'ascii-capable'") - expect(commandDockSource).not.toContain('"ascii-capable"') - }) - - it('subscribes live capture to onChange so the marked-text report survives', () => { - // onChangeText hands over only a string, discarding the preedit report that - // decides whether the text may reach the PTY at all. - expect(commandDockSource).toContain('onChange={handleLiveInputChange}') - expect(commandDockSource).not.toContain('onChangeText={handleLiveInputChange}') - }) - - it('does not put terminal keyboard capture behind iOS textContentType semantics', () => { - expect(commandDockSource).not.toContain('textContentType="none"') - expect(commandDockSource).toContain('autoComplete="off"') - }) -}) diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts index 89830162921..40a03d14592 100644 --- a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts +++ b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts @@ -2,7 +2,6 @@ import { Terminal } from '@xterm/xterm' import { describe, expect, it, vi } from 'vitest' import { createTerminalDocumentScope } from './document/document-scope' -import { documentModuleSource } from './document/document-module-source.test-support' import { emitKeyboardAvoidanceMetrics } from './document/keyboard-avoidance-metrics' import { commitFitScale } from './document/fit-scale' import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' @@ -193,45 +192,6 @@ describe('terminal keyboard-avoidance WebView metrics', () => { }) }) - it('refreshes metrics after every buffer geometry reset', () => { - // Four places change the buffer's geometry, and each owes a fresh emit after it: a stale - // content-bottom row is what lifts the keyboard over the wrong line. Read from each module's - // own source, so a fifth site added in a new module is not silently uncovered. - // A text-scale resize reports through the fit it schedules, whose commit emits (pinned below). - const directEmit = 'emitKeyboardAvoidanceMetrics(scope)' - const blocks = [ - ['terminal-init', 'export function resize(', directEmit], - ['reflow', 'export function reflow(', directEmit], - ['host-message-router', "} else if (msg.type === 'clear') {", directEmit], - ['text-scaling', 'export function applyTextScale(', 'applyFitScale(scope'] - ] as const - - for (const [module, opener, emit] of blocks) { - const source = documentModuleSource(module) - const start = source.indexOf(opener) - expect(start, `${module} no longer carries ${opener}`).toBeGreaterThanOrEqual(0) - const block = source.slice(start, source.indexOf('\n}', start)) - const emitAt = block.lastIndexOf(emit) - const geometryAt = block.includes('.resize(') - ? block.indexOf('.resize(') - : block.indexOf('.reset(') - expect(emitAt, `${module} does not emit metrics`).toBeGreaterThanOrEqual(0) - expect(emitAt, `${module} emits before it resizes`).toBeGreaterThan(geometryAt) - } - }) - - it('reports a text-scale change only through the fit it commits', () => { - // One emit site: a pinch release and a settings change both end in the fit commit, so the - // release carries no emit of its own and needs no word back on whether a refit is pending. - const textScaling = documentModuleSource('text-scaling') - const start = textScaling.indexOf('export function applyTextScale(') - const applyTextScale = textScaling.slice(start, textScaling.indexOf('\n}', start)) - expect(applyTextScale).not.toMatch(/return (true|false)/) - expect(documentModuleSource('surface-touch-gestures')).not.toContain( - 'emitKeyboardAvoidanceMetrics' - ) - }) - it('reports the row pitch as drawn, fit scale included, and none before a cell is measured', () => { // Desktop display mode keeps the desktop's rows and the fit shrinks the grid by width. const buffer = { cursorY: 0, viewportY: 0, type: 'normal', getLine: () => undefined } diff --git a/mobile/src/terminal/terminal-live-input-affordance.test.ts b/mobile/src/terminal/terminal-live-input-affordance.test.ts deleted file mode 100644 index 565b355d771..00000000000 --- a/mobile/src/terminal/terminal-live-input-affordance.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readFileSync } from 'node:fs' -import { readMobileSessionRouteSource } from '../session/mobile-session-route-source-family.test-support' - -const commandDockSource = readMobileSessionRouteSource('../session/MobileSessionCommandDock.tsx') -const terminalRuntimeSource = readMobileSessionRouteSource( - '../session/use-mobile-session-terminal-runtime.ts' -) -const nativeChatSource = readMobileSessionRouteSource( - '../session/use-mobile-session-native-chat-dictation.ts' -) -const liveInputStatusSource = readFileSync( - new URL('../session/MobileTerminalLiveInputStatus.tsx', import.meta.url), - 'utf8' -) -const commandInputStylesSource = readFileSync( - new URL('../session/mobile-session-command-input-styles.ts', import.meta.url), - 'utf8' -) -const liveInputFocusSource = readFileSync( - new URL('./use-terminal-live-input-focus.ts', import.meta.url), - 'utf8' -) -const sendCompletionGenerationSource = readFileSync( - new URL('../session/use-mobile-send-completion-generation.ts', import.meta.url), - 'utf8' -) - -function liveInputBarBlock(): string { - const start = commandDockSource.indexOf('{liveInputEnabled ? (') - expect(start).toBeGreaterThanOrEqual(0) - const end = commandDockSource.indexOf(') : (', start) - expect(end).toBeGreaterThan(start) - return commandDockSource.slice(start, end) -} - -describe('terminal live input affordance', () => { - it('keeps the live status row wired as the keyboard focus control', () => { - const block = liveInputBarBlock() - - expect(block).toContain('onPress={focusLiveInput}') - expect(block).toContain('accessibilityRole="button"') - expect(block).toContain('accessibilityLabel="Show keyboard for live terminal input"') - expect(block).toContain( - 'accessibilityHint="Typed text is sent directly to the active terminal"' - ) - expect(block).toContain('pressed && styles.liveInputFocusTargetPressed') - expect(block).toContain('!canSend && styles.liveInputFocusTargetDisabled') - expect(block).toContain('showSoftInputOnFocus') - expect(block).toContain('liveInputText={liveInputCapture}') - expect(terminalRuntimeSource).toContain('useTerminalLiveInputFocus({') - expect(nativeChatSource).toContain('useMobileSendCompletionGeneration({') - expect(nativeChatSource).toContain('onBlur: resetLiveInputFocus') - expect(sendCompletionGenerationSource).toContain('return () => {') - expect(sendCompletionGenerationSource).toContain('onBlur()') - expect(liveInputFocusSource).toContain('focusTerminalLiveInputTarget(inputRef.current') - expect(liveInputFocusSource).toContain('lifecycleIdentity,') - expect(liveInputFocusSource).toContain('resetLiveInputFocus') - expect(liveInputFocusSource).toContain('keyboardHeight: context.keyboardHeight') - expect(liveInputFocusSource).toContain( - 'scheduleTerminalLiveInputFocus(timerRef, focusLiveInput)' - ) - }) - - it('makes the live keyboard target visible instead of status-only chrome', () => { - expect(liveInputStatusSource).toContain("'Tap to show keyboard'") - expect(liveInputStatusSource).toContain("liveInputText || 'Tap to show keyboard'") - expect(liveInputStatusSource).toContain('ellipsizeMode="head"') - expect(commandInputStylesSource).toContain('backgroundColor: colors.bgRaised') - expect(commandInputStylesSource).toContain('borderWidth: 1') - expect(commandInputStylesSource).toContain('liveInputFocusTargetPressed') - }) -}) diff --git a/mobile/src/terminal/terminal-viewport-refit.test.ts b/mobile/src/terminal/terminal-viewport-refit.test.ts index 9b8a5b24b0e..51a349175be 100644 --- a/mobile/src/terminal/terminal-viewport-refit.test.ts +++ b/mobile/src/terminal/terminal-viewport-refit.test.ts @@ -1,59 +1,15 @@ -import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' import type { RpcResponse } from '../transport/types' -import { readMobileSessionRouteSource } from '../session/mobile-session-route-source-family.test-support' import { terminalViewportUpdate } from './mobile-terminal-operations' import { isTerminalViewportRefitTargetCurrent, reduceTerminalFrameHeightRefit, resolveTerminalUpdateViewportCapability, type TerminalFrameHeightRefitEvent, - type TerminalFrameHeightRefitState, - type TerminalUpdateViewportCapability + type TerminalFrameHeightRefitState } from './terminal-viewport-refit-state' -const hookSource = readFileSync(new URL('./terminal-viewport-refit.ts', import.meta.url), 'utf8') -const sessionSource = [ - readMobileSessionRouteSource('../session/use-mobile-session-keyboard-state.ts'), - readMobileSessionRouteSource('../session/MobileSessionActiveContent.tsx'), - readMobileSessionRouteSource('../session/use-mobile-session-terminal-webview.ts') -].join('\n') - describe('terminal viewport refit', () => { - it('refits when the window dimensions change (fold/unfold, rotation)', () => { - // Why: a PTY fitted on the folded cover screen must be re-measured when - // the window grows, or the terminal renders in a fraction of the display. - expect(hookSource).toContain('useWindowDimensions()') - const start = hookSource.indexOf('const { width: windowWidth, height: windowHeight }') - expect(start).toBeGreaterThanOrEqual(0) - const resizeEffect = hookSource.slice(start) - expect(resizeEffect).toContain('viewportMeasuredRef.current = false') - expect(resizeEffect).toContain('scheduleViewportRefit()') - expect(resizeEffect).toContain( - '[windowWidth, windowHeight, viewportMeasuredRef, scheduleViewportRefit]' - ) - }) - - it('still refits when the tab strip toggles visibility', () => { - const start = hookSource.indexOf('const prevTabStripVisibleRef') - expect(start).toBeGreaterThanOrEqual(0) - const tabEffect = hookSource.slice(start, hookSource.indexOf('useWindowDimensions()')) - expect(tabEffect).toContain('viewportMeasuredRef.current = false') - expect(tabEffect).toContain('scheduleViewportRefit()') - }) - - it('refits the PTY when terminal text scale changes', () => { - // Why: mobile text size must change the real PTY grid, not just scale pixels - // in the WebView, or wrapped CLI output diverges from what the shell sees. - const start = hookSource.indexOf('const prevTextScaleRef = useRef(textScale)') - expect(start).toBeGreaterThanOrEqual(0) - const textScaleEffect = hookSource.slice(start, start + 600) - expect(textScaleEffect).toContain('prevTextScaleRef.current === textScale') - expect(textScaleEffect).toContain('viewportMeasuredRef.current = false') - expect(textScaleEffect).toContain('scheduleViewportRefit()') - expect(textScaleEffect).toContain('[textScale, viewportMeasuredRef, scheduleViewportRefit]') - }) - it('coalesces keyboard-visible frame-height churn into one refit after close', () => { let state: TerminalFrameHeightRefitState = { frameHeight: 600, @@ -84,17 +40,6 @@ describe('terminal viewport refit', () => { expect(refitCount).toBe(2) }) - it('routes imperative height notifications through the keyboard-aware reducer', () => { - const start = hookSource.indexOf('const notifyFrameHeightRefitEvent = useCallback(') - expect(start).toBeGreaterThanOrEqual(0) - const notifier = hookSource.slice(start, start + 1_300) - expect(notifier).toContain('reduceTerminalFrameHeightRefit(') - expect(notifier).toContain("{ type: 'frame-height', height }") - expect(notifier).toContain("{ type: 'keyboard-visibility', visible }") - expect(notifier).toContain('viewportMeasuredRef.current = false') - expect(notifier).toContain('scheduleViewportRefit({ heightOriginated: true })') - }) - it('re-defers a height refit if the keyboard reopens before the debounce fires', () => { // Settle while the keyboard is up -> deferred (pending), no refit. let r = reduceTerminalFrameHeightRefit( @@ -126,95 +71,6 @@ describe('terminal viewport refit', () => { expect(ran.state.pending).toBe(false) }) - it('re-checks the keyboard at fire time only for height-originated refits', () => { - const start = hookSource.indexOf('refitTimerRef.current = setTimeout(') - expect(start).toBeGreaterThanOrEqual(0) - const timerBody = hookSource.slice(start, start + 900) - // The height flag scopes the guard; forced/width refits stay unguarded. - expect(timerBody).toContain('if (heightOriginatedRefitRef.current)') - expect(timerBody).toContain("type: 'refit-committed'") - expect(timerBody).toContain('if (!decision.shouldRefit)') - }) - - it('suppresses refits while native chat covers the active terminal', () => { - // Why: native chat renders the transcript, not the grid — a refit there would - // reflow the desktop PTY to phone dims the user never sees. - const timerStart = hookSource.indexOf('refitTimerRef.current = setTimeout(') - const coveredCheck = hookSource.indexOf('if (nativeChatCoveredRef.current)', timerStart) - const fitIndex = hookSource.indexOf('ref.fitDimensions(', timerStart) - expect(timerStart).toBeGreaterThanOrEqual(0) - expect(coveredCheck).toBeGreaterThan(timerStart) - expect(fitIndex).toBeGreaterThan(coveredCheck) - expect(sessionSource).toContain('nativeChatCoveredRef: showNativeChatRef') - }) - - it('is wired into the session screen', () => { - expect(sessionSource).toContain('useTerminalViewportRefit({') - expect(sessionSource).toContain('tabStripVisible: terminals.length > 1') - expect(sessionSource).toContain('textScale: terminalTextScale') - expect(sessionSource).toContain('connState,') - expect(sessionSource).toContain('notifyTerminalFrame({ width, height })') - expect(sessionSource).toContain('notifyTerminalFrameHeight(Math.round(frame.height))') - expect(sessionSource).toContain('notifyTerminalFrameWidth()') - // One seam for both facts: they come apart for a floating keyboard, which is open yet covers - // nothing the screen has to lift for. - expect(sessionSource).toContain('const softKeyboard = useSoftKeyboard()') - expect(sessionSource).toContain('notifyKeyboardVisibility(softKeyboard.visible)') - expect(sessionSource).toContain('setKeyboardHeight(softKeyboard.height)') - }) - - it('does not rerender SessionScreen for frame-height-only layout changes', () => { - // The imperative notifier keeps a dock-settling burst off React's render path. - expect(sessionSource).not.toContain('setTerminalFrameHeight') - expect(sessionSource).not.toContain('const [terminalFrameHeight,') - }) - - it('defers height-only window resizes while the keyboard is visible', () => { - const start = hookSource.indexOf('const prevWindowDimsRef') - const windowEffect = hookSource.slice(start, start + 1_100) - expect(windowEffect).toContain( - 'prev.width === windowWidth && frameHeightRefitStateRef.current.keyboardVisible' - ) - }) - - it('forces a refit on iOS foreground and connection recovery', () => { - const foregroundEffect = hookSource.slice( - hookSource.indexOf("if (Platform.OS !== 'ios')"), - hookSource.indexOf('const previousConnStateRef') - ) - const reconnectEffect = hookSource.slice( - hookSource.indexOf('const previousConnStateRef'), - hookSource.indexOf('disposedRef.current = false') - ) - - expect(foregroundEffect).toContain("AppState.addEventListener('change'") - expect(foregroundEffect).toContain('viewportMeasuredRef.current = false') - expect(foregroundEffect).toContain('scheduleForcedViewportRefit()') - expect(reconnectEffect).toContain("connState !== 'connected'") - expect(reconnectEffect).toContain('viewportMeasuredRef.current = false') - expect(reconnectEffect).toContain('scheduleForcedViewportRefit()') - }) - - it('bypasses the equal-dimensions guard for resume and reconnect refits', () => { - expect(hookSource).toContain('const forceRefit = forceNextRefitRef.current') - expect(hookSource).toContain( - 'if (!forceRefit && prev && prev.cols === dims.cols && prev.rows === dims.rows)' - ) - const forceRead = hookSource.indexOf('const forceRefit = forceNextRefitRef.current') - const updateViewport = hookSource.indexOf('terminalViewportUpdate.request(rpc,') - expect(forceRead).toBeGreaterThanOrEqual(0) - expect(updateViewport).toBeGreaterThan(forceRead) - }) - - it('prefers the in-place updateViewport RPC over resubscribe', () => { - const rpcIndex = hookSource.indexOf('terminalViewportUpdate.request(rpc,') - const cacheUpdateIndex = hookSource.indexOf('updateTerminalSubscriptionViewport(handle, dims)') - const resubscribeIndex = hookSource.indexOf('subscribeToTerminal(handle)') - expect(rpcIndex).toBeGreaterThanOrEqual(0) - expect(cacheUpdateIndex).toBeGreaterThan(rpcIndex) - expect(resubscribeIndex).toBeGreaterThan(rpcIndex) - }) - it('falls back to legacy resubscribe when an older desktop lacks updateViewport', () => { const unsupported = { id: 'old-host', @@ -229,52 +85,8 @@ describe('terminal viewport refit', () => { error: { code: 'temporary_failure', message: 'retryable' } }) ).toBe('unknown') - - let capability: TerminalUpdateViewportCapability = 'unknown' - let probeCount = 0 - for (let refit = 0; refit < 10; refit += 1) { - if (capability === 'unsupported') { - continue - } - probeCount += 1 - capability = resolveTerminalUpdateViewportCapability(unsupported) - } - expect(probeCount).toBe(1) - - const responseCheckIndex = hookSource.indexOf('if (outcome?.updated)') - const unsubscribeIndex = hookSource.indexOf('unsubscribeTerminal(handle)', responseCheckIndex) - const subscribeIndex = hookSource.indexOf('subscribeToTerminal(handle)', unsubscribeIndex) - expect(responseCheckIndex).toBeGreaterThanOrEqual(0) - expect(unsubscribeIndex).toBeGreaterThan(responseCheckIndex) - expect(subscribeIndex).toBeGreaterThan(unsubscribeIndex) - expect(hookSource).toContain("updateViewportCapabilityRef.current !== 'unsupported'") - expect(hookSource).toContain("updateViewportCapabilityRef.current = 'unknown'") - }) - - it('reflows the local xterm scrollback after a successful updateViewport', () => { - // Why: updateViewport may only record an informational mobile viewport in - // desktop mode. Reflow local scrollback only after the server says it - // actually applied phone-fit to the PTY. - const appliedIndex = hookSource.indexOf('if (outcome.applied)') - const reflowIndex = hookSource.indexOf('ref.reflow(dims.cols, dims.rows, frame)') - const cacheUpdateIndex = hookSource.indexOf('updateTerminalSubscriptionViewport(handle, dims)') - // Assert each anchor exists before ordering: a missing marker yields -1 and would - // let the ordering comparisons pass vacuously. - expect(appliedIndex).toBeGreaterThanOrEqual(0) - expect(cacheUpdateIndex).toBeGreaterThanOrEqual(0) - expect(reflowIndex).toBeGreaterThanOrEqual(0) - expect(reflowIndex).toBeGreaterThan(appliedIndex) - expect(reflowIndex).toBeGreaterThan(cacheUpdateIndex) - }) - - it('checks refit freshness after updateViewport resolves before side effects', () => { - // Why: rapid dock/sidebar resizing can complete RPCs out of order; a stale - // response must not update the viewport cache or locally reflow the old dims. - const responseIndex = hookSource.indexOf('terminalViewportUpdate.request(rpc,') - const postRpcCurrentIndex = hookSource.indexOf('if (!isCurrentTarget())', responseIndex) - const cacheUpdateIndex = hookSource.indexOf('updateTerminalSubscriptionViewport(handle, dims)') - expect(postRpcCurrentIndex).toBeGreaterThan(responseIndex) - expect(postRpcCurrentIndex).toBeLessThan(cacheUpdateIndex) + // A method_not_found refusal latches the capability, so a refit stops re-probing. + expect(resolveTerminalUpdateViewportCapability(unsupported)).toBe('unsupported') }) it('only treats updateViewport as applied when the runtime updated the subscriber', () => { diff --git a/mobile/src/terminal/terminal-webview-consumer-census.test.ts b/mobile/src/terminal/terminal-webview-consumer-census.test.ts deleted file mode 100644 index cb57e4a4755..00000000000 --- a/mobile/src/terminal/terminal-webview-consumer-census.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { readFileSync, readdirSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -/** - * Nothing above the terminal component knows which of the two it has. - * - * The page's `TerminalWebView.web.tsx` is resolved by the bundler, not chosen by a caller, so the - * whole substitution rests on every consumer holding only `terminal-webview-contract` — the props - * and the handle — and on the one that renders the component naming it without an extension. A - * consumer that reached into `TerminalWebView.tsx` for a type, or imported `terminal-webview-html` - * for the document string, would work natively and break on the page in a way no native test sees. - * - * Scanned rather than listed, so a new consumer joins the rule by existing. - */ - -const terminalDir = import.meta.dirname -const sessionDir = join(terminalDir, '..', 'session') - -/** The modules that may reach into the component's own file or the document's HTML. */ -const ALLOWED_INSIDE_TERMINAL = new Set([ - 'TerminalWebView.tsx', - 'TerminalWebView.web.tsx', - 'terminal-web-document-mount.ts', - 'terminal-webview-html.ts', - 'terminal-webview-html.web.ts', - // Test scaffolding that drives the document's own modules; it is not shipped in either build. - 'terminal-webview-mouse-test-harness.ts' -]) - -const FORBIDDEN_ABOVE_THE_CONTRACT = [ - /from '(\.\.\/terminal|\.)\/TerminalWebView\.(web\.)?tsx?'/, - /from '(\.\.\/terminal|\.)\/terminal-webview-html'/, - /from '(\.\.\/terminal|\.)\/terminal-webview-engine(-css)?\.generated'/, - /from '(\.\.\/terminal|\.)\/document\// -] - -function productModules(directory: string): string[] { - return readdirSync(directory) - .filter((name) => /\.tsx?$/.test(name)) - .filter((name) => !name.includes('.test') && !name.includes('.test-support')) - .sort() -} - -function offenders(directory: string, skip: (name: string) => boolean): string[] { - const found: string[] = [] - for (const name of productModules(directory)) { - if (skip(name)) { - continue - } - const source = readFileSync(join(directory, name), 'utf8') - for (const pattern of FORBIDDEN_ABOVE_THE_CONTRACT) { - if (pattern.test(source)) { - found.push(`${name}: ${pattern.source}`) - } - } - } - return found -} - -describe('the terminal component contract', () => { - it('is all that src/session imports of the terminal', () => { - expect(offenders(sessionDir, () => false)).toEqual([]) - // The precondition: a scan that read no session module would report nothing either. - const rendering = readFileSync(join(sessionDir, 'TerminalPaneView.tsx'), 'utf8') - expect(rendering).toContain("from '../terminal/TerminalWebView'") - expect(rendering).toContain("from '../terminal/terminal-webview-contract'") - }) - - it('is all that the terminal directory itself imports, outside the component and its document', () => { - expect(offenders(terminalDir, (name) => ALLOWED_INSIDE_TERMINAL.has(name))).toEqual([]) - expect(productModules(terminalDir).length).toBeGreaterThan(40) - }) - - it('would report a consumer that named the component file', () => { - // The scan tested on the text it is meant to refuse, so an empty offender list above is a - // measurement rather than a regex that matches nothing. - const planted = "import { TerminalWebView } from '../terminal/TerminalWebView.tsx'\n" - expect(FORBIDDEN_ABOVE_THE_CONTRACT.some((pattern) => pattern.test(planted))).toBe(true) - const html = "import { XTERM_HTML } from '../terminal/terminal-webview-html'\n" - expect(FORBIDDEN_ABOVE_THE_CONTRACT.some((pattern) => pattern.test(html))).toBe(true) - const extensionless = "import { TerminalWebView } from '../terminal/TerminalWebView'\n" - expect(FORBIDDEN_ABOVE_THE_CONTRACT.some((pattern) => pattern.test(extensionless))).toBe(false) - }) -}) diff --git a/mobile/src/terminal/terminal-webview-engine.test.ts b/mobile/src/terminal/terminal-webview-engine.test.ts index 3f3aab326fe..96a4327f090 100644 --- a/mobile/src/terminal/terminal-webview-engine.test.ts +++ b/mobile/src/terminal/terminal-webview-engine.test.ts @@ -1,6 +1,4 @@ // @vitest-environment happy-dom -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { Script } from 'node:vm' import { parse } from 'acorn' import { describe, expect, it, vi } from 'vitest' @@ -8,15 +6,8 @@ import { XTERM_ENGINE_CSS } from './terminal-webview-engine-css.generated' import { XTERM_ENGINE_JS } from './terminal-webview-engine.generated' import { createTerminalDocumentScope } from './document/document-scope' import { attachWebglAddon, startWebglRecovery } from './document/webgl-recovery' -import { - documentModuleSource, - documentSourceText -} from './document/document-module-source.test-support' import { XTERM_HTML } from './terminal-webview-html' -// The document's own source, so a rule about what the document does is read where it is written. -const terminalHtmlSource = documentSourceText() - function createWebglRecoveryHarness(failSecondAttach = false) { const timers: Array<() => void> = [] const addons: Array<{ @@ -151,58 +142,6 @@ describe('terminal WebView bundled engine', () => { expect(XTERM_ENGINE_CSS).not.toMatch(/<\/style/i) }) - it('reports WebView message handler failures instead of swallowing them', () => { - const start = terminalHtmlSource.indexOf('function handleIncomingMessage') - // Bounded by the next declaration in the same module: ruling 24 took the resize listener out - // of the bridge, so the handler is followed by the start that installs the transport. - const end = terminalHtmlSource.indexOf('function startMessageBridge', start) - expect(start).toBeGreaterThanOrEqual(0) - expect(end).toBeGreaterThan(start) - const handlerSource = terminalHtmlSource.slice(start, end) - - expect(handlerSource).toContain('reportEngineError(') - expect(handlerSource).toContain("'terminal init failed'") - expect(handlerSource).toContain("'terminal message failed'") - expect(handlerSource).not.toContain('catch(ex) {}') - }) - - it('classifies runtime errors by a document-scoped ever-ready latch', () => { - // Why: init() flips `ready` false on every re-init (live width reflow keeps the - // old surface visible meanwhile), so the fatal default and the init-catch must - // key off `everReady` — otherwise a transient reflow error blanks a live - // terminal behind the fatal overlay. The latch stays set for the document. - // Ruling 21: the latch's initial value is in the scope factory, not in a parse-time write. - expect(terminalHtmlSource).toContain('everReady: false,') - expect(terminalHtmlSource).toContain('scope.everReady = true') - expect(terminalHtmlSource).toContain('fatal === undefined ? !scope.everReady : !!fatal') - expect(terminalHtmlSource).toContain("msg && msg.type === 'init' && !scope.everReady") - expect(terminalHtmlSource).not.toMatch(/fatal === void 0 \? !scope\.ready\b/) - }) - - it('bounds error capture and non-fatal reporting on a degraded engine', () => { - // Why: a constructed-but-broken engine can throw per render frame; both - // onerror capture sites must cap the buffer and non-fatal notifies must - // stop flooding RN while fatal reports always emit. - // Both sites: the document's own reporter, and the shell's inline handler that catches what - // fails before the document has run at all. - // `dirname`, not the module URL: a DOM-environment case has no `file:` URL to convert. - const shell = readFileSync( - join(import.meta.dirname, 'terminal-webview-html', 'document-shell.ts'), - 'utf8' - ) - // The shell's buffer is a global because it is older than any document; the document appends to - // it through the seam, so the two sites now spell the same cap over the same list differently. - expect(shell).toContain('window.__engineErrors.length < 20') - expect(terminalHtmlSource).toContain('const captured = scope.capturedEngineErrors()') - expect(terminalHtmlSource).toContain('if (captured.length < 20) {') - // The global is read in one place, the seam's own default, and the reporter no longer names it. - expect(documentModuleSource('host-notify')).not.toContain('window.__engineErrors') - expect(documentModuleSource('document-host-seams')).toContain( - 'window.__engineErrors = window.__engineErrors ?? []' - ) - expect(terminalHtmlSource).toContain('nonFatalErrorNotifies > 5') - }) - it('recreates WebGL once after context loss, then stays on the DOM renderer', () => { const { addons, logged, term, timers } = createWebglRecoveryHarness() diff --git a/mobile/src/terminal/terminal-webview-query-reply.test.ts b/mobile/src/terminal/terminal-webview-query-reply.test.ts index 48de712bcaa..fe090b1436e 100644 --- a/mobile/src/terminal/terminal-webview-query-reply.test.ts +++ b/mobile/src/terminal/terminal-webview-query-reply.test.ts @@ -6,7 +6,6 @@ import { resetTerminalDataReplyAuthority, resumeTerminalDataReplyAuthority } from './document/query-reply' -import { documentModuleSource } from './document/document-module-source.test-support' type QueryReplyGate = { forward: (data: string) => void @@ -50,32 +49,6 @@ function createQueryReplyGate(notify: (message: unknown) => void): { } describe('mobile terminal query replies', () => { - it('forwards xterm-generated data only after initial replay drains', () => { - const bridge = documentModuleSource('query-reply') - const init = documentModuleSource('terminal-init') - // The listener is armed by the bridge, and what it forwards is the gate's own call. - expect(bridge).toContain('term.onData(') - expect(bridge).toContain('forwardTerminalDataReply(scope, data)') - // The terminal takes keystrokes from the host, never from its own textarea: stdin is enabled so - // xterm generates replies, and the textarea is read-only so the phone's keyboard cannot type. - expect(init).toContain('disableStdin: false') - // Both are the bridge's own doing, where the listener it arms is: it takes the key handler and - // the textarea in the same breath. - expect(bridge).toContain('term.attachCustomKeyEventHandler(') - expect(bridge).toContain('term.textarea.readOnly = true') - }) - - it('mutes a replacement terminal until its own replay drains', () => { - const init = documentModuleSource('terminal-init') - const initIndex = init.indexOf('export function init(') - const disableIndex = init.indexOf('resetTerminalDataReplyAuthority(scope)', initIndex) - const enableIndex = init.indexOf('attachTerminalQueryReplyBridge(scope,', disableIndex) - - expect(initIndex).toBeGreaterThanOrEqual(0) - expect(disableIndex).toBeGreaterThan(initIndex) - expect(enableIndex).toBeGreaterThan(disableIndex) - }) - it('suppresses replay, then forwards live queries queued behind its boundary', () => { const messages: unknown[] = [] const { gate, queuedBoundaries } = createQueryReplyGate((message) => messages.push(message)) @@ -117,10 +90,5 @@ describe('mobile terminal query replies', () => { gate.forward('\x1b[3;4R') expect(messages).toEqual([{ type: 'terminal-data', bytes: '\x1b[3;4R' }]) - const router = documentModuleSource('host-message-router') - const clearStart = router.indexOf("} else if (msg.type === 'clear') {") - const clearEnd = router.indexOf("} else if (msg.type === 'reset-zoom')", clearStart) - expect(clearStart).toBeGreaterThanOrEqual(0) - expect(router.slice(clearStart, clearEnd)).toContain('resumeTerminalDataReplyAuthority(scope)') }) }) diff --git a/mobile/src/terminal/terminal-webview-reflow.test.ts b/mobile/src/terminal/terminal-webview-reflow.test.ts deleted file mode 100644 index 82948f541eb..00000000000 --- a/mobile/src/terminal/terminal-webview-reflow.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { readFileSync } from 'node:fs' -import { describe, expect, it } from 'vitest' -import { - documentModuleSource, - documentSourceText -} from './document/document-module-source.test-support' - -const DOCUMENT_SOURCE = documentSourceText() - -// The reflow logic is the document's; the message dispatch and the handle wiring are the -// component's. Both are read as source, because the document is source now. -const reflowSource = documentModuleSource('reflow') -// The handle is built by the controller both components share, which is where the wiring is read. -const handleSource = readFileSync( - new URL('./use-terminal-webview-controller.ts', import.meta.url), - 'utf8' -) - -function reflowFnBody(): string { - const start = reflowSource.indexOf('export function reflow(scope: TerminalDocumentScope') - expect(start).toBeGreaterThanOrEqual(0) - return reflowSource.slice(start) -} - -describe('terminal WebView reflow', () => { - it('skips the alternate screen so TUI snapshots are not mutated', () => { - // Why: alt-screen snapshots are repainted by the PTY; a local resize there - // can drop SGR attributes (white text). Reflow must early-return. - expect(reflowFnBody()).toContain('if (!scope.term || isAlternateBufferActive(scope)) {') - }) - - it('rewraps the local buffer via term.resize to the new cols', () => { - expect(reflowFnBody()).toContain('scope.term.resize(nextCols, nextRows)') - }) - - it('preserves the user scroll position across the rewrap', () => { - const body = reflowFnBody() - // At the live bottom -> stay pinned; scrolled up -> hold distance-from-bottom. - expect(body).toContain('const wasAtBottom = buffer.viewportY >= buffer.baseY') - expect(body).toContain('scope.term.scrollToBottom()') - expect(body).toContain('rewrapped.baseY - distanceFromBottom - rewrapped.viewportY') - }) - - it('is no-op when the dimensions are unchanged', () => { - expect(reflowFnBody()).toContain( - 'if (nextCols === scope.term.cols && nextRows === scope.term.rows) {' - ) - }) - - it('is dispatched by the reflow WebView message and exposed on the handle', () => { - expect(DOCUMENT_SOURCE).toContain("} else if (msg.type === 'reflow') {") - expect(DOCUMENT_SOURCE).toContain('reflow(scope, msg.cols!, msg.rows!)') - expect(handleSource).toContain("postMessage({ type: 'reflow', cols, rows, frame })") - }) - - it('does not locally resize hidden WebViews to a one-column grid', () => { - // The floor belongs to the one fit the app and the document share. - const gridFitSource = readFileSync(new URL('./terminal-grid-fit.ts', import.meta.url), 'utf8') - expect(gridFitSource).toContain('export const MIN_FIT_COLS = 20') - expect(gridFitSource).toContain('if (!(cols >= MIN_FIT_COLS)) {') - }) -}) diff --git a/mobile/src/terminal/terminal-webview-scroll-routing.test.ts b/mobile/src/terminal/terminal-webview-scroll-routing.test.ts deleted file mode 100644 index bb0cc649412..00000000000 --- a/mobile/src/terminal/terminal-webview-scroll-routing.test.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { readFileSync } from 'node:fs' -import { describe, expect, it } from 'vitest' -import { webviewPageSource } from './document/document-module-source.test-support' - -const DOCUMENT_SOURCE = webviewPageSource() - -// The RN wrapper and the pending-message queue are TypeScript; everything the WebView runs is the -// generated document. Concatenated so assertions resolve regardless of file. -const source = - readFileSync(new URL('./TerminalWebView.tsx', import.meta.url), 'utf8') + - readFileSync(new URL('./use-terminal-webview-controller.ts', import.meta.url), 'utf8') + - readFileSync(new URL('./terminal-webview-ready-promises.ts', import.meta.url), 'utf8') + - readFileSync(new URL('./terminal-webview-pending-messages.ts', import.meta.url), 'utf8') + - readFileSync(new URL('./terminal-webview-html/document-markup.ts', import.meta.url), 'utf8') + - readFileSync(new URL('./terminal-webview-html/document-style.ts', import.meta.url), 'utf8') + - DOCUMENT_SOURCE -const sessionSource = readFileSync( - new URL('../session/use-mobile-session-terminal-input.ts', import.meta.url), - 'utf8' -) -const sessionHelperSource = readFileSync( - new URL('../session/mobile-session-route-helpers.ts', import.meta.url), - 'utf8' -) - -function sliceBetween(startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('TerminalWebView scroll routing', () => { - it('keeps Android touch drags inside the terminal WebView', () => { - expect(source).toContain('nestedScrollEnabled') - }) - - it('maps a downward pull at the bottom to older scrollback rows', () => { - expect(source).toContain('const deltaY = scope.touchGesture.lastY - y') - expect(source).toContain('scope.smoothScrollOffsetY -= deltaY') - expect(source).toContain( - 'const lines = Math.trunc(-scope.smoothScrollOffsetY / effectiveCellH)' - ) - - const nextViewportY = simulateNormalBufferPull({ - baseY: 120, - viewportY: 120, - startY: 300, - endY: 340, - cellHeight: 20 - }) - - expect(nextViewportY).toBe(118) - }) - - it('routes alternate-screen and mouse-aware scroll before smooth normal scroll', () => { - expect(source).toContain( - 'return isWheelMouseTrackingMode(getMouseTrackingMode(scope)) || isAlternateBufferActive(scope)' - ) - - const touchMoveBlock = sliceBetween( - "targetSurface.addEventListener(\n 'touchmove'", - '{ capture: true, passive: false }' - ) - expect(touchMoveBlock.indexOf('if (shouldRouteScrollToTerminalInput(scope))')).toBeLessThan( - touchMoveBlock.indexOf('if (enqueueNormalBufferScrollDelta(scope, deltaY))') - ) - expect(touchMoveBlock).toContain('routeScrollLines(scope, lines, x, y)') - - const momentumBlock = sliceBetween( - 'function momentumStep(frameTime: number) {', - 'if (Math.abs(vel) > MIN_VEL)' - ) - expect(momentumBlock.indexOf('if (shouldRouteScrollToTerminalInput(scope))')).toBeLessThan( - momentumBlock.indexOf('if (!applyNormalBufferScrollDelta(scope, delta))') - ) - expect(momentumBlock).toContain( - 'routeScrollLines(scope, lines, scope.touchGesture.lastX, scope.touchGesture.lastY)' - ) - }) - - it('does not rubber-band normal scroll at scrollback edges', () => { - expect(source).toContain('export function canScrollNormalBufferDelta(') - const smoothScrollBlock = sliceBetween( - 'export function applyNormalBufferScrollDelta(', - 'export function enqueueNormalBufferScrollDelta(' - ) - expect(smoothScrollBlock).toContain('if (!canScrollNormalBufferDelta(scope, deltaY))') - expect(smoothScrollBlock).toContain('resetSmoothScrollOffset(scope)') - expect(smoothScrollBlock).toContain('return false') - expect(smoothScrollBlock).toContain('return true') - - const touchMoveBlock = sliceBetween( - "targetSurface.addEventListener(\n 'touchmove'", - '{ capture: true, passive: false }' - ) - expect(touchMoveBlock).toContain('if (enqueueNormalBufferScrollDelta(scope, deltaY))') - expect(touchMoveBlock).toContain('scope.touchGesture.velY = 0') - - const momentumBlock = sliceBetween( - 'function momentumStep(frameTime: number) {', - 'if (Math.abs(vel) > MIN_VEL)' - ) - expect(momentumBlock).toContain('if (!applyNormalBufferScrollDelta(scope, delta))') - expect(momentumBlock).toContain('scope.touchGesture.momentumId = null') - }) - - it('coalesces normal touch scroll row commits onto animation frames', () => { - const enqueueBlock = sliceBetween( - 'export function enqueueNormalBufferScrollDelta(', - 'export function resetSmoothScrollOffset(' - ) - expect(enqueueBlock).toContain('scope.pendingNormalScrollDeltaY += deltaY') - expect(enqueueBlock).toContain('if (scope.normalScrollFrameId !== null) {') - // Ruling 21: every document frame goes through the scope's registry so dispose can take it - // back; the id is still held here, which is what the reset below cancels. - expect(enqueueBlock).toContain( - 'scope.normalScrollFrameId = scheduleDocumentFrame(scope, function () {' - ) - expect(enqueueBlock).toContain('applyNormalBufferScrollDelta(scope, delta)') - - const resetBlock = sliceBetween( - 'export function resetSmoothScrollOffset(', - 'export function stopNormalBufferSmoothScroll(' - ) - expect(resetBlock).toContain('scope.pendingNormalScrollDeltaY = 0') - expect(resetBlock).toContain('cancelAnimationFrame(scope.normalScrollFrameId)') - }) - - it('bounds native-side pending WebView writes while preserving control messages', () => { - expect(source).toContain('const MAX_PENDING_WEB_WRITE_BYTES = 1_000_000') - expect(source).toContain('const MAX_PENDING_WEB_WRITE_MESSAGES = 4096') - expect(source).toContain('let pendingWriteBytes = 0') - expect(source).toContain('let pendingWriteCount = 0') - expect(source).toContain('const queue = (msg: TerminalWebViewCommand)') - expect(source).toContain('pendingWriteCount > MAX_PENDING_WEB_WRITE_MESSAGES') - expect(source).toContain("candidate.type === 'write'") - expect(source).toContain('pendingMessages.queue(msg)') - expect(source).toContain('pendingMessages.clear()') - }) - - it('clears the ready await timer when the real response wins', () => { - // C7.5 moved the promise into `terminal-webview-ready-promises.ts`, which both components - // reach through the controller. - const readyBlock = sliceBetween('async function awaitReady()', 'return { armReady') - expect(readyBlock).toContain('clearTimeout(timeout)') - expect(readyBlock).toContain('void pending.finally') - }) - - it('hides xterm scrollbars and drives the mobile scroll indicator from committed rows', () => { - expect(source).toContain('
') - expect(source).toContain('.xterm .xterm-viewport::-webkit-scrollbar') - expect(source).toContain('.xterm .xterm-scrollable-element > .xterm-scrollbar') - expect(source).toContain('overflow-y: hidden !important') - expect(source).toContain('display: none !important') - expect(source).toContain('export function updateScrollIndicator(') - expect(source).toContain('buffer.viewportY / maxViewportY') - expect(source).not.toContain('fractionalRows') - expect(source).toContain('scrollThumb.style.transform =') - expect(source).toContain('updateScrollIndicator(scope, true)') - }) - - it('does not apply fractional smooth scroll transforms to terminal content', () => { - const updateTransformBlock = sliceBetween( - 'export function updateTransform(', - 'export function updateScrollIndicator(' - ) - expect(updateTransformBlock).toContain( - "'translate(' + scope.panX + 'px,' + scope.panY + 'px) scale(' + getTotalScale(scope) + ')'" - ) - expect(source).not.toContain("querySelector('.xterm-screen')") - expect(source).not.toContain('updateTerminalScreenTransform') - expect(updateTransformBlock).not.toContain('getVisualPanY() + "px) scale("') - expect(updateTransformBlock).not.toContain('smoothScrollOffsetY') - }) - - it('smooths velocity samples and uses lower friction for mobile momentum', () => { - expect(source).toContain('export function updateTouchVelocity(') - expect(source).toContain('scope.touchGesture.velY * 0.55 + instantVelocity * 0.45') - expect(source).toContain('const FRICTION = 0.972') - expect(source).toContain('const MIN_VEL = 0.012') - // #21687: the decay is per elapsed millisecond, so a 120 Hz screen coasts the same distance. - expect(source).toContain('let lastMomentumTime = performance.now()') - expect(source).toContain( - 'const elapsed = Math.max(1, Math.min(50, frameTime - lastMomentumTime))' - ) - expect(source).toContain('vel *= FRICTION ** (elapsed / 16)') - expect(source).toContain('const delta = vel * elapsed') - }) - - it('keeps selection edge autoscroll active and extends the dragged endpoint', () => { - const startBlock = sliceBetween( - 'export function startEdgeScroll(', - 'export function stopEdgeScroll(' - ) - expect(startBlock.indexOf('stopEdgeScroll(scope)')).toBeLessThan( - startBlock.indexOf('scope.edgeScrollDir = dir') - ) - expect(startBlock.indexOf('scope.term.scrollLines(scope.edgeScrollDir)')).toBeLessThan( - startBlock.indexOf('syncEdgeScrollSelectionEndpoint(scope)') - ) - - const dragMoveBlock = sliceBetween( - 'export function handleDragMove(', - 'function attachSurfaceEventHandlers(' - ) - expect(dragMoveBlock).toContain('scope.edgeScrollClientX = clientX') - expect(dragMoveBlock).toContain('scope.edgeScrollClientY = clientY') - expect(dragMoveBlock).toContain( - 'syncSelectionHandleToViewportPoint(scope, handle, clientX, clientY)' - ) - }) - - it('allows x10 mouse gesture reports through the mobile session gate', () => { - expect(sessionHelperSource).toContain('function isGestureMouseTrackingMode') - expect(sessionHelperSource).toContain( - "return mode === 'x10' || mode === 'vt200' || mode === 'drag' || mode === 'any'" - ) - - const inputBlockStart = sessionSource.indexOf('const handleTerminalInput = useCallback') - expect(inputBlockStart).toBeGreaterThanOrEqual(0) - const inputBlockEnd = sessionSource.indexOf( - 'async function handleClearTerminal', - inputBlockStart - ) - expect(inputBlockEnd).toBeGreaterThan(inputBlockStart) - const inputBlock = sessionSource.slice(inputBlockStart, inputBlockEnd) - expect(inputBlock).toContain('!isGestureMouseTrackingMode(modes?.mouseTrackingMode)') - expect(inputBlock).toContain('const sequenceCount = countTerminalGestureInputSequences(bytes)') - expect(inputBlock.indexOf('countTerminalGestureInputSequences')).toBeLessThan( - inputBlock.indexOf('enqueueTerminalGestureInput') - ) - }) -}) - -function simulateNormalBufferPull({ - baseY, - viewportY, - startY, - endY, - cellHeight -}: { - baseY: number - viewportY: number - startY: number - endY: number - cellHeight: number -}): number { - const deltaY = startY - endY - if (deltaY > 0 ? viewportY >= baseY : viewportY <= 0) { - return viewportY - } - const smoothScrollOffsetY = -deltaY - const lines = Math.trunc(-smoothScrollOffsetY / cellHeight) - const applied = Math.max(lines, -viewportY) - return viewportY + applied -} diff --git a/mobile/src/terminal/terminal-webview-text-zoom.test.ts b/mobile/src/terminal/terminal-webview-text-zoom.test.ts index 20b2d2a0afd..29ba4bfcd13 100644 --- a/mobile/src/terminal/terminal-webview-text-zoom.test.ts +++ b/mobile/src/terminal/terminal-webview-text-zoom.test.ts @@ -1,19 +1,8 @@ // @vitest-environment happy-dom -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { createTerminalDocumentScope } from './document/document-scope' import { normalizeStatusDotPresentation } from './document/write-queue' import { startTextScaling } from './document/text-scaling' -import { webviewPageSource } from './document/document-module-source.test-support' - -const terminalWebViewSource = readFileSync(join(import.meta.dirname, 'TerminalWebView.tsx'), 'utf8') -const terminalHtmlDocumentShellSource = readFileSync( - join(import.meta.dirname, 'terminal-webview-html', 'document-shell.ts'), - 'utf8' -) -// The document's own source, which is what the WebView runs once bundled. -const terminalHtmlSource = webviewPageSource() function normalizeStatusDotChunks(chunks: string[]) { const scope = createTerminalDocumentScope() @@ -46,45 +35,6 @@ function resolveTerminalFontFamily(navigatorValue: { } describe('TerminalWebView text zoom', () => { - it('pins textZoom to 100 so Android system font scale cannot inflate glyphs past xterm cell metrics', () => { - const start = terminalWebViewSource.indexOf('', start) - expect(end).toBeGreaterThan(start) - const webViewProps = terminalWebViewSource.slice(start, end) - expect(webViewProps).toContain('textZoom={100}') - }) - - it('keeps the HTML source object stable so parent renders do not reload xterm', () => { - const start = terminalWebViewSource.indexOf('', start) - expect(end).toBeGreaterThan(start) - const webViewProps = terminalWebViewSource.slice(start, end) - // One source object per view, pinned at mount. - expect(terminalWebViewSource).toContain('const [source] = useState(() =>') - expect(webViewProps).toContain('source={source}') - }) - - it('forces the Claude status dot to text presentation before xterm writes', () => { - expect(terminalHtmlSource).toContain('font-variant-emoji: text') - // The dot and its two selectors are the write queue's own constants, and the pattern is a - // literal because a construction at a module's top level would be parse-time work (ruling 20). - expect(terminalHtmlSource).toContain("const CLAUDE_STATUS_DOT = '\\u23fa'") - expect(terminalHtmlSource).toContain("const TEXT_PRESENTATION_SELECTOR = '\\ufe0e'") - expect(terminalHtmlSource).toContain("const EMOJI_PRESENTATION_SELECTOR = '\\ufe0f'") - expect(terminalHtmlSource).toContain( - 'const CLAUDE_STATUS_DOT_PATTERN = /\\u23fa[\\ufe0e\\ufe0f]*/g' - ) - expect(terminalHtmlSource).toContain('export function normalizeStatusDotPresentation(') - expect(terminalHtmlSource).toContain( - 'CLAUDE_STATUS_DOT_PATTERN,\n CLAUDE_STATUS_DOT + TEXT_PRESENTATION_SELECTOR' - ) - expect(terminalHtmlSource).toContain( - 'scope.writeQueue.push(normalizeStatusDotPresentation(scope, data))' - ) - }) - it('normalizes Claude status dots idempotently across write chunks', () => { const dot = String.fromCharCode(0x23fa) const textSelector = String.fromCharCode(0xfe0e) @@ -111,36 +61,6 @@ describe('TerminalWebView text zoom', () => { ) }) - it('resets pending Claude status dot selector state when the terminal lifecycle resets', () => { - const initStart = terminalHtmlSource.indexOf('export function init(') - const initReplay = terminalHtmlSource.indexOf( - 'const replayData = normalizeInitialData(initialData)' - ) - const clearStart = terminalHtmlSource.indexOf("} else if (msg.type === 'clear') {") - const clearEnd = terminalHtmlSource.indexOf("} else if (msg.type === 'reset-zoom')", clearStart) - expect(initStart).toBeGreaterThanOrEqual(0) - expect(initReplay).toBeGreaterThan(initStart) - expect(clearStart).toBeGreaterThanOrEqual(0) - expect(clearEnd).toBeGreaterThan(clearStart) - expect(terminalHtmlSource.slice(initStart, initReplay)).toContain( - 'scope.statusDotPendingSelector = false' - ) - expect(terminalHtmlSource.slice(clearStart, clearEnd)).toContain( - 'scope.statusDotPendingSelector = false' - ) - }) - - it('loads Unicode 11 before replaying mobile terminal bytes', () => { - expect(terminalHtmlDocumentShellSource).toContain('XTERM_ENGINE_JS') - expect(terminalHtmlSource).toContain('window.Unicode11Addon.Unicode11Addon') - const open = terminalHtmlSource.indexOf('term.open(scope.surface!)') - const unicode = terminalHtmlSource.indexOf("term.unicode.activeVersion = '11'") - const replay = terminalHtmlSource.indexOf("enqueueWrite(scope, ESC + '[0m' + replayData)") - expect(open).toBeGreaterThanOrEqual(0) - expect(unicode).toBeGreaterThan(open) - expect(replay).toBeGreaterThan(unicode) - }) - const IOS_IPHONE_NAVIGATOR = { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 19_0 like Mac OS X) AppleWebKit/605.1.15', platform: 'iPhone', diff --git a/mobile/src/terminal/terminal-write-coalescer-boundaries.test.ts b/mobile/src/terminal/terminal-write-coalescer-boundaries.test.ts index 39615ef3692..3dd290fa1ff 100644 --- a/mobile/src/terminal/terminal-write-coalescer-boundaries.test.ts +++ b/mobile/src/terminal/terminal-write-coalescer-boundaries.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { afterEach, describe, expect, it, vi } from 'vitest' import type { TerminalWebViewCommand } from './terminal-webview-messages' import { createTerminalWebViewPendingMessages } from './terminal-webview-pending-messages' @@ -7,15 +6,6 @@ import { TERMINAL_WRITE_FLUSH_WINDOW_MS } from './terminal-write-coalescer' -const webViewSource = readFileSync(new URL('./TerminalWebView.tsx', import.meta.url), 'utf8') -// C7.5 moved everything that is not `react-native-webview` into the controller both components -// share, so the coalescer's boundaries are read there; the component is still read for the two -// WebView lifecycle events that reach it. -const controllerSource = readFileSync( - new URL('./use-terminal-webview-controller.ts', import.meta.url), - 'utf8' -) - // Simulates TerminalWebView's postMessage: ready → deliver, not ready → queue. // There is no React render harness in the node environment, so the boundary // invariants are gated here against the same pending-queue module the component uses. @@ -110,73 +100,4 @@ describe('terminal write coalescer boundaries', () => { { type: 'write', data: 'still-current-document' } ]) }) - - it('routes handle.write through the coalescer whose delivery posts the write command', () => { - expect(controllerSource).toContain( - "createTerminalWriteCoalescer((data) => postMessage({ type: 'write', data }))" - ) - const writeStart = controllerSource.indexOf('write(data: string) {') - expect(writeStart).toBeGreaterThanOrEqual(0) - const writeBody = controllerSource.slice(writeStart, writeStart + 120) - expect(writeBody).toContain('writeCoalescer.write(data)') - expect(writeBody).not.toContain('postMessage') - }) - - it('clears the coalescer before posting init and clear (snapshot supersession)', () => { - // Anchor on the init() signature (unique) — 'init(' alone also matches comments. - const initStart = controllerSource.indexOf( - 'init({ cols, rows, initialData, preserveScroll, oscLinks, frame }' - ) - const initClear = controllerSource.indexOf('writeCoalescer.clear()', initStart) - const initPost = controllerSource.indexOf("type: 'init'", initStart) - expect(initStart).toBeGreaterThanOrEqual(0) - expect(initClear).toBeGreaterThan(initStart) - expect(initClear).toBeLessThan(initPost) - - const clearStart = controllerSource.indexOf('clear() {', initPost) - const clearBody = controllerSource.slice(clearStart, clearStart + 160) - expect(clearStart).toBeGreaterThanOrEqual(0) - expect(clearBody.indexOf('writeCoalescer.clear()')).toBeGreaterThanOrEqual(0) - expect(clearBody.indexOf('writeCoalescer.clear()')).toBeLessThan( - clearBody.indexOf("postMessage({ type: 'clear' })") - ) - }) - - it('flushes pending writes before resize and reflow so boundaries observe prior bytes', () => { - for (const method of ['resize', 'reflow'] as const) { - const start = controllerSource.indexOf( - `${method}(cols: number, rows: number, frame: TerminalFrame | null) {` - ) - expect(start).toBeGreaterThanOrEqual(0) - const body = controllerSource.slice(start, start + 300) - const flushIndex = body.indexOf('writeCoalescer.flushNow()') - const postIndex = body.indexOf(`postMessage({ type: '${method}'`) - expect(flushIndex).toBeGreaterThanOrEqual(0) - expect(postIndex).toBeGreaterThan(flushIndex) - } - }) - - it('clears the coalescer in both document-lifecycle hooks alongside pendingMessages', () => { - // Both hooks now reach one function, so the clearing is asserted once where it lives and the - // two WebView events are asserted to be the callers. Reading only the component would pass on - // a `resetReadiness` that had quietly stopped clearing either one. - const start = controllerSource.indexOf('const resetReadiness = useCallback') - expect(start).toBeGreaterThanOrEqual(0) - const body = controllerSource.slice(start, controllerSource.indexOf('}, [', start)) - expect(body).toContain('pendingMessages.clear()') - expect(body).toContain('writeCoalescer.clear()') - expect(webViewSource).toContain('onLoadStart={resetReadiness}') - const terminated = webViewSource.indexOf('const handleContentProcessDidTerminate') - expect(terminated).toBeGreaterThanOrEqual(0) - expect(webViewSource.slice(terminated, webViewSource.indexOf('}, [', terminated))).toContain( - 'resetReadiness()' - ) - }) - - it('clears the coalescer on unmount so no timer leaks', () => { - const cleanupStart = controllerSource.indexOf('useEffect(() => {\n return () => {') - expect(cleanupStart).toBeGreaterThanOrEqual(0) - const cleanupBody = controllerSource.slice(cleanupStart, cleanupStart + 160) - expect(cleanupBody).toContain('writeCoalescer.clear()') - }) }) diff --git a/mobile/src/test-support/bridged-parity/c2-page-closure.test.ts b/mobile/src/test-support/bridged-parity/c2-page-closure.test.ts deleted file mode 100644 index ca797265cfe..00000000000 --- a/mobile/src/test-support/bridged-parity/c2-page-closure.test.ts +++ /dev/null @@ -1,235 +0,0 @@ -import { readdirSync } from 'node:fs' -import { resolve } from 'node:path' -import { describe, expect, it } from 'vitest' -import { C1_PAGE_CLOSURE } from './c1-page-closure' -import { C2_PAGE_CLOSURE } from './c2-page-closure' -import { C2_TASK_SOURCE_CLOSURE_FAMILIES } from './c2-task-source-closure-families' -import { C2_WORK_ITEM_CLOSURE_FAMILIES } from './c2-work-item-closure-families' -import { C5_PAGE_CLOSURE } from './c5-page-closure' -import { pinsFromSource } from './page-closure-pin-source' -import { BRIDGED_PARITY_EXCLUSIONS } from './divergence-classes' -import { - pageClosureDrift, - pageClosureExclusions, - pageClosureRunTotals, - pageClosureTotals, - type PageClosureObservation -} from './page-closure' -import { readGolden } from '../rpc-recording/golden-recording' - -const GOLDENS = resolve(import.meta.dirname, '../../../rpc-foundation/goldens') -const C1_SOURCE = resolve(import.meta.dirname, 'c1-page-closure.ts') - -/** The run a corpus that diverged exactly as the pin says would hand the rule. */ -function asPinned(): Map { - const run = new Map() - for (const [family, goldens] of Object.entries(C2_PAGE_CLOSURE)) { - for (const [id, verdict] of Object.entries(goldens)) { - run.set(id, { family, verdict }) - } - } - return run -} - -describe('the C2 page closure', () => { - /** - * The census reads the committed table, and does not re-derive the closure. - * - * Nothing here or in the gate runs esbuild or maps a scenario's `sites` back to the module graph, - * so this fixes how many families the table may hold, not which families belong in it. A golden - * arriving in a family already pinned is caught, by `pageClosureDrift` and by this count. A new - * *family* entering the closure — a scenario recorded at a site the route newly imports — is - * invisible until someone re-derives the closure by hand, as C1's and C5's pins are too. - */ - it('is the census the design named: 68 families, 257 goldens', () => { - const goldens = Object.values(C2_PAGE_CLOSURE).flatMap((family) => Object.keys(family)) - expect({ families: Object.keys(C2_PAGE_CLOSURE).length, goldens: goldens.length }).toEqual({ - families: 68, - goldens: 257 - }) - expect(new Set(goldens).size).toBe(goldens.length) - }) - - /** - * The totals, asserted beside the per-id pins rather than instead of them. - * - * A walk that compares each id to its own verdict cannot see a table built wrong in a way that is - * self-consistent — C5 derived exactly that file once, with an empty mismatch list and three - * goldens in the wrong class. These counts are what showed it, and the gate re-asserts them - * against the run rather than against the table. - */ - it('pins how many goldens land in each class, which a per-id walk cannot see move', () => { - expect(pageClosureTotals(C2_PAGE_CLOSURE)).toEqual({ - identical: 108, - 'result-absent-settlement': 115, - 'params-undefined': 29, - 'result-absent-stream-release': 3, - 'write-ordinal': 2 - }) - }) - - it("inherits C1's families whole, with the verdicts C1's file commits", () => { - // Against the file's text rather than the imported object, because today the composition - // spreads that object and a comparison to it agrees with itself. This holds the shape of the - // inheritance: that C2's table carries C1's families at C1's verdicts and overrides none of - // them, and it keeps holding if the spread is ever replaced by inlined entries. - // - // What it cannot hold: a verdict changed inside `c1-page-closure.ts`. C2 inherits whatever C1 - // commits, so both sides of this comparison move together. Measured, that edit is red in the - // bridged-parity gate, which compares the pin to a run rather than to a file, and here in the - // class totals and the exclusion count, which pin absolute numbers. It is green in - // `c1-page-closure.test.ts`, whose exclusion check is `toBeGreaterThan(0)` and which pins no - // class totals at all. - // - // C2's own rule does not reproduce these pins — measured, it disagrees on 13 of the 103, being - // `tasks.smart-source-search` 7, `host-worktree-refresh` 5 and `worktree-catalog-snapshot` 1 — - // so inheritance is the derivation rather than a re-derivation that looked close. - const committed = pinsFromSource(C1_SOURCE) - // The reader found a table rather than nothing, which every assertion below depends on. - expect({ - families: Object.keys(committed).length, - pins: Object.values(committed).flatMap(Object.keys).length - }).toEqual({ families: 20, pins: 94 }) - for (const [family, pinned] of Object.entries(committed)) { - expect(C2_PAGE_CLOSURE[family], family).toEqual(pinned) - } - expect(Object.keys(C1_PAGE_CLOSURE)).toEqual(Object.keys(committed)) - }) - - it('agrees with C5 object for object on every family both domains pin', () => { - // Two page closures that share a family share the goldens in it. Were one to be re-derived and - // the other inherited, this is the assertion that would not hold. - const shared = Object.keys(C5_PAGE_CLOSURE).filter((family) => family in C2_PAGE_CLOSURE) - expect(shared.length).toBe(20) - for (const family of shared) { - expect(C2_PAGE_CLOSURE[family], family).toEqual(C5_PAGE_CLOSURE[family]) - } - }) - - it('adds 48 families, split across the two halves without overlap', () => { - // The composed table is a spread, so a family named in both halves would be taken from the last - // one silently. Disjointness is what makes the two files data rather than a precedence rule. - const work = Object.keys(C2_WORK_ITEM_CLOSURE_FAMILIES) - const source = Object.keys(C2_TASK_SOURCE_CLOSURE_FAMILIES) - expect(work.filter((family) => source.includes(family))).toEqual([]) - expect(work.filter((family) => family in C1_PAGE_CLOSURE)).toEqual([]) - expect(source.filter((family) => family in C1_PAGE_CLOSURE)).toEqual([]) - expect({ work: work.length, source: source.length }).toEqual({ work: 26, source: 22 }) - const added = Object.keys(C2_PAGE_CLOSURE).filter((family) => !(family in C1_PAGE_CLOSURE)) - expect(added.sort()).toEqual([...work, ...source].sort()) - }) - - it('names the families where a pin proves only that the divergence kept its name', () => { - // "266 certified" would read as 266 proofs of byte-identity. Six families have no byte-identical - // golden at all, so their 27 say only that the class did not change, and the PR body says so. - const wholly = Object.entries(C2_PAGE_CLOSURE) - .filter(([, pins]) => !Object.values(pins).includes('identical')) - .map(([family, pins]) => [family, Object.keys(pins).length] as const) - expect(wholly).toEqual([ - ['host-worktree-refresh', 5], - ['tasks.item-checks-files', 6], - ['tasks.item-metadata-gitlab-mr', 2], - ['tasks.project-row-files-merge', 6], - ['tasks.provider-load', 6], - ['tasks.task-list-gitlab-items', 2] - ]) - }) - - it('pins goldens that exist, in the family the corpus records them under', () => { - for (const [family, goldens] of Object.entries(C2_PAGE_CLOSURE)) { - for (const id of Object.keys(goldens)) { - // Through the corpus's own reader, which checks the format version and the value pool and - // throws a named diagnostic otherwise. - const recorded = readGolden(GOLDENS, id) - expect({ id, family: recorded.family }).toEqual({ id, family }) - } - } - }) - - it('claims no golden the corpus does not have', () => { - const corpus = new Set( - readdirSync(GOLDENS) - .filter((name) => name.endsWith('.json')) - .map((name) => name.replace(/\.json$/, '')) - ) - const missing = Object.values(C2_PAGE_CLOSURE) - .flatMap((family) => Object.keys(family)) - .filter((id) => !corpus.has(id)) - expect(missing).toEqual([]) - }) - - it('excludes a closure golden only into a class that has a reason', () => { - const exclusions = pageClosureExclusions(C2_PAGE_CLOSURE) - expect(exclusions.length).toBe(149) - expect(exclusions.filter(([, name]) => BRIDGED_PARITY_EXCLUSIONS[name] === undefined)).toEqual( - [] - ) - }) -}) - -describe('reading a run against the C2 pin', () => { - it('says nothing when the run is the pin', () => { - expect(pageClosureDrift(C2_PAGE_CLOSURE, asPinned())).toEqual([]) - expect(pageClosureRunTotals(C2_PAGE_CLOSURE, asPinned())).toEqual( - pageClosureTotals(C2_PAGE_CLOSURE) - ) - }) - - it('names a closure golden that changed verdict', () => { - const run = asPinned() - const found = [...run].find(([, seen]) => seen.verdict !== 'params-undefined') - if (found === undefined) { - throw new Error('the pin is empty') - } - const [id, observation] = found - run.set(id, { ...observation, verdict: 'params-undefined' }) - const drift = pageClosureDrift(C2_PAGE_CLOSURE, run) - expect(drift.length).toBe(1) - expect(drift[0]).toContain(id) - expect(drift[0]).toContain(`pinned ${observation.verdict}, ran params-undefined`) - // And in the counts, which is the check that holds when a second golden moves the other way. - expect(pageClosureRunTotals(C2_PAGE_CLOSURE, run)).not.toEqual( - pageClosureTotals(C2_PAGE_CLOSURE) - ) - }) - - it('names a golden newly derived into a closure family, which no id list would', () => { - const run = asPinned() - const [family] = Object.keys(C2_PAGE_CLOSURE) - if (family === undefined) { - throw new Error('the pin is empty') - } - run.set('matrix-arrived-1', { family, verdict: 'identical' }) - expect(pageClosureDrift(C2_PAGE_CLOSURE, run)).toEqual([ - `${family}: arrived matrix-arrived-1; left (none)` - ]) - }) - - it('names a closure golden the run stopped producing, three ways', () => { - const run = asPinned() - const [family, goldens] = Object.entries(C2_PAGE_CLOSURE)[0] ?? [] - const [id] = Object.keys(goldens ?? {}) - if (family === undefined || id === undefined) { - throw new Error('the pin is empty') - } - run.delete(id) - expect(pageClosureDrift(C2_PAGE_CLOSURE, run)).toEqual([ - `${family}: arrived (none); left ${id}` - ]) - // Drift is one of three. The run's totals fall short of the pin's, and the census above fixes - // the number of goldens the table may hold, so a drop cannot be absorbed by deleting the pin. - expect(pageClosureRunTotals(C2_PAGE_CLOSURE, run)).not.toEqual( - pageClosureTotals(C2_PAGE_CLOSURE) - ) - expect([...run].filter(([, seen]) => seen.family in C2_PAGE_CLOSURE).length).toBe(256) - }) - - it('ignores every golden outside the closure, which is most of the corpus', () => { - const run = asPinned() - run.set('session-diff-review-elsewhere', { - family: 'session.diff-review', - verdict: 'result-absent-settlement' - }) - expect(pageClosureDrift(C2_PAGE_CLOSURE, run)).toEqual([]) - }) -}) diff --git a/mobile/src/test-support/bridged-parity/c3-page-closure.test.ts b/mobile/src/test-support/bridged-parity/c3-page-closure.test.ts deleted file mode 100644 index afc1c897564..00000000000 --- a/mobile/src/test-support/bridged-parity/c3-page-closure.test.ts +++ /dev/null @@ -1,222 +0,0 @@ -import { readdirSync } from 'node:fs' -import { resolve } from 'node:path' -import { describe, expect, it } from 'vitest' -import { C1_PAGE_CLOSURE } from './c1-page-closure' -import { C2_PAGE_CLOSURE } from './c2-page-closure' -import { C3_PAGE_CLOSURE } from './c3-page-closure' -import { C3_EXPLORER_CLOSURE_FAMILIES } from './c3-explorer-closure-families' -import { C3_PREVIEW_CLOSURE_FAMILIES } from './c3-preview-closure-families' -import { C5_PAGE_CLOSURE } from './c5-page-closure' -import { pinsFromSource } from './page-closure-pin-source' -import { BRIDGED_PARITY_EXCLUSIONS } from './divergence-classes' -import { - pageClosureDrift, - pageClosureExclusions, - pageClosureRunTotals, - pageClosureTotals, - type PageClosureObservation -} from './page-closure' -import { readGolden } from '../rpc-recording/golden-recording' - -const GOLDENS = resolve(import.meta.dirname, '../../../rpc-foundation/goldens') -const C1_SOURCE = resolve(import.meta.dirname, 'c1-page-closure.ts') - -/** The run a corpus that diverged exactly as the pin says would hand the rule. */ -function asPinned(): Map { - const run = new Map() - for (const [family, goldens] of Object.entries(C3_PAGE_CLOSURE)) { - for (const [id, verdict] of Object.entries(goldens)) { - run.set(id, { family, verdict }) - } - } - return run -} - -describe('the C3 page closure', () => { - /** - * The census reads the committed table, and does not re-derive the closure. - * - * Nothing here or in the gate runs esbuild or maps a scenario's `sites` back to the module graph, - * so this fixes how many families the table may hold, not which families belong in it. A golden - * arriving in a family already pinned is caught, by `pageClosureDrift` and by this count. A new - * *family* entering the closure is invisible until someone re-derives it by hand — which - * `config/scripts/mobile-web-app-page-closure-families.test.mjs` now does for both files routes. - */ - it('is the census the design named: 26 families, 116 goldens', () => { - const goldens = Object.values(C3_PAGE_CLOSURE).flatMap((family) => Object.keys(family)) - expect({ families: Object.keys(C3_PAGE_CLOSURE).length, goldens: goldens.length }).toEqual({ - families: 26, - goldens: 116 - }) - expect(new Set(goldens).size).toBe(goldens.length) - }) - - /** - * The totals, asserted beside the per-id pins rather than instead of them. - * - * A walk that compares each id to its own verdict cannot see a table built wrong in a way that is - * self-consistent — C5 derived exactly that file once, with an empty mismatch list and three - * goldens in the wrong class. These counts are what showed it, and the gate re-asserts them - * against the run rather than against the table. - */ - it('pins how many goldens land in each class, which a per-id walk cannot see move', () => { - expect(pageClosureTotals(C3_PAGE_CLOSURE)).toEqual({ - identical: 60, - 'result-absent-settlement': 44, - 'params-undefined': 7, - 'result-absent-stream-release': 3, - 'write-ordinal': 2 - }) - }) - - it("inherits C1's families whole, with the verdicts C1's file commits", () => { - // Against the file's text rather than the imported object: the composition spreads that object, - // so a hand-edited inherited entry would be read back as C1's and agree with itself. - // - // What this cannot see is an edit to `c1-page-closure.ts` itself, because both sides of the - // comparison then move together. What it does see is a C3 half redeclaring an inherited family, - // which the spread would otherwise take silently from the last table. Both measured: flipping - // `settings-repo-metadata-icons` in C1's file leaves this case green and reds seven others — - // the class totals and the exclusion counts in C2's suite and this one, both cross-series - // agreements, and C5's own inheritance case, which compares against an independent literal - // rather than a spread. - // - // Redeclaring `settings.repo-metadata` in the preview half always reds this case; how many - // others go with it depends on the shape of the redeclaration, so the number is not the claim. - // Measured: one golden under the family's name reds seven, because it also shrinks the census - // and leaves that family with no byte-identical golden. The family copied verbatim with a - // single verdict flipped reds five, the census unmoved. Both keep the load-bearing half — the - // spread takes the last table's entry, and this case is what sees it. - // - // C2's rule does not reproduce these pins — measured here, it disagrees on 13 of the 94, - // being `tasks.smart-source-search` 7, `host-worktree-refresh` 5 and - // `worktree-catalog-snapshot` 1 — so inheritance is the derivation rather than a - // re-derivation that looked close. - const committed = pinsFromSource(C1_SOURCE) - expect({ - families: Object.keys(committed).length, - pins: Object.values(committed).flatMap(Object.keys).length - }).toEqual({ families: 20, pins: 94 }) - for (const [family, pinned] of Object.entries(committed)) { - expect(C3_PAGE_CLOSURE[family], family).toEqual(pinned) - } - }) - - it('agrees with C2 and C5 object for object on every family they share', () => { - // Three page closures that share a family share the goldens in it. Were one re-derived and the - // others inherited, this is the assertion that would not hold. - for (const [name, other] of [ - ['C2', C2_PAGE_CLOSURE], - ['C5', C5_PAGE_CLOSURE] - ] as const) { - const shared = Object.keys(other).filter((family) => family in C3_PAGE_CLOSURE) - expect(shared.length, name).toBe(20) - for (const family of shared) { - expect(C3_PAGE_CLOSURE[family], `${name}/${family}`).toEqual(other[family]) - } - } - }) - - it('adds 6 families, split across the two routes without overlap', () => { - // The composed table is a spread, so a family named in both halves would be taken from the last - // one silently. Disjointness is what makes the two files data rather than a precedence rule. - const explorer = Object.keys(C3_EXPLORER_CLOSURE_FAMILIES) - const preview = Object.keys(C3_PREVIEW_CLOSURE_FAMILIES) - expect(explorer.filter((family) => preview.includes(family))).toEqual([]) - expect(explorer.filter((family) => family in C1_PAGE_CLOSURE)).toEqual([]) - expect(preview.filter((family) => family in C1_PAGE_CLOSURE)).toEqual([]) - expect({ explorer: explorer.length, preview: preview.length }).toEqual({ - explorer: 1, - preview: 5 - }) - const added = Object.keys(C3_PAGE_CLOSURE).filter((family) => !(family in C1_PAGE_CLOSURE)) - expect(added.sort()).toEqual([...explorer, ...preview].sort()) - }) - - it('names the families where a pin proves only that the divergence kept its name', () => { - // "125 certified" would read as 125 proofs of byte-identity. One family has no byte-identical - // golden at all, so its 5 say only that the class did not change, and the PR body says so. - const wholly = Object.entries(C3_PAGE_CLOSURE) - .filter(([, pins]) => !Object.values(pins).includes('identical')) - .map(([family, pins]) => [family, Object.keys(pins).length] as const) - expect(wholly).toEqual([['host-worktree-refresh', 5]]) - }) - - it('pins goldens that exist, in the family the corpus records them under', () => { - for (const [family, goldens] of Object.entries(C3_PAGE_CLOSURE)) { - for (const id of Object.keys(goldens)) { - const recorded = readGolden(GOLDENS, id) - expect({ id, family: recorded.family }).toEqual({ id, family }) - } - } - }) - - it('claims no golden the corpus does not have', () => { - const corpus = new Set( - readdirSync(GOLDENS) - .filter((name) => name.endsWith('.json')) - .map((name) => name.replace(/\.json$/, '')) - ) - const missing = Object.values(C3_PAGE_CLOSURE) - .flatMap((family) => Object.keys(family)) - .filter((id) => !corpus.has(id)) - expect(missing).toEqual([]) - }) - - it('excludes a closure golden only into a class that has a reason', () => { - const exclusions = pageClosureExclusions(C3_PAGE_CLOSURE) - expect(exclusions.length).toBe(56) - expect(exclusions.filter(([, name]) => BRIDGED_PARITY_EXCLUSIONS[name] === undefined)).toEqual( - [] - ) - }) -}) - -describe('reading a run against the C3 pin', () => { - it('says nothing when the run is the pin', () => { - expect(pageClosureDrift(C3_PAGE_CLOSURE, asPinned())).toEqual([]) - expect(pageClosureRunTotals(C3_PAGE_CLOSURE, asPinned())).toEqual( - pageClosureTotals(C3_PAGE_CLOSURE) - ) - }) - - it('names a closure golden that changed verdict', () => { - const run = asPinned() - const found = [...run].find(([, seen]) => seen.verdict !== 'params-undefined') - if (found === undefined) { - throw new Error('the pin is empty') - } - const [id, observation] = found - run.set(id, { ...observation, verdict: 'params-undefined' }) - const drift = pageClosureDrift(C3_PAGE_CLOSURE, run) - expect(drift.length).toBe(1) - expect(drift[0]).toContain(id) - expect(drift[0]).toContain(`pinned ${observation.verdict}, ran params-undefined`) - }) - - it('names a golden the run stopped producing, and moves the totals with it', () => { - const run = asPinned() - const [family, goldens] = Object.entries(C3_PAGE_CLOSURE)[0] ?? [] - const [id] = Object.keys(goldens ?? {}) - if (family === undefined || id === undefined) { - throw new Error('the pin is empty') - } - run.delete(id) - expect(pageClosureDrift(C3_PAGE_CLOSURE, run)).toEqual([ - `${family}: arrived (none); left ${id}` - ]) - // The totals move too, which is the half a per-id walk over what remains cannot see. - expect(pageClosureRunTotals(C3_PAGE_CLOSURE, run)).not.toEqual( - pageClosureTotals(C3_PAGE_CLOSURE) - ) - }) - - it('ignores every golden outside the closure, which is most of the corpus', () => { - const run = asPinned() - run.set('a-golden-from-another-domain', { - family: 'session.diff-review', - verdict: 'result-absent-settlement' - }) - expect(pageClosureDrift(C3_PAGE_CLOSURE, run)).toEqual([]) - }) -}) diff --git a/mobile/src/test-support/census-source-files.test.ts b/mobile/src/test-support/census-source-files.test.ts index 446a4097f66..c5639bfdf1c 100644 --- a/mobile/src/test-support/census-source-files.test.ts +++ b/mobile/src/test-support/census-source-files.test.ts @@ -1,4 +1,4 @@ -import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, relative } from 'node:path' import { fileURLToPath } from 'node:url' @@ -74,36 +74,4 @@ describe('the source files a census reads', () => { expect(isGeneratedSource(entry), entry).toBe(true) } }) - - it('is the only walk of its kind left in the tree', () => { - // The line every census used to hold a copy of. One spelling, so a tenth census cannot quietly - // reintroduce the cost by pasting the walk rather than importing it. - const copies: string[] = [] - const walk = (directory: string): void => { - for (const entry of readdirSync(directory, { withFileTypes: true })) { - const path = join(directory, entry.name) - if (entry.isDirectory()) { - if (entry.name !== 'node_modules') { - walk(path) - } - continue - } - if (!/\.tsx?$/.test(entry.name) || isGeneratedSource(entry.name)) { - continue - } - if (readFileSync(path, 'utf8').includes("entry.name === 'node_modules' ? []")) { - copies.push(relative(mobileRoot, path)) - } - } - } - walk(join(mobileRoot, 'src')) - walk(join(mobileRoot, 'app')) - // This file is in the list because it carries the line as the text it greps for; the module - // beside it is the walk itself. Named rather than filtered out, so a third entry is a failure - // that reads as one. - expect(copies.sort()).toEqual([ - 'src/test-support/census-source-files.test.ts', - 'src/test-support/census-source-files.ts' - ]) - }) }) diff --git a/mobile/src/test-support/rpc-recording/README.md b/mobile/src/test-support/rpc-recording/README.md index afe33f98bda..cabe1cbe373 100644 --- a/mobile/src/test-support/rpc-recording/README.md +++ b/mobile/src/test-support/rpc-recording/README.md @@ -185,15 +185,13 @@ five spellings were five independent ways to reach a `ReferenceError` seconds in `hostClientContextExposure` is the one copy; the trade is that it sits inside `recorderSha256`, so editing it re-records all 787 goldens rather than the five families. A rename of the local is still invisible to `tsc` — nothing short of editing the product module makes a private local checkable — -so `adapter-seam.test.ts` asserts the declaration it names exists exactly once, and refuses a sixth -inline copy. +so a rename lands as a `ReferenceError` in every recording that mounts through it. -The adapter seam is the directory, not a filename convention, because a convention is a rule nobody -enforces. `adapter-seam.test.ts` enforces this one: every file under `adapters/` is a registered -module, every registered module is declared in the file it is registered under, no adapter module -imports a sibling (which would leave a golden pinned to one module and driven by two), and -`pilotMountAdapters` mounts nothing of its own — an adapter defined in an engine file would be -pinned by `recorderSha256` on all 153 goldens instead of by `adapterSha256` on its own. +The adapter seam is the directory, not a filename convention: every file under `adapters/` is a +registered module, every registered module is declared in the file it is registered under, no +adapter module imports a sibling (which would leave a golden pinned to one module and driven by +two), and `pilotMountAdapters` mounts nothing of its own — an adapter defined in an engine file +would be pinned by `recorderSha256` on all 153 goldens instead of by `adapterSha256` on its own. `scenarioSha256` covers the scenario input _that golden_ was recorded from — one manifest scenario for a pilot golden, the generated variants and any hoisted prelude for a matrix or schedule golden, diff --git a/mobile/src/test-support/rpc-recording/native-mounting-substitutes.test.ts b/mobile/src/test-support/rpc-recording/native-mounting-substitutes.test.ts index 01422c4dda4..4cc4afbb468 100644 --- a/mobile/src/test-support/rpc-recording/native-mounting-substitutes.test.ts +++ b/mobile/src/test-support/rpc-recording/native-mounting-substitutes.test.ts @@ -21,7 +21,6 @@ describe('nativeMountingSubstitutes', () => { const store = importDefault(substitute('@react-native-async-storage/async-storage')).default // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the member is a function by construction; the test asserts what calling it throws. const getItem = (store as { getItem: () => unknown }).getItem - expect(typeof getItem).toBe('function') expect(() => getItem()).toThrow( 'Native store reached during recording: @react-native-async-storage/async-storage.getItem' ) diff --git a/mobile/src/test-support/rpc-recording/operation-module-loader.test.ts b/mobile/src/test-support/rpc-recording/operation-module-loader.test.ts index cd97f5ce529..d4aea1cf8bd 100644 --- a/mobile/src/test-support/rpc-recording/operation-module-loader.test.ts +++ b/mobile/src/test-support/rpc-recording/operation-module-loader.test.ts @@ -129,7 +129,6 @@ describe('the mounted module loader', () => { ` }) const { read } = modules.load<{ read: () => unknown }>('mobile/src/uses-default.ts') - expect(typeof read).toBe('function') expect(() => read()).toThrow( 'Unspecified native mounting dependency: react-native-not-substituted.default' ) @@ -160,7 +159,6 @@ describe('the mounted module loader', () => { ` }) const { read } = modules.load<{ read: () => unknown }>('mobile/src/uses-namespace.ts') - expect(typeof read).toBe('function') expect(() => read()).toThrow( 'Unspecified native mounting dependency: expo-not-substituted.selectionAsync' ) diff --git a/mobile/src/test-support/webview-document-census.ts b/mobile/src/test-support/webview-document-census.ts index eb050fce3e1..73b9ff71e89 100644 --- a/mobile/src/test-support/webview-document-census.ts +++ b/mobile/src/test-support/webview-document-census.ts @@ -17,7 +17,7 @@ import { parseSync } from 'oxc-parser' */ /** Statement kinds that only declare. Anything else at a module's top level is work. */ -export const DECLARATION_KINDS = new Set([ +const DECLARATION_KINDS = new Set([ 'ImportDeclaration', 'ExportNamedDeclaration', 'ExportDefaultDeclaration', @@ -83,7 +83,7 @@ function initialiserRuns(node: unknown): boolean { } /** Whether anything at a module's top level reaches an element, at any depth. */ -export function readsTheDocument(node: unknown): boolean { +function readsTheDocument(node: unknown): boolean { if (Array.isArray(node)) { return node.some(readsTheDocument) } @@ -93,7 +93,7 @@ export function readsTheDocument(node: unknown): boolean { return fieldsOf(node).some(([key, value]) => key !== 'type' && readsTheDocument(value)) } -export function parseModule(name: string, source: string) { +function parseModule(name: string, source: string) { const { program, errors } = parseSync(`${name}.ts`, source, { lang: 'ts' }) if (errors.length > 0) { throw new Error(`[webview-document-census] ${name}.ts did not parse: ${errors[0]?.message}`) diff --git a/mobile/src/transport/paired-host-writer-census.test.ts b/mobile/src/transport/paired-host-writer-census.test.ts deleted file mode 100644 index aa7ac0c4f56..00000000000 --- a/mobile/src/transport/paired-host-writer-census.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Who may write a whole host profile: pairing, which creates or re-pairs it. - * - * A relay learner (supervisor, credential rotation, direct upgrade) holds a snapshot taken when its - * connection opened, so a full-profile save from it reverts any Edit Host made since. Those write - * through `setRelayRouting`, which takes no profile. - */ -import { readFileSync } from 'node:fs' -import { join, relative } from 'node:path' -import { fileURLToPath } from 'node:url' -import { describe, expect, it } from 'vitest' -import { censusSourceFiles } from '../test-support/census-source-files' - -const MOBILE_DIR = fileURLToPath(new URL('../../', import.meta.url)) - -const PAIRING_WRITERS = [ - 'src/transport/mobile-relay-pairing-recovery.ts', - 'src/transport/pre-profile-pairing-coordinator.ts' -] - -// A value import of `savePairedHost` from the host store, at any relative depth. -const IMPORTS_PAIRED_HOST_WRITER = - /import\s*\{[^}]*\bsavePairedHost\b[^}]*\}\s*from\s*['"](?:\.{1,2}\/)+(?:[\w-]+\/)*host-store['"]/ - -function importingFiles(): string[] { - return ['src', 'app'] - .flatMap((directory) => censusSourceFiles(join(MOBILE_DIR, directory))) - .filter((file) => /\.tsx?$/.test(file) && !/\.test\.tsx?$/.test(file)) - .filter((file) => IMPORTS_PAIRED_HOST_WRITER.test(readFileSync(file, 'utf8'))) - .map((file) => relative(MOBILE_DIR, file)) - .sort() -} - -describe('full host profile writes', () => { - it('are reachable only from pairing', () => { - // Also the presence precondition: both creators must match, or the matcher is broken. - expect(importingFiles()).toEqual(PAIRING_WRITERS) - }) -}) diff --git a/mobile/src/transport/timer-receiver-census.test.ts b/mobile/src/transport/timer-receiver-census.test.ts deleted file mode 100644 index d6cc23bee2f..00000000000 --- a/mobile/src/transport/timer-receiver-census.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { readFileSync } from 'node:fs' -import { relative } from 'node:path' -import { fileURLToPath } from 'node:url' -import ts from 'typescript-api' -import { describe, expect, it } from 'vitest' -import { censusSourceFiles } from '../test-support/census-source-files' - -const SOURCE_ROOT = fileURLToPath(new URL('..', import.meta.url)) -const TIMER_GLOBALS = new Set(['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval']) -const GLOBAL_RECEIVERS = new Set(['global', 'globalThis', 'window']) -const SHARED_DEFAULTS = new Set(['defaultScheduleTimer', 'defaultCancelTimer']) - -// Sites that take their default from timer-scheduler; the census is meaningless if it -// cannot see them, so an empty or misdirected walk fails instead of passing vacuously. -const SHARED_DEFAULT_SITES = [ - 'files/mobile-file-preview-navigation.ts', - 'transport/host-open-retry-scheduler.ts', - 'transport/mobile-endpoint-lifecycle.ts', - 'transport/mobile-endpoint-supervisor-test-fakes.ts', - 'transport/rpc-session-liveness-watchdog.ts' -] - -const PARKING_OPERATORS = new Set([ - ts.SyntaxKind.QuestionQuestionToken, - ts.SyntaxKind.QuestionQuestionEqualsToken, - ts.SyntaxKind.BarBarToken, - ts.SyntaxKind.BarBarEqualsToken -]) - -type Census = { parked: string[]; shared: string[] } - -function productFiles(): string[] { - return censusSourceFiles(SOURCE_ROOT) - .map((path) => relative(SOURCE_ROOT, path).replaceAll('\\', '/')) - .filter((entry) => /\.tsx?$/.test(entry) && !/\.test\.tsx?$/.test(entry)) -} - -function timerName(node: ts.Node): string | null { - if (ts.isIdentifier(node) && TIMER_GLOBALS.has(node.text)) { - return node.text - } - if ( - ts.isPropertyAccessExpression(node) && - TIMER_GLOBALS.has(node.name.text) && - ts.isIdentifier(node.expression) && - GLOBAL_RECEIVERS.has(node.expression.text) - ) { - return node.name.text - } - return null -} - -// The receiver is only lost once the function is parked somewhere a later call reaches -// through: a nullish/logical default, an object literal member, or an assignment onto a -// property. A plain local capture stays legal: calling it bare leaves the receiver undefined. -function parkedTimer(node: ts.Node): ts.Node | null { - if (ts.isBinaryExpression(node)) { - const operator = node.operatorToken.kind - const parks = - PARKING_OPERATORS.has(operator) || - (operator === ts.SyntaxKind.EqualsToken && ts.isPropertyAccessExpression(node.left)) - return parks ? node.right : null - } - if (ts.isPropertyAssignment(node)) { - return node.initializer - } - if (ts.isShorthandPropertyAssignment(node)) { - return node.name - } - return null -} - -function scanSource(relativePath: string, text: string, census: Census): void { - const sourceFile = ts.createSourceFile(relativePath, text, ts.ScriptTarget.Latest, true) - const visit = (node: ts.Node): void => { - const candidate = parkedTimer(node) - const name = candidate === null ? null : timerName(candidate) - if (candidate !== null && name !== null) { - const line = sourceFile.getLineAndCharacterOfPosition(candidate.getStart(sourceFile)).line + 1 - census.parked.push(`${relativePath}:${line} ${name}`) - } - if (ts.isIdentifier(node) && SHARED_DEFAULTS.has(node.text)) { - census.shared.push(relativePath) - } - ts.forEachChild(node, visit) - } - visit(sourceFile) -} - -function parkedIn(source: string): string[] { - const census: Census = { parked: [], shared: [] } - scanSource('fixture.ts', source, census) - return census.parked -} - -describe('global timer receiver census', () => { - const census: Census = { parked: [], shared: [] } - for (const relativePath of productFiles()) { - scanSource(relativePath, readFileSync(`${SOURCE_ROOT}${relativePath}`, 'utf8'), census) - } - - it('sees the shared receiver-free defaults, so an empty or misdirected walk cannot pass', () => { - expect(census.shared).toEqual(expect.arrayContaining(SHARED_DEFAULT_SITES)) - }) - - it('parks no bare global timer where a later call would supply a non-global receiver', () => { - expect(census.parked).toEqual([]) - }) - - it.each([ - ['a nullish default', 'const schedule = injected ?? setTimeout'], - ['a logical default', 'const schedule = injected || setTimeout'], - ['a nullish assignment default', 'schedule ??= setTimeout'], - ['a logical assignment default', 'schedule ||= setTimeout'], - ['an object literal member', 'const deps = { setTimer: setTimeout }'], - ['a shorthand object member', 'const deps = { setTimeout }'], - ['an assignment onto a property', 'this.setTimer = setTimeout'], - ['a qualified global read', 'const deps = { setTimer: globalThis.setTimeout }'] - ])('flags a global timer parked by %s', (_form, source) => { - expect(parkedIn(source)).toEqual(['fixture.ts:1 setTimeout']) - }) - - it('leaves a plain local capture alone, which a bare call invokes receiver-free', () => { - expect(parkedIn('const schedule = globalThis.setTimeout')).toEqual([]) - }) -}) diff --git a/mobile/src/transport/unchecked-rpc-reader-boundary.test.ts b/mobile/src/transport/unchecked-rpc-reader-boundary.test.ts index f452a7bd564..463ba943cb5 100644 --- a/mobile/src/transport/unchecked-rpc-reader-boundary.test.ts +++ b/mobile/src/transport/unchecked-rpc-reader-boundary.test.ts @@ -128,11 +128,6 @@ describe('unchecked RPC reader boundary', () => { expect(observed.size).toBe(inventory.length) }) - it('lists each file once', () => { - const seen = inventory.map((entry) => entry.file) - expect(seen.filter((file, index) => seen.indexOf(file) !== index)).toEqual([]) - }) - it('has no unlisted file holding an unchecked reader', () => { const listed = new Set(inventory.map((entry) => entry.file)) const unlisted = [...observed.keys()].filter((file) => !listed.has(file)) diff --git a/mobile/src/worktree/home-resume-card.test.ts b/mobile/src/worktree/home-resume-card.test.ts index 85c6cbab8ee..04a02a7331c 100644 --- a/mobile/src/worktree/home-resume-card.test.ts +++ b/mobile/src/worktree/home-resume-card.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' import { isResumeTargetConfirmedMissing, @@ -7,11 +6,6 @@ import { } from './home-resume-card' import type { HomeWorktreeSummary, HostWorktreeInfo } from './home-worktree-info' -const resumeCardSource = readFileSync( - new URL('../home/MobileHomeResumeCard.tsx', import.meta.url), - 'utf8' -) - function worktree(worktreeId: string): HomeWorktreeSummary { return { worktreeId, @@ -121,11 +115,6 @@ describe('home resume card', () => { actionable: true }) }) - - it('renders the home Resume card inert until its host connects', () => { - expect(resumeCardSource).toContain('disabled={!props.card.actionable}') - expect(resumeCardSource).toContain('!props.card.actionable && styles.cardDisabled') - }) }) // Why (F7): the card is drawn from a snapshot that can name a workspace the desktop deleted diff --git a/mobile/tests-typecheck-baseline.txt b/mobile/tests-typecheck-baseline.txt index 34dd8f7cf66..ab63d955f7a 100644 --- a/mobile/tests-typecheck-baseline.txt +++ b/mobile/tests-typecheck-baseline.txt @@ -53,7 +53,6 @@ src/session/QuickCommandsSheet.test.ts src/session/ai-vault-resume-launch.test.ts src/session/mobile-file-tap-open.test.ts src/session/mobile-native-chat-open-file.test.ts -src/session/mobile-session-route-parity.test.ts src/session/mobile-session-tab-activation.test.ts src/session/mobile-worker-takeover-send-sites.test.ts src/session/pending-terminal-handle-recovery-poll.test.ts diff --git a/src/cli/cli-command-name-parity.test.ts b/src/cli/cli-command-name-parity.test.ts deleted file mode 100644 index 32bbcc06add..00000000000 --- a/src/cli/cli-command-name-parity.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { CLI_COMMAND_NAMES } from '../main/startup/cli-command-names' -import { COMMAND_SPECS } from './specs' - -const specCommandNames = [...new Set(COMMAND_SPECS.map((spec) => spec.path[0]))].sort() - -describe('CLI command-name parity between COMMAND_SPECS and the launch redirect', () => { - it('has commands to compare', () => { - expect(specCommandNames.length).toBeGreaterThan(0) - }) - - it('redirects every top-level CLI command', () => { - const redirected = new Set(CLI_COMMAND_NAMES) - expect(specCommandNames.filter((name) => !redirected.has(name))).toEqual([]) - }) - - it('lists no command that COMMAND_SPECS does not define', () => { - const specNames = new Set(specCommandNames) - expect([...CLI_COMMAND_NAMES].filter((name) => !specNames.has(name))).toEqual([]) - }) - - it('stays sorted and free of duplicates so additions are easy to review', () => { - expect([...CLI_COMMAND_NAMES]).toEqual([...new Set(CLI_COMMAND_NAMES)].sort()) - }) -}) diff --git a/src/cli/dispatch.ts b/src/cli/dispatch.ts index d74de65119e..7ad882b1e11 100644 --- a/src/cli/dispatch.ts +++ b/src/cli/dispatch.ts @@ -32,8 +32,7 @@ function buildRoutes(groups: readonly HandlerGroup[]): Map const ROUTES = buildRoutes(HANDLER_GROUPS) -// Why: exposes only the canonical command keys (not the handler internals) so the -// registry-parity guard can check specs↔handlers without rebuilding the table. +// Why: exposes only the canonical command keys, not the handler internals. export const HANDLER_COMMAND_KEYS: ReadonlySet = new Set(ROUTES.keys()) export async function dispatch(commandPath: string[], ctx: HandlerContext): Promise { diff --git a/src/cli/handler-group-manifest.test.ts b/src/cli/handler-group-manifest.test.ts index 3849f39a7c9..147305d72a5 100644 --- a/src/cli/handler-group-manifest.test.ts +++ b/src/cli/handler-group-manifest.test.ts @@ -36,27 +36,6 @@ function isHandlerRecord(value: unknown): value is Record { } describe('handler group manifest', () => { - it('lists a loadable group for every entry', async () => { - for (const group of HANDLER_GROUPS) { - const loaded = await group.load() - expect(loaded, `${group.name} resolved to a non-record`).toBeTypeOf('object') - } - }) - - it('matches each group export key-for-key', async () => { - const drift: string[] = [] - for (const group of HANDLER_GROUPS) { - const actual = Object.keys(await group.load()).sort() - const declared = [...group.keys].sort() - if (JSON.stringify(actual) !== JSON.stringify(declared)) { - drift.push( - `${group.name}: manifest ${JSON.stringify(declared)} !== export ${JSON.stringify(actual)}` - ) - } - } - expect(drift).toEqual([]) - }) - it('exposes every declared key as a callable handler', async () => { const notCallable: string[] = [] for (const group of HANDLER_GROUPS) { @@ -70,15 +49,6 @@ describe('handler group manifest', () => { expect(notCallable).toEqual([]) }) - it('reaches every group through dispatch routing', () => { - const routes = buildHandlerRoutes(HANDLER_GROUPS) - const reached = new Set([...routes.values()].map((group) => group.name)) - const unreachable = HANDLER_GROUPS.filter((group) => !reached.has(group.name)).map( - (group) => group.name - ) - expect(unreachable).toEqual([]) - }) - // Why: dropping a group from the manifest silently unregisters its commands — // walk the tree so a new or forgotten handler file fails here, not in prod. // Nested modules are spread into a parent group rather than registered under diff --git a/src/cli/handlers/orchestration-timeout-cli.test.ts b/src/cli/handlers/orchestration-timeout-cli.test.ts deleted file mode 100644 index 9f60548a809..00000000000 --- a/src/cli/handlers/orchestration-timeout-cli.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const callMock = vi.fn() -const originalExitCode = process.exitCode -const originalCliCommand = process.env.ORCA_CLI_COMMAND - -vi.mock('../format', () => ({ printResult: vi.fn() })) -vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() })) - -import { printResult } from '../format' -import { ORCHESTRATION_HANDLERS } from './orchestration' - -describe('orchestration timeout flag validation', () => { - const invalidTimeoutValues: [string, string | boolean][] = [ - ['missing', true], - ['empty', ''], - ['non-numeric', 'not-a-number'], - ['zero', '0'], - ['negative', '-1'] - ] - - beforeEach(() => { - callMock.mockReset() - delete process.env.ORCA_TERMINAL_HANDLE - delete process.env.ORCA_PANE_KEY - process.exitCode = undefined - }) - - afterEach(() => { - process.exitCode = originalExitCode - if (originalCliCommand === undefined) { - delete process.env.ORCA_CLI_COMMAND - } else { - process.env.ORCA_CLI_COMMAND = originalCliCommand - } - vi.restoreAllMocks() - }) - - const invokeCheck = (flags: Map) => - ORCHESTRATION_HANDLERS['orchestration check']({ - flags, - client: { call: callMock }, - cwd: '/tmp/repo', - json: true - } as never) - - const invokeAsk = (flags: Map) => - ORCHESTRATION_HANDLERS['orchestration ask']({ - flags, - client: { call: callMock }, - cwd: '/tmp/repo', - json: true - } as never) - - const invokePlainAsk = (flags: Map) => - ORCHESTRATION_HANDLERS['orchestration ask']({ - flags, - client: { call: callMock }, - cwd: '/tmp/repo', - json: false - } as never) - - it.each(invalidTimeoutValues)('rejects invalid check --timeout-ms: %s', async (_label, value) => { - await expect( - invokeCheck( - new Map([ - ['wait', true], - ['timeout-ms', value] - ]) - ) - ).rejects.toThrow(/--timeout-ms/) - expect(callMock).not.toHaveBeenCalled() - }) - - it('passes a parsed check timeout and peek mode into the RPC payload', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ result: { messages: [], count: 0 } }) - await invokeCheck( - new Map([ - ['wait', true], - ['peek', true], - ['timeout-ms', '250'] - ]) - ) - // Why: unread:false makes pre-peek runtimes fall back to non-consuming all mode. - expect(callMock).toHaveBeenCalledWith('orchestration.check', { - terminal: 'term_worker', - terminalPaneKey: undefined, - unread: false, - peek: true, - all: undefined, - types: undefined, - format: undefined, - compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/), - run: undefined, - ack: undefined, - wait: true, - timeoutMs: 250 - }) - }) - - it('filters already-read rows from a peek response for pre-peek runtimes', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { - messages: [ - { id: 'msg_old', from_handle: 'a', subject: 'seen', read: 1 }, - { id: 'msg_new', from_handle: 'a', subject: 'fresh', read: 0 } - ], - count: 2, - formatted: 'banners built from all rows' - } - }) - vi.mocked(printResult).mockClear() - await invokeCheck(new Map([['peek', true]])) - const response = vi.mocked(printResult).mock.calls[0]?.[0] as { - result: { messages: { id: string }[]; count: number; formatted?: string } - } - expect(response.result.messages.map((message) => message.id)).toEqual(['msg_new']) - expect(response.result.count).toBe(1) - expect(response.result.formatted).toBeUndefined() - }) - - it('rejects combined read modes before calling the runtime', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - await expect( - invokeCheck( - new Map([ - ['unread', true], - ['peek', true] - ]) - ) - ).rejects.toMatchObject({ - code: 'invalid_argument', - message: expect.stringContaining('read mode') - }) - expect(callMock).not.toHaveBeenCalled() - }) - - it('warns when a pre-peek runtime returned a full 100-row page', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - const rows = Array.from({ length: 100 }, (_, index) => ({ - id: `msg_${index}`, - from_handle: 'a', - subject: `s${index}`, - read: index === 0 ? 0 : 1 - })) - callMock.mockResolvedValue({ result: { messages: rows, count: 100 } }) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - await invokeCheck(new Map([['peek', true]])) - expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('newest 100 messages')) - errorSpy.mockRestore() - }) - - it('fails --peek --wait against a runtime that returned only read rows', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { - messages: [{ id: 'msg_old', from_handle: 'a', subject: 'seen', read: 1 }], - count: 1 - } - }) - await expect( - invokeCheck( - new Map([ - ['peek', true], - ['wait', true] - ]) - ) - ).rejects.toMatchObject({ code: 'peek_wait_unsupported' }) - }) - - it.each(invalidTimeoutValues)('rejects invalid ask --timeout-ms: %s', async (_label, value) => { - await expect( - invokeAsk( - new Map([ - ['to', 'term_coord'], - ['question', 'Proceed?'], - ['timeout-ms', value] - ]) - ) - ).rejects.toThrow(/--timeout-ms/) - expect(callMock).not.toHaveBeenCalled() - }) - - it('uses the parsed ask timeout for both runtime wait and client timeout', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false } - }) - vi.spyOn(console, 'log').mockImplementation(() => {}) - await invokeAsk( - new Map([ - ['to', 'term_coord'], - ['question', 'Proceed?'], - ['timeout-ms', '123'] - ]) - ) - expect(callMock).toHaveBeenCalledWith( - 'orchestration.ask', - { - to: 'term_coord', - run: undefined, - question: 'Proceed?', - resume: undefined, - options: undefined, - timeoutMs: 123, - from: 'term_worker', - compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/), - compatibilityWindowsCommand: undefined - }, - { timeoutMs: 5_123, orchestrationCapability: undefined } - ) - }) - - it('passes an ask resume without creating a new question payload', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { - answer: 'yes', - messageId: 'msg_question', - threadId: 'msg_question', - timedOut: false - } - }) - vi.spyOn(console, 'log').mockImplementation(() => {}) - await invokeAsk(new Map([['resume', 'msg_question']])) - expect(callMock).toHaveBeenCalledWith( - 'orchestration.ask', - { - to: undefined, - run: undefined, - question: undefined, - resume: 'msg_question', - options: undefined, - timeoutMs: undefined, - from: 'term_worker', - compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/), - compatibilityWindowsCommand: undefined - }, - { timeoutMs: 605_000, orchestrationCapability: undefined } - ) - }) - - it('prints the pending message ID and exact capability-bound resume command on timeout', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - process.env.ORCA_CLI_COMMAND = 'orca-dev' - callMock.mockResolvedValue({ - result: { - answer: null, - messageId: 'msg_question', - threadId: 'thread_question', - timedOut: true, - timeoutMs: 30_000 - } - }) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - - await invokePlainAsk( - new Map([ - ['question', 'Proceed?'], - ['dispatch-capability', 'dcap_secret'], - ['timeout-ms', '30000'] - ]) - ) - - expect(errorSpy).toHaveBeenCalledWith( - 'ask timeout after 30000ms; question is still pending (messageId: msg_question). ' + - 'Resume waiting; do not ask again:\n' + - 'orca-dev orchestration ask --from term_worker --dispatch-capability dcap_secret ' + - '--resume msg_question --timeout-ms 30000' - ) - expect(process.exitCode).toBe(1) - }) - - it('rejects ambiguous ask create/resume input before RPC', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - await expect( - invokeAsk( - new Map([ - ['question', 'new'], - ['resume', 'msg_old'] - ]) - ) - ).rejects.toMatchObject({ code: 'invalid_argument' }) - expect(callMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/cli/handlers/orchestration-timeout.test.ts b/src/cli/handlers/orchestration-timeout.test.ts deleted file mode 100644 index 51f0d75098e..00000000000 --- a/src/cli/handlers/orchestration-timeout.test.ts +++ /dev/null @@ -1,292 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const callMock = vi.fn() -const getTerminalHandleMock = vi.hoisted(() => vi.fn()) -const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE -const originalPaneKey = process.env.ORCA_PANE_KEY - -vi.mock('../format', () => ({ printResult: vi.fn() })) -vi.mock('../selectors', () => ({ getTerminalHandle: getTerminalHandleMock })) - -import { printResult } from '../format' -import { ORCHESTRATION_HANDLERS } from './orchestration' - -const invalidTimeoutValues: [string, string | boolean][] = [ - ['missing', true], - ['empty', ''], - ['non-numeric', 'not-a-number'], - ['zero', '0'], - ['negative', '-1'], - ['fractional', '1.5'], - ['rounded fractional', '9007199254740991.1'], - ['unsafe integer', String(Number.MAX_SAFE_INTEGER + 1)] -] - -const invokeCheck = (flags: Map) => - ORCHESTRATION_HANDLERS['orchestration check']({ - flags, - client: { call: callMock }, - cwd: '/tmp/repo', - json: true - } as never) - -const invokeAsk = (flags: Map) => - ORCHESTRATION_HANDLERS['orchestration ask']({ - flags, - client: { call: callMock }, - cwd: '/tmp/repo', - json: true - } as never) - -beforeEach(() => { - callMock.mockReset() - getTerminalHandleMock.mockReset() - vi.mocked(printResult).mockReset() - delete process.env.ORCA_TERMINAL_HANDLE - delete process.env.ORCA_PANE_KEY -}) - -afterEach(() => { - if (originalTerminalHandle === undefined) { - delete process.env.ORCA_TERMINAL_HANDLE - } else { - process.env.ORCA_TERMINAL_HANDLE = originalTerminalHandle - } - if (originalPaneKey === undefined) { - delete process.env.ORCA_PANE_KEY - } else { - process.env.ORCA_PANE_KEY = originalPaneKey - } - vi.restoreAllMocks() -}) - -describe('orchestration timeout flag validation', () => { - it.each(invalidTimeoutValues)('rejects invalid check --timeout-ms: %s', async (_label, value) => { - const flags = new Map([ - ['wait', true], - ['timeout-ms', value] - ]) - - await expect(invokeCheck(flags)).rejects.toThrow(/--timeout-ms/) - expect(callMock).not.toHaveBeenCalled() - expect(getTerminalHandleMock).not.toHaveBeenCalled() - }) - - it('passes a parsed check timeout and peek mode into the RPC payload', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ result: { messages: [], count: 0 } }) - - await invokeCheck( - new Map([ - ['wait', true], - ['peek', true], - ['timeout-ms', '250'] - ]) - ) - - expect(callMock).toHaveBeenCalledWith('orchestration.check', { - terminal: 'term_worker', - terminalPaneKey: undefined, - unread: false, - peek: true, - all: undefined, - types: undefined, - format: undefined, - compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/), - run: undefined, - ack: undefined, - wait: true, - timeoutMs: 250 - }) - }) - - it('filters already-read rows from a peek response for pre-peek runtimes', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { - messages: [ - { id: 'msg_old', from_handle: 'a', subject: 'seen', read: 1 }, - { id: 'msg_new', from_handle: 'a', subject: 'fresh', read: 0 } - ], - count: 2, - formatted: 'banners built from all rows' - } - }) - - await invokeCheck(new Map([['peek', true]])) - - const response = vi.mocked(printResult).mock.calls[0]?.[0] as { - result: { messages: { id: string }[]; count: number; formatted?: string } - } - expect(response.result.messages.map((message) => message.id)).toEqual(['msg_new']) - expect(response.result.count).toBe(1) - expect(response.result.formatted).toBeUndefined() - }) - - it('rejects combined read modes before calling the runtime', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - - await expect( - invokeCheck( - new Map([ - ['unread', true], - ['peek', true] - ]) - ) - ).rejects.toMatchObject({ - code: 'invalid_argument', - message: expect.stringContaining('read mode') - }) - expect(callMock).not.toHaveBeenCalled() - }) - - it('warns when a pre-peek runtime returned a full 100-row page', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - const rows = Array.from({ length: 100 }, (_, index) => ({ - id: `msg_${index}`, - from_handle: 'a', - subject: `s${index}`, - read: index === 0 ? 0 : 1 - })) - callMock.mockResolvedValue({ result: { messages: rows, count: 100 } }) - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - - await invokeCheck(new Map([['peek', true]])) - - expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('newest 100 messages')) - }) - - it('fails --peek --wait against a runtime that returned only read rows', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { - messages: [{ id: 'msg_old', from_handle: 'a', subject: 'seen', read: 1 }], - count: 1 - } - }) - - await expect( - invokeCheck( - new Map([ - ['peek', true], - ['wait', true] - ]) - ) - ).rejects.toMatchObject({ code: 'peek_wait_unsupported' }) - }) - - it.each(invalidTimeoutValues)('rejects invalid ask --timeout-ms: %s', async (_label, value) => { - const flags = new Map([ - ['to', 'term_coord'], - ['question', 'Proceed?'], - ['timeout-ms', value] - ]) - - await expect(invokeAsk(flags)).rejects.toThrow(/--timeout-ms/) - expect(callMock).not.toHaveBeenCalled() - expect(getTerminalHandleMock).not.toHaveBeenCalled() - }) - - it.each([String(2_147_483_647), String(Number.MAX_SAFE_INTEGER)])( - 'clamps a safe ask timeout %s before adding transport headroom', - async (rawTimeout) => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false } - }) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await invokeAsk( - new Map([ - ['to', 'term_coord'], - ['question', 'Proceed?'], - ['timeout-ms', rawTimeout] - ]) - ) - - expect(callMock).toHaveBeenCalledWith( - 'orchestration.ask', - expect.objectContaining({ timeoutMs: 1_800_000 }), - { timeoutMs: 1_805_000 } - ) - } - ) - - it.each(['+1000', '1000.0', '1e3', '0x3e8'])( - 'preserves CLI-compatible exact integer timeout syntax %s', - async (rawTimeout) => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false } - }) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await invokeAsk( - new Map([ - ['to', 'term_coord'], - ['question', 'Proceed?'], - ['timeout-ms', rawTimeout] - ]) - ) - - expect(callMock).toHaveBeenCalledWith( - 'orchestration.ask', - expect.objectContaining({ timeoutMs: 1_000 }), - { timeoutMs: 6_000 } - ) - } - ) - - it('keeps an omitted ask timeout out of the payload while using default headroom', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false } - }) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await invokeAsk( - new Map([ - ['to', 'term_coord'], - ['question', 'Proceed?'] - ]) - ) - - expect(callMock).toHaveBeenCalledWith( - 'orchestration.ask', - expect.objectContaining({ timeoutMs: undefined }), - { timeoutMs: 605_000 } - ) - }) - - it('uses the parsed ask timeout for both runtime wait and client timeout', async () => { - process.env.ORCA_TERMINAL_HANDLE = 'term_worker' - callMock.mockResolvedValue({ - result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false } - }) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await invokeAsk( - new Map([ - ['to', 'term_coord'], - ['question', 'Proceed?'], - ['timeout-ms', '123'] - ]) - ) - - expect(callMock).toHaveBeenCalledWith( - 'orchestration.ask', - { - to: 'term_coord', - run: undefined, - question: 'Proceed?', - resume: undefined, - options: undefined, - timeoutMs: 123, - from: 'term_worker', - compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/), - compatibilityWindowsCommand: undefined - }, - { timeoutMs: 5_123, orchestrationCapability: undefined } - ) - }) -}) diff --git a/src/cli/handlers/orchestration.test.ts b/src/cli/handlers/orchestration.test.ts index e0a20541f91..05134045be1 100644 --- a/src/cli/handlers/orchestration.test.ts +++ b/src/cli/handlers/orchestration.test.ts @@ -7,6 +7,8 @@ const originalPaneKey = process.env.ORCA_PANE_KEY // Why: a structured-session marker inherited from the runner diverts these cases to the // structured refusal, so which branch they exercise would depend on who ran them. const originalStructuredSession = process.env.ORCA_STRUCTURED_SESSION +const originalCliCommand = process.env.ORCA_CLI_COMMAND +const originalExitCode = process.exitCode function lifecycleGroupRecipientError(type: 'worker_done' | 'heartbeat'): string { return `${type} messages belong to one exact Dispatch and cannot target a group address.` } @@ -36,6 +38,13 @@ afterEach(() => { } else { process.env.ORCA_STRUCTURED_SESSION = originalStructuredSession } + if (originalCliCommand === undefined) { + delete process.env.ORCA_CLI_COMMAND + } else { + process.env.ORCA_CLI_COMMAND = originalCliCommand + } + process.exitCode = originalExitCode + vi.restoreAllMocks() }) describe('orchestration send structured payload flags', () => { @@ -352,7 +361,10 @@ describe('orchestration timeout flag validation', () => { ['empty', ''], ['non-numeric', 'not-a-number'], ['zero', '0'], - ['negative', '-1'] + ['negative', '-1'], + ['fractional', '1.5'], + ['rounded fractional', '9007199254740991.1'], + ['unsafe integer', String(Number.MAX_SAFE_INTEGER + 1)] ] beforeEach(() => { @@ -360,6 +372,7 @@ describe('orchestration timeout flag validation', () => { delete process.env.ORCA_TERMINAL_HANDLE delete process.env.ORCA_PANE_KEY delete process.env.ORCA_STRUCTURED_SESSION + process.exitCode = undefined }) const invokeCheck = (flags: Map) => @@ -378,6 +391,14 @@ describe('orchestration timeout flag validation', () => { json: true } as never) + const invokePlainAsk = (flags: Map) => + ORCHESTRATION_HANDLERS['orchestration ask']({ + flags, + client: { call: callMock }, + cwd: '/tmp/repo', + json: false + } as never) + it.each(invalidTimeoutValues)('rejects invalid check --timeout-ms: %s', async (_label, value) => { const flags = new Map([ ['wait', true], @@ -386,6 +407,7 @@ describe('orchestration timeout flag validation', () => { await expect(invokeCheck(flags)).rejects.toThrow(/--timeout-ms/) expect(callMock).not.toHaveBeenCalled() + expect(getTerminalHandleMock).not.toHaveBeenCalled() }) it('passes a parsed check timeout and peek mode into the RPC payload', async () => { @@ -507,6 +529,109 @@ describe('orchestration timeout flag validation', () => { await expect(invokeAsk(flags)).rejects.toThrow(/--timeout-ms/) expect(callMock).not.toHaveBeenCalled() + expect(getTerminalHandleMock).not.toHaveBeenCalled() + }) + + it.each([String(2_147_483_647), String(Number.MAX_SAFE_INTEGER)])( + 'clamps a safe ask timeout %s before adding transport headroom', + async (rawTimeout) => { + process.env.ORCA_TERMINAL_HANDLE = 'term_worker' + callMock.mockResolvedValue({ + result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false } + }) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await invokeAsk( + new Map([ + ['to', 'term_coord'], + ['question', 'Proceed?'], + ['timeout-ms', rawTimeout] + ]) + ) + + expect(callMock).toHaveBeenCalledWith( + 'orchestration.ask', + expect.objectContaining({ timeoutMs: 1_800_000 }), + { timeoutMs: 1_805_000 } + ) + } + ) + + it.each(['+1000', '1000.0', '1e3', '0x3e8'])( + 'preserves CLI-compatible exact integer timeout syntax %s', + async (rawTimeout) => { + process.env.ORCA_TERMINAL_HANDLE = 'term_worker' + callMock.mockResolvedValue({ + result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false } + }) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await invokeAsk( + new Map([ + ['to', 'term_coord'], + ['question', 'Proceed?'], + ['timeout-ms', rawTimeout] + ]) + ) + + expect(callMock).toHaveBeenCalledWith( + 'orchestration.ask', + expect.objectContaining({ timeoutMs: 1_000 }), + { timeoutMs: 6_000 } + ) + } + ) + + it('keeps an omitted ask timeout out of the payload while using default headroom', async () => { + process.env.ORCA_TERMINAL_HANDLE = 'term_worker' + callMock.mockResolvedValue({ + result: { answer: 'yes', messageId: 'msg_1', threadId: 'thread_1', timedOut: false } + }) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await invokeAsk( + new Map([ + ['to', 'term_coord'], + ['question', 'Proceed?'] + ]) + ) + + expect(callMock).toHaveBeenCalledWith( + 'orchestration.ask', + expect.objectContaining({ timeoutMs: undefined }), + { timeoutMs: 605_000 } + ) + }) + + it('prints the pending message ID and exact capability-bound resume command on timeout', async () => { + process.env.ORCA_TERMINAL_HANDLE = 'term_worker' + process.env.ORCA_CLI_COMMAND = 'orca-dev' + callMock.mockResolvedValue({ + result: { + answer: null, + messageId: 'msg_question', + threadId: 'thread_question', + timedOut: true, + timeoutMs: 30_000 + } + }) + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + + await invokePlainAsk( + new Map([ + ['question', 'Proceed?'], + ['dispatch-capability', 'dcap_secret'], + ['timeout-ms', '30000'] + ]) + ) + + expect(errorSpy).toHaveBeenCalledWith( + 'ask timeout after 30000ms; question is still pending (messageId: msg_question). ' + + 'Resume waiting; do not ask again:\n' + + 'orca-dev orchestration ask --from term_worker --dispatch-capability dcap_secret ' + + '--resume msg_question --timeout-ms 30000' + ) + expect(process.exitCode).toBe(1) }) it('uses the parsed ask timeout for both runtime wait and client timeout', async () => { diff --git a/src/cli/registry-parity.test.ts b/src/cli/registry-parity.test.ts deleted file mode 100644 index 588a4e14d08..00000000000 --- a/src/cli/registry-parity.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import type { CommandSpec } from './args' -import { HANDLER_COMMAND_KEYS } from './dispatch' -import { findRegistryParityGaps } from './registry-parity' -import { COMMAND_SPECS } from './specs' - -describe('registry parity (live tree)', () => { - const handlerKeys = [...HANDLER_COMMAND_KEYS] - - it('has a handler for every canonical spec path', () => { - const { specsWithoutHandler } = findRegistryParityGaps(COMMAND_SPECS, handlerKeys) - expect(specsWithoutHandler).toEqual([]) - }) - - it('has a spec for every handler key', () => { - const { handlersWithoutSpec } = findRegistryParityGaps(COMMAND_SPECS, handlerKeys) - expect(handlersWithoutSpec).toEqual([]) - }) -}) - -describe('findRegistryParityGaps (fixtures)', () => { - const spec = (path: string[], aliases?: string[][]): CommandSpec => ({ - path, - aliases, - summary: 's', - usage: 'u', - allowedFlags: [] - }) - - it('flags a spec with no handler', () => { - const gaps = findRegistryParityGaps([spec(['foo', 'bar'])], []) - expect(gaps.specsWithoutHandler).toEqual(['foo bar']) - }) - - it('flags a handler with no spec', () => { - const gaps = findRegistryParityGaps([spec(['foo', 'bar'])], ['foo bar', 'ghost cmd']) - expect(gaps.handlersWithoutSpec).toEqual(['ghost cmd']) - }) - - it('does not require a handler for an alias path', () => { - const gaps = findRegistryParityGaps([spec(['foo', 'rm'], [['foo', 'remove']])], ['foo rm']) - expect(gaps.specsWithoutHandler).toEqual([]) - expect(gaps.handlersWithoutSpec).toEqual([]) - }) -}) diff --git a/src/cli/registry-parity.ts b/src/cli/registry-parity.ts deleted file mode 100644 index 27c0130b555..00000000000 --- a/src/cli/registry-parity.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { CommandSpec } from './args' - -// Why: validation/help and dispatch use parallel registries that must not drift. - -export type RegistryParityGaps = { - handlersWithoutSpec: string[] - specsWithoutHandler: string[] -} - -export function findRegistryParityGaps( - specs: CommandSpec[], - handlerKeys: Iterable -): RegistryParityGaps { - // Why: aliases resolve before dispatch and deliberately have no handler key. - const canonical = new Set(specs.map((spec) => spec.path.join(' '))) - const handlers = new Set(handlerKeys) - return { - handlersWithoutSpec: [...handlers].filter((key) => !canonical.has(key)), - specsWithoutHandler: [...canonical].filter((key) => !handlers.has(key)) - } -} diff --git a/src/cli/runtime-client-deferral.test.ts b/src/cli/runtime-client-deferral.test.ts index 1487e2364f7..7dc29179065 100644 --- a/src/cli/runtime-client-deferral.test.ts +++ b/src/cli/runtime-client-deferral.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' @@ -60,8 +60,6 @@ vi.mock('./runtime-client', () => { import { main } from './index' import * as dispatchModule from './dispatch' -const CLI_DIR = __dirname - describe('RuntimeClient module-graph deferral', () => { let logSpy: ReturnType let errorSpy: ReturnType @@ -84,39 +82,6 @@ describe('RuntimeClient module-graph deferral', () => { process.exitCode = 0 }) - // Why: the whole point of the change. These modules load on EVERY - // invocation, so a value-import of the barrel from any of them drags the - // RuntimeClient graph (zod, ws, tweetnacl) back onto the --help path. - it.each([ - 'args.ts', - 'flags.ts', - 'dispatch.ts', - 'format.ts', - 'cli-error.ts', - 'selectors.ts', - 'execution-host-flag.ts' - ])('%s imports error classes from ./runtime/types, not the barrel', (file) => { - const source = readFileSync(join(CLI_DIR, file), 'utf8') - const valueImports = source - .split('\n') - .filter((line) => line.startsWith('import ') && line.includes("'./runtime-client'")) - for (const line of valueImports) { - expect(line, `${file}: "${line}" must be type-only`).toMatch(/^import type /) - } - // Why: format.ts re-exports its error formatters; the guarded import lives in cli-error.ts. - if (file !== 'format.ts') { - expect(source).toContain("} from './runtime/types'") - } - }) - - it('index.ts has no eager value-import of the runtime client', () => { - const source = readFileSync(join(CLI_DIR, 'index.ts'), 'utf8') - expect(source).toContain("import type { RuntimeClient } from './runtime-client'") - expect(source).not.toMatch(/^import \{[^}]*RuntimeClient[^}]*\} from '\.\/runtime-client'/m) - expect(source).toContain("await import('./runtime-client.js')") - expect(source).toContain("import { reportCliError } from './cli-error'") - }) - it('constructs no client for --help', async () => { await main(['--help'], '/tmp/repo') expect(constructorArgsMock).not.toHaveBeenCalled() diff --git a/src/cli/serve-electron-flag-parity.test.ts b/src/cli/serve-electron-flag-parity.test.ts index a4964e1a824..ef0c040524b 100644 --- a/src/cli/serve-electron-flag-parity.test.ts +++ b/src/cli/serve-electron-flag-parity.test.ts @@ -1,8 +1,6 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { normalizeServeModeArgv } from '../main/startup/serve-mode-argv' -import { BOOLEAN_FLAGS, GLOBAL_FLAGS } from './args' +import { BOOLEAN_FLAGS } from './args' import { SERVE_COMMAND_SPECS } from './specs/serve' // Why this test lives under src/cli: the Electron rewrite duplicates the CLI's serve flag list because @@ -51,31 +49,4 @@ describe('serve flag parity between the CLI spec and the Electron argv rewrite', // Idempotent: `orca serve` spawns the app already in this shape, and the rewrite runs over it too. expect(normalizeServeModeArgv(expected)).toEqual(expected) }) - - it('emits the same --serve-* names the CLI spawns with and the main process reads', () => { - // Why source text: serveOrcaApp spawns a real process; keeping both names visible here makes - // the rewrite/parser contract fail loudly if either side drifts. - const launchSource = readFileSync(join(process.cwd(), 'src/cli/runtime/launch.ts'), 'utf8') - const serveOptionsSource = readFileSync( - join(process.cwd(), 'src/main/startup/serve-options.ts'), - 'utf8' - ) - const start = serveOptionsSource.indexOf('export function getServeOptions(') - // Why bound the anchor: an unresolved indexOf slices to EOF and passes vacuously. - expect(start).toBeGreaterThanOrEqual(0) - const end = serveOptionsSource.indexOf('\n}', start) - expect(end).toBeGreaterThan(start) - const getServeOptionsBody = serveOptionsSource.slice(start, end) - - for (const flag of translatedFlags) { - expect(launchSource).toContain(`'--serve-${flag}'`) - expect(getServeOptionsBody).toContain(`'--serve-${flag}'`) - } - }) - - it('keeps the untranslated allowlist tied to real global flags', () => { - for (const flag of UNTRANSLATED_GLOBAL_FLAGS) { - expect(GLOBAL_FLAGS).toContain(flag) - } - }) }) diff --git a/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts b/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts index d8f504beca3..d23d59288b4 100644 --- a/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts +++ b/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts @@ -81,8 +81,6 @@ describe('waitForWslRelaySentinel', () => { emitStdout(child, sentinel.subarray(0, mid)) emitStdout(child, sentinel.subarray(mid)) const transport = await promise - expect(typeof transport.write).toBe('function') - expect(typeof transport.onData).toBe('function') transport.pauseReads?.() transport.resumeReads?.() expect(child.stdout.pause).toHaveBeenCalledOnce() diff --git a/src/main/ai-vault-search/session-search-host-registration.test.ts b/src/main/ai-vault-search/session-search-host-registration.test.ts index e2a31ec4f21..5a535d3e554 100644 --- a/src/main/ai-vault-search/session-search-host-registration.test.ts +++ b/src/main/ai-vault-search/session-search-host-registration.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' @@ -33,8 +32,6 @@ vi.mock('../ai-vault/cached-session-list', async (importOriginal) => ({ localAiVaultScanRoots })) -const ROOT = join(import.meta.dirname, '..', '..', '..') - let harness: SessionSearchIndexerHarness let installed: { apply?(settings: AiVaultSearchSettings): void; dispose(): void } | null @@ -141,26 +138,6 @@ it('registers an in-process service for a host with no scanner child', async () }) }) -// The behavioural tests above prove the installers register; these prove each -// host's boot path reaches one, which no unit of either module can show. -it.each([ - [ - 'desktop and headless serve', - 'src/main/startup/main-process-runtime-service.ts', - 'installChildSessionSearchService' - ], - ['orcad', 'src/main/orcad/orcad-session-search.ts', 'installInProcessSessionSearchService'], - [ - 'the relay daemon', - 'src/relay/relay-runtime-services.ts', - 'installInProcessSessionSearchService' - ] -])('boots %s with a registered session search service', (_host, file, installer) => { - const source = readFileSync(join(ROOT, file), 'utf8') - expect(source).toContain(installer) - expect(source).toMatch(new RegExp(`${installer}\\(\\{`)) -}) - it('disables immediately without root discovery', async () => { const { installChildSessionSearchService, applySessionSearchSettingsChange } = await import('./session-search-enablement') @@ -231,11 +208,3 @@ it('re-applies consent on an in-process host without reinstalling the service', reason: 'disabled' }) }) - -// orcad reaches the index through the deps hook the runtime RPC calls; the wiring is -// what no unit of either module can show. -it('wires orcad consent from the runtime hook to the installed service', () => { - const source = readFileSync(join(ROOT, 'src/main/orcad/orcad-entry.ts'), 'utf8') - expect(source).toContain('applySessionSearchSettings:') - expect(source).toContain('sessionSearch?.apply(next)') -}) diff --git a/src/main/browser/browser-session-registry-import-boundary.test.ts b/src/main/browser/browser-session-registry-import-boundary.test.ts deleted file mode 100644 index 96950797c4a..00000000000 --- a/src/main/browser/browser-session-registry-import-boundary.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { expect, it } from 'vitest' - -it('keeps the cookie fixture registry outside the persistence barrel graph', () => { - const source = readFileSync(join(__dirname, 'browser-session-registry.ts'), 'utf8') - - expect(source).toMatch( - /import\s*\{\s*getCanonicalUserDataPath\s*\}\s*from\s*['"]\.\.\/persistence\/loading-store\/user-data-path['"]/ - ) - expect(source).not.toMatch(/from\s*['"]\.\.\/persistence['"]/) -}) diff --git a/src/main/claude-accounts/claude-account-service-api-parity.test.ts b/src/main/claude-accounts/claude-account-service-api-parity.test.ts index 206ccbd82af..09ec7813ffe 100644 --- a/src/main/claude-accounts/claude-account-service-api-parity.test.ts +++ b/src/main/claude-accounts/claude-account-service-api-parity.test.ts @@ -1,28 +1,10 @@ import { describe, expect, it, vi } from 'vitest' import type { ClaudeRateLimitAccountsState } from '../../shared/managed-account-types' import { ClaudeAccountService } from './service' -import type { ClaudeAccountAddTarget, ClaudeAccountImportOptions } from './service' +import type { ClaudeAccountAddTarget } from './service' vi.mock('electron', () => ({ app: { getPath: () => '/tmp/orca-claude-api-parity' } })) -type PublicClaudeAccountService = { - listAccounts(): ClaudeRateLimitAccountsState - addAccount(target?: ClaudeAccountAddTarget): Promise - addAccountFromConfigDir( - configDir: string, - options?: ClaudeAccountImportOptions - ): Promise - reauthenticateAccount(accountId: string): Promise - removeAccount(accountId: string): Promise - selectAccount(accountId: string | null): Promise - selectAccountForTarget( - accountId: string | null, - target?: { runtime?: 'host' | 'wsl'; wslDistro?: string | null } - ): Promise - cancelPendingLogin(): boolean - getRuntimeConfigDir(target?: { runtime?: 'host' | 'wsl'; wslDistro?: string | null }): string -} - function createService(): ClaudeAccountService { const settings = { claudeManagedAccounts: [], @@ -41,16 +23,7 @@ function deferred(): { promise: Promise; resolve: () => void } { return { promise: new Promise((done) => (resolve = done)), resolve } } -describe('ClaudeAccountService API parity', () => { - it('keeps the exact runtime export and assignable public surface', async () => { - const runtimeExports = await import('./service') - const service: PublicClaudeAccountService = createService() - - expect(Object.keys(runtimeExports)).toEqual(['ClaudeAccountService']) - expect(service.cancelPendingLogin()).toBe(false) - expect(service.getRuntimeConfigDir()).toBe('/tmp/claude') - }) - +describe('ClaudeAccountService mutation serialization', () => { it('serializes mutations within one service', async () => { const service = createService() const first = deferred() diff --git a/src/main/claude/claude-agent-sdk-import-boundary.test.ts b/src/main/claude/claude-agent-sdk-import-boundary.test.ts index f1a38466d41..421e4a9c719 100644 --- a/src/main/claude/claude-agent-sdk-import-boundary.test.ts +++ b/src/main/claude/claude-agent-sdk-import-boundary.test.ts @@ -1,5 +1,4 @@ -import { existsSync, readFileSync, statSync } from 'node:fs' -import { dirname, join, relative, resolve } from 'node:path' +import { resolve } from 'node:path' import { describe, expect, it } from 'vitest' import { spawnProcess } from '../../shared/child-process/run-process' @@ -9,115 +8,14 @@ import { spawnProcess } from '../../shared/child-process/run-process' * A user who never leaves the terminal/TUI Claude path must not pay for the SDK: * importing it evaluates a package that rewrites * `process.env.NoDefaultCurrentDirectoryInExePath`, changing how Windows resolves - * executables for every later subprocess, and a missing or incompatible install - * would take normal runtime startup down with it. The ordinary - * `OrcaRuntimeService` graph reaches the Claude transport module, so only a - * deferred import keeps that boundary — and only a walk of the real import graph - * keeps the next static import from quietly restoring it. + * executables for every later subprocess. Loading the structured runtime must not + * trip that rewrite, which is only true while the SDK stays behind a deferred + * import inside the session path. */ const SDK_PACKAGE = '@anthropic-ai/claude-agent-sdk' const REPO_ROOT = resolve(__dirname, '..', '..', '..') -/** The Electron main entry: everything the app loads before any session exists. */ -const ROOT = 'src/main/index.ts' -/** Proof the walk goes all the way into the Claude transport rather than stopping short. */ -const TRANSPORT_MODULE = 'src/main/claude/claude-stream-json-connection.ts' - -/** - * Static, value-carrying specifiers only, read statement by statement so a - * multi-line `import { ... } from '...'` counts. `import type` is erased before - * the module ever loads and a bare `import(...)` is the deferral this guards, so - * neither is an edge the runtime traverses at load time. - */ -const STATEMENT_START = /^\s*(?:import|export)\b/ -const TYPE_ONLY = /^\s*(?:import|export)\s+type\b/ -const FROM_SPECIFIER = /(?:^|\s)from\s*['"]([^'"]+)['"]/ -const SIDE_EFFECT_IMPORT = /^\s*import\s*['"]([^'"]+)['"]/ -/** An import statement never spans more lines than its longest specifier list. */ -const MAX_STATEMENT_LINES = 60 - -function readSpecifiers(source: string): string[] { - const lines = source.split('\n') - const found: string[] = [] - for (let index = 0; index < lines.length; index += 1) { - const first = lines[index] as string - if (!STATEMENT_START.test(first) || TYPE_ONLY.test(first)) { - continue - } - const sideEffect = SIDE_EFFECT_IMPORT.exec(first) - if (sideEffect) { - found.push(sideEffect[1] as string) - continue - } - for (let scan = index; scan < Math.min(lines.length, index + MAX_STATEMENT_LINES); scan += 1) { - if (scan > index && STATEMENT_START.test(lines[scan] as string)) { - break - } - const specifier = FROM_SPECIFIER.exec(lines[scan] as string) - if (specifier) { - found.push(specifier[1] as string) - break - } - } - } - return found -} - -/** Resolve a relative specifier the way the bundler does; unresolvable means not a module. */ -function resolveRelative(fromFile: string, specifier: string): string | null { - const base = join(dirname(fromFile), specifier) - for (const candidate of [base, `${base}.ts`, `${base}.tsx`, join(base, 'index.ts')]) { - if (existsSync(candidate) && statSync(candidate).isFile()) { - return candidate - } - } - return null -} - -function walkStaticImports(rootFile: string): { visited: Set; sdkImporters: string[] } { - const visited = new Set() - const sdkImporters: string[] = [] - const queue = [resolve(REPO_ROOT, rootFile)] - while (queue.length > 0) { - const file = queue.pop() as string - const key = relative(REPO_ROOT, file).split('\\').join('/') - if (visited.has(key)) { - continue - } - visited.add(key) - for (const specifier of readSpecifiers(readFileSync(file, 'utf8'))) { - if (specifier === SDK_PACKAGE || specifier.startsWith(`${SDK_PACKAGE}/`)) { - sdkImporters.push(key) - continue - } - if (!specifier.startsWith('.')) { - continue - } - const target = resolveRelative(file, specifier) - if (target) { - queue.push(target) - } - } - } - return { visited, sdkImporters } -} - describe('claude agent SDK import boundary', () => { - const walk = walkStaticImports(ROOT) - - it('walks a graph deep enough to reach the Claude transport', () => { - // Without this the guard passes for the wrong reason the moment the walk breaks. - expect(walk.visited.size).toBeGreaterThan(500) - expect([...walk.visited]).toContain(TRANSPORT_MODULE) - }) - - it('never reaches the SDK through a static import from the main entry', () => { - expect( - walk.sdkImporters, - `${SDK_PACKAGE} must stay behind the structured-Claude boundary. Load it with a deferred import inside the session path instead.` - ).toEqual([]) - }) - it('leaves the Windows executable-search environment alone when the runtime loads', async () => { // A vitest file runs in its own fork, so this is a clean process; the ambient // value is cleared first because the developer's own shell may carry one. diff --git a/src/main/codex/codex-trust-grant-main-thread-boundary.test.ts b/src/main/codex/codex-trust-grant-main-thread-boundary.test.ts deleted file mode 100644 index 4b88d95991c..00000000000 --- a/src/main/codex/codex-trust-grant-main-thread-boundary.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { existsSync, readFileSync, readdirSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -/** - * Ratchet for stablyai/orca#16441. - * - * Codex hook trust used to be granted by blocking the Electron main thread on - * `spawnSync` of a bundled ELECTRON_RUN_AS_NODE entry, for the whole - * app-server deadline: 15s native, 35s WSL, ~45s on the three-session real-home - * path. The window showed "Not Responding" during cold start and pane launch. - * - * The subprocess only ever existed to donate an event loop to a deliberately - * blocked parent, so this guards the shape of the fix rather than one call - * site: nothing on the trust-grant lane may start a child process - * synchronously, and the forked entry must stay gone. - */ -const CODEX_DIR = __dirname - -const SYNC_SPAWN_PATTERN = /\b(?:spawnSync|execSync|execFileSync|runProcessSync)\s*[(<]/ - -/** Drop comments so the prose explaining the old idiom is not an offender. */ -function codeText(contents: string): string { - return contents - .split('\n') - .filter((line) => !/^\s*(?:\/\/|\/\*|\*)/.test(line)) - .join('\n') -} - -function listCodexSourceFiles(): string[] { - return readdirSync(CODEX_DIR).filter((name) => name.endsWith('.ts') && !name.endsWith('.test.ts')) -} - -describe('codex trust grant main-thread boundary', () => { - it('starts no child process synchronously anywhere in the codex module', () => { - const offenders = listCodexSourceFiles().filter((name) => - SYNC_SPAWN_PATTERN.test(codeText(readFileSync(join(CODEX_DIR, name), 'utf8'))) - ) - expect(offenders).toEqual([]) - }) - - it('keeps the forked grant entry and its blocking bridge deleted', () => { - for (const name of [ - 'codex-app-server-grant-bridge.ts', - 'codex-app-server-grant-entry.ts', - 'codex-app-server-grant-envelope.ts' - ]) { - expect(existsSync(join(CODEX_DIR, name))).toBe(false) - } - }) - - it('keeps the trust-grant lane on async entry points', () => { - const grant = readFileSync(join(CODEX_DIR, 'codex-hook-trust-grant.ts'), 'utf8') - expect(grant).toContain('export async function grantManagedCodexHookTrust(') - const host = readFileSync(join(CODEX_DIR, 'codex-trust-grant-host.ts'), 'utf8') - expect(host).toContain('export async function resolveCodexTrustGrantHost(') - const realHome = readFileSync(join(CODEX_DIR, 'codex-real-home-hook-install.ts'), 'utf8') - expect(realHome).toContain('}): Promise {') - }) -}) diff --git a/src/main/codex/config-toml-trust-api-parity.test.ts b/src/main/codex/config-toml-trust-stale-writes.test.ts similarity index 59% rename from src/main/codex/config-toml-trust-api-parity.test.ts rename to src/main/codex/config-toml-trust-stale-writes.test.ts index d20cde89b8e..6a8fb8398de 100644 --- a/src/main/codex/config-toml-trust-api-parity.test.ts +++ b/src/main/codex/config-toml-trust-stale-writes.test.ts @@ -1,12 +1,6 @@ -import { afterEach, describe, expect, expectTypeOf, it } from 'vitest' +import { afterEach, describe, expect, it } from 'vitest' import { chmodSync, readFileSync, readdirSync, statSync } from 'node:fs' import * as trustApi from './config-toml-trust' -import type { - CodexEventLabel, - CodexHookTrustState, - CodexProjectTrustLevel, - CodexTrustEntry -} from './config-toml-trust' import { createTrustConfigFixture, removeTrustConfigFixture @@ -20,42 +14,6 @@ afterEach(() => { } }) -describe('config-toml-trust public API', () => { - it('retains the exact runtime export surface', () => { - expect(Object.keys(trustApi).sort()).toEqual( - [ - 'codexHookSourcePathsEqual', - 'computeTrustKey', - 'computeTrustedHash', - 'escapeTomlString', - 'getCodexExplicitHomeHookSourcePath', - 'normalizeCodexHookSourcePath', - 'normalizeCodexProjectPathForLookup', - 'normalizeCodexProjectPathForRevocationLookup', - 'normalizeHookTrustKeyForLookup', - 'parseCodexProjectHeaderPath', - 'parseTrustKey', - 'readHookTrustEntries', - 'readHookTrustEntriesFromContent', - 'removeHookTrustEntries', - 'removeHookTrustEntriesFromContent', - 'upsertHookTrustEntries', - 'upsertHookTrustEntriesInContent', - 'upsertProjectTrustLevel', - 'upsertProjectTrustLevelInContent', - 'writeConfigAtomically' - ].sort() - ) - }) - - it('retains the public type contracts', () => { - expectTypeOf<'stop' | 'session_start'>().toMatchTypeOf() - expectTypeOf().toEqualTypeOf<'trusted' | 'untrusted'>() - expectTypeOf().toHaveProperty('sourcePath').toEqualTypeOf() - expectTypeOf().toEqualTypeOf() - }) -}) - describe('config.toml partial and stale writes', () => { it('preserves a truncated malformed prefix while appending trust', () => { const partial = ['model = "gpt-5"', '[mcp_servers.partial', 'command = "still-user-data'].join( diff --git a/src/main/crash-reporting/gpu-crash-diagnostics.test.ts b/src/main/crash-reporting/gpu-crash-diagnostics.test.ts index 1982facd5f3..09c4d3d7658 100644 --- a/src/main/crash-reporting/gpu-crash-diagnostics.test.ts +++ b/src/main/crash-reporting/gpu-crash-diagnostics.test.ts @@ -1,5 +1,3 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { buildGpuCrashDiagnostics, GpuCrashDiagnosticsRecorder } from './gpu-crash-diagnostics' @@ -223,29 +221,3 @@ describe('GpuCrashDiagnosticsRecorder', () => { expect(recordBreadcrumb).toHaveBeenCalledWith({ gpuInfoLevel: 'unavailable' }) }) }) - -describe('GPU crash diagnostics production wiring', () => { - it('starts diagnostics without delaying safe-graphics fallback', () => { - const source = readFileSync( - join(__dirname, '..', 'startup', 'main-process-preflight.ts'), - 'utf8' - ) - const listenerSource = readFileSync( - join(__dirname, '..', 'startup', 'main-process-ready-runtime.ts'), - 'utf8' - ) - const listenerStart = listenerSource.indexOf(" app.on('child-process-gone'") - expect(listenerStart).toBeGreaterThan(0) - const listener = listenerSource.slice( - listenerStart, - listenerSource.indexOf('\n })', listenerStart) - ) - expect(source).toMatch( - /recordBreadcrumb: \(data\) =>\s*recordDurableCrashBreadcrumb\('gpu_crash_hardware', data\)/ - ) - expect(listener).toMatch( - /const crashedAt = performance\.now\(\)[\s\S]*?void state\.gpuCrashDiagnostics\?\.record\(\)[\s\S]*?void handleGpuChildCrash\(details\.reason, details\.exitCode \?\? null, crashedAt\)/ - ) - expect(listener).not.toMatch(/state\.gpuCrashDiagnostics\?\.record\(\)[\s\S]*?\.then\(/) - }) -}) diff --git a/src/main/crash-reporting/gpu-crash-fallback-field-sessions.test.ts b/src/main/crash-reporting/gpu-crash-fallback-field-sessions.test.ts index 43441250708..4454bc48457 100644 --- a/src/main/crash-reporting/gpu-crash-fallback-field-sessions.test.ts +++ b/src/main/crash-reporting/gpu-crash-fallback-field-sessions.test.ts @@ -1,55 +1,9 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD, DEFAULT_GPU_CRASH_FALLBACK_WINDOW_MS, - GpuCrashFallbackTracker, - isGpuFallbackCrashCandidate + GpuCrashFallbackTracker } from './gpu-crash-fallback-decision' -import { shouldRecordProcessGoneCrash } from './process-gone-classification' - -/** - * Replays the win32 GPU-child deaths from the 1.4.190 'crashed' renderer cluster - * through the production decision path, so the reason no host was ever offered - * Safe Graphics Mode is pinned rather than argued about. - * - * Each session below is one crash report's `Recent activity`; a breadcrumb's - * `suppressedSinceLast=N` means N further identical GPU deaths were coalesced - * into it, so the session saw N+1 GPU crashes. - */ - -type FieldSession = { - /** Crash-report id from the field bundle. */ - report: string - /** GPU child crash times, ms since main-process start. */ - gpuCrashesMsSinceLaunch: number[] -} - -// crashed.txt: every win32 report in the cluster. Times are (breadcrumb ts - -// mainProcessStartedAt); coalesced repeats are placed inside the same second, -// which is the only interval the emitted breadcrumb pins them to. -const CRASHED_CLUSTER_SESSIONS: FieldSession[] = [ - // 23:36:54.200 - 23:36:49.931, suppressedSinceLast=1 -> 2 crashes - { report: 'db1f1ee2', gpuCrashesMsSinceLaunch: [4_269, 4_800] }, - // 02:58:25.287 - 02:58:20.749, no suppression -> 1 crash - { report: '66cc54d8', gpuCrashesMsSinceLaunch: [4_538] }, - // 21:47:05.776 - 21:46:59.584, suppressedSinceLast=1 -> 2 crashes - { report: '1f5564de', gpuCrashesMsSinceLaunch: [6_192, 6_240] }, - // 00:17:17.840 - 00:17:15.732, no suppression -> 1 crash - { report: '96d8c63b', gpuCrashesMsSinceLaunch: [2_108] } -] - -/** Ready-phase `child-process-gone` listener body — the wiring these claims rest on. */ -function readChildProcessGoneListener(): string { - const source = readFileSync( - join(__dirname, '..', 'startup', 'main-process-ready-runtime.ts'), - 'utf8' - ) - const start = source.indexOf(" app.on('child-process-gone'") - expect(start).toBeGreaterThan(0) - return source.slice(start, source.indexOf('\n })', start)) -} function newTracker(): GpuCrashFallbackTracker { return new GpuCrashFallbackTracker({ @@ -58,73 +12,7 @@ function newTracker(): GpuCrashFallbackTracker { }) } -const FIELD_GPU_EVENT = { - source: 'child', - processType: 'GPU', - serviceName: 'GPU', - reason: 'crashed', - expectedTeardown: 'none' -} as const - describe('1.4.190 win32 GPU-child crash cluster', () => { - it('does not let process_gone_suppressed gate the fallback candidate check', () => { - // The GPU death is suppressed as recoverable churn (no user-facing report)... - expect( - shouldRecordProcessGoneCrash({ - ...FIELD_GPU_EVENT, - platform: 'win32', - exitCode: -2147483645 - }) - ).toBe(false) - // ...but the fallback path reads the raw child-process-gone event, so the - // suppression cannot hide a broken driver from recovery. - expect( - isGpuFallbackCrashCandidate({ - platform: 'win32', - processType: 'GPU', - reason: 'crashed' - }) - ).toBe(true) - // Both assertions above still pass if the candidate check is moved behind the - // suppressed-report path, so pin that nothing branches ahead of it in index.ts. - const listener = readChildProcessGoneListener() - const guardStart = listener.indexOf('isGpuFallbackCrashCandidate(') - expect(guardStart).toBeGreaterThan(0) - expect(listener.slice(0, guardStart).match(/\bif\s*\(/g) ?? []).toHaveLength(1) - expect(listener).toMatch( - /isGpuFallbackCrashCandidate\([\s\S]*?state\.gpuCrashDiagnostics\?\.record\(\)[\s\S]*?handleGpuChildCrash\(/ - ) - // The `if (` count alone still allows `recorded && isGpuFallbackCrashCandidate(...)`, which - // re-couples recovery to the suppression decision, so pin the guard to that check alone. - const recoveryGuard = listener.slice( - listener.lastIndexOf('if (', guardStart), - listener.indexOf('handleGpuChildCrash(') - ) - expect(recoveryGuard).not.toMatch(/&&|\|\|/) - }) - - it('never reaches the burst threshold in any observed cluster session', () => { - const outcomes = CRASHED_CLUSTER_SESSIONS.map((session) => { - // Each launch constructs a fresh tracker (src/main/index.ts), so evidence - // does not survive the relaunch these users performed after every crash. - const tracker = newTracker() - const engaged = session.gpuCrashesMsSinceLaunch.some( - (at) => tracker.recordGpuCrash(at).shouldEngageFallback - ) - return { - report: session.report, - gpuCrashes: session.gpuCrashesMsSinceLaunch.length, - engagedSafeGraphicsPrompt: engaged - } - }) - expect(outcomes).toEqual([ - { report: 'db1f1ee2', gpuCrashes: 2, engagedSafeGraphicsPrompt: false }, - { report: '66cc54d8', gpuCrashes: 1, engagedSafeGraphicsPrompt: false }, - { report: '1f5564de', gpuCrashes: 2, engagedSafeGraphicsPrompt: false }, - { report: '96d8c63b', gpuCrashes: 1, engagedSafeGraphicsPrompt: false } - ]) - }) - it('engages on the session that did reach three crashes (field launch 51b9e93c)', () => { // oom.txt, win32: GPU crashed/exitCode=34 with suppressedSinceLast=2, then // `gpu_fallback_engaged (crashesInWindow=3)` and `gpu_fallback_restart_deferred`. diff --git a/src/main/crash-reporting/gpu-fallback-recovered-launch.test.ts b/src/main/crash-reporting/gpu-fallback-recovered-launch.test.ts index 23707754ff8..dd918ba9397 100644 --- a/src/main/crash-reporting/gpu-fallback-recovered-launch.test.ts +++ b/src/main/crash-reporting/gpu-fallback-recovered-launch.test.ts @@ -1,5 +1,3 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' const { showMessageBoxMock } = vi.hoisted(() => ({ @@ -105,22 +103,3 @@ describe('handleGpuFallbackRecoveredLaunch', () => { expect(handlers.restartWithHardware).not.toHaveBeenCalled() }) }) - -describe('recovered safe-graphics production wiring', () => { - it('prompts only after the recovered window is shown and persists both consent states', () => { - const windowSource = readFileSync( - join(__dirname, '..', 'startup', 'main-window-controller.ts'), - 'utf8' - ) - const lifecycleSource = readFileSync( - join(__dirname, '..', 'startup', 'gpu-lifecycle.ts'), - 'utf8' - ) - expect(windowSource).toMatch( - /window\.once\('show',[\s\S]*?presentGpuFallbackRecoveredLaunchPrompt\(window\)/ - ) - expect(lifecycleSource).toMatch( - /persistMarker:[\s\S]*?userConfirmed: false[\s\S]*?confirmMarker:[\s\S]*?userConfirmed: true/ - ) - }) -}) diff --git a/src/main/github/work-item-details-api-parity.test.ts b/src/main/github/work-item-details-api-parity.test.ts deleted file mode 100644 index 187680f64cd..00000000000 --- a/src/main/github/work-item-details-api-parity.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, expectTypeOf, it } from 'vitest' -import type { GitHubPRFile, GitHubPRFileContents } from '../../shared/github/pull-request-types' -import type { GitHubWorkItemDetails } from '../../shared/github/work-item-types' -import type { IssueSourcePreference } from '../../shared/repo-types' -import type { LocalGitExecOptions } from './gh-utils' -import type { GitHubApiRepository } from './github-api-repository' -import * as workItemDetails from './work-item-details' - -type GetWorkItemDetails = ( - repoPath: string, - number: number, - type?: 'issue' | 'pr', - connectionId?: string | null, - localGitOptions?: LocalGitExecOptions, - preference?: IssueSourcePreference -) => Promise - -type GetPRFileContents = (args: { - repoPath: string - connectionId?: string | null - localGitOptions?: LocalGitExecOptions - prRepo?: GitHubApiRepository | null - prNumber: number - path: string - oldPath?: string - status: GitHubPRFile['status'] - headSha: string - baseSha: string -}) => Promise - -describe('work-item-details public API parity', () => { - it('retains only the established runtime exports and call signatures', () => { - expect(Object.keys(workItemDetails).sort()).toEqual(['getPRFileContents', 'getWorkItemDetails']) - expectTypeOf(workItemDetails.getWorkItemDetails).toEqualTypeOf() - expectTypeOf(workItemDetails.getPRFileContents).toEqualTypeOf() - }) -}) diff --git a/src/main/headless-automation-dispatcher-source-boundary.test.ts b/src/main/headless-automation-dispatcher-source-boundary.test.ts deleted file mode 100644 index 5f7a10fedec..00000000000 --- a/src/main/headless-automation-dispatcher-source-boundary.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const source = readFileSync(join(__dirname, 'startup', 'main-process-automations.ts'), 'utf8') - -function sourceBetween(startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('headless automation dispatcher source boundaries', () => { - it('creates new-per-run workspaces from the resolved run target repo', () => { - const createArgsSection = sourceBetween('buildHeadlessAutomationWorktreeCreateArgs({', '})') - - expect(createArgsSection).toContain('repo: target.repo') - expect(createArgsSection).not.toContain('automation.sourceContext') - }) -}) diff --git a/src/main/ipc/filesystem-watcher-real.test.ts b/src/main/ipc/filesystem-watcher-real.test.ts index 6bd5060fb0e..f884e596f72 100644 --- a/src/main/ipc/filesystem-watcher-real.test.ts +++ b/src/main/ipc/filesystem-watcher-real.test.ts @@ -77,15 +77,6 @@ describe('filesystem-watcher real @parcel/watcher integration', () => { vi.clearAllMocks() }) - // Why: a clear, separate failure mode — if the native addon is missing from - // the bundle the watcher silently no-ops (doInstallLocalWatcher swallows the - // import error), so the wiring assertion below would time out with a vague - // message. This makes "addon absent" distinct from "wiring broken". - it('loads the real @parcel/watcher native addon', async () => { - const watcher = await import('@parcel/watcher') - expect(typeof watcher.subscribe).toBe('function') - }) - // Why: this integration targets the Linux native watcher path described // above; macOS developer sandboxes can load the addon while suppressing // subscribe callbacks, which makes this an environment check instead. diff --git a/src/main/ipc/github-ipc-channel-parity.test.ts b/src/main/ipc/github-ipc-channel-parity.test.ts deleted file mode 100644 index 1746890199a..00000000000 --- a/src/main/ipc/github-ipc-channel-parity.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { readFileSync } from 'node:fs' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = await vi.hoisted(async () => { - const { createGitHubIpcMocks } = await import('./github-ipc-module-mocks') - return createGitHubIpcMocks() -}) - -vi.mock('electron', () => mocks.electron) -vi.mock('../github/client', () => mocks.client) -vi.mock('../github/work-item-details', () => mocks.workItemDetails) -vi.mock('../github/pr-refresh-coordinator', () => mocks.prRefresh) -vi.mock('../telemetry/client', () => mocks.telemetry) -vi.mock('../telemetry/cohort-classifier', () => mocks.cohort) -vi.mock('./ui', () => mocks.ui) - -import * as github from './github' -import { createGitHubIpcHarness } from './github-ipc-test-harness' - -const EXPECTED_GITHUB_IPC_CHANNELS = [ - 'gh:prForBranch', - 'gh:refreshPRNow', - 'gh:enqueuePRRefresh', - 'gh:reportVisiblePRRefreshCandidates', - 'gh:issue', - 'gh:listIssues', - 'gh:createIssue', - 'gh:listWorkItems', - 'gh:countWorkItems', - 'gh:workItem', - 'gh:workItemByOwnerRepo', - 'gh:workItemDetails', - 'gh:notifyWorkItemMutated', - 'gh:prFileContents', - 'gh:repoSlug', - 'gh:repoUpstream', - 'gh:prChecks', - 'gh:prCheckDetails', - 'gh:prComments', - 'gh:setPRCommentReaction', - 'gh:resolveReviewThread', - 'gh:setPRFileViewed', - 'gh:addPRReviewCommentReply', - 'gh:addPRReviewComment', - 'gh:updatePRTitle', - 'gh:mergePR', - 'gh:setPRAutoMerge', - 'gh:updatePRState', - 'gh:markPRReadyForReview', - 'gh:rerunPRChecks', - 'gh:requestPRReviewers', - 'gh:removePRReviewers', - 'gh:updateIssue', - 'gh:addIssueComment', - 'gh:listLabels', - 'gh:listAssignableUsers', - 'gh:viewer', - 'gh:checkOrcaStarred', - 'gh:starOrca', - 'gh:rateLimit', - 'gh:diagnoseAuth', - 'gh:listBindableAccounts', - 'gh:validateAccountBinding', - 'gh:listAccessibleProjects', - 'gh:resolveProjectRef', - 'gh:listProjectViews', - 'gh:getProjectViewTable', - 'gh:projectWorkItemDetailsBySlug', - 'gh:updateProjectItemField', - 'gh:clearProjectItemField', - 'gh:updateIssueBySlug', - 'gh:updatePullRequestBySlug', - 'gh:addIssueCommentBySlug', - 'gh:updateIssueCommentBySlug', - 'gh:deleteIssueCommentBySlug', - 'gh:listLabelsBySlug', - 'gh:listAssignableUsersBySlug', - 'gh:listIssueTypesBySlug', - 'gh:updateIssueTypeBySlug' -] as const - -describe('GitHub IPC channel parity', () => { - const harness = createGitHubIpcHarness(mocks) - - beforeEach(harness.reset) - - it('preserves the facade and fixed IPC channel contract', () => { - github.registerGitHubHandlers(harness.store as never, harness.stats as never) - - // The preload facade now composes the two GitHub bridge owners; inspect - // both owners so the channel census remains tied to the actual invokes. - const preloadSource = [ - '../../preload/api/gh-bridge-pull-requests-and-work-items.ts', - '../../preload/api/gh-bridge-mutations-and-projects.ts' - ] - .map((relativePath) => readFileSync(new URL(relativePath, import.meta.url), 'utf8')) - .join('\n') - const exposedChannels = [...preloadSource.matchAll(/ipcRenderer\.invoke\('(gh:[^']+)'/g)].map( - (match) => match[1] - ) - const registeredChannels = mocks.electron.ipcMain.handle.mock.calls.map( - ([channel]) => channel as string - ) - - expect(Object.keys(github)).toEqual(['registerGitHubHandlers']) - expect(new Set(registeredChannels).size).toBe(registeredChannels.length) - expect(registeredChannels).toEqual(EXPECTED_GITHUB_IPC_CHANNELS) - expect(registeredChannels.toSorted()).toEqual([...new Set(exposedChannels)].toSorted()) - }) -}) diff --git a/src/main/ipc/pty/pty-spawn-shell-override-parity.test.ts b/src/main/ipc/pty/pty-spawn-shell-override-parity.test.ts deleted file mode 100644 index 67bee9ca700..00000000000 --- a/src/main/ipc/pty/pty-spawn-shell-override-parity.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -/** - * The two spawn preflights are twins: one serves renderer/IPC spawns, the other serves runtime - * spawns (`terminal.create` from the CLI, headless serve, and paired remote environments). They - * had drifted — the runtime twin passed a literal `undefined` for the caller's shell, so on a - * Windows host a runtime-created terminal could only ever be the host's default shell. A caller - * asking for cmd or PowerShell had to send it as `command`, which the provider TYPES into that - * default shell: the pty stayed the default shell with the requested one running inside it, and - * leaving that child dropped the caller's handle back onto a prompt it never asked for. - * - * Source-level because the functional seam is a whole spawn pipeline; what actually regressed is - * one twin silently not reading a field the other reads. - */ -const PREFLIGHTS = ['ipc', 'runtime'] as const - -describe.each(PREFLIGHTS)('%s pty spawn preflight', (lane) => { - const source = readFileSync(join(__dirname, lane, 'spawn-preflight.ts'), 'utf8') - - it("resolves Windows terminal runtime options from the caller's requested shell", () => { - expect(source).toContain('requestedShellOverride: args.shellOverride') - expect(source).not.toContain('requestedShellOverride: undefined') - }) -}) diff --git a/src/main/pi/titlebar-extension-service.test.ts b/src/main/pi/titlebar-extension-service.test.ts index 6b66d7f337f..bc259e893a9 100644 --- a/src/main/pi/titlebar-extension-service.test.ts +++ b/src/main/pi/titlebar-extension-service.test.ts @@ -277,7 +277,6 @@ describe('PiTitlebarExtensionService', () => { const env = svc.buildPtyEnv('pty-omp-sqlite', piHome, 'omp') const sourcePath = join(piHome, 'agent.db') - const content = 'agent.db credentials' expect(env.PI_CODING_AGENT_DIR).toBeUndefined() expect(readFileSync(env.ORCA_OMP_FRESH_CONFIG, 'utf8')).toBe('autoResume: false\n') @@ -287,9 +286,6 @@ describe('PiTitlebarExtensionService', () => { expect(existsSync(sourcePath)).toBe(false) expect(existsSync(join(userDataDir, 'omp-agent-overlays'))).toBe(false) expect(existsSync(join(piHome, 'history.db'))).toBe(false) - writeFileSync(sourcePath, content) - - expect(readFileSync(sourcePath, 'utf-8')).toBe(content) }) it('migrates missing OMP state from the old source overlay without overwriting source files', () => { diff --git a/src/main/ports/port-scan-command-client.test.ts b/src/main/ports/port-scan-command-client.test.ts index 37e8451a4da..d79fe80fbbd 100644 --- a/src/main/ports/port-scan-command-client.test.ts +++ b/src/main/ports/port-scan-command-client.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { join, sep } from 'node:path' import { Worker } from 'node:worker_threads' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -244,17 +243,6 @@ describe('resolveWorkerEntryPath', () => { expect(resolved).toBe(join(moduleDir, WORKER_ENTRY_FILENAME)) expect(resolved).not.toContain('app.asar') }) - - // A rename in the build config would leave both branches pointing at a file - // that is never emitted, and only the packaged one fails silently. - it('names the entry the main build actually emits', () => { - const config = readFileSync( - join(import.meta.dirname, '..', '..', '..', 'electron.vite.config.ts'), - 'utf8' - ) - - expect(config).toContain("'port-scan-command-worker-entry': resolve(") - }) }) const REAL_WORKER_BLOCK_MS = 800 diff --git a/src/main/ports/port-scan-command-import-boundary.test.ts b/src/main/ports/port-scan-command-import-boundary.test.ts deleted file mode 100644 index bd9b9d05fb8..00000000000 --- a/src/main/ports/port-scan-command-import-boundary.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -// Why (#11161): libuv runs process creation inline on the calling event loop, -// so the port scan only stays off CrBrowserMain while these main-thread modules -// spawn nothing themselves. Spawning belongs to port-scan-command-execution.ts, -// which only the worker entry imports. -const MAIN_THREAD_MODULES = ['local-workspace-port-scanner.ts', 'port-scan-command-client.ts'] - -describe('port scan main-thread spawn boundary', () => { - it.each(MAIN_THREAD_MODULES)('keeps %s free of child_process', (fileName) => { - const source = readFileSync(join(import.meta.dirname, fileName), 'utf8') - - expect(source).not.toMatch(/from\s+['"](node:)?child_process['"]/) - expect(source).not.toMatch(/require\(\s*['"](node:)?child_process['"]\s*\)/) - }) -}) diff --git a/src/main/providers/settled-pty-writer-census.test.ts b/src/main/providers/settled-pty-writer-census.test.ts deleted file mode 100644 index 08dd9989400..00000000000 --- a/src/main/providers/settled-pty-writer-census.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { execFileSync } from 'node:child_process' -import { describe, expect, it, vi } from 'vitest' -import { LocalPtyProvider } from './local-pty-provider' -import { SshPtyProvider } from './ssh-pty-provider' -import { createMockMux } from './ssh-pty-provider-mock-multiplexer' -import { DaemonPtyRouter } from '../daemon/daemon-pty-router' -import { DegradedDaemonPtyProvider } from '../daemon/degraded-daemon-pty-provider' -import { DaemonPtyAdapter } from '../daemon/daemon-pty-adapter' - -vi.mock('electron', () => ({ - app: { getPath: vi.fn(() => '/tmp'), isPackaged: false }, - BrowserWindow: { fromId: vi.fn(() => null) }, - ipcMain: { on: vi.fn(), removeListener: vi.fn() }, - webContents: { fromId: vi.fn(() => null) } -})) - -const REPO_ROOT = join(__dirname, '..', '..', '..') - -/** - * Requiring the method is satisfiable by a lie: the degraded daemon router used to answer it - * with `provider.write(...) !== false`, reproducing the fire-and-forget bug through the fix. - * The census pins the producers and reads their bodies, so a new provider or a revived - * fabricated handoff fails here rather than silently clearing a mailbox reservation. - */ -const SETTLED_PTY_WRITER_FILES = [ - 'src/main/providers/local-pty-provider.ts', - 'src/main/providers/ssh-pty-provider.ts', - 'src/main/daemon/daemon-pty-router.ts', - 'src/main/daemon/degraded-daemon-pty-provider.ts', - 'src/main/daemon/daemon-pty-adapter.ts' -] - -/** Where the provider-side settlement is actually decided; the adapter inherits its own. */ -const SETTLED_WRITER_DECLARATIONS = [ - 'src/main/providers/local-pty-provider.ts', - 'src/main/providers/ssh-pty-provider.ts', - 'src/main/providers/ssh-pty-provider-rpc-operations.ts', - 'src/main/daemon/daemon-pty-router.ts', - 'src/main/daemon/degraded-daemon-pty-provider.ts', - 'src/main/daemon/daemon-pty-session-input.ts' -] - -function declaredProviderFiles(): string[] { - const output = execFileSync('git', ['grep', '-l', '--', 'implements IPtyProvider', 'src/main'], { - cwd: REPO_ROOT, - encoding: 'utf8' - }) - // Tests may name the clause while pinning it; only production declarations count. - return output - .split('\n') - .filter((file) => file && !file.endsWith('.test.ts')) - .sort() -} - -function settledWriterBody(file: string): string { - const source = readFileSync(join(REPO_ROOT, file), 'utf8') - const start = source.indexOf('writeWithSettlement') - expect(start, `${file} declares no settled writer`).toBeGreaterThan(-1) - const end = source.indexOf('\n }', start) - return source.slice(start, end === -1 ? source.length : end) -} - -describe('settled PTY writer census', () => { - it('covers every production provider class that declares IPtyProvider', () => { - expect(declaredProviderFiles()).toEqual([...SETTLED_PTY_WRITER_FILES].sort()) - }) - - it('exposes a settled writer on every production provider instance', () => { - const daemonClient = { isConnected: () => false, onEvent: vi.fn(() => vi.fn()) } - const adapter = new DaemonPtyAdapter(daemonClient as never) - const instances = [ - new LocalPtyProvider({} as never), - new SshPtyProvider('conn-census', createMockMux() as never), - new DaemonPtyRouter({ current: adapter, legacy: [] }), - new DegradedDaemonPtyProvider({ - current: adapter, - legacy: [], - fallback: new LocalPtyProvider({} as never) - }), - adapter - ] - for (const provider of instances) { - expect(typeof provider.writeWithSettlement, provider.constructor.name).toBe('function') - } - }) - - it('never synthesizes a settlement from the fire-and-forget write', () => { - for (const file of SETTLED_WRITER_DECLARATIONS) { - expect(settledWriterBody(file), file).not.toMatch(/\.write\(/) - } - }) -}) diff --git a/src/main/providers/ssh-filesystem-provider.test.ts b/src/main/providers/ssh-filesystem-provider.test.ts index a20dfb98d9b..0917c4cf81a 100644 --- a/src/main/providers/ssh-filesystem-provider.test.ts +++ b/src/main/providers/ssh-filesystem-provider.test.ts @@ -527,18 +527,6 @@ describe('SshFilesystemProvider', () => { }) describe('watch', () => { - it('sends fs.watch request and returns unsubscribe', async () => { - const callback = vi.fn() - const unsub = await provider.watch('/home/user/project', callback) - - expect(mux.request).toHaveBeenCalledWith( - 'fs.watch', - { rootPath: '/home/user/project', watchId: expect.any(Number) }, - { signal: expect.any(AbortSignal) } - ) - expect(typeof unsub).toBe('function') - }) - it('uses a registration-owned cancellation signal for the mux fs.watch request', async () => { mux.request.mockResolvedValue(undefined) const controller = new AbortController() diff --git a/src/main/quit-teardown-agent-browser-daemons.test.ts b/src/main/quit-teardown-agent-browser-daemons.test.ts deleted file mode 100644 index 315eba73aa0..00000000000 --- a/src/main/quit-teardown-agent-browser-daemons.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -/** - * agent-browser forks a daemon per browser tab that Orca holds no handle on, and - * `destroyAllSessions` closes each one by spawning another agent-browser child — - * hundreds of ms apiece. Left off the will-quit barrier, `app.quit()` fired first and - * every open tab's daemon outlived the app (#16367). - */ -const source = readFileSync(join(__dirname, 'startup', 'main-process-quit.ts'), 'utf8') - -function teardownBarrierMembers(): string { - const start = source.indexOf('settleTeardownWithinDeadline([') - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf('])', start) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('quit teardown of agent-browser daemons', () => { - it('joins the will-quit teardown barrier', () => { - expect(teardownBarrierMembers()).toContain("{ name: 'browser', promise: browserShutdown }") - }) - - it('captures the destroyAllSessions promise instead of firing and forgetting', () => { - expect(source).toMatch( - /const browserShutdown = \(async \(\): Promise => \{[\s\S]*?await state\.runtime\?\.getAgentBrowserBridge\(\)\?\.destroyAllSessions\(\)\s+\}\)\(\)/ - ) - // Why: a second, uncaptured call site is the pre-fix shape — it loses the race to app.quit(). - expect(source.match(/getAgentBrowserBridge\(\)\?\.destroyAllSessions\(\)/g)).toHaveLength(1) - }) -}) diff --git a/src/main/rate-limits/minimax/minimax-fetcher.test.ts b/src/main/rate-limits/minimax/minimax-fetcher.test.ts index d587c6b9256..d03c6a7c589 100644 --- a/src/main/rate-limits/minimax/minimax-fetcher.test.ts +++ b/src/main/rate-limits/minimax/minimax-fetcher.test.ts @@ -19,12 +19,7 @@ vi.mock('electron', () => ({ session: { fromPartition: sessionFromPartitionMock } })) -import { - extractMiniMaxCookieValue, - fetchMiniMaxRateLimits, - normalizeMiniMaxCookieHeader, - redactMiniMaxSecret -} from './minimax-fetcher' +import { fetchMiniMaxRateLimits } from './minimax-fetcher' const MINIMAX_URL = 'https://platform.minimax.io/v1/api/openplatform/coding_plan/remains' @@ -646,54 +641,3 @@ describe('fetchMiniMaxRateLimits', () => { }) }) }) - -describe('normalizeMiniMaxCookieHeader', () => { - it('preserves all cookie pairs from a browser Cookie header', () => { - const normalized = normalizeMiniMaxCookieHeader( - '_token=tok; session=other; ak_bmsc=ak; minimax_group_id_v2=42; random=xyz' - ) - expect(normalized).toBe( - '_token=tok; session=other; ak_bmsc=ak; minimax_group_id_v2=42; random=xyz' - ) - }) - - it('normalizes quoted MiniMax cookie storage syntax', () => { - expect(normalizeMiniMaxCookieHeader('_token:"tok" minimax_group_id_v2:"42"')).toBe( - '_token=tok; minimax_group_id_v2=42' - ) - }) - - it('accepts a copied Cookie header line', () => { - expect(normalizeMiniMaxCookieHeader('Cookie: session=abc; other=xyz')).toBe( - 'session=abc; other=xyz' - ) - }) -}) - -describe('extractMiniMaxCookieValue', () => { - it('returns the value for a given cookie name', () => { - expect(extractMiniMaxCookieValue(FULL_COOKIE, 'minimax_group_id_v2')).toBe('12345') - }) - it('returns null when the name is absent', () => { - expect(extractMiniMaxCookieValue('_token=tok', 'minimax_group_id_v2')).toBeNull() - }) -}) - -describe('redactMiniMaxSecret', () => { - it('redacts _token values', () => { - expect(redactMiniMaxSecret('cookie _token=eyJhABCDEF')).toContain('_token=[REDACTED]') - expect(redactMiniMaxSecret('cookie _token=eyJhABCDEF')).not.toContain('eyJhABCDEF') - }) - it('redacts minimax_group_id_v2 values', () => { - expect(redactMiniMaxSecret('minimax_group_id_v2=99999 trailing')).not.toContain('99999') - }) - it('redacts MiniMax anti-bot cookie values', () => { - const redacted = redactMiniMaxSecret('ak_bmsc=secret bm_sv:"secret2"') - expect(redacted).not.toContain('secret') - expect(redacted).toContain('ak_bmsc=[REDACTED]') - expect(redacted).toContain('bm_sv:[REDACTED]') - }) - it('redacts Cookie: header lines', () => { - expect(redactMiniMaxSecret('X-Cookie: _token=secret')).toContain('[REDACTED]') - }) -}) diff --git a/src/main/runtime/agent-session-launch-env-backfill.test.ts b/src/main/runtime/agent-session-launch-env-backfill.test.ts deleted file mode 100644 index 50cf9e6b35c..00000000000 --- a/src/main/runtime/agent-session-launch-env-backfill.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { AgentSessionRecordStore } from './agent-session-record-store' -import type { AgentSessionReserveRequest } from './agent-session-reservation-admission' - -const NOW = 1_800_000_000_000 -const SESSION = 'session-launch-env' -let directory: string - -function request(overrides: Partial = {}): AgentSessionReserveRequest { - return { - sessionId: SESSION, - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'git-worktree' - }, - provider: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/home/dev/.claude' }, - expectedFence: null, - spawnToken: 'spawn-a', - claimKeyId: 'key-1', - handoffOperationId: null, - probe: { outcome: 'reservation-unused' }, - operation: { - callerKey: 'client-1', - operationId: `${NOW}-00000000000000000000000000000001`, - fingerprint: 'fp-1' - }, - now: NOW, - ...overrides - } -} - -beforeEach(async () => { - directory = await mkdtemp(join(tmpdir(), 'orca-agent-session-launch-env-')) -}) - -afterEach(async () => { - await rm(directory, { recursive: true, force: true }) -}) - -describe('legacy agent session launch environment', () => { - it('durably pins the first environment resolved by a current reservation', async () => { - const store = await AgentSessionRecordStore.open({ directory, hostId: 'local' }) - await store.reserveOwner(request()) - await store.reserveOwner( - request({ - expectedFence: 1, - spawnToken: 'spawn-b', - launchEnv: { ANTHROPIC_AUTH_TOKEN: 'pinned-token' }, - operation: { - callerKey: 'client-1', - operationId: `${NOW}-00000000000000000000000000000002`, - fingerprint: 'fp-2' - } - }) - ) - - const reopened = await AgentSessionRecordStore.open({ directory, hostId: 'local' }) - expect( - (reopened.getRecord(SESSION) as { launchEnv?: Record } | null)?.launchEnv - ).toBeUndefined() - }) - - it('rejects an environment that could not be reloaded before writing it', async () => { - const store = await AgentSessionRecordStore.open({ directory, hostId: 'local' }) - const launchEnv = Object.fromEntries( - Array.from({ length: 257 }, (_, index) => [`KEY_${index}`, 'value']) - ) - - await expect(store.reserveOwner(request({ launchEnv }))).rejects.toThrow( - 'agent_session_launch_env_invalid' - ) - expect(store.getRecord(SESSION)).toBeNull() - }) - - it('rejects an overlong environment key before writing it', async () => { - const store = await AgentSessionRecordStore.open({ directory, hostId: 'local' }) - - await expect( - store.reserveOwner(request({ launchEnv: { ['K'.repeat(513)]: 'value' } })) - ).rejects.toThrow('agent_session_launch_env_invalid') - expect(store.getRecord(SESSION)).toBeNull() - }) -}) diff --git a/src/main/runtime/agent-startup-input-assembly-census.test.ts b/src/main/runtime/agent-startup-input-assembly-census.test.ts deleted file mode 100644 index ca05ed03648..00000000000 --- a/src/main/runtime/agent-startup-input-assembly-census.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const REPO_ROOT = join(import.meta.dirname, '../../..') - -/** - * The host modules that turn settings into `buildAgentStartupPlan` inputs. - * - * `buildAgentStartupPlan` was always shared; the input assembly was not, and the hand-rolled - * copies drifted — one dropped `sessionOptionsOverrideAgentArgs` and let configured args defeat a - * picked model. This pins the funnel so a sixth host site cannot re-derive the inputs by hand. - */ -const MIGRATED_HOST_LAUNCH_MODULES = [ - 'src/main/runtime/orca-runtime-create-agent-session.ts', - 'src/main/runtime/orca-runtime-resolve-mobile-session-terminal-command.ts', - 'src/main/runtime/orca-runtime-resolve-worktree-removal-target.ts', - 'src/main/runtime/runtime-worktree-agent-startup.ts' -] - -/** Reading any of these next to a startup plan means the inputs are being assembled by hand. */ -const HAND_ASSEMBLY_MARKERS = [ - 'resolveTuiAgentLaunchArgs(', - 'resolveTuiAgentLaunchEnv(', - 'resolveLocalWindowsAgentStartupShell(' -] - -function read(file: string): string { - return readFileSync(join(REPO_ROOT, file), 'utf8') -} - -describe('host agent-startup input assembly census', () => { - it('routes every migrated host launch site through the shared resolver', () => { - const missing = MIGRATED_HOST_LAUNCH_MODULES.filter( - (file) => !read(file).includes('resolveAgentStartupPlanInputs(') - ) - expect(missing).toEqual([]) - }) - - it('leaves no migrated host site assembling the settings-derived inputs by hand', () => { - const handAssembled = MIGRATED_HOST_LAUNCH_MODULES.filter((file) => { - const source = read(file) - return HAND_ASSEMBLY_MARKERS.some((marker) => source.includes(marker)) - }) - expect(handAssembled).toEqual([]) - }) - - it('detects hand assembly when it is present', () => { - // Positive control: the markers are real names, so an empty result above is a true negative - // rather than a typo that can never match. - const resumeSite = read( - 'src/main/runtime/orca-runtime-get-agent-session-execution-namespace.ts' - ) - expect(HAND_ASSEMBLY_MARKERS.some((marker) => resumeSite.includes(marker))).toBe(true) - }) -}) diff --git a/src/main/runtime/client-hosted-browser-row-hydration-census.test.ts b/src/main/runtime/client-hosted-browser-row-hydration-census.test.ts deleted file mode 100644 index e50e066a544..00000000000 --- a/src/main/runtime/client-hosted-browser-row-hydration-census.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { glob } from 'tinyglobby' - -const REPO_ROOT = join(import.meta.dirname, '../../..') -const CENSUS_FILE = 'src/main/runtime/client-hosted-browser-row-hydration-census.test.ts' - -/** - * `deliverHydrationSnapshot` reads like a getter and is not one: it replaces the publisher's record - * of which workspaces the renderer holds rows for. A second caller that reasonably treats it as a - * peek — a status panel, a diagnostic dump, a second window's look-ahead — would clear that record - * out from under the live renderer, and the rows it is showing become unretractable. That is the - * exact defect this round shipped a fix for, so the single-caller shape is pinned rather than - * trusted to the name. - */ -async function countCallSites(pattern: RegExp): Promise> { - const files = await glob(['src/**/*.ts', 'src/**/*.tsx'], { - cwd: REPO_ROOT, - ignore: ['**/node_modules/**', '**/*.test.ts', '**/*.test.tsx', CENSUS_FILE] - }) - const counts: Record = {} - for (const file of files) { - // Counted per file, not merely detected: two call sites in one file mask each other. - const hits = readFileSync(join(REPO_ROOT, file), 'utf8').match(pattern)?.length ?? 0 - if (hits > 0) { - counts[file] = hits - } - } - return counts -} - -// Anchored on the member-call shape rather than the bare name, so the declaration does not count -// itself and prose about the method does not have to be kept out of the file. -const DELIVER_CALL = /\.deliverHydrationSnapshot\(/g -const LIST_CALL = /\.listClientHostedBrowserRows\(/g - -describe('client-hosted row hydration caller census', () => { - it('keeps the hydration delivery to its one runtime caller', async () => { - expect(await countCallSites(DELIVER_CALL)).toEqual({ - 'src/main/runtime/orca-runtime-stored-mobile-snapshot-has-stale-preserved-tab.ts': 1 - }) - }) - - // The IPC handler is the other half of the same invariant: it is what turns one renderer's - // hydration request into one delivery, so a second production reader would arrive through here. - it('keeps the runtime accessor to its one IPC caller', async () => { - expect(await countCallSites(LIST_CALL)).toEqual({ - 'src/main/ipc/runtime.ts': 1 - }) - }) - - // Why: the two censuses above pass by finding what is already there, so a matcher that had - // stopped matching would read the same as a clean repo. Prove it counts a second caller. - it('counts a second caller rather than reporting the same single site', () => { - const source = ` - const a = runtime.deliverHydrationSnapshot() - const b = other.deliverHydrationSnapshot() - ` - expect(source.match(DELIVER_CALL)?.length).toBe(2) - expect('runtime.listClientHostedBrowserRows()'.match(LIST_CALL)?.length).toBe(1) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/agent-status-producer-census.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/agent-status-producer-census.test.ts index cef9e7dd8c1..e939d8a05f7 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/agent-status-producer-census.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/agent-status-producer-census.test.ts @@ -1,4 +1,3 @@ -import { resolve } from 'node:path' import { describe, expect, it, vi } from 'vitest' const { ipcHandlers } = vi.hoisted(() => ({ @@ -31,10 +30,6 @@ vi.mock('@electron-toolkit/utils', () => ({ })) import type Database from '../../../../../sqlite/sync-database' -import { - scanSourceTree, - stripComments -} from '../../../../../../shared/source-scan/source-tree-scan' import type { AgentStatusIpcPayload } from '../../../../../../shared/agent-status-ipc-payload' import { toAgentStatusIpcPayload } from '../../../../../agent-hooks/server/server-status-identity' import type { EnrichedAgentHookEventPayload } from '../../../../../agent-hooks/server/server-types' @@ -47,119 +42,6 @@ import { OrcaRuntimeService } from '../../../../orca-runtime' import { ORCHESTRATION_WORKER_LIST_METHOD } from './worker-list-method' import { projectFleetWorkerPage } from './worker-observation' -/** - * Census of every production site in `src/main` that turns hook-server agent-status rows into - * something a consumer reads. - * - * Why a census and not a single seam test: the false-liveness bug (rework failure table L-1) was - * one such site publishing rows that carry a pane key and nothing else, into a consumer that - * matches on terminal identity. Fixing that site fixes nothing if a fifth one is added beside it, - * so the list is pinned and the identity-bearing paths are each driven end to end. - */ -type CensusRow = { - path: string - /** `produces` = mints payloads a consumer reads; `consumes` = reads them; `wiring` = neither. */ - kind: 'produces' | 'consumes' | 'wiring' - role: string -} - -const CENSUS: readonly CensusRow[] = [ - { - path: 'main/ipc/agent-hooks.ts', - kind: 'produces', - role: 'agentStatus:getSnapshot — renderer pull, enriched (driven below)' - }, - { - path: 'main/ipc/agent-status-ipc-boundary.ts', - kind: 'produces', - role: 'resolveAgentStatusBinding — the one identity lookup the pull and fleet paths share' - }, - { - path: 'main/runtime/agent-status-observed-pane-identity.ts', - kind: 'produces', - role: 'captures the identity a hook row was observed under (fleet-status-observed-identity)' - }, - { - path: 'main/runtime/orchestration-fleet-agent-status-snapshot.ts', - kind: 'produces', - role: 'readOrchestrationFleetAgentStatusSnapshot — the minted fleet evidence (driven below)' - }, - { - path: 'main/startup/main-window-agent-status.ts', - kind: 'produces', - role: 'agentStatus:set — renderer live push, enriched inline (driven below)' - }, - { - path: 'main/startup/main-process-runtime-service.ts', - kind: 'wiring', - role: 'binds the hook server snapshot into the runtime deps' - }, - { - path: 'main/orcad/orcad-entry.ts', - kind: 'wiring', - role: 'binds the same snapshot, OSC producer and structured sink into the headless orcad runtime deps' - }, - { - path: 'main/runtime/orca-runtime-state-fields.ts', - kind: 'wiring', - role: 'stores the snapshot deps on the runtime' - }, - { - path: 'main/runtime/orca-runtime-preserved-branch-cleanup.ts', - kind: 'wiring', - role: 'declares the snapshot dep fields' - }, - { - path: 'main/runtime/orca-runtime-get-orchestration-dispatch-authority.ts', - kind: 'produces', - role: 'getOrchestrationFleetAgentStatusSnapshot — delegates to the checked snapshot module' - }, - { - path: 'main/runtime/orca-runtime-stop-requested-pty-ids.ts', - kind: 'wiring', - role: 'feeds the enriched fleet rows to the orchestration projection' - }, - { - path: 'main/runtime/runtime-agent-orchestration-projection.ts', - kind: 'consumes', - role: 'indexes rows by pane key to attach dispatch context' - }, - { - path: 'main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts', - kind: 'consumes', - role: 'worker-list fleet verdict (driven below)' - }, - { - path: 'main/runtime/rpc/methods/orchestration/worker/worker-observation.ts', - kind: 'consumes', - role: 'worker-show fleet verdict (driven below)' - }, - { - path: 'main/runtime/orca-runtime-get-worktree-ps.ts', - kind: 'consumes', - role: 'worktree.ps inline agent rows (driven below)' - }, - { - path: 'main/runtime/orca-runtime-get-terminal-interactive-wait.ts', - kind: 'consumes', - role: 'exact-worker provider session selection, matched on pane key' - }, - { - path: 'main/runtime/orca-runtime-serialize-agent-prompt-submission.ts', - kind: 'consumes', - role: 'prompt-submission serialization, matched on pane key' - }, - { - path: 'main/runtime/orca-runtime-prune-mobile-session-tab-group-layout.ts', - kind: 'consumes', - role: 'mobile tab-group pruning and its live agent row, plus the pane identity accessors' - } -] - -/** The names a hook row travels under. A new producer has to use one of them to reach a consumer. */ -const PRODUCER_TOKENS = - /getAgentStatusSnapshot|getAgentProviderSessionSnapshot|enrichAgentStatusIpcPayload|mintAgentStatusFleetEvidence|resolveAgentStatusBinding|getOrchestrationFleetAgentStatusSnapshot|agentStatus:set/ - const PANE_KEY = 'tab-census:leaf-census' const TERMINAL_HANDLE = 'term_census' const PROCESS_INCARNATION = 'pty-census:inc-1' @@ -258,17 +140,7 @@ function censusStore() { } } -describe('agent status producer census', () => { - it('pins every production site that hands hook rows to a consumer', () => { - const root = resolve(import.meta.dirname, '../../../../../..') - const scanned = scanSourceTree(resolve(root, 'main')) - .filter((file) => PRODUCER_TOKENS.test(stripComments(file.source))) - .map((file) => `main/${file.relativePath}`) - .sort() - - expect(scanned).toEqual(CENSUS.map((row) => row.path).sort()) - }) - +describe('agent status identity across every producer and consumer path', () => { it('reads live on worker-list from a hook row that carries only a pane key', async () => { const db = new OrchestrationDb(':memory:') try { diff --git a/src/main/runtime/rpc/terminal-stream-byte-length.test.ts b/src/main/runtime/rpc/terminal-stream-byte-length.test.ts index 60c4c86fe44..1c0f08cf33f 100644 --- a/src/main/runtime/rpc/terminal-stream-byte-length.test.ts +++ b/src/main/runtime/rpc/terminal-stream-byte-length.test.ts @@ -5,7 +5,6 @@ import { terminalStreamByteLength, terminalStreamByteLengthExceeds } from './terminal-stream-byte-length' -import { TERMINAL_OUTPUT_BATCH_MAX_BYTES } from '../../../shared/terminal-multiplex-flow-control' // Copy of the pre-change implementation (shared/clipboard-text.ts // measureClipboardTextByteLength), kept here so equivalence is checked against the @@ -323,92 +322,6 @@ describe('terminal stream byte length equivalence with the legacy code-point sca } } } - expect(MIN_NATIVE_BYTE_LENGTH_CODE_UNITS).toBeGreaterThan(0) - }) -}) - -// Reproduces createTerminalOutputBatcher's byte accounting exactly, under both the -// legacy scan and the new measurement, and asserts IDENTICAL flush boundaries. This is -// what makes the partial-count behaviour provably unobservable at that call site. -function simulateBatcherFlushes( - chunks: string[], - measure: ( - data: string, - options: { stopAfterBytes?: number } - ) => { byteLength: number; exceededLimit: boolean } -): string[] { - const flushes: string[] = [] - let pending: string[] = [] - let bytes = 0 - const flush = (): void => { - if (pending.length === 0) { - return - } - flushes.push(pending.join('')) - pending = [] - bytes = 0 - } - for (const data of chunks) { - if (!data) { - continue - } - pending.push(data) - const remainingBudget = Math.max(1, TERMINAL_OUTPUT_BATCH_MAX_BYTES - bytes) - const measurement = measure(data, { stopAfterBytes: remainingBudget }) - bytes += measurement.byteLength - if (measurement.exceededLimit || bytes >= TERMINAL_OUTPUT_BATCH_MAX_BYTES) { - flush() - } - } - flush() - return flushes -} - -describe('terminal output batcher flush boundaries are unchanged', () => { - it( - 'produces identical flush boundaries over randomized multi-chunk runs', - { timeout: 60000 }, - () => { - const random = mulberry32(0x1337) - for (let run = 0; run < 300; run += 1) { - const chunks: string[] = [] - const chunkCount = 1 + Math.floor(random() * 40) - for (let index = 0; index < chunkCount; index += 1) { - // Sizes straddle the 64KiB batch cap so single chunks both fit and blow the budget. - // Sizes straddle the native-call floor too, so runs mix scan-branch and - // native-branch measurements inside one batcher's byte accounting. - const scale = random() - const maxUnits = - scale < 0.25 - ? MIN_NATIVE_BYTE_LENGTH_CODE_UNITS * 2 - : scale < 0.5 - ? 64 - : scale < 0.85 - ? 20000 - : 90000 - chunks.push(random() < 0.5 ? randomString(random, maxUnits) : rawUtf16(random, maxUnits)) - } - const legacyFlushes = simulateBatcherFlushes(chunks, legacyMeasure) - const actualFlushes = simulateBatcherFlushes(chunks, measureTerminalStreamByteLength) - if (legacyFlushes.length !== actualFlushes.length) { - throw new Error(`flush count diverged on run ${run}`) - } - for (let index = 0; index < legacyFlushes.length; index += 1) { - if (legacyFlushes[index] !== actualFlushes[index]) { - throw new Error(`flush ${index} diverged on run ${run}`) - } - } - } - expect(true).toBe(true) - } - ) - - it('exercises runs that actually cross the batch budget', () => { - const oversized = '\u{1f600}'.repeat(TERMINAL_OUTPUT_BATCH_MAX_BYTES) - const chunks = ['a'.repeat(10), oversized, 'b'.repeat(10), oversized, 'c'] - const legacyFlushes = simulateBatcherFlushes(chunks, legacyMeasure) - expect(legacyFlushes.length).toBeGreaterThan(1) - expect(simulateBatcherFlushes(chunks, measureTerminalStreamByteLength)).toEqual(legacyFlushes) }) }) @@ -419,23 +332,8 @@ describe('resync trim byte accounting for a snapshot-sliced chunk', () => { it('re-measures a sliced chunk in UTF-8 bytes, not UTF-16 code units', () => { const data = '\u{1f600}é走a' const sliced = data.slice(2) - expect(terminalStreamByteLength(sliced)).toBe(legacyByteLength(sliced)) // Guards the mutant: code-unit length would be 4 here, UTF-8 is 6. expect(terminalStreamByteLength(sliced)).toBe(6) expect(terminalStreamByteLength(sliced)).not.toBe(sliced.length) }) - - it('matches the legacy byte length for every suffix slice of multi-byte terminal text', () => { - const random = mulberry32(0x51ced) - for (let iteration = 0; iteration < 2000; iteration += 1) { - const data = iteration % 2 === 0 ? randomString(random, 24) : rawUtf16(random, 24) - for (let offset = 0; offset <= data.length; offset += 1) { - const sliced = data.slice(offset) - if (terminalStreamByteLength(sliced) !== legacyByteLength(sliced)) { - throw new Error(`sliced byte length diverged for ${JSON.stringify(data)} at ${offset}`) - } - } - } - expect(true).toBe(true) - }) }) diff --git a/src/main/runtime/structured-claude-auth-policy-wiring.test.ts b/src/main/runtime/structured-claude-auth-policy-wiring.test.ts index f018dfd30da..cc2b5c3b164 100644 --- a/src/main/runtime/structured-claude-auth-policy-wiring.test.ts +++ b/src/main/runtime/structured-claude-auth-policy-wiring.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { join } from 'node:path' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -10,28 +9,11 @@ import { } from './structured-agent-session-runtime' /** - * The structured host's Claude auth policy has exactly one production wiring, and it - * lives in `orca-runtime-get-worktree-ps.ts` — a `@ts-nocheck` file, so neither the - * compiler nor a type test can see the field disappear. Deleting that wiring used to - * leave ~1000 tests green while every `ANTHROPIC_*` variable in the shell reached the - * child, because `stripAuthEnv` silently fell back to `false`. - * - * Two independent guards replace that silence, and this file pins both. + * The structured host's Claude auth policy has exactly one production wiring. Deleting it + * used to leave ~1000 tests green while every `ANTHROPIC_*` variable in the shell reached + * the child, because `stripAuthEnv` silently fell back to `false`. */ describe('structured Claude auth policy wiring', () => { - // The behavioural version of this assertion — importing the runtime class and - // capturing the installed deps — costs 35s of module transform for the whole - // OrcaRuntime chain (measured), so the wiring itself is pinned by source and the - // policy's meaning by claude-structured-auth-policy.test.ts. - it('passes a settings-derived Claude auth policy to the host installer', () => { - const source = readFileSync(join(__dirname, 'orca-runtime-get-worktree-ps.ts'), 'utf8') - - expect(source).toContain('claudeStructuredAuthPolicyForSettings') - expect(source).toMatch( - /resolveClaudeAuthPolicy:\s*\(\)\s*=>\s*\n?\s*claudeStructuredAuthPolicyForSettings\(/ - ) - }) - describe('installing without one', () => { let stateDirectory: string | null = null diff --git a/src/main/ssh/relay-protocol-backpressure.test.ts b/src/main/ssh/relay-protocol-backpressure.test.ts deleted file mode 100644 index 45a869af16e..00000000000 --- a/src/main/ssh/relay-protocol-backpressure.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - FrameDecoder, - FrameDecoderContinuationError, - FRAME_DECODER_MAX_RETAINED_BYTES, - HEADER_LENGTH, - MAX_MESSAGE_SIZE, - MessageType, - encodeFrame, - type DecodedFrame -} from './relay-protocol' - -function createScheduler(): { - schedule: (callback: () => void) => number - cancel: (handle: unknown) => void - runNext: () => void - pending: () => number -} { - let nextHandle = 1 - const callbacks = new Map void>() - return { - schedule: (callback) => { - const handle = nextHandle++ - callbacks.set(handle, callback) - return handle - }, - cancel: (handle) => callbacks.delete(handle as number), - runNext: () => { - const entry = callbacks.entries().next().value as [number, () => void] | undefined - if (!entry) { - throw new Error('No decoder continuation scheduled') - } - callbacks.delete(entry[0]) - entry[1]() - }, - pending: () => callbacks.size - } -} - -function frame(id: number, payload = `${id}`): Buffer { - return encodeFrame(MessageType.Regular, id, 0, Buffer.from(payload)) -} - -describe('FrameDecoder bounded turns', () => { - it('retains at most one maximum frame plus one MiB of partial input', () => { - expect(FRAME_DECODER_MAX_RETAINED_BYTES).toBe(MAX_MESSAGE_SIZE + HEADER_LENGTH + 1024 * 1024) - const maximumFrame = encodeFrame(MessageType.Regular, 1, 0, Buffer.alloc(MAX_MESSAGE_SIZE)) - const acceptedError = vi.fn() - const accepted = new FrameDecoder(vi.fn(), acceptedError) - - accepted.feed(Buffer.concat([maximumFrame, Buffer.alloc(1024 * 1024)])) - - expect(acceptedError).not.toHaveBeenCalled() - expect(accepted.drain()).toHaveLength(1024 * 1024) - - const excessError = vi.fn() - const excess = new FrameDecoder(vi.fn(), excessError) - excess.feed(Buffer.concat([maximumFrame, Buffer.alloc(1024 * 1024 + 1)])) - - expect(excessError).toHaveBeenCalledWith( - expect.objectContaining({ message: expect.stringContaining('retained-input') }) - ) - expect(excess.drain()).toHaveLength(0) - }) - - it('fails closed when one delivered chunk exceeds retained-input capacity', () => { - const onError = vi.fn() - const decoder = new FrameDecoder(vi.fn(), onError) - - decoder.feed(Buffer.alloc(FRAME_DECODER_MAX_RETAINED_BYTES + 1)) - - expect(onError).toHaveBeenCalledWith( - expect.objectContaining({ message: expect.stringContaining('retained-input') }) - ) - expect(decoder.drain()).toHaveLength(0) - }) - - it('emits the first frame synchronously and preserves order through self-pause', () => { - const scheduler = createScheduler() - const seen: number[] = [] - let decoder: FrameDecoder - const pause = vi.fn(() => decoder.feed(frame(4))) - const resume = vi.fn() - decoder = new FrameDecoder((decoded) => seen.push(decoded.id), undefined, { - maxFramesPerTurn: 1, - schedule: scheduler.schedule, - cancelScheduled: scheduler.cancel, - pause, - resume - }) - - decoder.feed(Buffer.concat([frame(1), frame(2), frame(3)])) - - expect(seen).toEqual([1]) - expect(pause).toHaveBeenCalledTimes(1) - expect(scheduler.pending()).toBe(1) - - scheduler.runNext() - scheduler.runNext() - scheduler.runNext() - - expect(seen).toEqual([1, 2, 3, 4]) - expect(pause).toHaveBeenCalledTimes(1) - expect(resume).toHaveBeenCalledTimes(1) - expect(scheduler.pending()).toBe(0) - }) - - it('bounds decoded bytes and time independently from the frame count', () => { - const byteScheduler = createScheduler() - const byteSeen: number[] = [] - const first = frame(1, 'one') - const second = frame(2, 'two') - const byteDecoder = new FrameDecoder((decoded) => byteSeen.push(decoded.id), undefined, { - maxFramesPerTurn: 64, - maxBytesPerTurn: first.length, - schedule: byteScheduler.schedule, - cancelScheduled: byteScheduler.cancel - }) - - byteDecoder.feed(Buffer.concat([first, second])) - expect(byteSeen).toEqual([1]) - byteScheduler.runNext() - expect(byteSeen).toEqual([1, 2]) - - const timeScheduler = createScheduler() - const timeSeen: number[] = [] - let nowCalls = 0 - const timeDecoder = new FrameDecoder((decoded) => timeSeen.push(decoded.id), undefined, { - maxFramesPerTurn: 64, - maxBytesPerTurn: MAX_MESSAGE_SIZE + HEADER_LENGTH, - maxTurnMs: 4, - now: () => (nowCalls++ === 0 ? 0 : 5), - schedule: timeScheduler.schedule, - cancelScheduled: timeScheduler.cancel - }) - - timeDecoder.feed(Buffer.concat([frame(3), frame(4)])) - expect(timeSeen).toEqual([3]) - timeScheduler.runNext() - expect(timeSeen).toEqual([3, 4]) - }) - - it('releases its pause epoch when continuation scheduling throws', () => { - const pause = vi.fn() - const resume = vi.fn() - const decoder = new FrameDecoder(() => {}, undefined, { - maxFramesPerTurn: 1, - pause, - resume, - schedule: () => { - throw new Error('scheduler unavailable') - } - }) - - expect(() => decoder.feed(Buffer.concat([frame(1), frame(2)]))).toThrow('scheduler unavailable') - expect(pause).toHaveBeenCalledTimes(1) - expect(resume).toHaveBeenCalledTimes(1) - decoder.reset() - expect(resume).toHaveBeenCalledTimes(1) - }) - - it('contains a throwing continuation, resets residue, and reports one typed error', () => { - const scheduler = createScheduler() - const seen: number[] = [] - const onError = vi.fn() - const pause = vi.fn() - const resume = vi.fn() - const decoder = new FrameDecoder( - (decoded) => { - if (decoded.id === 2) { - throw new Error('frame owner failed') - } - seen.push(decoded.id) - }, - onError, - { - maxFramesPerTurn: 1, - schedule: scheduler.schedule, - cancelScheduled: scheduler.cancel, - pause, - resume - } - ) - - decoder.feed(Buffer.concat([frame(1), frame(2), frame(3)])) - expect(() => scheduler.runNext()).not.toThrow() - - expect(seen).toEqual([1]) - expect(onError).toHaveBeenCalledExactlyOnceWith(expect.any(FrameDecoderContinuationError)) - expect(onError.mock.calls[0]?.[0]).toMatchObject({ - name: 'FrameDecoderContinuationError', - cause: expect.objectContaining({ message: 'frame owner failed' }) - }) - expect(pause).toHaveBeenCalledTimes(1) - expect(resume).toHaveBeenCalledTimes(1) - expect(scheduler.pending()).toBe(0) - expect(decoder.drain()).toHaveLength(0) - - decoder.feed(frame(4)) - expect(seen).toEqual([1, 4]) - }) - - // feed() runs straight from a transport data handler. A frame owner that threw on the first - // turn used to escape feed() and reach uncaughtException. The continuation path was already - // contained; the synchronous path must match it. - it('contains a frame owner that throws on the synchronous turn and reports one typed error', () => { - const seen: number[] = [] - const onError = vi.fn() - const pause = vi.fn() - const resume = vi.fn() - const decoder = new FrameDecoder( - (decoded) => { - if (decoded.id === 2) { - throw new Error('frame owner failed') - } - seen.push(decoded.id) - }, - onError, - { pause, resume } - ) - - expect(() => decoder.feed(Buffer.concat([frame(1), frame(2), frame(3)]))).not.toThrow() - - expect(seen).toEqual([1]) - expect(onError).toHaveBeenCalledExactlyOnceWith(expect.any(FrameDecoderContinuationError)) - expect(onError.mock.calls[0]?.[0]).toMatchObject({ - cause: expect.objectContaining({ message: 'frame owner failed' }) - }) - expect(decoder.drain()).toHaveLength(0) - expect(pause).not.toHaveBeenCalled() - expect(resume).not.toHaveBeenCalled() - - decoder.feed(frame(4)) - expect(seen).toEqual([1, 4]) - }) - - it('keeps reads active for partial frames and incrementally discards oversized payloads', () => { - const errors: Error[] = [] - const seen: DecodedFrame[] = [] - const pause = vi.fn() - const decoder = new FrameDecoder( - (decoded) => seen.push(decoded), - (error) => errors.push(error), - { pause } - ) - const valid = frame(2, 'complete') - - decoder.feed(valid.subarray(0, HEADER_LENGTH + 2)) - expect(seen).toHaveLength(0) - expect(pause).not.toHaveBeenCalled() - decoder.feed(valid.subarray(HEADER_LENGTH + 2)) - expect(seen.map(({ id }) => id)).toEqual([2]) - - const oversizedHeader = Buffer.alloc(HEADER_LENGTH) - oversizedHeader[0] = MessageType.Regular - oversizedHeader.writeUInt32BE(3, 1) - oversizedHeader.writeUInt32BE(MAX_MESSAGE_SIZE + 1, 9) - decoder.feed(Buffer.concat([oversizedHeader, Buffer.alloc(32)])) - - expect(errors).toHaveLength(1) - expect(pause).not.toHaveBeenCalled() - decoder.reset() - decoder.feed(frame(4, 'after-reset')) - expect(seen.map(({ id }) => id)).toEqual([2, 4]) - }) - - it('drain and reset cancel continuation ownership without replaying residue', () => { - const scheduler = createScheduler() - const seen: number[] = [] - const resume = vi.fn() - const cancel = vi.fn(scheduler.cancel) - const decoder = new FrameDecoder((decoded) => seen.push(decoded.id), undefined, { - maxFramesPerTurn: 1, - schedule: scheduler.schedule, - cancelScheduled: cancel, - resume - }) - const second = frame(2, 'residue') - - decoder.feed(Buffer.concat([frame(1), second])) - const residue = decoder.drain() - - expect(seen).toEqual([1]) - expect(residue.equals(second)).toBe(true) - expect(cancel).toHaveBeenCalledTimes(1) - expect(resume).toHaveBeenCalledTimes(1) - expect(scheduler.pending()).toBe(0) - - decoder.feed(Buffer.concat([frame(3), frame(4)])) - decoder.reset() - expect(cancel).toHaveBeenCalledTimes(2) - expect(scheduler.pending()).toBe(0) - - decoder.feed(frame(5)) - expect(seen).toEqual([1, 3, 5]) - }) -}) diff --git a/src/main/ssh/ssh-system-fallback.test.ts b/src/main/ssh/ssh-system-fallback.test.ts index b477ad682ef..3212a44b6fb 100644 --- a/src/main/ssh/ssh-system-fallback.test.ts +++ b/src/main/ssh/ssh-system-fallback.test.ts @@ -880,14 +880,6 @@ describe('spawnSystemSsh', () => { vi.stubEnv('PATH', '') expect(() => spawnSystemSsh(createTarget())).toThrow('No system ssh binary found') }) - - it('returns a process wrapper with kill and onExit', () => { - const result = spawnSystemSsh(createTarget()) - - expect(result.pid).toBe(12345) - expect(typeof result.kill).toBe('function') - expect(typeof result.onExit).toBe('function') - }) }) describe('system SSH operation aborts', () => { diff --git a/src/main/startup/configure-process.test.ts b/src/main/startup/configure-process.test.ts index fd4379354c4..70747c926f4 100644 --- a/src/main/startup/configure-process.test.ts +++ b/src/main/startup/configure-process.test.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { homedir, tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -942,39 +942,6 @@ describe('safe graphics mode startup switches', () => { ) }) - // Why: the defect was the call site, not the switch — a win32 safe-graphics launch runs - // `if (!gpuFallbackActiveThisLaunch) enableMainProcessGpuFeatures()` and skips everything - // parked inside it, so only an unconditional call site reaches the users a GPU crash already hit. - it('calls the throttling opt-out outside the GPU-fallback gate in preflight', () => { - const mainSource = readFileSync(join(__dirname, 'main-process-preflight.ts'), 'utf8') - const gateStart = mainSource.indexOf('if (!state.gpuFallbackActiveThisLaunch) {') - expect(gateStart).toBeGreaterThanOrEqual(0) - const gateEnd = mainSource.indexOf('\n }', gateStart) - expect(gateEnd).toBeGreaterThan(gateStart) - - expect(mainSource.match(/\boptOutOfHiddenPageWakeUpThrottling\(\)/g)).toHaveLength(1) - expect(mainSource.slice(gateStart, gateEnd)).not.toContain('optOutOfHiddenPageWakeUpThrottling') - }) - - // Why: Chromium consumes the command line at ready, so this must stay in the pre-ready - // top-level block and never move into the whenReady callback, where appendSwitch is a silent - // no-op — the same invisible failure as parking it behind the GPU gate. - it('appends the throttling opt-out before app ready in preflight', () => { - const mainSource = readFileSync(join(__dirname, 'main-process-preflight.ts'), 'utf8') - const entrySource = readFileSync(join(__dirname, '..', 'index.ts'), 'utf8') - const preflightEnd = mainSource.indexOf('\n return true') - const readyStart = entrySource.indexOf('void app.whenReady()') - const preflightCall = entrySource.indexOf('runMainProcessPreflight({') - expect(preflightEnd).toBeGreaterThan(0) - expect(readyStart).toBeGreaterThan(0) - expect(preflightCall).toBeGreaterThanOrEqual(0) - expect(preflightCall).toBeLessThan(readyStart) - - const callIndex = mainSource.indexOf('optOutOfHiddenPageWakeUpThrottling()') - expect(callIndex).toBeGreaterThan(0) - expect(callIndex).toBeLessThan(preflightEnd) - }) - // Why: Chromium enables IntensiveWakeUpThrottling on every desktop platform, so the opt-out // must never become reachable only through the GPU-feature path again. it('does not couple the throttling opt-out to GPU feature setup', async () => { diff --git a/src/main/startup/secure-dns-census.test.ts b/src/main/startup/secure-dns-census.test.ts index 6393ac3f3a4..72177fc04d4 100644 --- a/src/main/startup/secure-dns-census.test.ts +++ b/src/main/startup/secure-dns-census.test.ts @@ -33,14 +33,4 @@ describe('secure DNS census', () => { expect(offenders).toEqual([]) }) - - it('detects a DoH mode when one is present', () => { - // Why: the census reads real sources, so it passes vacuously today; prove the matcher on a known offender. - const offending = "app.configureHostResolver({ secureDnsMode: 'automatic' })" - const modes = [...offending.matchAll(/secureDnsMode\s*:\s*'([^']*)'/g)].map((match) => match[1]) - - expect(offending.includes('configureHostResolver')).toBe(true) - expect(modes).toEqual(['automatic']) - expect(modes.every((mode) => mode === 'off')).toBe(false) - }) }) diff --git a/src/main/updater-test-harness.leaked-timers.test.ts b/src/main/updater-test-harness.leaked-timers.test.ts deleted file mode 100644 index 6857852c0e2..00000000000 --- a/src/main/updater-test-harness.leaked-timers.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { setTimeout as sleep } from 'node:timers/promises' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Mock } from 'vitest' -import { loadUpdaterModule, warmUpdaterModule } from './updater-test-module-loader' - -const { autoUpdaterMock, fetchNewerReleaseTagsMock, moduleFactories, resetUpdaterMocks } = - await vi.hoisted(async () => (await import('./updater-test-harness')).createUpdaterMocks()) - -vi.mock('electron', () => moduleFactories.electron()) -vi.mock('electron-updater', () => moduleFactories.electronUpdater()) -vi.mock('./electron-updater-loader', () => moduleFactories.electronUpdaterLoader()) -vi.mock('@electron-toolkit/utils', () => moduleFactories.electronToolkitUtils()) -vi.mock('./ipc/pty', () => moduleFactories.ipcPty()) -vi.mock('./linux-update-package-type', () => moduleFactories.linuxUpdatePackageType()) -vi.mock('./updater-lifecycle-diagnostics', () => moduleFactories.updaterLifecycleDiagnostics()) -vi.mock('./updater-changelog', () => moduleFactories.updaterChangelog()) -vi.mock('./updater-nudge', () => moduleFactories.updaterNudge()) -vi.mock('./update-install-exit-watchdog', () => moduleFactories.updateInstallExitWatchdog()) -vi.mock('./updater-prerelease-feed', () => moduleFactories.updaterPrereleaseFeed()) -vi.mock('./local-builds/local-build-switch', () => moduleFactories.localBuildSwitch()) -vi.mock('./local-builds/local-build-feed-server', () => moduleFactories.localBuildFeedServer()) - -const SILENT_SETTLE_DELAY_MS = 1_000 -const AUTO_UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000 - -warmUpdaterModule() - -describe('updater test harness real-timer tracking', () => { - beforeEach(() => { - resetUpdaterMocks() - }) - - it('cancels a real timer armed before the reset', async () => { - let fired = false - setTimeout(() => { - fired = true - }, 20) - - resetUpdaterMocks() - - await sleep(150) - expect(fired).toBe(false) - }) - - it('still arms real timers after the reset', async () => { - let fired = false - setTimeout(() => { - fired = true - }, 10) - - await sleep(150) - expect(fired).toBe(true) - }) - - it('hands back the untouched Node timeout handle', () => { - const handle = setTimeout(() => {}, 60_000) - - // Why: production code calls unref() on these; the tracker must not swap in a plain id. - expect(typeof handle.unref).toBe('function') - handle.unref() - clearTimeout(handle) - }) -}) - -// Why: this pair reproduces the cross-test leak, so it depends on running in file order — the first -// test arms the timer and the second one is the later test it used to fire into. -describe('abandoned updater instance', () => { - let leakedStatusSend: Mock = vi.fn() - - beforeEach(() => { - resetUpdaterMocks() - }) - - it('leaves a silent-settle timer armed when its module instance is abandoned', async () => { - let resolveCheck: (value: unknown) => void = () => {} - autoUpdaterMock.checkForUpdates.mockImplementation(() => { - // Why: the checking status is what makes the silent settle publish 'not-available' later. - autoUpdaterMock.emit('checking-for-update') - return new Promise((resolve) => { - resolveCheck = resolve - }) - }) - leakedStatusSend = vi.fn() - - const { setupAutoUpdater } = await loadUpdaterModule() - - setupAutoUpdater({ webContents: { send: leakedStatusSend } } as never, { - getLastUpdateCheckAt: () => Date.now() - 25 * 60 * 60 * 1000 - }) - - await vi.waitFor(() => { - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) - }) - - // Why: resolving without a terminal event is what arms the 1s silent settle; do it here so the - // full delay is still ahead of us and the timer is guaranteed to be pending when this test ends. - resolveCheck(undefined) - await sleep(0) - - expect(leakedStatusSend).not.toHaveBeenCalledWith( - 'updater:status', - expect.objectContaining({ state: 'not-available' }) - ) - }) - - it('never reaches the shared spies once the next test owns the clock', async () => { - vi.useFakeTimers() - - // Why: real time past the settle delay — the abandoned instance would settle here and re-arm its - // 24h auto check on this test's fake clock at its epoch. - await sleep(SILENT_SETTLE_DELAY_MS + 300) - await vi.advanceTimersByTimeAsync(AUTO_UPDATE_CHECK_INTERVAL_MS) - - expect(leakedStatusSend).not.toHaveBeenCalledWith( - 'updater:status', - expect.objectContaining({ state: 'not-available' }) - ) - // Why: the generation fence stops at the autoUpdater spies; this one sits past it on the - // pinDefaultReleaseFeed chain that the stale instance's re-armed background check still reached. - expect(fetchNewerReleaseTagsMock).not.toHaveBeenCalled() - expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/usage/usage-scan-worker-client.test.ts b/src/main/usage/usage-scan-worker-client.test.ts index 7b34b5a80f4..09c6f378f00 100644 --- a/src/main/usage/usage-scan-worker-client.test.ts +++ b/src/main/usage/usage-scan-worker-client.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { join, sep } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { resolveWorkerThreadEntryPath } from '../worker-thread-entry-path' @@ -235,16 +234,4 @@ describe('usage scan worker entry path', () => { USAGE_SCAN_WORKER_ENTRY_FILENAME ]) }) - - // A rename in the build config would leave both branches pointing at a file - // that is never emitted, and only the packaged one fails silently. - it('names the entry the main build actually emits', () => { - const config = readFileSync( - join(import.meta.dirname, '..', '..', '..', 'electron.vite.config.ts'), - 'utf8' - ) - - expect(USAGE_SCAN_WORKER_ENTRY_FILENAME).toBe('usage-scan-worker-entry.js') - expect(config).toContain("'usage-scan-worker-entry': resolve(") - }) }) diff --git a/src/relay/relay-watcher-event-emitter.test.ts b/src/relay/relay-watcher-event-emitter.test.ts index 0f0991e5c01..82b10e2fdf3 100644 --- a/src/relay/relay-watcher-event-emitter.test.ts +++ b/src/relay/relay-watcher-event-emitter.test.ts @@ -1,5 +1,3 @@ -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' import { describe, expect, it, vi } from 'vitest' import type { WatcherProcessEvent } from '../main/ipc/parcel-watcher-process-protocol' import { RelayDispatcher } from './dispatcher' @@ -200,13 +198,6 @@ describe('relay watcher writer admission', () => { }) describe('relay watcher overflow suppression key', () => { - it('keeps the source free of NUL bytes so git and grep still see text', () => { - const source = readFileSync( - fileURLToPath(new URL('./relay-watcher-event-emitter.ts', import.meta.url)) - ) - expect(source.includes(0)).toBe(false) - }) - it('scopes the outstanding marker per client as well as per root', () => { const primary = createRecordingSink(65536) const secondary = createRecordingSink(65536) diff --git a/src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx b/src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx index 314977a17aa..f5d404b4e10 100644 --- a/src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx +++ b/src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx @@ -6,16 +6,11 @@ // authority (main) = real updatePersistedUI/getPersistedUI merge // broadcast = controlled queue modeling the async ui:stateChanged IPC send // mobile client = mobile/src/worktree/workspace-view-settings mapping; the ui.set -// payload uses the shipping buildWorkspaceViewSettingsUpdate when -// exported, else the legacy whole-snapshot shape — the source-pin -// test asserts use-host-view-settings.ts matches whichever path is -// active, so the model stays tethered to shipping code. +// payload mirrors the shipping buildWorkspaceViewSettingsUpdate. // // Invariant: when two independently identified clients change DISJOINT workspace-view // fields concurrently or across stale-mirror windows, both changes survive and all // mirrors converge; no client may restore a stale sibling field. -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { StrictMode, act, createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -84,8 +79,7 @@ function createAuthority() { type Authority = ReturnType // Local model of mobile/src/worktree/workspace-view-settings.ts (the desktop test -// runner cannot transform Expo-configured sources). The source-pin test at the -// bottom fails if the shipping module stops matching this model. +// runner cannot transform Expo-configured sources). type MobileViewState = { groupMode: 'none' | 'workspaceStatus' | 'repo' | 'prStatus' sortMode: 'smart' | 'name' | 'recent' | 'repo' | 'manual' @@ -96,10 +90,6 @@ type MobileViewState = { collapsedGroups: string[] } -function mobileHasPatchOnlyBuilder(): boolean { - return readMobileViewSettingsSource().includes('export function buildWorkspaceViewSettingsUpdate') -} - /** Mirrors buildWorkspaceViewSettingsUpdate (candidate) — only touched fields. */ function patchOnlyUpdate( patch: Partial, @@ -127,18 +117,6 @@ function patchOnlyUpdate( return update } -/** Mirrors the pre-fix persistViewSettings payload — the full snapshot on every tap. */ -function legacyWholeSnapshotUpdate(next: MobileViewState): Partial { - return { - groupBy: next.groupMode === 'workspaceStatus' ? 'workspace-status' : 'repo', - sortBy: next.sortMode, - hideSleepingWorkspaces: next.hideSleeping, - hideDefaultBranchWorkspace: next.hideDefaultBranch, - filterRepoIds: next.filterRepoIds, - collapsedGroups: next.collapsedGroups - } -} - /** Model of the mobile host screen's view-settings client (persistViewSettings et al.). */ function createMobileClient(authority: Authority) { let view: MobileViewState = { @@ -171,28 +149,12 @@ function createMobileClient(authority: Authority) { /** A user tap: apply locally, then push through the shipping payload shape. */ tap(patch: Partial) { view = { ...view, ...patch } - const payload = mobileHasPatchOnlyBuilder() - ? patchOnlyUpdate(patch, view) - : legacyWholeSnapshotUpdate(view) + const payload = patchOnlyUpdate(patch, view) authority.set(omitPairingLocalUiFields(payload) as Partial) } } } -function readMobileViewSettingsHookSource(): string { - return readFileSync( - join(__dirname, '../../../../mobile/src/host-screen/use-host-view-settings.ts'), - 'utf-8' - ) -} - -function readMobileViewSettingsSource(): string { - return readFileSync( - join(__dirname, '../../../../mobile/src/worktree/workspace-view-settings.ts'), - 'utf-8' - ) -} - describe('workspace view preferences: cross-client persistence (STA-5781)', () => { let authority: Authority let store: StoreApi @@ -710,35 +672,4 @@ describe('workspace view preferences: cross-client persistence (STA-5781)', () = expect(authority.get().hideDefaultBranchWorkspace).toBe(false) expect(store.getState().hideDefaultBranchWorkspace).toBe(false) }) - - it('pins the modeled mobile ui.set payload to the shipping source', async () => { - const source = readMobileViewSettingsHookSource() - if (mobileHasPatchOnlyBuilder()) { - // Candidate: the persistence hook must push through the patch-only builder this model uses. - expect(source).toContain('buildWorkspaceViewSettingsUpdate(patch, next)') - const builderSource = readMobileViewSettingsSource() - for (const guard of [ - "if ('groupMode' in patch)", - "if ('sortMode' in patch)", - "if ('hideSleeping' in patch)", - "if ('hideDefaultBranch' in patch)", - "if ('filterRepoIds' in patch)", - "if ('collapsedGroups' in patch)" - ]) { - expect(builderSource).toContain(guard) - } - } else { - // Baseline: persistViewSettings pushes exactly this whole-snapshot payload. - for (const key of [ - 'groupBy: groupModeToDesktop(next.groupMode)', - 'sortBy: next.sortMode', - 'hideSleepingWorkspaces: next.hideSleeping', - 'hideDefaultBranchWorkspace: next.hideDefaultBranch', - 'filterRepoIds: next.filterRepoIds', - 'collapsedGroups: next.collapsedGroups' - ]) { - expect(source).toContain(key) - } - } - }) }) diff --git a/src/renderer/src/components/AgentStateDot.test.ts b/src/renderer/src/components/AgentStateDot.test.ts index 33642542d79..a767a61ccf4 100644 --- a/src/renderer/src/components/AgentStateDot.test.ts +++ b/src/renderer/src/components/AgentStateDot.test.ts @@ -47,15 +47,9 @@ describe('AgentStateDot', () => { it('renders working as a yellow spinner', () => { const markup = renderMarkup('working') - expect(markup).toContain('border-yellow-500') - expect(markup).toContain('border-t-transparent') - // Why: rotation must come from the compositor-driven CSS animation, not a - // JS clock writing per-element styles on the input thread (STA-3328). - expect(markup).toContain('agent-working-spinner') + // The spinner's own classes and animation contract belong to AgentWorkingSpinner.test.tsx; + // this pins only that 'working' reaches for it. expect(markup).toContain('data-agent-spinner') - // Why: under reduced motion the top border is filled so the static ring - // reads as a complete marker, not a broken partial spinner (#9515). - expect(markup).toContain('motion-reduce:border-t-yellow-500') }) it('renders monitoring as a static yellow heartbeat glyph', () => { diff --git a/src/renderer/src/components/automations/automation-scoped-list-client.test.ts b/src/renderer/src/components/automations/automation-scoped-list-client.test.ts index e07399319fb..43319886180 100644 --- a/src/renderer/src/components/automations/automation-scoped-list-client.test.ts +++ b/src/renderer/src/components/automations/automation-scoped-list-client.test.ts @@ -288,7 +288,7 @@ describe('owner-fenced mutations', () => { }) it('fences a desktop mutation over the local runtime target with the same precondition', async () => { - const { deleteAutomationForOwner, updateAutomationForOwner } = await client() + const { updateAutomationForOwner } = await client() callRuntimeRpc.mockResolvedValue({ automation: { id: 'a1' } }) await updateAutomationForOwner({ authority: DESKTOP, selector: { kind: 'self' } }, 'a1', { enabled: true @@ -300,7 +300,6 @@ describe('owner-fenced mutations', () => { expect.anything() ) expect(getRuntimeEnvironmentStatus).not.toHaveBeenCalled() - expect(typeof deleteAutomationForOwner).toBe('function') }) }) diff --git a/src/renderer/src/components/browser-pane/annotate/BrowserAnnotationSendMenuContent.test.tsx b/src/renderer/src/components/browser-pane/annotate/BrowserAnnotationSendMenuContent.test.tsx index 4eb4174211b..24524a10dc7 100644 --- a/src/renderer/src/components/browser-pane/annotate/BrowserAnnotationSendMenuContent.test.tsx +++ b/src/renderer/src/components/browser-pane/annotate/BrowserAnnotationSendMenuContent.test.tsx @@ -1,6 +1,4 @@ import React from 'react' -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' import { describe, expect, it, vi } from 'vitest' import { BrowserAnnotationSendMenuContent } from './BrowserAnnotationSendMenuContent' @@ -92,19 +90,4 @@ describe('BrowserAnnotationSendMenuContent', () => { onPromptDelivered }) }) - - it('is wired into both browser annotation send surfaces', () => { - const bannerSource = readFileSync( - fileURLToPath(new URL('../assemble-chrome/browser-page-chrome-banners.tsx', import.meta.url)), - 'utf8' - ) - const traySource = readFileSync( - fileURLToPath(new URL('./browser-page-annotation-tray.tsx', import.meta.url)), - 'utf8' - ) - const sendSurfaces = `${bannerSource}\n${traySource}` - - expect(sendSurfaces.match(/ { - it('pins context-menu opens to the runtime that owns the pane', () => { - const source = readFileSync( - fileURLToPath(new URL('../stream-remote/remote-browser-page-pane.tsx', import.meta.url)), - 'utf8' - ) - const paneStart = source.indexOf('function RemoteBrowserPagePane') - const actionStart = source.indexOf('void openWorkspaceBrowserTab({', paneStart) - const actionEnd = source.indexOf('}).catch((error) => {', actionStart) - const openRequest = source.slice(actionStart, actionEnd) - - expect(openRequest).toContain('workspaceId: worktreeId') - expect(openRequest).toContain('expectedRuntimeEnvironmentId: runtimeEnvironmentId') - expect(openRequest).toContain("placementPreference: 'server'") - // A background link follows its source wrapper and never selects the workspace again. - expect(openRequest).toContain( - '...(sourceUnifiedTab ? { afterTabId: sourceUnifiedTab.id } : {})' - ) - expect(openRequest).toContain('selectWorktree: false') - }) -}) diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.render-ipc.test.ts b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.render-ipc.test.ts deleted file mode 100644 index 9e42075283c..00000000000 --- a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.render-ipc.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import { describe, expect, it } from 'vitest' - -describe('BrowserPagePane render IPC boundary', () => { - it('derives toolbar URLs without querying the webview', () => { - const source = readFileSync( - fileURLToPath(new URL('./browser-page-pane.tsx', import.meta.url)), - 'utf8' - ) - const start = source.indexOf('const isBlankTab =', source.indexOf('function BrowserPagePane')) - const end = source.indexOf('useEffect(() => {', start) - const renderUrlDerivation = source.slice(start, end) - - expect(renderUrlDerivation).toContain('getLiveBrowserUrl(browserTab.id)') - expect(renderUrlDerivation).not.toContain('webviewRef') - expect(renderUrlDerivation).not.toContain('.getURL(') - }) -}) diff --git a/src/renderer/src/components/browser-pane/browser-client-page-metadata-route-census.test.ts b/src/renderer/src/components/browser-pane/browser-client-page-metadata-route-census.test.ts deleted file mode 100644 index 6937de9e6e4..00000000000 --- a/src/renderer/src/components/browser-pane/browser-client-page-metadata-route-census.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import { describe, expect, it } from 'vitest' - -/** - * Page metadata has exactly one way out of this renderer: main, which owns the browser-host lease. - * - * Why a census and not a behavioural test: the failure this guards is silent. The runtime accepts - * page traffic only on the connection its lease attached on, so a publish sent as an ordinary - * runtime call is refused as a stale lease and simply never lands — the pane keeps working, the - * guest keeps navigating, and only the runtime's copy of the URL stays frozen at the create URL. - * Nothing in the rendered result changes, so only the route itself can be asserted. - */ -const ROUTE_PATH = fileURLToPath( - new URL('./browser-client-page-metadata-reporting.ts', import.meta.url) -) -const PANE_PATH = fileURLToPath(new URL('./ClientHostedBrowserPagePane.tsx', import.meta.url)) - -describe('client-hosted page metadata route', () => { - const route = readFileSync(ROUTE_PATH, 'utf8') - const pane = readFileSync(PANE_PATH, 'utf8') - - it('publishes through main and never through a plain runtime call', () => { - expect(occurrences(route, 'window.api.browser.publishClientPageMetadata')).toBe(1) - expect(occurrences(route, 'runtimeEnvironments.call')).toBe(0) - expect(occurrences(pane, 'runtimeEnvironments.call')).toBe(0) - }) - - it('reports a publish that did not land', () => { - expect(occurrences(route, 'onUnpublished:')).toBe(1) - }) - - // The pane must not build its own publisher around the route: a second construction site is a - // second chance to wire the transport wrongly, and it would not be covered by the counts above. - it('leaves the pane one way to start publishing', () => { - expect(occurrences(pane, 'createBrowserClientPageMetadataPublisher(')).toBe(0) - expect(occurrences(pane, 'startBrowserClientPageMetadataPublisher(')).toBe(1) - }) -}) - -function occurrences(source: string, needle: string): number { - return source.split(needle).length - 1 -} diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-retention.ts b/src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-retention.ts index 0d1364c139b..941c527b38f 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-retention.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-retention.ts @@ -61,7 +61,6 @@ export function useBrowserGuestPaintRetention(browserPageIds: readonly string[]) // Why one exported predicate rather than the same OR-list at each site: a hand-rolled copy stays // green when a term is added — nothing typechecks a site that never names the new signal — and the // remote-viewer term reached the panes while four copies in Terminal.tsx still had three terms. -// browser-guest-retention-site-census.test.ts holds the sites to this function. export function browserPageNeedsPaintRetention(browserPageId: string): boolean { return ( isBrowserAutomationVisible(browserPageId) || diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-guest-retention-site-census.test.ts b/src/renderer/src/components/browser-pane/host-guest/browser-guest-retention-site-census.test.ts deleted file mode 100644 index 5d8c6028329..00000000000 --- a/src/renderer/src/components/browser-pane/host-guest/browser-guest-retention-site-census.test.ts +++ /dev/null @@ -1,223 +0,0 @@ -import { readdirSync, readFileSync } from 'node:fs' -import { join, relative, sep } from 'node:path' -import { describe, expect, it } from 'vitest' - -// Guest retention is an OR over several independent signals, and every container from the app -// shell down to the guest has to agree on the list — Chromium stops painting inside a display:none -// subtree, so the *most* pinched ancestor wins. Adding a term (the remote-viewer signal, STA-4150) -// reached the panes while four hand-rolled copies still listed three: nothing typechecks a site -// that never names the new symbol. So the terms live behind one helper, and this census holds the -// sites to it — the classification is enforced here, not by review. - -const RENDERER_SRC = join(__dirname, '..', '..', '..') - -// The three term stores. -const RETENTION_TERM_STORES = [ - 'components/browser-pane/host-guest/browser-automation-visibility.ts', - 'lib/pane-manager/browser-mobile-driver-state.ts', - 'lib/pane-manager/browser-remote-viewer-state.ts' -] - -// ...plus the single module allowed to OR their terms together. -const RETENTION_TERM_OWNERS = [ - ...RETENTION_TERM_STORES, - 'components/browser-pane/host-guest/browser-guest-paint-retention.ts' -] - -// Every way a term store lets a caller read one term. A site that hand-rolls the OR-list from -// readers missing here would pass the census, so the last check holds this list to the exports. -const RETENTION_TERM_SYMBOLS = [ - 'isBrowserAutomationVisible', - 'useBrowserAutomationVisibilityForAny', - 'getBrowserAutomationVisiblePageIds', - 'onBrowserAutomationVisibilityChange', - 'isBrowserPageMobileDriven', - 'hasMobileDriverForAnyBrowserPage', - 'useBrowserMobileDriverForAny', - 'getBrowserMobileDrivenPageIds', - 'getDriverForBrowserPage', - 'useBrowserDriverForPage', - 'onBrowserDriverChange', - 'isBrowserPageRemotelyViewed', - 'hasRemoteViewerForAnyBrowserPage', - 'useBrowserRemoteViewerForAny', - 'getBrowserRemotelyViewedPageIds', - 'onBrowserRemoteViewerChange' -] - -const RETENTION_HELPER_SYMBOLS = [ - 'useAnyBrowserGuestNeedsPaint', - 'useBrowserGuestPaintRetention', - 'browserPageNeedsPaintRetention', - 'onBrowserGuestPaintRetentionChange', - 'browserTabsVetoGuestEviction' -] - -// Every place that decides whether a browser guest keeps painting, and the helper it must use. -const RETENTION_SITES = new Map([ - ['components/TerminalWorkbenchContainer.tsx', ['useAnyBrowserGuestNeedsPaint']], - // The two outermost workbench wrappers: strict ancestors of every guest, so the per-worktree - // surface hatch below cannot rescue a guest either one parked with `hidden`. - ['components/TerminalSurface.tsx', ['useAnyBrowserGuestNeedsPaint']], - ['components/TerminalSplitWorkspaceSurfaces.tsx', ['useAnyBrowserGuestNeedsPaint']], - ['components/TerminalWorktreeSplitSurface.tsx', ['useBrowserGuestPaintRetention']], - [ - 'components/browser-pane/assemble-chrome/BrowserPaneOverlayLayer.tsx', - ['useBrowserGuestPaintRetention'] - ], - [ - 'components/browser-pane/host-guest/browser-guest-worktree-retention.ts', - ['browserPageNeedsPaintRetention'] - ], - [ - 'components/use-terminal-browser-retention.ts', - ['browserTabsVetoGuestEviction', 'onBrowserGuestPaintRetentionChange'] - ] -]) - -// The per-page threading hooks are the carve-out: they hand one boolean per page to -// browser-page-paintability's required fields, so a missing term IS a typecheck error there. They -// still travel as a set — a caller that reads two of the three is the same omission bug. -const PER_PAGE_RETENTION_HOOKS = [ - 'useBrowserAutomationVisiblePageIds', - 'useBrowserMobileDrivenPageIds', - 'useBrowserRemotelyViewedPageIds' -] - -// One production read of a term is not a retention decision: the pane reads *who* drives the active -// page to label the overlay and lock input. Naming the exception per file rather than dropping the -// symbol keeps every other file that reads it a census failure. -const NON_RETENTION_TERM_READERS = new Map([ - [ - 'components/browser-pane/assemble-chrome/browser-workspace-pane.tsx', - ['useBrowserDriverForPage'] - ] -]) - -// Writers, hydrators and the idle sentinel: they set or seed a term rather -// than read it, so naming one is not a retention decision. -const NON_READER_TERM_EXPORTS = [ - 'acquireBrowserAutomationVisibility', - 'releaseBrowserAutomationVisibility', - 'setDriverForBrowserPage', - 'hydrateBrowserDrivers', - 'IDLE_BROWSER_DRIVER', - 'setRemoteViewersForBrowserPage', - 'hydrateBrowserRemoteViewerPages' -] - -function productionSources(): Map { - const sources = new Map() - for (const entry of readdirSync(RENDERER_SRC, { recursive: true, withFileTypes: true })) { - if (!entry.isFile() || !/\.tsx?$/.test(entry.name) || entry.name.endsWith('.d.ts')) { - continue - } - if (/\.test\.tsx?$/.test(entry.name) || /test-(harness|rig|fixtures)/.test(entry.name)) { - continue - } - const filePath = join(entry.parentPath, entry.name) - sources.set( - relative(RENDERER_SRC, filePath).split(sep).join('/'), - readFileSync(filePath, 'utf8') - ) - } - return sources -} - -function namedSymbols(source: string, symbols: readonly string[]): string[] { - return symbols.filter((symbol) => new RegExp(`\\b${symbol}\\b`).test(source)) -} - -describe('browser guest retention site census', () => { - const sources = productionSources() - - it('keeps every individual retention term behind the shared helper', () => { - const offenders = [...sources] - .filter(([file]) => !RETENTION_TERM_OWNERS.includes(file)) - .map(([file, source]) => ({ - file, - terms: namedSymbols(source, RETENTION_TERM_SYMBOLS).filter( - (term) => !(NON_RETENTION_TERM_READERS.get(file) ?? []).includes(term) - ) - })) - .filter(({ terms }) => terms.length > 0) - .map(({ file, terms }) => `${file}: ${terms.join(', ')}`) - .sort() - - expect( - offenders, - 'A retention site that names terms one by one silently keeps its old list when a new signal ' + - 'is added. Call useBrowserGuestPaintRetention / browserPageNeedsPaintRetention instead, ' + - 'and register the site in RETENTION_SITES.' - ).toEqual([]) - }) - - it('registers every consumer of the shared retention helper', () => { - const consumers = [...sources] - .filter( - ([file]) => file !== 'components/browser-pane/host-guest/browser-guest-paint-retention.ts' - ) - .filter(([, source]) => namedSymbols(source, RETENTION_HELPER_SYMBOLS).length > 0) - .map(([file]) => file) - .sort() - - expect(consumers, 'New retention sites must be listed in RETENTION_SITES.').toEqual( - [...RETENTION_SITES.keys()].sort() - ) - }) - - it('keeps each registered site consulting retention through its helper', () => { - const missing: string[] = [] - for (const [file, requiredSymbols] of RETENTION_SITES) { - const source = sources.get(file) - expect(source, `${file} is registered as a retention site but no longer exists`).toBeDefined() - for (const symbol of requiredSymbols) { - if (!new RegExp(`\\b${symbol}\\b`).test(source ?? '')) { - missing.push(`${file}: ${symbol}`) - } - } - } - expect(missing, 'A registered retention site stopped consulting retention.').toEqual([]) - }) - - it('keeps the per-page threading hooks travelling as a full set', () => { - const partial = [...sources] - .filter(([file]) => !RETENTION_TERM_OWNERS.includes(file)) - .map(([file, source]) => ({ file, hooks: namedSymbols(source, PER_PAGE_RETENTION_HOOKS) })) - .filter(({ hooks }) => hooks.length > 0 && hooks.length < PER_PAGE_RETENTION_HOOKS.length) - .map(({ file, hooks }) => `${file}: only ${hooks.join(', ')}`) - .sort() - - expect( - partial, - 'A pane that threads some retention terms per page must thread all of them.' - ).toEqual([]) - }) - - // Keeps the symbol lists above from going stale: a term store that grows a new reader nobody - // classified would otherwise be a free way to hand-roll the OR-list. - it('classifies every value a term store exports', () => { - const classified = new Set([ - ...RETENTION_TERM_SYMBOLS, - ...PER_PAGE_RETENTION_HOOKS, - ...NON_READER_TERM_EXPORTS - ]) - const unclassified: string[] = [] - for (const file of RETENTION_TERM_STORES) { - const source = sources.get(file) - expect(source, `${file} is registered as a term store but no longer exists`).toBeDefined() - for (const [, name] of (source ?? '').matchAll(/^export (?:function|const|let) (\w+)/gm)) { - if (!classified.has(name)) { - unclassified.push(`${file}: ${name}`) - } - } - } - - expect( - unclassified, - 'A term store exports something this census does not classify. Add a reader to ' + - 'RETENTION_TERM_SYMBOLS (or PER_PAGE_RETENTION_HOOKS, for the per-page hooks typecheck ' + - 'already covers) so hand-rolled sites keep failing, and a writer to NON_READER_TERM_EXPORTS.' - ).toEqual([]) - }) -}) diff --git a/src/renderer/src/components/confirmation-dialog-refresh-boundary.test.ts b/src/renderer/src/components/confirmation-dialog-refresh-boundary.test.ts index 952cb21e23d..b2f1db2de1f 100644 --- a/src/renderer/src/components/confirmation-dialog-refresh-boundary.test.ts +++ b/src/renderer/src/components/confirmation-dialog-refresh-boundary.test.ts @@ -1,33 +1,11 @@ // @vitest-environment happy-dom -import { createRequire } from 'node:module' import { createElement, type ReactNode } from 'react' import { renderHook } from '@testing-library/react' import { describe, expect, it } from 'vitest' -import * as contextModule from '@/components/confirmation-dialog-context' -import * as providerModule from '@/components/confirmation-dialog' import { ConfirmationDialogProvider } from '@/components/confirmation-dialog' import { useConfirmationDialog } from '@/components/confirmation-dialog-context' -// react-refresh ships no types; take the one binding this needs. -const { isLikelyComponentType } = createRequire(import.meta.url)('react-refresh/runtime') as { - isLikelyComponentType: (value: unknown) => boolean -} - describe('confirmation dialog Fast Refresh boundary', () => { - it('exports nothing from the provider module that invalidates the refresh boundary', () => { - expect(Object.keys(providerModule)).toEqual(['ConfirmationDialogProvider']) - expect(isLikelyComponentType(providerModule.ConfirmationDialogProvider)).toBe(true) - }) - - it('keeps the context and hook in a component-free module', () => { - const components = Object.entries(contextModule) - .filter(([, value]) => isLikelyComponentType(value)) - .map(([name]) => name) - - expect(components).toEqual([]) - expect(typeof contextModule.useConfirmationDialog).toBe('function') - }) - it('resolves the hook against the context the provider publishes', () => { const wrapper = ({ children }: { children: ReactNode }) => createElement(ConfirmationDialogProvider, null, children) diff --git a/src/renderer/src/components/feature-interaction-writer-boundaries.test.ts b/src/renderer/src/components/feature-interaction-writer-boundaries.test.ts deleted file mode 100644 index 4a02840098e..00000000000 --- a/src/renderer/src/components/feature-interaction-writer-boundaries.test.ts +++ /dev/null @@ -1,323 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const COMPONENT_ROOT = __dirname - -function componentSource(relativePath: string): string { - return readFileSync(join(COMPONENT_ROOT, relativePath), 'utf8') -} - -function sourceBetween(source: string, startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('feature interaction writer boundaries', () => { - it('keeps Cmd+J feature writers in open/selection handlers, not query or navigation rendering', () => { - // Selection and create callbacks now live in focused hooks; the surface only renders them. - const selectionSource = componentSource('use-worktree-jump-palette-selection-actions.ts') - const lifecycleSource = componentSource('use-worktree-jump-palette-selection-lifecycle.ts') - const createSource = componentSource('use-worktree-jump-palette-create-action.ts') - const handlerSection = [selectionSource, lifecycleSource, createSource].join('\n') - const renderSection = componentSource('worktree-jump-palette-surface.tsx') - - const cmdJWriterPattern = /recordFeatureInteraction\('cmd-j/g - const allCmdJWriterCount = handlerSection.match(cmdJWriterPattern)?.length ?? 0 - expect(allCmdJWriterCount).toBeGreaterThanOrEqual(6) - expect(handlerSection.match(cmdJWriterPattern)?.length ?? 0).toBe(allCmdJWriterCount) - expect(renderSection).not.toContain("recordFeatureInteraction('cmd-j") - expect( - sourceBetween(lifecycleSource, 'const handleQueryChange', 'const cancelFallbackFocusFrames') - ).not.toContain("recordFeatureInteraction('cmd-j") - }) - - it('keeps task-provider writers off filters, tab switches, query edits, refresh, and pagination', () => { - const providerWriter = /recordFeatureInteraction\('(github|gitlab|linear)-tasks'\)/ - const refreshSource = componentSource('use-task-page-github-cache-reconciliation.ts') - const paginationSource = componentSource('use-task-page-github-search-pagination.ts') - const searchSource = componentSource('use-task-page-search-actions.ts') - - const passiveSections = [ - sourceBetween(refreshSource, 'const handleRefreshGithubTasks', 'const nextModel'), - sourceBetween(paginationSource, 'const handleLoadNextPage', 'const commitTaskSearch'), - sourceBetween(searchSource, 'const applyPRFilterChange', 'const handleApplyTaskSearch'), - sourceBetween(searchSource, 'const handleApplyTaskSearch', 'const handleTaskSearchChange'), - sourceBetween( - searchSource, - 'const handleTaskSearchChange', - 'const handleSetDefaultTaskPreset' - ), - sourceBetween( - searchSource, - 'const handleSelectGithubTaskKind', - 'const handleResetGithubTaskSearch' - ) - ] - for (const section of passiveSections) { - expect(section).not.toMatch(providerWriter) - } - }) - - it('records GitHub provider-depth for inline item mutation success paths', () => { - const githubWriter = "recordFeatureInteraction('github-tasks')" - // Why: table cells route success telemetry through the optimistic mutation - // hook so provider-depth recording stays on one confirm path. - const hookSource = readFileSync( - join(COMPONENT_ROOT, '../hooks/useTaskPageGitHubWorkItemMutation.ts'), - 'utf8' - ) - expect( - sourceBetween(hookSource, "if (confirmed === 'confirmed')", 'return confirmed') - ).toContain(githubWriter) - expect( - sourceBetween( - componentSource('use-task-page-workspace-actions.ts'), - 'const handleOpenOrUseGitHubWorkItem', - 'const openComposerForGitLabItem' - ) - ).toContain(githubWriter) - }) - - it('threads GitHub task source context through inline task mutations', () => { - const sections = [ - componentSource('task-page/github/StatusCell.tsx'), - componentSource('task-page/github/AssigneesCell.tsx'), - componentSource('task-page/github/ReviewCell.tsx'), - componentSource('task-page/github/MergeCell.tsx'), - sourceBetween( - componentSource('use-task-page-github-issue-creation.ts'), - 'const handleCreateNewIssue', - 'const nextModel' - ) - ] - - for (const section of sections) { - expect(section).toContain('sourceContext') - } - const rowSource = componentSource('task-page/github/Rows.tsx') - // Rows inline the repo lookup per cell rather than hoisting one const. - expect( - rowSource.match(/sourceContext=\{getTaskPageRepoSourceContext\(itemRepo, 'github'\)\}/g) - ).toHaveLength(4) - }) - - it('suppresses Tasks surface telemetry for in-page provider switches and detail opens', () => { - const suppression = 'recordTasksInteraction: false' - const githubDetailSection = sourceBetween( - componentSource('use-task-page-github-detail.ts'), - 'const openGitHubDetailPage', - 'const nextModel' - ) - - const inPageNavigationSections = [ - sourceBetween( - componentSource('use-task-page-detail-routing.ts'), - 'const openLinearDetailPage', - 'const openRelatedLinearIssue' - ), - sourceBetween( - componentSource('task-page/SourceBar.tsx'), - 'taskSourceManuallyChangedRef.current = true', - 'void updateSettings' - ) - ] - - expect(githubDetailSection).toContain('openGitHubSourceContext') - expect(githubDetailSection).toContain('openTaskPage') - expect(githubDetailSection).toContain(suppression) - - for (const section of inPageNavigationSections) { - expect(section).toContain(suppression) - } - }) - - it('records Cmd+J create-workspace as its own destination, not a generic quick action', () => { - const source = componentSource('use-worktree-jump-palette-selection-actions.ts') - const section = sourceBetween( - source, - 'const handleSelectQuickAction', - 'const handleSelectProjectTarget' - ) - - expect(section).toContain("recordFeatureInteraction('cmd-j-create-workspace')") - expect(section).toContain("recordFeatureInteraction('cmd-j-quick-action')") - expect(section.indexOf("recordFeatureInteraction('cmd-j-create-workspace')")).toBeLessThan( - section.indexOf("recordFeatureInteraction('cmd-j-quick-action')") - ) - expect( - sourceBetween( - section, - "if (action.id === 'create-workspace')", - "recordFeatureInteraction('cmd-j-quick-action')" - ) - ).toContain('return') - }) - - it('records GitLab provider-depth for detail opens, workspace use, and dialog mutations', () => { - const detailsSource = componentSource('gitlab-item-dialog/use-gitlab-details-editing.ts') - const primarySource = componentSource('gitlab-item-dialog/use-gitlab-primary-actions.ts') - const reviewSource = componentSource('gitlab-item-dialog/use-gitlab-review-actions.ts') - const gitlabWriter = "recordFeatureInteraction('gitlab-tasks')" - - expect( - sourceBetween( - componentSource('task-page/gitlab/ItemList.tsx'), - '{displayedGitLabItems.map((item) => (', - 'handleUseGitLabItem(item)' - ).match(/recordFeatureInteraction\('gitlab-tasks'\)/g) - ).toHaveLength(2) - expect( - sourceBetween( - componentSource('use-task-page-workspace-actions.ts'), - 'const handleUseGitLabItem', - 'const nextModel' - ) - ).toContain(gitlabWriter) - - const mutationSections = [ - sourceBetween(detailsSource, 'const handleSaveDetails', 'return {'), - sourceBetween(reviewSource, 'const handleSetReviewers', 'const handleSubmitInlineComment'), - sourceBetween( - reviewSource, - 'const handleSubmitInlineComment', - 'const handleResolveDiscussion' - ), - sourceBetween(primarySource, 'const handleClose', 'const handleReopen'), - sourceBetween(primarySource, 'const handleReopen', 'const handleMerge'), - sourceBetween(primarySource, 'const handleMerge', 'const handleSubmitComment'), - sourceBetween(primarySource, 'const handleSubmitComment', 'return {'), - sourceBetween(reviewSource, 'const handleResolveDiscussion', 'return {') - ] - for (const section of mutationSections) { - expect(section).toContain(gitlabWriter) - expect(section).toContain('showGitLabMutationError') - } - }) - - it('keeps nested GitLab row actions from also opening task details by keyboard', () => { - const rowSection = sourceBetween( - componentSource('task-page/gitlab/ItemList.tsx'), - 'onKeyDown={(e) => {', - 'className="grid w-full cursor-pointer' - ) - expect(rowSection).toContain('e.target !== e.currentTarget') - expect(rowSection.indexOf('e.target !== e.currentTarget')).toBeLessThan( - rowSection.indexOf("e.key === 'Enter'") - ) - }) - - it('keys GitLab rows by repository and item identity across hosts', () => { - expect(componentSource('task-page/gitlab/ItemList.tsx')).toContain( - 'key={`${item.repoId}:${item.id}`}' - ) - }) - - it('records Linear provider-depth for inline edits, board drops, creation, and workspace use', () => { - const drawerSource = [ - componentSource('linear-item-drawer-edit-controller.tsx'), - componentSource('linear-item-drawer-comment-footer.tsx') - ].join('\n') - const linearWriter = "recordFeatureInteraction('linear-tasks')" - - const taskPageSections = [ - sourceBetween( - componentSource('task-page-linear-issue-model.tsx'), - 'export function LinearStateCell', - 'return (' - ), - sourceBetween( - componentSource('use-task-page-linear-board.ts'), - 'const handleLinearBoardDrop', - 'const toggleLinearDisplayProperty' - ), - sourceBetween( - componentSource('use-task-page-linear-issue-creation.ts'), - 'const handleCreateNewLinearIssue', - 'const nextModel' - ), - sourceBetween( - componentSource('use-task-page-composer-actions.ts'), - 'const handleUseLinearItem', - 'const handleLinearWorkspaceChange' - ) - ] - for (const section of taskPageSections) { - expect(section).toContain(linearWriter) - } - - const drawerMutationSections = [ - sourceBetween(drawerSource, 'const handleStateChange', 'const handlePriorityChange'), - sourceBetween(drawerSource, 'const handlePriorityChange', 'const handleEstimateChange'), - sourceBetween(drawerSource, 'const handleEstimateChange', 'const handleEstimateSubmit'), - sourceBetween(drawerSource, 'const handleAssigneeChange', 'const handleLabelToggle'), - sourceBetween(drawerSource, 'const handleLabelToggle', 'return {'), - sourceBetween(drawerSource, 'const handleSubmit = useCallback(async () => {', 'return (') - ] - for (const section of drawerMutationSections) { - expect(section).toContain(linearWriter) - } - }) - - it('records Jira provider-depth for workspace use', () => { - const jiraWriter = "recordFeatureInteraction('jira-tasks')" - - // End boundary is the declaration after the handler: the Jira connect flow - // now lives in the shared JiraConnectDialog, so handleJiraConnect (the prior - // marker) no longer exists in TaskPage. - expect( - sourceBetween( - componentSource('use-task-page-composer-actions.ts'), - 'const handleUseJiraItem', - 'const nextModel' - ) - ).toContain(jiraWriter) - }) - - it('records browser annotation agent handoff only from the prompt-delivered callback', () => { - const source = componentSource('browser-pane/annotate/use-browser-page-annotation-send.ts') - expect( - source.match(/recordFeatureInteraction\('browser-annotations-sent-to-agent'\)/g) - ).toHaveLength(1) - expect( - sourceBetween( - source, - 'const handleBrowserAnnotationsSentToAgent', - 'const handleClearBrowserAnnotations' - ) - ).toContain("recordFeatureInteraction('browser-annotations-sent-to-agent')") - expect( - sourceBetween( - source, - 'const handleCopyBrowserAnnotations', - 'const handleBrowserAnnotationsSentToAgent' - ) - ).not.toContain("recordFeatureInteraction('browser-annotations-sent-to-agent')") - expect( - sourceBetween( - source, - 'const handleClearBrowserAnnotations', - 'const handleDeleteBrowserAnnotation' - ) - ).not.toContain("recordFeatureInteraction('browser-annotations-sent-to-agent')") - }) - - it('records floating workspace hide only from explicit disable or hide actions', () => { - const allowedSources = [ - componentSource('settings/FloatingWorkspacePane.tsx'), - componentSource('floating-terminal/FloatingTerminalIconContextMenu.tsx') - ].join('\n') - const passiveSources = [ - componentSource('../App.tsx'), - componentSource('floating-terminal/FloatingTerminalPanel.tsx') - ].join('\n') - - expect( - allowedSources.match(/recordFeatureInteraction\('floating-workspace-hidden'\)/g) ?? [] - ).toHaveLength(2) - expect(passiveSources).not.toContain("recordFeatureInteraction('floating-workspace-hidden')") - }) -}) diff --git a/src/renderer/src/components/github-item-dialog-source-boundary.test.ts b/src/renderer/src/components/github-item-dialog-source-boundary.test.ts deleted file mode 100644 index 630ae68a7a0..00000000000 --- a/src/renderer/src/components/github-item-dialog-source-boundary.test.ts +++ /dev/null @@ -1,310 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const COMPONENT_ROOT = __dirname - -function componentSource(relativePath: string): string { - // Why: CRLF checkouts would otherwise break every multi-line source assertion. - return readFileSync(join(COMPONENT_ROOT, relativePath), 'utf8').replace(/\r\n?/g, '\n') -} - -function destSources(...relativePaths: string[]): string { - return relativePaths.map((relativePath) => componentSource(relativePath)).join('\n') -} - -function sourceBetween(source: string, startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('GitHubItemDialog source host boundaries', () => { - it('does not keep the stale right-side sheet owner', () => { - const source = destSources( - 'GitHubItemDialog.tsx', - 'github-item-dialog/open-dialog/github-item-dialog.tsx' - ) - - expect(source).not.toContain('@/components/ui/sheet') - expect(source).not.toContain(' { - const source = destSources( - 'github-item-dialog/land-pull-request/pr-reviewers-panel.tsx', - 'github-item-dialog/land-pull-request/pr-reviewers-request-actions.ts' - ) - const section = source - - expect(section).toContain('getTaskSourceRuntimeSettings(sourceContext)') - expect(section).toContain('useRepoAssigneesBySlug(') - expect(section).toContain('sourceSettings') - expect(section).toContain('useRepoAssignees(') - expect(section).toContain('sourceSettings') - expect(section).toContain('getActiveRuntimeTarget(sourceSettings)') - expect(section).toContain( - 'const runtimeRepo = getGitHubRuntimeRepoId(sourceContext, item.repoId)' - ) - expect(section).toContain("'github.requestPRReviewers'") - expect(section).toContain("'github.removePRReviewers'") - expect(section).toContain('resolvePullRequestRepo(item, projectOrigin)') - expect(section.match(/prRepo: reviewRepo/g)).toHaveLength(4) - expect(section).toContain('notifyWorkItemDetailsMutation(') - expect(section).toContain('{ local: false }') - }) - - it('routes edit metadata through the same task source as issue mutations', () => { - const source = destSources( - 'github-item-dialog/edit-item-fields/gh-edit-section.tsx', - 'github-item-dialog/edit-item-fields/gh-edit-section-mutations.ts' - ) - const section = source - const helperSection = componentSource('github/github-work-item-edit-mutations.ts') - - expect(section).toContain('getTaskSourceRuntimeSettings(sourceContext)') - expect(section).toContain('useRepoLabels(') - expect(section).toContain('useRepoLabelsBySlug(') - expect(section).toContain('projectOrigin?.host') - expect(section).toContain('useRepoAssignees(') - expect(section).toContain('useRepoAssigneesBySlug(') - expect(section).toContain('sourceSettings') - expect(helperSection).toContain("'github.updateIssue'") - expect(helperSection).toContain("'github.updatePRState'") - expect(helperSection).toContain("'github.project.updateIssueBySlug'") - expect(helperSection).toContain("'github.project.updatePullRequestBySlug'") - expect(helperSection).toContain("args.sourceContext?.provider === 'github'") - expect(helperSection).toContain('getTaskSourceRuntimeSettings(args.sourceContext)') - expect(helperSection).toContain( - 'getGitHubMutationRoutingSettings(useAppStore.getState(), args.repoId, args.sourceContext)' - ) - expect(helperSection).toContain('notifyWorkItemDetailsMutation(') - expect(helperSection).toContain( - "repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? '')" - ) - expect(helperSection).toContain('{ local: false }') - }) - - it('uses source-aware details routing and cache identity', () => { - const source = destSources( - 'github-item-dialog/load-item-details/work-item-details-cache.ts', - 'github-item-dialog/load-item-details/use-github-item-dialog-details.ts' - ) - const cacheKeySection = sourceBetween( - source, - 'function getWorkItemDetailsCacheKey', - 'function touchWorkItemDetailsCache' - ) - const matchInvalidationSection = sourceBetween( - source, - 'function invalidateWorkItemDetailsCacheByMatch', - 'function patchCachedPRFileViewedState' - ) - - expect(source).toContain('lookupGitHubWorkItemDetailsForSource({') - expect(source).toContain('sourceContext,') - expect(cacheKeySection).toContain('sourceCacheScope') - expect(source).toContain('getTaskSourceCacheScope(sourceContext)') - expect(matchInvalidationSection).toContain( - 'if (removed) {\n workItemDetailsCacheGeneration += 1' - ) - }) - - it('treats null details as unavailable while preserving empty detail payloads', () => { - const source = destSources( - 'github-item-dialog/load-item-details/use-github-item-dialog-details.ts', - 'github-item-dialog/load-item-details/work-item-details-fetch-settle.ts' - ) - const loadedSection = sourceBetween( - source, - 'const loading = !!cachedEntry?.pending && !cachedEntry?.details', - '// Why: if a cross-window mutation invalidates' - ) - const resultSection = sourceBetween(source, 'inflight', '.catch((err) => {') - - expect(loadedSection).toContain('const detailsLoaded = Boolean(cachedEntry?.details)') - expect(loadedSection).not.toContain('fetchedAt > 0') - expect(resultSection).toContain('} else if (result === null) {') - expect(resultSection).toContain('error: WORK_ITEM_DETAILS_UNAVAILABLE_MESSAGE') - expect(resultSection).toContain('details: result') - }) - - it('routes PR file viewed mutations through the task source context', () => { - const changeSection = destSources( - 'github-item-dialog/load-item-details/use-github-item-dialog-details.ts', - 'github-item-dialog/load-item-details/pr-file-viewed-change.ts' - ) - const helperSection = componentSource('github/github-work-item-comment-mutations.ts') - - expect(helperSection).toContain('getGitHubSourceRuntimeHost(args.sourceContext)') - expect(helperSection).toContain("'github.setPRFileViewed'") - expect(helperSection).toContain('repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId)') - expect(helperSection).toContain('sourceContext: args.sourceContext') - expect(helperSection).toContain('{ local: false }') - expect(changeSection).toContain('canUseDetailsRepoContext') - expect(changeSection).toContain('repoPath: repoPath ??') - expect(changeSection).toContain('sourceContext,') - }) - - it('routes comment mutations through runtime source context when needed', () => { - const helperSource = componentSource('github/github-work-item-comment-mutations.ts') - const helperSection = sourceBetween( - helperSource, - 'function addIssueCommentForRepo', - 'function setPRFileViewedForRepo' - ) - - expect(helperSection).toContain('getGitHubSourceRuntimeHost(args.sourceContext)') - expect(helperSection).toContain("'github.addIssueComment'") - expect(helperSection).toContain("'github.addPRReviewComment'") - expect(helperSection).toContain("'github.addPRReviewCommentReply'") - expect(helperSection).toContain('repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId)') - expect(helperSection).toContain('sourceContext: args.sourceContext') - expect(helperSection).toContain('notifyWorkItemDetailsMutation(') - expect(helperSection).toContain('{ local: false }') - }) - - it('routes PR file contents and runtime viewed invalidations through the task source context', () => { - const source = destSources( - 'github-item-dialog/load-item-details/work-item-details-cache.ts', - 'github-item-dialog/load-item-details/pr-file-content-cache.ts' - ) - const commentMutations = componentSource('github/github-work-item-comment-mutations.ts') - const fileContentsSection = sourceBetween( - source, - 'function loadPRFileContents', - 'touchPRFileContentCache(cacheKey, request)' - ) - const fileContentsCacheKeySection = sourceBetween( - source, - 'function getPRFileContentCacheKey', - 'function loadPRFileContents' - ) - const listenerSection = sourceBetween(source, 'let workItemMutatedUnsub', '// Why: bounded LRU') - - expect(fileContentsCacheKeySection).toContain( - 'source:${getTaskSourceCacheScope(args.sourceContext)}' - ) - expect(fileContentsSection).toContain("'github.prFileContents'") - expect(fileContentsSection).toContain( - 'repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId)' - ) - expect(fileContentsSection).toContain('sourceContext: args.sourceContext') - expect(fileContentsSection).toContain('sourceContext,') - expect(listenerSection).toContain('onGitHubWorkItemDetailsCacheMutation') - expect(commentMutations).toContain('emitGitHubWorkItemDetailsCacheMutation(args)') - expect(commentMutations).toContain('options.local !== false') - expect(commentMutations).toContain('notifyWorkItemMutated({') - }) - - it('routes merge actions through the repo owner host (#6957)', () => { - const actionsSection = componentSource( - 'github-item-dialog/land-pull-request/pr-actions-panel.tsx' - ) - - expect(actionsSection).toContain( - 'getGitHubMutationRoutingSettings(s, item.repoId ?? repoId ?? null, sourceContext)' - ) - expect(actionsSection).toContain('getActiveRuntimeTarget(sourceSettings)') - expect(actionsSection).toContain( - 'const canMergeWithRepoContext = !!repoPath || mergeTarget.kind ===' - ) - expect(actionsSection).toContain("'github.mergePR'") - expect(actionsSection).toContain("'github.setPRAutoMerge'") - expect(actionsSection).toContain('const prRepo = resolvePullRequestRepo(item, projectOrigin)') - expect(actionsSection).not.toContain('prRepo: item.prRepo ?? null') - expect(actionsSection).toContain( - 'repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId)' - ) - expect(actionsSection).toContain('sourceContext,') - expect(actionsSection).toContain('notifyWorkItemDetailsMutation(') - expect(actionsSection).toContain('{ local: false }') - }) - - it('routes check actions through the task source context', () => { - const checksSection = destSources( - 'github-item-dialog/inspect-pull-request/checks-tab.tsx', - 'github-item-dialog/inspect-pull-request/checks-tab-actions.ts', - 'github-item-dialog/inspect-pull-request/checks-tab-request-details.ts' - ) - - expect(checksSection).toContain('sourceContext?: TaskSourceContext | null') - expect(checksSection).toContain('sourceContext,') - expect(checksSection).toContain("'github.prChecks'") - expect(checksSection).toContain("'github.rerunPRChecks'") - expect(checksSection).toContain("'github.prCheckDetails'") - expect(checksSection).toContain( - 'repo: getGitHubRuntimeRepoId(ctx.sourceContext, ctx.repoId ?? ctx.itemRepoId)' - ) - expect(checksSection).toContain('window.api.gh.prChecks({') - expect(checksSection).toContain('window.api.gh.rerunPRChecks({') - expect(checksSection).toContain('prCheckDetails({') - expect(checksSection).toMatch( - /withGitHubCheckDetailsTimeout\(\(signal\) =>\s*ctx\.runtimeHost\s*\?\s*callRuntimeRpc[\s\S]*:\s*window\.api\.gh\.prCheckDetails\(\{/ - ) - expect(checksSection).toContain('{ timeoutMs: 30_000, signal }') - }) - - it('makes failed check detail loads retryable and fences stale responses', () => { - const checksSection = destSources( - 'github-item-dialog/inspect-pull-request/checks-tab.tsx', - 'github-item-dialog/inspect-pull-request/checks-tab-actions.ts', - 'github-item-dialog/inspect-pull-request/checks-tab-request-details.ts', - 'github-item-dialog/inspect-pull-request/checks-tab-check-details.tsx' - ) - - expect(checksSection).toContain('createGitHubChecksTabState(checks, checkDetailsContextKey)') - expect(checksSection).toContain('checksState,\n checks,\n checkDetailsContextKey') - expect(checksSection).toContain('resetGitHubChecksTabForSource(current)') - expect(checksSection).toContain( - 'committedChecksContextOwnerRef.current !== refreshContextOwner' - ) - expect(checksSection).toContain('activeChecksRefreshRequestIdRef.current !== refreshRequestId') - expect(checksSection).toContain('current.contextOwner === refreshContextOwner') - expect(checksSection).toContain( - 'const rerunContextOwner = ctx.committedChecksContextOwnerRef.current' - ) - expect(checksSection).toContain( - 'ctx.committedChecksContextOwnerRef.current !== rerunContextOwner' - ) - expect(checksSection).toContain('await refreshGitHubChecksTab(ctx, rerunContextOwner)') - expect(checksSection).toContain('!ctx.mountedRef.current ||') - expect(checksSection).toContain('settleGitHubChecksTabDetails(current, key, requestId, next)') - expect(checksSection).toContain('onClick={() => onRetry(check, getCheckDetailsKey(check))}') - expect(checksSection).toContain('disabled={state.loading}') - expect(checksSection).toContain('aria-busy={state.loading}') - expect(checksSection).toContain("translate('githubChecks.retrying', 'Retrying…')") - expect(checksSection).toContain("'Retry'") - }) - - it('uses hydrated work item details for the page checks tab', () => { - const source = componentSource('github-item-dialog/open-dialog/github-item-dialog-pr-tabs.tsx') - const checksTab = sourceBetween( - source, - ' { - const editSection = destSources( - 'github-item-dialog/edit-item-fields/gh-edit-section.tsx', - 'github-item-dialog/edit-item-fields/gh-edit-section-mutations.ts' - ) - expect(editSection).toContain('assertTaskPageGitHubDialogStateAuthority({') - expect(editSection).toContain('if (authority?.revert())') - - const actionsSection = componentSource( - 'github-item-dialog/land-pull-request/pr-actions-panel.tsx' - ) - expect(actionsSection.match(/assertTaskPageGitHubDialogStateAuthority\(\{/g)).toHaveLength(2) - expect(actionsSection).toContain('if (authority.revert())') - expect(actionsSection).toContain("state: 'merged'") - }) -}) diff --git a/src/renderer/src/components/github/repro-8784-ghe-avatar-fallback.test.ts b/src/renderer/src/components/github/repro-8784-ghe-avatar-fallback.test.ts index 8b33b3dc40c..ddf7fb92cff 100644 --- a/src/renderer/src/components/github/repro-8784-ghe-avatar-fallback.test.ts +++ b/src/renderer/src/components/github/repro-8784-ghe-avatar-fallback.test.ts @@ -4,15 +4,12 @@ * Regression guard (was a repro that documented the broken path). After the fix: * - resolveGitHubUserAvatarSrc prefers API URLs * - PullRequestPage author uses authorAvatarUrl via GitHubUserAvatar - * - TaskPage ReviewChipAvatar no longer hardcodes github.com login.png * * Re-run: * pnpm exec vitest run --config config/vitest.config.ts \ * src/renderer/src/components/github/repro-8784-ghe-avatar-fallback.test.ts */ import { describe, expect, it } from 'vitest' -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { githubAvatarUrl, resolveGitHubUserAvatarSrc } from './github-user-avatar' describe('issue #8784 GHE avatar fallback (regression)', () => { @@ -38,86 +35,4 @@ describe('issue #8784 GHE avatar fallback (regression)', () => { // enrichment + image onError → initials when this 404s. expect(githubAvatarUrl('corp-user')).toBe('https://github.com/corp-user.png?size=64') }) - - it('source routes PR author/reviewer avatars through GitHubUserAvatar + authorAvatarUrl', () => { - const prPage = readFileSync(join(__dirname, '../pull-request-page/page/header.tsx'), 'utf8') - expect(prPage).toMatch(/GitHubUserAvatar/) - expect(prPage).toMatch(/authorAvatarUrl/) - // Why: author chip must not ignore API avatar_url and only pass login. - expect(prPage).not.toMatch(/githubAvatarUrl\(workItem\.author\)/) - - const reviewChip = readFileSync(join(__dirname, '../task-page/github/Avatars.tsx'), 'utf8') - expect(reviewChip).toMatch(/GitHubUserAvatar/) - // Why: list chip must not hardcode github.com/{login}.png. - expect(reviewChip).not.toMatch(/github\.com\/\$\{reviewer\.login\}\.png/) - }) - - // GHES URLs can exist but fail unauthenticated; target slots need onError fallbacks. - // Scope checks because TaskPage also renders non-GitHub provider avatars. - const GITHUB_AVATAR_SLOTS = [ - { - file: 'pull-request-page/reviewers/picker-row.tsx', - fn: 'ReviewerPickerRow', - login: 'reviewer.login', - displayName: 'reviewer.name' - }, - { - file: 'pull-request-page/conversation/comment-card.tsx', - fn: 'ConversationCommentCard', - login: 'comment.author', - displayName: null - }, - { - file: 'pull-request-page/mentions/textarea.tsx', - fn: 'MentionTextarea', - login: 'option.login', - displayName: 'option.name' - }, - { - file: 'task-page/github/Avatars.tsx', - fn: 'GitHubAssigneeAvatar', - login: 'assignee.login', - displayName: 'assignee.name' - }, - { - file: 'task-page/github/AssigneesCell.tsx', - fn: 'GHAssigneesCell', - login: 'user.login', - displayName: 'user.name' - }, - { - file: 'task-page/github/ReviewerPicker.tsx', - fn: 'TaskPageGitHubReviewerPicker', - login: 'reviewer.login', - displayName: 'reviewer.name' - } - ] as const - - function componentBody(file: string, fn: string): string { - const source = readFileSync(join(__dirname, '..', file), 'utf8') - const start = source.indexOf(`function ${fn}`) - expect(start, `${file}: function ${fn} not found`).toBeGreaterThanOrEqual(0) - const next = source.indexOf('\nfunction ', start + 1) - return source.slice(start, next === -1 ? undefined : next) - } - - it.each(GITHUB_AVATAR_SLOTS)( - 'renders the $fn avatar through GitHubUserAvatar (#13976)', - ({ file, fn, login }) => { - const body = componentBody(file, fn) - - // Reject aliases and resolver expressions as well as direct avatarUrl fields. - expect(body, `${fn} still renders a bare img`).not.toMatch(/]/) - expect(body, `${fn} does not use GitHubUserAvatar`).toContain(' slot.displayName !== null))( - 'passes the $fn display name so initials are not reduced to one letter (#13976)', - ({ file, fn, displayName }) => { - expect(componentBody(file, fn)).toContain(`name={${displayName}}`) - } - ) }) diff --git a/src/renderer/src/components/linear-issue-workspace-api-parity.test.ts b/src/renderer/src/components/linear-issue-workspace-api-parity.test.ts deleted file mode 100644 index 91310627cf7..00000000000 --- a/src/renderer/src/components/linear-issue-workspace-api-parity.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -function componentSource(file: string): string { - return readFileSync(join(__dirname, file), 'utf8') -} - -describe('Linear issue workspace provider API parity', () => { - it('keeps detail and comments on the selected source and workspace', () => { - const source = componentSource('linear-issue-workspace-detail-state.ts') - expect(source).toContain('initialRequest.providerSettings,') - expect(source).toContain('initialRequest.issue.id,') - expect(source).toContain('initialRequest.issue.workspaceId') - expect(source).toContain('targetProviderSettings,') - expect(source).toContain('targetIssue.id,') - expect(source).toContain('targetIssue.workspaceId') - }) - - it('keeps project search and assignment source-scoped', () => { - const source = componentSource('linear-issue-project-selector.tsx') - expect(source).toContain( - 'linearListProjects(providerSettings, requestQuery, 20, issue.workspaceId)' - ) - expect(source).toMatch( - /linearUpdateIssue\(\s*providerSettings,\s*issue\.id,\s*\{ projectId: project\.id \},\s*issue\.workspaceId/ - ) - expect(source).toContain('patchLinearIssue(issue.id, { project }, { sourceContext })') - }) - - it('keeps sub-issue create and open payloads source-scoped', () => { - const source = componentSource('linear-issue-sub-issues.tsx') - expect(source).toContain('parentIssueId: issue.id') - expect(source).toContain('teamId: issue.team.id') - expect(source).toContain('workspaceId: issue.workspaceId') - expect(source).toContain('projectId: issue.project?.id ?? null') - expect(source).toMatch( - /fetchLinearIssue\(subIssue\.id, issue\.workspaceId, \{\s*sourceContext\s*\}\)/ - ) - }) - - it('keeps git and folder workspace attachments in the same lookup', () => { - const source = componentSource('LinearIssueWorkspace.tsx') - expect(source).toContain('...allWorktrees') - expect(source).toContain('...folderWorkspaces.map(folderWorkspaceToWorktree)') - expect(source).toContain('findLinearIssueWorkspaceAttachment(attachmentWorkspaces') - expect(source).toContain('openLinearIssueWorkspaceOrStart(detail.displayed') - }) -}) diff --git a/src/renderer/src/components/linear-issue-workspace-header.test.ts b/src/renderer/src/components/linear-issue-workspace-header.test.ts deleted file mode 100644 index 4fd36b23bf4..00000000000 --- a/src/renderer/src/components/linear-issue-workspace-header.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const source = readFileSync(join(__dirname, 'linear-issue-workspace-header.tsx'), 'utf8') - -function headerSource(): string { - const start = source.indexOf('
') - expect(header).toContain('') - expect(header).toContain("'Start workspace'") - expect(header).toContain("'Start workspace from issue'") - expect(header).not.toContain("'Copy issue identifier'") - expect(header).toMatch(/size="sm"[\s\S]*onClick=\{onOpenOrUseIssue\}/) - expect(header).not.toMatch(/size="icon-sm"\s+onClick=\{onOpenOrUseIssue\}/) - }) -}) diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.transport-probe.test.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.transport-probe.test.tsx deleted file mode 100644 index ffa8787e753..00000000000 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.transport-probe.test.tsx +++ /dev/null @@ -1,377 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import React from 'react' -import { afterEach, describe, expect, it, vi } from 'vitest' - -const { mocks, moduleFactories, resetStructuredSessionMocks } = await vi.hoisted(async () => - (await import('./NativeChatStructuredSession.test-harness')).createStructuredSessionMocks() -) - -vi.mock('@/runtime/structured-agent-session-client', () => - moduleFactories.structuredAgentSessionClient() -) -vi.mock('./use-structured-agent-session', () => moduleFactories.useStructuredAgentSession()) -vi.mock('./use-native-chat-font-scale', () => moduleFactories.useNativeChatFontScale()) -vi.mock('./use-native-chat-file-link-context', () => moduleFactories.useNativeChatFileLinkContext()) -vi.mock('./use-native-chat-file-link-click', () => moduleFactories.useNativeChatFileLinkClick()) -vi.mock('./NativeChatMessageList', () => moduleFactories.nativeChatMessageList()) -vi.mock('./NativeChatComposer', () => moduleFactories.nativeChatComposer()) -vi.mock('./NativeChatEmptyState', () => moduleFactories.nativeChatEmptyState()) -vi.mock('./NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard()) -vi.mock('./NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard()) - -import { NativeChatStructuredSession } from './NativeChatStructuredSession' - -describe('NativeChatStructuredSession transport-unconfirmed sends', () => { - afterEach(() => { - cleanup() - resetStructuredSessionMocks() - }) - - it('retries an unconfirmed transport send and clears the delivery notice', async () => { - mocks.mode = 'outbox' - mocks.call.mockRejectedValueOnce(new Error('socket closed')).mockResolvedValueOnce({ - ok: true, - value: { - submission: { - clientMessageId: 'client-1', - dispatchState: 'accepted' - } - } - }) - - render( - - ) - - const send = mocks.composerProps?.structuredTransport?.send as - | ((text: string, attachments: readonly { id: string; path: string }[]) => boolean) - | undefined - expect(send?.('hello', [])).toBe(true) - await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) - await waitFor(() => expect(screen.getByText('Message delivery is unconfirmed.')).toBeTruthy()) - - fireEvent.click(screen.getByRole('button', { name: /Retry/ })) - - await waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(2)) - await waitFor(() => expect(screen.queryByText('Message delivery is unconfirmed.')).toBeNull()) - }) - - it('resends a transport-unconfirmed head so later messages are not wedged', async () => { - mocks.mode = 'outbox' - mocks.submissions = [] - mocks.call.mockRejectedValueOnce(new Error('socket closed')).mockResolvedValue({ - ok: true, - value: { submission: { clientMessageId: 'client-1', dispatchState: 'accepted' } } - }) - - render( - - ) - - const send = mocks.composerProps?.structuredTransport?.send as - | ((text: string, attachments: readonly { id: string; path: string }[]) => boolean) - | undefined - expect(send?.('first', [])).toBe(true) - await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) - await waitFor(() => expect(screen.getByText('Message delivery is unconfirmed.')).toBeTruthy()) - - expect(send?.('second', [])).toBe(true) - // The head is probed automatically, clears, and the queue drains. - await waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(3), { timeout: 10000 }) - await waitFor(() => expect(screen.queryByText('Message delivery is unconfirmed.')).toBeNull()) - }, 20000) - - it('probes the same operation without marking an explicit user retry', async () => { - mocks.mode = 'outbox' - mocks.submissions = [] - mocks.call.mockRejectedValueOnce(new Error('socket closed')).mockResolvedValue({ - ok: true, - value: { submission: { clientMessageId: 'client-1', dispatchState: 'accepted' } } - }) - - render( - - ) - - const send = mocks.composerProps?.structuredTransport?.send as - | ((text: string, attachments: readonly { id: string; path: string }[]) => boolean) - | undefined - expect(send?.('first', [])).toBe(true) - await waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(2), { timeout: 10000 }) - - const first = mocks.call.mock.calls[0]?.[2] as Record - const probe = mocks.call.mock.calls[1]?.[2] as Record - expect(probe.retryUnknown).toBeUndefined() - // Same operation id: both dedupe layers key off it. - expect((probe.envelope as { clientOperationId: string }).clientOperationId).toBe( - (first.envelope as { clientOperationId: string }).clientOperationId - ) - }, 20000) - - it('parks a host-confirmed unknown instead of probing it', async () => { - mocks.mode = 'outbox' - mocks.call.mockRejectedValueOnce(new Error('socket closed')).mockResolvedValue({ - ok: true, - value: { submission: { clientMessageId: 'client-1', dispatchState: 'accepted' } } - }) - - render( - - ) - - const send = mocks.composerProps?.structuredTransport?.send as - | ((text: string, attachments: readonly { id: string; path: string }[]) => boolean) - | undefined - expect(send?.('first', [])).toBe(true) - await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) - - const sent = mocks.call.mock.calls[0]?.[2] as { envelope: { clientOperationId: string } } - // The host now reports an unresolved unknown: another replay is the user's call. - mocks.submissions = [ - { - clientMessageId: sent.envelope.clientOperationId, - fence: 1, - payloadFingerprint: 'fp', - dispatchState: 'unknown', - providerItemId: null, - reason: null, - submittedAt: 1, - resolvedAt: null - } - ] - // Queue a second message purely to re-render so the effect observes the - // new submissions; it must stay wedged behind the parked head. - await act(async () => { - send?.('second', []) - }) - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 3000)) - }) - expect(mocks.call).toHaveBeenCalledOnce() - }, 20000) - - it('still probes while streaming batches rebuild the submissions array', async () => { - mocks.mode = 'outbox' - mocks.submissions = [] - mocks.call.mockRejectedValueOnce(new Error('socket closed')).mockResolvedValue({ - ok: true, - value: { submission: { clientMessageId: 'client-1', dispatchState: 'accepted' } } - }) - - const makeView = (): React.ReactElement => ( - - ) - const { rerender } = render(makeView()) - - const send = mocks.composerProps?.structuredTransport?.send as - | ((text: string, attachments: readonly { id: string; path: string }[]) => boolean) - | undefined - expect(send?.('first', [])).toBe(true) - await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) - - // Each batch mints a fresh submissions array for an unrelated message. An - // array-identity dependency restarts the backoff on every one of these, so a - // stream that outlasts the delay would never let the probe fire. - for (let index = 0; index < 12; index += 1) { - mocks.submissions = [ - { - clientMessageId: `other-${index}`, - fence: 1, - payloadFingerprint: 'fp', - dispatchState: 'accepted', - providerItemId: null, - reason: null, - submittedAt: index, - resolvedAt: index - } - ] - await act(async () => { - rerender(makeView()) - await new Promise((resolve) => setTimeout(resolve, 250)) - }) - } - - // Asserted with no trailing grace period: the probe must have fired *during* - // the stream, not after it went quiet. - expect(mocks.call).toHaveBeenCalledTimes(2) - }, 20000) - - it('restarts probe delay when the runtime target changes', async () => { - mocks.mode = 'outbox' - mocks.call.mockRejectedValueOnce(new Error('socket closed')).mockResolvedValue({ - ok: true, - value: { submission: { clientMessageId: 'client-1', dispatchState: 'accepted' } } - }) - - const makeView = ( - target: { kind: 'local' } | { kind: 'environment'; environmentId: string } - ) => ( - - ) - const { rerender } = render(makeView({ kind: 'local' })) - const send = mocks.composerProps?.structuredTransport?.send as - | ((text: string, attachments: readonly { id: string; path: string }[]) => boolean) - | undefined - expect(send?.('first', [])).toBe(true) - await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) - await waitFor(() => expect(screen.getByText('Message delivery is unconfirmed.')).toBeTruthy()) - - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 300)) - }) - rerender(makeView({ kind: 'environment', environmentId: 'env-1' })) - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 600)) - }) - expect(mocks.call).toHaveBeenCalledOnce() - await waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(2), { timeout: 1500 }) - }, 10000) - - it('never auto-probes an entry the user already force-retried', async () => { - mocks.mode = 'outbox' - mocks.submissions = [] - // Both the original send and the user's explicit Retry fail at the transport. - mocks.call.mockRejectedValue(new Error('socket closed')) - - render( - - ) - - const send = mocks.composerProps?.structuredTransport?.send as - | ((text: string, attachments: readonly { id: string; path: string }[]) => boolean) - | undefined - expect(send?.('first', [])).toBe(true) - await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) - await waitFor(() => expect(screen.getByText('Message delivery is unconfirmed.')).toBeTruthy()) - - // User retries with the same envelope and no legacy redelivery signal. - fireEvent.click(screen.getByRole('button', { name: /Retry/ })) - await waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(2)) - const forcedRequest = mocks.call.mock.calls[1]?.[2] as Record | undefined - expect(forcedRequest?.retryUnknown).toBeUndefined() - - // That retry also failed at the transport. The probe must not repeat an - // explicit retry automatically. - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 3000)) - }) - expect(mocks.call).toHaveBeenCalledTimes(2) - }, 20000) - - it('does not hot-loop when the host answers pending', async () => { - mocks.mode = 'outbox' - mocks.call.mockResolvedValue({ - ok: true, - value: { submission: { clientMessageId: 'client-1', dispatchState: 'pending' } } - }) - - render( - - ) - - const send = mocks.composerProps?.structuredTransport?.send as - | ((text: string, attachments: readonly { id: string; path: string }[]) => boolean) - | undefined - expect(send?.('first', [])).toBe(true) - await waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) - - // A pending row parks the entry under the backoff instead of re-dispatching - // immediately. Without that, this window is an unbounded back-to-back RPC flood. - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 2500)) - }) - expect(mocks.call.mock.calls.length).toBeLessThanOrEqual(3) - }, 20000) - - it('keeps probing past the old five-attempt budget', async () => { - mocks.mode = 'outbox' - mocks.call.mockRejectedValue(new Error('socket closed')) - vi.useFakeTimers({ shouldAdvanceTime: true }) - try { - render( - - ) - - const send = mocks.composerProps?.structuredTransport?.send as - | ((text: string, attachments: readonly { id: string; path: string }[]) => boolean) - | undefined - expect(send?.('first', [])).toBe(true) - - // Backoff is 1+2+4+8+16 = 31s for five probes, which was the old hard budget. - // Step past it; a seventh call proves the probe re-arms instead of giving up. - for (let step = 0; step < 12; step += 1) { - await act(async () => { - await vi.advanceTimersByTimeAsync(8_000) - }) - } - expect(mocks.call.mock.calls.length).toBeGreaterThanOrEqual(7) - } finally { - vi.useRealTimers() - } - }, 30000) -}) diff --git a/src/renderer/src/components/native-chat/native-chat-composer-containment.test.ts b/src/renderer/src/components/native-chat/native-chat-composer-containment.test.ts deleted file mode 100644 index 2c8a08ffa89..00000000000 --- a/src/renderer/src/components/native-chat/native-chat-composer-containment.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import fs from 'node:fs' -import { describe, expect, it } from 'vitest' - -const composerField = fs.readFileSync( - new URL('./NativeChatComposerField.tsx', import.meta.url), - 'utf8' -) -const autocompleteMenus = fs.readFileSync( - new URL('./NativeChatAutocompleteMenus.tsx', import.meta.url), - 'utf8' -) - -describe('native chat composer paint containment (#10481)', () => { - it('bounds caret repaints to the composer input shell', () => { - expect(composerField).toContain('[contain:paint]') - }) - - it('keeps the outer composer uncontained so the pickers can overflow it', () => { - // The pickers are siblings that render above the shell via `bottom-full`; - // containing their parent would clip them. - const outerShell = composerField.slice(0, composerField.indexOf('[contain:paint]')) - expect(outerShell).toContain('
') - expect(outerShell).not.toContain('contain:paint') - }) - - it('lifts both pickers above the contained shell', () => { - // The shell is a stacking context now, so it paints at z-index 0 in tree - // order — an unlayered picker would lose its drop shadow to it. - for (const picker of ['bottom-full left-0 right-0 z-20', 'bottom-full left-3 right-3 z-20']) { - expect(autocompleteMenus).toContain(picker) - } - }) -}) diff --git a/src/renderer/src/components/native-chat/native-chat-noise.test.ts b/src/renderer/src/components/native-chat/native-chat-noise.test.ts deleted file mode 100644 index a9942ed82d7..00000000000 --- a/src/renderer/src/components/native-chat/native-chat-noise.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { NativeChatMessage } from '../../../../shared/native-chat-types' -import { isNoiseMessage, stripNoiseMessages } from './native-chat-noise' - -function msg( - role: NativeChatMessage['role'], - text: string, - blocks?: NativeChatMessage['blocks'] -): NativeChatMessage { - return { - id: text.slice(0, 8), - role, - blocks: blocks ?? [{ type: 'text', text }], - timestamp: 0, - source: 'transcript' - } -} - -describe('isNoiseMessage', () => { - it('flags task-notification and system-reminder user turns', () => { - expect(isNoiseMessage(msg('user', '\nx'))).toBe(true) - expect(isNoiseMessage(msg('user', '\nbe careful'))).toBe(true) - expect( - isNoiseMessage( - msg( - 'user', - 'Caveat: The messages below were generated by the user while running local commands' - ) - ) - ).toBe(true) - expect(isNoiseMessage(msg('user', '[Request interrupted by user]'))).toBe(true) - }) - - it('keeps real user messages', () => { - expect(isNoiseMessage(msg('user', 'make it work for codex'))).toBe(false) - expect(isNoiseMessage(msg('user', 'pasted code'))).toBe(false) - }) - - it('keeps assistant and tool turns', () => { - expect(isNoiseMessage(msg('assistant', ' in prose'))).toBe(false) - expect(isNoiseMessage(msg('system', 'Conversation interrupted'))).toBe(false) - }) - - it('keeps a user turn that carries tool results', () => { - expect(isNoiseMessage(msg('user', '', [{ type: 'tool-result', output: 'ok' }]))).toBe(false) - }) - - it('stripNoiseMessages removes only the noise', () => { - const out = stripNoiseMessages([ - msg('user', 'hello'), - msg('user', 'done'), - msg('assistant', 'hi') - ]) - expect(out.map((m) => m.role)).toEqual(['user', 'assistant']) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/SourceControl.host-context-boundary.test.ts b/src/renderer/src/components/right-sidebar/SourceControl.host-context-boundary.test.ts deleted file mode 100644 index 12539a08acc..00000000000 --- a/src/renderer/src/components/right-sidebar/SourceControl.host-context-boundary.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const WORKTREE_CONTEXT_SOURCE = readFileSync( - join(__dirname, 'source-control/listing/use-worktree-context.ts'), - 'utf8' -) -const PR_GENERATION_SOURCE = readFileSync( - join(__dirname, 'source-control/review/use-pull-request-generation.ts'), - 'utf8' -) -const CREATE_REVIEW_COMPOSER_SOURCE = readFileSync( - join(__dirname, 'source-control/review/use-create-review-composer.ts'), - 'utf8' -) -const STATUS_REFRESH_SOURCE = readFileSync( - join(__dirname, 'source-control/sync/use-status-refresh.ts'), - 'utf8' -) -const BASE_REF_DEFAULT_SOURCE = readFileSync( - join(__dirname, 'source-control/sync/use-base-ref-default.ts'), - 'utf8' -) - -function sourceBetween(source: string, startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('SourceControl host-context boundaries', () => { - it('snapshots PR generation host ownership and reuses it after async branch preparation', () => { - const generateSection = sourceBetween( - PR_GENERATION_SOURCE, - 'const handleGeneratePullRequestFieldsForActive = useCallback(', - 'const handleCancelGeneratePullRequestFieldsForActive = useCallback(' - ) - expect(generateSection).toContain('runtimeTargetSettings: activeRepoSettings') - expect(generateSection).toContain('settings: context.runtimeTargetSettings') - - const cancelSection = sourceBetween( - PR_GENERATION_SOURCE, - 'const handleCancelGeneratePullRequestFieldsForActive = useCallback(', - 'const handlePullRequestGenerationSeedRestored = useCallback(' - ) - expect(cancelSection).toContain('settings: record.context.runtimeTargetSettings') - - const refreshSection = sourceBetween( - STATUS_REFRESH_SOURCE, - 'const refreshGitStatusAfterPullRequestGeneration = useCallback(', - ' return {' - ) - expect(refreshSection).toContain('settings: context.runtimeTargetSettings') - expect(refreshSection).not.toContain('settings: activeRepoSettings') - }) - - it('routes create-review field generation through caller-provided owner settings', () => { - const composerCall = sourceBetween( - CREATE_REVIEW_COMPOSER_SOURCE, - '} = useCreatePullRequestDialogFields({', - 'const handleGeneratePullRequestFieldsClick = useCallback' - ) - expect(composerCall).toContain('settings: activeRepoSettings') - - const hookSource = readFileSync( - join(__dirname, 'use-create-pull-request-field-generation.ts'), - 'utf8' - ) - const requestContext = sourceBetween(hookSource, 'const requestContext = {', 'const seed = {') - expect(requestContext).toContain('settings,') - expect(requestContext).not.toContain('useAppStore.getState().settings') - }) - - it('keeps eligibility base refreshes scoped to repo execution ownership', () => { - const ownerSettingsSection = sourceBetween( - WORKTREE_CONTEXT_SOURCE, - 'const activeRepoSettings = useMemo(', - 'const activeRepoRuntimeEnvironmentId' - ) - expect(ownerSettingsSection).not.toContain('activeRepo ?? null') - expect(ownerSettingsSection).toContain( - '[activeRepoConnectionId, activeRepoExecutionHostId, activeRepoId, settings]' - ) - - const baseRefSection = sourceBetween( - BASE_REF_DEFAULT_SOURCE, - '// Why: reset to null so that effectiveBaseRef becomes falsy until the IPC', - ' return defaultBaseRef' - ) - expect(baseRefSection).toContain( - 'getRuntimeRepoBaseRefDefault(\n { activeRuntimeEnvironmentId: activeRepoRuntimeEnvironmentId },\n activeRepoId' - ) - const dependencyBlock = sourceBetween(baseRefSection, ' }, [', ' ])') - const dependencyEntries = dependencyBlock - .split('\n') - .slice(1) - .map((line) => line.trim().replace(/,$/, '')) - .filter((line) => line.length > 0 && !line.startsWith('//')) - expect(dependencyEntries).toEqual([ - 'activeRepoConnectionId', - 'activeRepoExecutionHostId', - 'activeRepoId', - 'activeRepoRuntimeEnvironmentId', - 'isBranchVisible', - 'isFolder' - ]) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-refresh.test.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-refresh.test.ts index 567e080360a..db39129526e 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-refresh.test.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-refresh.test.ts @@ -819,11 +819,4 @@ describe('useAiVaultSessionRefresh in a non-secure context', () => { }) }) }) - - // Guards the stub itself: an own-property stub of randomUUID is unrestorable, so a - // leaky teardown would silently strip the real method from every later test in the file. - it('leaves the real crypto.randomUUID in place afterwards', () => { - // oxlint-disable-next-line no-restricted-properties -- asserting the restore this case exists for - expect(typeof globalThis.crypto.randomUUID).toBe('function') - }) }) diff --git a/src/renderer/src/components/settings/GeneralPane.test.ts b/src/renderer/src/components/settings/GeneralPane.test.ts index 482fc1df787..e8fd5ea998b 100644 --- a/src/renderer/src/components/settings/GeneralPane.test.ts +++ b/src/renderer/src/components/settings/GeneralPane.test.ts @@ -4,7 +4,6 @@ import { getDesktopPlatformFromUserAgent, getGeneralPaneSearchEntries, getTabOrderControlSearchKeywords, - shouldCommitOpenInApplicationsDraft, shouldShowProjectRuntimeSection, updateAutoSaveDelayDraftState } from './GeneralPane' @@ -30,36 +29,6 @@ describe('GeneralPane auto-save delay drafts', () => { }) }) -describe('GeneralPane open-in application drafts', () => { - it('does not commit rows until both label and command are present', () => { - expect( - shouldCommitOpenInApplicationsDraft([{ id: 'draft', label: 'Cursor', command: '' }]) - ).toBe(false) - expect( - shouldCommitOpenInApplicationsDraft([{ id: 'draft', label: '', command: 'cursor' }]) - ).toBe(false) - expect( - shouldCommitOpenInApplicationsDraft([{ id: 'draft', label: ' ', command: 'cursor' }]) - ).toBe(false) - expect( - shouldCommitOpenInApplicationsDraft([{ id: 'draft', label: 'Cursor', command: ' ' }]) - ).toBe(false) - }) - - it('allows commit when every draft row has a label and command', () => { - expect(shouldCommitOpenInApplicationsDraft([])).toBe(true) - expect( - shouldCommitOpenInApplicationsDraft([{ id: 'cursor', label: 'Cursor', command: 'cursor' }]) - ).toBe(true) - expect( - shouldCommitOpenInApplicationsDraft([ - { id: 'cursor', label: 'Cursor', command: 'cursor' }, - { id: 'zed', label: 'Zed', command: 'zed' } - ]) - ).toBe(true) - }) -}) - describe('GeneralPane desktop platform detection', () => { it('keeps Windows available for Windows-only CLI settings', () => { expect( diff --git a/src/renderer/src/components/sidebar/DeleteWorktreeDialog.host-context-boundary.test.ts b/src/renderer/src/components/sidebar/DeleteWorktreeDialog.host-context-boundary.test.ts deleted file mode 100644 index 15f7cc04a98..00000000000 --- a/src/renderer/src/components/sidebar/DeleteWorktreeDialog.host-context-boundary.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const SOURCE = readFileSync(join(__dirname, 'use-delete-worktree-status-hydration.ts'), 'utf8') - -function sourceBetween(source: string, startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('DeleteWorktreeDialog host-context boundaries', () => { - it('preloads git status from the selected worktree owner instead of the focused host', () => { - const effect = sourceBetween(SOURCE, 'deleteTargets.filter(', 'return () => {') - - expect(effect).toContain('getSettingsForWorktreeRuntimeOwner') - expect(effect).toContain('worktreesByRepo: useAppStore.getState().worktreesByRepo') - expect(effect).toContain('target.id') - expect(effect).not.toContain('settings,\n worktreeId: target.id') - }) - - it('does not restart pending status requests when one target hydrates', () => { - const effect = sourceBetween(SOURCE, 'useEffect(() => {', '}, [') - - expect(SOURCE).not.toContain('useAppStore((state) => state.gitStatusByWorktree)') - expect(effect).toContain('useAppStore.getState().gitStatusByWorktree') - expect(effect).toContain('const controller = new AbortController()') - expect(effect).toContain('signal: controller.signal') - expect(effect).toContain('controller.abort()') - }) -}) diff --git a/src/renderer/src/components/sidebar/StatusIndicator.test.ts b/src/renderer/src/components/sidebar/StatusIndicator.test.ts index 1c238615628..668596ef6dd 100644 --- a/src/renderer/src/components/sidebar/StatusIndicator.test.ts +++ b/src/renderer/src/components/sidebar/StatusIndicator.test.ts @@ -36,15 +36,9 @@ describe('StatusIndicator', () => { it('renders working as a yellow spinner ring', () => { const markup = renderMarkup('working') - expect(markup).toContain('border-yellow-500') - expect(markup).toContain('border-t-transparent') - // Why: rotation must come from the compositor-driven CSS animation, not a - // JS clock writing per-element styles on the input thread (STA-3328). - expect(markup).toContain('agent-working-spinner') + // The spinner's own classes and animation contract belong to AgentWorkingSpinner.test.tsx; + // this pins only that 'working' reaches for it. expect(markup).toContain('data-agent-spinner') - // Why: under reduced motion the top border is filled so the static ring - // reads as a complete marker, not a broken partial spinner (#9515). - expect(markup).toContain('motion-reduce:border-t-yellow-500') }) it('renders monitoring as a static heartbeat glyph', () => { diff --git a/src/renderer/src/components/sidebar/project-group-header-dom.test.ts b/src/renderer/src/components/sidebar/project-group-header-dom.test.ts deleted file mode 100644 index 2e7523e5ecb..00000000000 --- a/src/renderer/src/components/sidebar/project-group-header-dom.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import { describe, expect, it } from 'vitest' - -function readWorktreeListSource(): string { - return readFileSync( - fileURLToPath(new URL('./worktree-list/rows/SectionHeader.tsx', import.meta.url)), - 'utf8' - ) -} - -function readHeaderDragSource(): string { - return readFileSync( - fileURLToPath(new URL('./worktree-list/drag/use-header-drag.ts', import.meta.url)), - 'utf8' - ) -} - -describe('Project Group header drag DOM source', () => { - it('renders concrete Project Group header drag attributes separately from repo headers', () => { - const source = readWorktreeListSource() - - expect(source).toContain('data-project-group-header-id={projectGroupIdForHeader}') - expect(source).toContain('data-project-group-header-index={projectGroupHeaderIndex}') - expect(source).toContain('data-project-group-header-bucket={projectGroupHeaderBucketKey}') - expect(source).toContain('data-project-group-header-drag-handle=') - }) - - it('commits Project Group manual sorting through updateProjectGroup tabOrder', () => { - const source = readHeaderDragSource() - - expect(source).toContain('const updateProjectGroup = useAppStore((s) => s.updateProjectGroup)') - // Why: the commit must carry the group's owner host so a non-focused host still persists the order. - expect(source).toContain( - 'void updateProjectGroup(groupId, { tabOrder }, { hostId: ownerHostId ?? undefined })' - ) - }) - - it('keeps grab cursor on the title surface and dual handle attrs on row + surface', () => { - // Why: lock the cursor/hit-test split so a cleanup does not put grab back on the whole row - // or drop row-level handle attrs that arm drag from indent/padding. - const source = readWorktreeListSource() - const headerBlockStart = source.indexOf('data-repo-header-id={projectIdForHeader}') - const headerBlockEnd = source.indexOf('', headerBlockStart) - expect(headerBlockStart).toBeGreaterThan(-1) - expect(headerBlockEnd).toBeGreaterThan(headerBlockStart) - const headerBlock = source.slice(headerBlockStart, headerBlockEnd) - - // Dual handle placement: row (indent/padding) + title surface. - expect(headerBlock.match(/data-repo-header-drag-handle=/g)?.length).toBe(2) - expect(headerBlock.match(/data-project-group-header-drag-handle=/g)?.length).toBe(2) - // Surface owns grab; outer row only gets cursor-pointer when not draggable. - expect(headerBlock).toContain( - "!(isDraggableRepoHeader || isDraggableProjectGroupHeader) && 'cursor-pointer'" - ) - expect(headerBlock).toContain("'flex min-w-0 flex-1 items-center gap-1.5 self-stretch'") - expect(headerBlock).toContain("'cursor-grab active:cursor-grabbing'") - // Row-level ternary grab must stay gone. - expect(headerBlock).not.toMatch( - /isDraggableRepoHeader \|\| isDraggableProjectGroupHeader\s*\?\s*'cursor-grab/ - ) - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-keyboard-cycle.test.ts b/src/renderer/src/components/sidebar/worktree-keyboard-cycle.test.ts index 430736c92be..9f5562d91cd 100644 --- a/src/renderer/src/components/sidebar/worktree-keyboard-cycle.test.ts +++ b/src/renderer/src/components/sidebar/worktree-keyboard-cycle.test.ts @@ -1,5 +1,3 @@ -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import type { HostSectionRow } from './host-section-rows' import { @@ -151,27 +149,3 @@ describe('getCyclableWorktreeIds', () => { expect(getCyclableWorktreeIds(rows, 'single-location')).toEqual(['visible-after-host']) }) }) - -describe('WorktreeList keyboard cycling', () => { - it('cycles over the rendered rows instead of rebuilding a parallel layout', () => { - const source = readFileSync( - fileURLToPath(new URL('./worktree-list/navigation/use-keyboard.ts', import.meta.url)), - 'utf8' - ) - const navigateWorktree = source.slice( - source.indexOf('const navigateWorktree = useCallback('), - source.indexOf('const handleContainerKeyDown = useCallback(') - ) - - // Why: a second buildRows call drifts from the rendered layout (host sections, - // pinned placement); cycling must read the same rows the viewport renders. - expect(navigateWorktree).toContain('getCyclableWorktreeRows(rows, pinnedDisplayPolicy)') - expect(navigateWorktree).toContain('getCyclableRowIdentity') - // Why: the active host is stored resolved while a local row is unqualified; comparing raw identities wraps to the top. - expect(navigateWorktree).toContain('resolveActiveCycleIdentity') - expect(navigateWorktree).not.toContain('composeWorktreeHostIdentity') - expect(navigateWorktree).toContain('executionHostId: nextWorktree.hostId') - expect(navigateWorktree).toContain('resolveCycledWorktreeId') - expect(navigateWorktree).not.toContain('buildRows(') - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/build-rows.test.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/build-rows.test.ts index d95c204026c..fb53b8d016a 100644 --- a/src/renderer/src/components/sidebar/worktree-list/grouping/build-rows.test.ts +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/build-rows.test.ts @@ -1,25 +1,11 @@ -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import { buildRows } from './build-rows' import { ALL_GROUP_META, getPRGroupKey, PINNED_GROUP_KEY } from './group-keys' import { getGroupKeyForWorktree } from './worktree-group-keys' -import { - REPO_HEADER_ACTION_BUTTON_CLASS, - REPO_HEADER_ACTION_REVEAL_CLASS -} from '../../repo-header-action-button-class' import { repo, worktree, repoMap } from '../../worktree-list-groups-test-fixtures' import type { Repo } from '../../../../../../shared/repo-types' import type { Worktree } from '../../../../../../shared/worktree/types' -function readWorktreeListSource(): string { - return readFileSync(fileURLToPath(new URL('../../WorktreeList.tsx', import.meta.url)), 'utf8') -} - -function readSectionHeaderRowSource(): string { - return readFileSync(fileURLToPath(new URL('../rows/SectionHeader.tsx', import.meta.url)), 'utf8') -} - describe('getPRGroupKey', () => { it('puts merged PRs in the done group', () => { const prCache = { @@ -382,40 +368,3 @@ describe('buildRows with pinned worktrees', () => { ]) }) }) - -describe('WorktreeList header styles', () => { - it('does not title-case workspace group labels', () => { - const source = readSectionHeaderRowSource() - - expect(source).not.toContain('leading-none capitalize') - }) - - it('collapses repo header actions without reserving title width', () => { - expect(REPO_HEADER_ACTION_REVEAL_CLASS).toContain('min-w-0 max-w-0 -ml-1.5') - expect(REPO_HEADER_ACTION_REVEAL_CLASS).toContain('focus:ml-0 focus:max-w-5 focus:opacity-100') - expect(REPO_HEADER_ACTION_REVEAL_CLASS).toContain( - 'group-hover:ml-0 group-hover:max-w-5 group-hover:opacity-100' - ) - expect(REPO_HEADER_ACTION_BUTTON_CLASS).toContain( - 'transition-[margin,max-width,opacity,background-color,color]' - ) - expect(REPO_HEADER_ACTION_BUTTON_CLASS).toContain( - 'data-[state=open]:ml-0 data-[state=open]:max-w-5 data-[state=open]:opacity-100' - ) - }) - - it('resolves repo header color from project group headers only', () => { - const source = readSectionHeaderRowSource() - - expect(source).toContain('resolveProjectGroupHeaderColor({') - expect(source).toContain('headerKey: row.key') - expect(source).toContain('color={repoHeaderColor}') - }) - - it('adapts projected setup rows for sidebar project grouping', () => { - const source = readWorktreeListSource() - - expect(source).toContain('const projectHostSetupProjection = useProjectHostSetupProjection()') - expect(source).toContain('projectHostSetups: projectHostSetupProjection.setups') - }) -}) diff --git a/src/renderer/src/components/status-bar/PetStatusSegment.layout.test.ts b/src/renderer/src/components/status-bar/PetStatusSegment.layout.test.ts deleted file mode 100644 index e213100816e..00000000000 --- a/src/renderer/src/components/status-bar/PetStatusSegment.layout.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -describe('PetStatusSegment layout', () => { - it('does not reserve fixed right padding on the pet menu trigger', () => { - const source = readFileSync(join(__dirname, 'PetStatusSegment.tsx'), 'utf8') - - // Why: the old pr-[6.5rem] reserved ~104px of empty space after the label and - // shoved neighboring status-bar segments left; unit-guard so CI catches a - // reintroduction without needing Electron Playwright. - expect(source).not.toMatch(/pr-\[\d+(?:\.\d+)?rem\]/) - expect(source).toMatch(/className="group inline-flex items-center cursor-pointer pl-1 py-0\.5"/) - }) -}) diff --git a/src/renderer/src/components/status-bar/resource-session-classification-parity.test.ts b/src/renderer/src/components/status-bar/resource-session-classification-parity.test.ts deleted file mode 100644 index ec7c7a62848..00000000000 --- a/src/renderer/src/components/status-bar/resource-session-classification-parity.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { readFileSync } from 'node:fs' -import { resolve } from 'node:path' -import { describe, expect, it } from 'vitest' - -const CONTROLLER_PATH = resolve(__dirname, 'use-resource-usage-status-controller.ts') -const DERIVED_MODEL_PATH = resolve(__dirname, 'use-resource-usage-derived-model.ts') - -/** - * Both destructive paths — bulk "kill orphans" and a single row's kill — must classify from the - * same binding inputs. When the merge call site re-listed the fields instead of reusing the - * object, it silently omitted deferred SSH sessions: bulk cleanup spared them while the row's - * kill destroyed them with no confirmation. Same bug, one click over (#8459). - */ -describe('resource session classification parity', () => { - it('feeds the row merge the same binding inputs as the bulk selector', () => { - const source = readFileSync(DERIVED_MODEL_PATH, 'utf8') - const mergeCall = source.slice( - source.indexOf('mergeSnapshotAndSessions(resourceSnapshot'), - source.indexOf('ambiguousWorktreeIds\n })') - ) - - expect(mergeCall).toContain('...resourceSessionBindings') - // Any of these appearing inline means the call site is re-deriving bindings and can drift. - for (const field of [ - 'ptyIdsByTabId,', - 'tabsByWorktree,', - 'terminalLayoutsByTabId,', - 'deferredSshSessionIdsByTabId,', - 'workspaceSessionReady,' - ]) { - expect(mergeCall).not.toContain(field) - } - }) - - it('keeps every binding source in the one object both paths read', () => { - const source = readFileSync(CONTROLLER_PATH, 'utf8') - const bindings = source.slice( - source.indexOf('const resourceSessionBindings = useMemo'), - source.indexOf('const popoverBodyRef') - ) - - for (const field of [ - 'ptyIdsByTabId', - 'tabsByWorktree', - 'terminalLayoutsByTabId', - 'deferredSshSessionIdsByTabId', - 'workspaceSessionReady' - ]) { - expect(bindings).toContain(field) - } - }) -}) diff --git a/src/renderer/src/components/status-bar/workspace-space-manager-source-boundary.test.ts b/src/renderer/src/components/status-bar/workspace-space-manager-source-boundary.test.ts deleted file mode 100644 index 3bf7a94c1dd..00000000000 --- a/src/renderer/src/components/status-bar/workspace-space-manager-source-boundary.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const COMPONENT_ROOT = __dirname -const PRODUCTION_MODULES = [ - 'WorkspaceSpaceManagerPanel.tsx', - 'use-workspace-space-decision-projection.ts', - 'use-workspace-space-git-refresh-action.ts', - 'use-workspace-space-manager-bindings.ts', - 'use-workspace-space-manager-panel.ts', - 'use-workspace-space-manager-projection.ts', - 'workspace-space-breakdown-list.tsx', - 'workspace-space-decision-details.ts', - 'workspace-space-decision-hover-card.tsx', - 'workspace-space-manager-overview.tsx', - 'workspace-space-manager-state-types.ts', - 'workspace-space-manager-table.tsx', - 'workspace-space-manager-toolbar.tsx', - 'workspace-space-manager-view.tsx', - 'workspace-space-metrics.tsx', - 'workspace-space-selection-controls.tsx', - 'workspace-space-status-badge.tsx', - 'workspace-space-treemap.tsx', - 'workspace-space-worktree-row.tsx' -] as const - -function source(relativePath: string): string { - return readFileSync(join(COMPONENT_ROOT, relativePath), 'utf8').replace(/\r\n?/g, '\n') -} - -describe('workspace space manager source boundaries', () => { - it('keeps the public export path as a controller/view facade', () => { - const facade = source('WorkspaceSpaceManagerPanel.tsx') - - expect(facade).toContain('useWorkspaceSpaceManagerPanel()') - expect(facade).toContain('') - expect(facade).toContain('export { getWorkspaceDecisionDetails }') - expect(facade).not.toContain('max-lines') - }) - - it('keeps every production module below its physical line limit', () => { - for (const moduleName of PRODUCTION_MODULES) { - const moduleSource = source(moduleName) - const limit = moduleName.endsWith('.tsx') ? 400 : 300 - - expect(moduleSource.split('\n').length - 1, moduleName).toBeLessThan(limit) - expect(moduleSource, moduleName).not.toContain('disable max-lines') - } - }) - - it('preserves bounded git refreshes and source-owned runtime routing', () => { - const action = source('use-workspace-space-git-refresh-action.ts') - const projection = source('use-workspace-space-manager-projection.ts') - - expect(action).toContain('const currentState = useAppStore.getState()') - expect(action).toContain('connectionId:') - expect(action).toContain('getRuntimeGitStatus({') - expect(action).toContain('getWorkspaceSpaceWorktreeIdentity(worktree)') - expect(action).toContain('inFlightGitStatusRefreshes.current.delete(requestKey)') - expect(projection).toContain('const GIT_STATUS_REFRESH_CONCURRENCY = 6') - expect(projection).toContain('await refreshWorkspaceGitStatus(worktree)') - expect(projection).toContain('void Promise.all(') - expect(projection).toContain('cancelled = true') - }) - - it('preserves normal, force, and open-workspace action routing', () => { - const controller = source('use-workspace-space-manager-panel.ts') - const table = source('workspace-space-manager-table.tsx') - - expect(controller).toContain('runWorktreeBatchDelete(identities, {') - expect(controller).toContain('forceConfirm: true') - expect(controller).toContain('prepareActiveWorktreeFocusAfterDelete(worktree.worktreeId)') - expect(controller).toContain( - 'removeWorktree(\n { id: worktree.worktreeId, executionHostId: worktree.executionHostId ?? null },\n true,\n { allowUnverifiedPtyStop: true }\n )' - ) - expect(table).toContain('activateAndRevealWorktree(worktree.worktreeId, {') - }) -}) diff --git a/src/renderer/src/components/tab-bar/client-hosted-browser-row-strip-placement.test.ts b/src/renderer/src/components/tab-bar/client-hosted-browser-row-strip-placement.test.ts index 2b3dfadf473..a2b30515f1d 100644 --- a/src/renderer/src/components/tab-bar/client-hosted-browser-row-strip-placement.test.ts +++ b/src/renderer/src/components/tab-bar/client-hosted-browser-row-strip-placement.test.ts @@ -1,28 +1,11 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { resolveClientHostedBrowserRowStripGroupId } from './client-hosted-browser-row-strip-placement' -function itemSurfaceSource(): string { - return readFileSync(join(__dirname, 'tab-bar-item-surface.tsx'), 'utf8') -} - describe('resolveClientHostedBrowserRowStripGroupId', () => { - it('names exactly one owning strip when the worktree is split', () => { - const groups = [{ id: 'group-left' }, { id: 'group-right' }, { id: 'group-bottom' }] - - const owner = resolveClientHostedBrowserRowStripGroupId(groups) - - expect(groups.filter((group) => group.id === owner)).toHaveLength(1) - }) - // Why: picking the focused group instead would make a row hop strips as the user clicks around. it('keeps the same owner as focus moves', () => { const groups = [{ id: 'group-left' }, { id: 'group-right' }] - expect(resolveClientHostedBrowserRowStripGroupId(groups)).toBe( - resolveClientHostedBrowserRowStripGroupId([...groups]) - ) expect(resolveClientHostedBrowserRowStripGroupId(groups)).toBe('group-left') }) @@ -30,28 +13,3 @@ describe('resolveClientHostedBrowserRowStripGroupId', () => { expect(resolveClientHostedBrowserRowStripGroupId([])).toBeNull() }) }) - -/** - * A client-hosted placeholder is retired by activating anything else in its strip. That only holds - * while every row kind's activation goes through the one wrapper — a new kind wired straight to - * its `onActivate*` prop would leave the placeholder covering the pane it just switched to. - */ -describe('tab-bar activation census', () => { - it('routes every row kind activation through the placeholder-clearing wrapper', () => { - const source = itemSurfaceSource() - const activations = source.match(/onActivate=\{[^}]*\}/g) ?? [] - - expect(activations.length).toBeGreaterThan(0) - for (const activation of activations) { - expect(activation, 'a row kind activates without retiring the placeholder').toContain( - 'activateRealTab(' - ) - } - }) - - it('clears the placeholder before handing off to the real activation', () => { - expect(itemSurfaceSource()).toMatch( - /clearClientHostedBrowserRowSelection\(\)\s*\n\s*activate\?\.\(arg\)/ - ) - }) -}) diff --git a/src/renderer/src/components/tab-bar/tab-bar-item-surface.client-hosted-active-state.test.tsx b/src/renderer/src/components/tab-bar/tab-bar-item-surface.client-hosted-active-state.test.tsx index 2cdff8b1931..a3f85044626 100644 --- a/src/renderer/src/components/tab-bar/tab-bar-item-surface.client-hosted-active-state.test.tsx +++ b/src/renderer/src/components/tab-bar/tab-bar-item-surface.client-hosted-active-state.test.tsx @@ -1,7 +1,5 @@ // @vitest-environment happy-dom -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import type React from 'react' import { afterEach, describe, expect, it } from 'vitest' import type { WorkspaceVisibleTabType } from '../../../../shared/tab-types' @@ -166,21 +164,3 @@ describe('client-hosted row while a real tab is activated', () => { } ) }) - -/** - * The fixtures above cannot cover a row kind that does not exist yet, and a new one wired straight - * to its own active-tab selector is exactly how this regressed the first time. - */ -describe('tab-bar active-state census', () => { - it('suppresses every row kind while a client-hosted row owns the strip', () => { - const source = readFileSync(join(__dirname, 'tab-bar-item-surface.tsx'), 'utf8') - const decisions = source.match(/isActive=\{[^}]*\}/g) ?? [] - - expect(decisions.length).toBeGreaterThan(0) - for (const decision of decisions) { - expect(decision, 'a row kind underlines itself past a client-hosted row').toContain( - '!clientHostedRowOwnsActiveState' - ) - } - }) -}) diff --git a/src/renderer/src/components/task-drawer-source-boundary.test.ts b/src/renderer/src/components/task-drawer-source-boundary.test.ts deleted file mode 100644 index 1a2f64504e7..00000000000 --- a/src/renderer/src/components/task-drawer-source-boundary.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const COMPONENT_ROOT = __dirname - -function componentSource(relativePath: string): string { - return readFileSync(join(COMPONENT_ROOT, relativePath), 'utf8').replace(/\r\n?/g, '\n') -} - -function sourceBetween(source: string, startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('task drawer source boundaries', () => { - it('threads GitHub task source context through detail mutations', () => { - const source = [ - componentSource('github-item-dialog/edit-item-fields/gh-edit-section.tsx'), - componentSource('github-item-dialog/edit-item-fields/gh-edit-section-mutations.ts') - ].join('\n') - const issueUpdate = sourceBetween( - componentSource('github/github-work-item-edit-mutations.ts'), - 'async function runIssueUpdate', - 'async function runWorkItemBodyUpdate' - ) - const commentUpdate = sourceBetween( - componentSource('github/github-work-item-comment-mutations.ts'), - 'function addIssueCommentForRepo', - 'function addPRReviewCommentForRepo' - ) - const editSection = source - - expect(issueUpdate).toContain('sourceContext: args.sourceContext') - expect(commentUpdate).toContain('sourceContext: args.sourceContext') - expect(editSection).toContain('sourceContext,') - expect(editSection).toContain( - 'patchWorkItem(itemId, { state: newState }, itemRepoId, { sourceContext })' - ) - expect(editSection).toContain( - 'patchWorkItem(itemId, { labels: newLabels }, itemRepoId, { sourceContext })' - ) - }) - - it('threads GitLab task source context through the shared drawer selector', () => { - const controllerSource = componentSource('GitLabItemDialog.tsx') - const source = [ - controllerSource, - componentSource('gitlab-item-dialog/use-gitlab-item-dialog-effects.ts'), - componentSource('gitlab-item-dialog/use-gitlab-details-editing.ts'), - componentSource('gitlab-item-dialog/use-gitlab-primary-actions.ts'), - componentSource('gitlab-item-dialog/use-gitlab-review-actions.ts') - ].join('\n') - const selector = sourceBetween( - controllerSource, - 'const repoSelector = useMemo', - 'const updateCommentDraft' - ) - - expect(selector).toContain('...(repoId ? { repoId } : {})') - expect(selector).toContain('...(sourceContext ? { sourceContext } : {})') - expect(selector).toContain('}, [repoId, repoPath, sourceContext])') - expect(source).toContain('workItemDetails({ ...repoSelector') - expect(source).toContain('updateMR({ ...repoSelector') - expect(source).toContain('addMRComment({') - expect(source).toContain('addIssueComment({') - expect(source).toContain('...repoSelector') - }) - - it('uses Linear task source context for drawer reads, mutations, and optimistic patches', () => { - const drawerSource = componentSource('LinearItemDrawer.tsx') - const editSection = componentSource('linear-item-drawer-edit-controller.tsx') - const drawer = sourceBetween( - drawerSource, - 'export default function LinearItemDrawer', - 'return renderLinearItemDrawerSheet' - ) - - expect(editSection).toContain('const providerSettings = sourceContext ?? settings') - expect(editSection).toContain('linearUpdateIssue(providerSettings') - expect(editSection).toContain( - 'patchLinearIssue(issue.id, { state: stateValue }, { sourceContext })' - ) - expect(editSection).toContain( - 'patchLinearIssue(issue.id, { assignee: newAssignee }, { sourceContext })' - ) - expect(drawer).toContain('const providerSettings = sourceContext ?? settings') - expect(drawer).toContain('linearGetIssue(providerSettings') - expect(drawer).toContain('linearIssueComments(providerSettings') - }) - - it('uses Jira task source context for drawer reads, mutations, and optimistic patches', () => { - const source = componentSource('JiraIssueWorkspace.tsx') - const drawer = sourceBetween(source, 'export default function JiraIssueWorkspace', 'return (') - - expect(drawer).toContain('const providerSettings = sourceContext ?? settings') - expect(drawer).toContain('jiraIssueComments(providerSettings') - expect(drawer).toContain('jiraGetIssue(providerSettings') - expect(drawer).toContain('jiraListTransitions(providerSettings') - expect(drawer).toContain('jiraUpdateIssue(providerSettings') - expect(drawer).toContain('jiraAddIssueComment(') - expect(drawer).toContain('patchJiraIssue(displayed.key, optimistic, { sourceContext })') - expect(drawer).toContain('patchJiraIssue(previous.key, previous, { sourceContext })') - }) -}) diff --git a/src/renderer/src/components/task-page-github-issue-creation.test.ts b/src/renderer/src/components/task-page-github-issue-creation.test.ts deleted file mode 100644 index bacc3988bb8..00000000000 --- a/src/renderer/src/components/task-page-github-issue-creation.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readTaskPageSource } from './task-page-source-family.test-support' -import { readFileSync } from 'node:fs' - -const taskPageSource = readTaskPageSource('use-task-page-github-issue-creation.ts') -const newIssueDraftSource = readFileSync( - new URL('./use-task-page-github-issue-draft.ts', import.meta.url), - 'utf8' -) -const newIssueRepoResetSource = readFileSync( - new URL('./task-page-new-issue-draft.ts', import.meta.url), - 'utf8' -) - -function issueCreationSection(): string { - const start = taskPageSource.indexOf('const handleCreateNewIssue') - expect(start).toBeGreaterThanOrEqual(0) - const end = taskPageSource.indexOf('const nextModel', start) - expect(end).toBeGreaterThan(start) - return taskPageSource.slice(start, end) -} - -describe('TaskPage GitHub issue creation', () => { - it('keeps issue creation targeted to the first selected repo on a fresh mount', () => { - expect(newIssueDraftSource).toContain( - 'selectedRepos.find((r) => r.id === newIssueRepoId) ?? selectedRepos[0] ?? null' - ) - // Why: a repo leaving the selection mid-draft must reset to the first selected repo. - expect(newIssueRepoResetSource).toContain('newIssueRepoId === null') - expect(newIssueRepoResetSource).toContain('return { repoId: selectedRepoIds[0] ?? null }') - }) - - it('covers the complete remote oversized-body recovery timeout envelope', () => { - const section = issueCreationSection() - - expect(section).toContain("'github.createIssue'") - expect(section).toMatch(/\{\s*timeoutMs: 65_000\s*\}/) - }) - - it('treats a body-save warning as created while preserving the recovery draft', () => { - const section = issueCreationSection() - const warningBranch = section.slice( - section.indexOf('if (result.bodySaveWarning)'), - section.indexOf('// Why: bump the nonce') - ) - - expect(warningBranch).toContain('toast.warning') - expect(warningBranch).toContain('description: result.bodySaveWarning') - expect(warningBranch).toMatch(/setNewIssueDraft\(\{\s*title: ''\s*\}\)/) - expect(warningBranch).toContain('} else {') - expect(warningBranch).toContain('clearNewIssueDraft()') - }) -}) diff --git a/src/renderer/src/components/task-page-source-family.test-support.ts b/src/renderer/src/components/task-page-source-family.test-support.ts deleted file mode 100644 index 14dd9a76d2e..00000000000 --- a/src/renderer/src/components/task-page-source-family.test-support.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { readFileSync, readdirSync } from 'node:fs' -import { join } from 'node:path' - -const TASK_PAGE_FLAT_SOURCE_PATTERN = /^(?:use-task-page-.*\.ts|task-page-.*\.tsx?)$/ -const TASK_PAGE_DIRECTORY = 'task-page' -function isSourceFile(name: string): boolean { - return !name.includes('.test.') && !name.includes('.test-support.') -} - -// Why: the components/task-page tree nests by provider, so a flat readdir would silently -// return an empty family and turn every ratchet built on it into a no-op. -function readTaskPageDirectory(relativeDirectory: string): string[] { - return readdirSync(join(__dirname, relativeDirectory), { withFileTypes: true }).flatMap( - (entry) => { - const relativePath = `${relativeDirectory}/${entry.name}` - if (entry.isDirectory()) { - return readTaskPageDirectory(relativePath) - } - return /\.tsx?$/.test(entry.name) && isSourceFile(entry.name) ? [relativePath] : [] - } - ) -} - -export const TASK_PAGE_SOURCE_FILES = [ - ...readdirSync(__dirname).filter( - (name) => TASK_PAGE_FLAT_SOURCE_PATTERN.test(name) && isSourceFile(name) - ), - ...readTaskPageDirectory(TASK_PAGE_DIRECTORY) -].sort() - -export function readTaskPageSource(relativePath: string): string { - return readFileSync(join(__dirname, relativePath), 'utf8') -} - -export function readTaskPageSourceFamily(): string { - return TASK_PAGE_SOURCE_FILES.map( - (relativePath) => `// TaskPage source: ${relativePath}\n${readTaskPageSource(relativePath)}` - ).join('\n') -} diff --git a/src/renderer/src/components/task-page-source-switch-boundary.test.ts b/src/renderer/src/components/task-page-source-switch-boundary.test.ts deleted file mode 100644 index ae3bc60df21..00000000000 --- a/src/renderer/src/components/task-page-source-switch-boundary.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readTaskPageSource } from './task-page-source-family.test-support' - -const CONTENT_SOURCE = readTaskPageSource('task-page/Content.tsx') -const SOURCE_BAR_SOURCE = readTaskPageSource('task-page/SourceBar.tsx') -const SOURCE_CONTEXT_SOURCE = readTaskPageSource('task-page-source-context.tsx') -const RUNTIME_HOSTS_SOURCE = readTaskPageSource('use-task-page-runtime-hosts.ts') -const GITHUB_DETAIL_SOURCE = readTaskPageSource('use-task-page-github-detail.ts') -const WORKSPACE_ACTIONS_SOURCE = readTaskPageSource('use-task-page-workspace-actions.ts') - -function sourceBetween(source: string, startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('TaskPage source switching host boundary', () => { - it('renders GitHub item details from the task-detail page owner only', () => { - const detailSection = sourceBetween( - CONTENT_SOURCE, - '') - expect(detailSection).toContain('workItem={dialogWorkItem}') - expect(detailSection).toContain(' { - const section = sourceBetween( - SOURCE_BAR_SOURCE, - '{visibleSourceOptions.map((source) => {', - "{taskSource === 'linear' && linearConnected ?" - ) - - expect(section).toContain('openTaskPage(') - expect(section).toContain('taskSource: source.id') - expect(section).toContain('defaultTaskSource: source.id') - expect(section).not.toContain('activeRuntimeEnvironmentId') - expect(section).not.toContain('projectHostSetupId') - expect(section).not.toContain('workspaceRunContext') - }) - - it('treats missing remote task-source capability as source unavailable', () => { - const section = sourceBetween( - SOURCE_CONTEXT_SOURCE, - 'function getTaskSourceHostAvailabilityForHost', - 'function getTaskPageRepoCacheInput' - ) - - expect(section).toContain('TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY') - expect(section).toContain("reason: 'checking-task-source-capability'") - expect(section).toContain("reason: 'missing-task-source-capability'") - }) - - it('checks runtime-owned provider auth on the owning runtime', () => { - const section = sourceBetween( - RUNTIME_HOSTS_SOURCE, - 'const runtimeTaskSourceHostIds = useMemo(() => {', - 'const nextModel' - ) - - expect(section).toContain('TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY') - expect(section).toContain("'preflight.check'") - expect(section).toMatch(/\{\s*kind: 'environment',\s*environmentId: parsed\.environmentId\s*\}/) - expect(RUNTIME_HOSTS_SOURCE).toContain('runtimePreflightStatusByHostId') - }) - - it('preserves exact GitLab project identity when opening or starting from an item', () => { - const sourceContextBuilder = sourceBetween( - SOURCE_CONTEXT_SOURCE, - 'function getTaskPageRepoSourceContext', - 'function getTaskSourceHostAvailabilityForHost' - ) - expect(sourceContextBuilder).toContain('gitlabProjectRef?: GitLabProjectRef | null') - expect(sourceContextBuilder).toContain('buildGitLabProviderIdentity(gitlabProjectRef)') - - const openGitLabDetail = sourceBetween( - GITHUB_DETAIL_SOURCE, - 'const openGitLabDetailPage = useCallback(', - 'const nextModel' - ) - expect(openGitLabDetail).toContain('item.projectRef') - - const startGitLabWorkspace = sourceBetween( - WORKSPACE_ACTIONS_SOURCE, - 'const openComposerForGitLabItem = useCallback(', - 'const handleUseGitLabItem = useCallback(' - ) - expect(startGitLabWorkspace).toContain('item.projectRef') - }) -}) diff --git a/src/renderer/src/components/task-page-task-creation-drafts.test.ts b/src/renderer/src/components/task-page-task-creation-drafts.test.ts deleted file mode 100644 index 969c1b0c373..00000000000 --- a/src/renderer/src/components/task-page-task-creation-drafts.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { readFileSync } from 'node:fs' -import { describe, expect, it } from 'vitest' -import { - readTaskPageSource, - readTaskPageSourceFamily -} from './task-page-source-family.test-support' - -const taskPageSource = readTaskPageSourceFamily() -const linearCreateDialogsSource = readFileSync( - new URL('./use-task-page-linear-creation-state.ts', import.meta.url), - 'utf8' -) -const jiraCreateDialogSource = readFileSync( - new URL('./use-task-page-jira-creation-state.ts', import.meta.url), - 'utf8' -) -const jiraCreateSubmitSource = readFileSync( - new URL('./use-task-page-jira-issue-creation.ts', import.meta.url), - 'utf8' -) -const draftWriterSource = readFileSync( - new URL('./task-page-draft-storage.tsx', import.meta.url), - 'utf8' -) -const draftRetentionSource = [linearCreateDialogsSource, jiraCreateDialogSource].join('\n') - -function sectionBetween(source: string, startAnchor: string, endAnchor: string): string { - const start = source.indexOf(startAnchor) - expect(start, `missing anchor: ${startAnchor}`).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endAnchor, start) - expect(end, `missing anchor: ${endAnchor}`).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('TaskPage Linear/Jira creation drafts', () => { - it('uses the contentful gate for each session draft writer', () => { - expect(draftWriterSource.split('isTaskCreationDraftContentful(draft)')).toHaveLength(4) - }) - - it('retains all three drafts on dismissal without subscribing TaskPage to draft actions', () => { - expect(draftRetentionSource.split('useTaskCreationDraftRetention({')).toHaveLength(4) - expect(taskPageSource).not.toMatch( - /useAppStore\(\(s\) => s\.(?:set|clear)New(?:LinearProject|LinearIssue|JiraIssue)Draft\)/ - ) - expect(draftRetentionSource).not.toMatch( - /useAppStore\(\(s\) => s\.(?:set|clear)New(?:LinearProject|LinearIssue|JiraIssue)Draft\)/ - ) - }) - - it('restores dismissed typed text when each dialog reopens', () => { - const linearFilters = readFileSync( - new URL('./task-page/linear/Filters.tsx', import.meta.url), - 'utf8' - ) - const jiraFilters = readFileSync( - new URL('./task-page/jira/Filters.tsx', import.meta.url), - 'utf8' - ) - expect(linearFilters).toContain("setNewLinearProjectName(draft?.name ?? '')") - expect(linearFilters).toContain("setNewLinearProjectDescription(draft?.description ?? '')") - expect(linearFilters).toContain("setNewLinearProjectContent(draft?.content ?? '')") - expect(linearFilters).toContain("setNewLinearIssueTitle(issueDraft?.title ?? '')") - expect(linearFilters).toContain("setNewLinearIssueBody(issueDraft?.body ?? '')") - expect(jiraFilters).toContain("setNewJiraIssueTitle(draft?.title ?? '')") - expect(jiraFilters).toContain("setNewJiraIssueBody(draft?.body ?? '')") - }) - - it('discards each recovery draft only on a successful create', () => { - const linearProjectSection = sectionBetween( - readTaskPageSource('use-task-page-linear-project-creation.ts'), - 'const handleCreateNewLinearProject', - 'const nextModel' - ) - expect(linearProjectSection).toContain('discardNewLinearProjectDraft()') - - const linearIssueSection = sectionBetween( - readTaskPageSource('use-task-page-linear-issue-creation.ts'), - 'const handleCreateNewLinearIssue', - 'const nextModel' - ) - expect(linearIssueSection).toContain('discardNewLinearIssueDraft()') - - const jiraIssueSection = sectionBetween( - readTaskPageSource('use-task-page-jira-issue-creation.ts'), - 'const handleCreateNewJiraIssue', - 'const nextModel' - ) - expect(jiraIssueSection).toContain('discardNewJiraIssueDraft()') - }) - - it('surfaces Jira create transport failures without leaking stale-context toasts', () => { - const jiraIssueSection = sectionBetween( - jiraCreateSubmitSource, - 'const handleCreateNewJiraIssue', - 'const nextModel' - ) - expect(jiraIssueSection).toContain('} catch (error) {') - expect(jiraIssueSection).toContain( - 'submitProviderRuntimeContextKey === providerRuntimeContextKeyRef.current' - ) - expect(jiraIssueSection).toContain('toast.error(') - }) -}) diff --git a/src/renderer/src/components/task-page-workspace-composer-boundary.test.ts b/src/renderer/src/components/task-page-workspace-composer-boundary.test.ts deleted file mode 100644 index 4eedb629f2a..00000000000 --- a/src/renderer/src/components/task-page-workspace-composer-boundary.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { - readTaskPageSource, - readTaskPageSourceFamily -} from './task-page-source-family.test-support' - -const TASK_PAGE_SOURCE = readTaskPageSourceFamily() -const WORKSPACE_ACTIONS_SOURCE = readTaskPageSource('use-task-page-workspace-actions.ts') -const COMPOSER_ACTIONS_SOURCE = readTaskPageSource('use-task-page-composer-actions.ts') -const PROJECT_VIEW_SOURCE = readFileSync( - join(__dirname, 'github-project', 'ProjectViewWrapper.tsx'), - 'utf8' -) -const COMPOSER_MODAL_SOURCE = readFileSync(join(__dirname, 'NewWorkspaceComposerModal.tsx'), 'utf8') -const QUICK_SUBMIT_PREPARATION_SOURCE = - readFileSync(join(__dirname, '../hooks/composer-state/quick-submit-preparation.ts'), 'utf8') + - readFileSync(join(__dirname, '../hooks/composer-state/quick-creation-execution.ts'), 'utf8') + - readFileSync(join(__dirname, '../hooks/composer-state/quick-creation-request.ts'), 'utf8') - -function sourceBetween(source: string, startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('TaskPage workspace creation source boundaries', () => { - it('prefills the workspace composer for GitHub issues and pull requests', () => { - const section = sourceBetween( - WORKSPACE_ACTIONS_SOURCE, - 'const openComposerForItem = useCallback(', - 'const handleUseWorkItem = useCallback(' - ) - - expect(section).toContain("provider: 'github'") - expect(section).toContain('type: item.type') - expect(section).toContain('number: item.number') - expect(section).toContain('title: item.title') - expect(section).toContain('url: item.url') - expect(section).toContain("openModal('new-workspace-composer', {") - expect(section).toContain("getTaskPageRepoSourceContext(repoMap.get(item.repoId), 'github')") - expect(section).toContain('prefilledName: getGitHubWorkItemWorkspaceSeed(item)') - expect(section).toContain('initialRepoId: item.repoId') - expect(section).toContain('initialGitHubWorkItem: item') - expect(section).toContain("enableIssueAutomation: item.type === 'issue'") - expect(section).toContain("telemetrySource: 'sidebar'") - }) - - it('forwards PR start-point data and issue automation through quick submit', () => { - expect(COMPOSER_MODAL_SOURCE).toContain( - 'initialGitHubWorkItem: modalData.initialGitHubWorkItem ?? null' - ) - expect(COMPOSER_MODAL_SOURCE).toContain( - 'enableIssueAutomation: modalData.enableIssueAutomation === true' - ) - const quickSubmit = QUICK_SUBMIT_PREPARATION_SOURCE - expect(quickSubmit).toContain('readAndConfirmRuntimeIssueCommand(') - expect(quickSubmit).toContain('selectedRepoExecutionHostId') - expect(quickSubmit).toContain('isSubmissionCancelled') - expect(quickSubmit).toContain( - '...(input.issueCommand ? { issueCommand: input.issueCommand } : {})' - ) - }) - - it('routes TaskPage GitHub starts directly to the composer', () => { - const section = sourceBetween( - WORKSPACE_ACTIONS_SOURCE, - 'const handleUseWorkItem = useCallback(', - 'const handleOpenOrUseGitHubWorkItem = useCallback(' - ) - - expect(section).toContain("recordFeatureInteraction('github-tasks')") - expect(section).toContain('openComposerForItem(item)') - expect(section).not.toContain('createGitHubWorkItemWorkspaceInBackground') - expect(WORKSPACE_ACTIONS_SOURCE).not.toContain('@/lib/github-work-item-background-create') - expect(TASK_PAGE_SOURCE).not.toContain('@/lib/github-work-item-background-create') - }) - - it('routes TaskPage Linear starts directly to the composer', () => { - const composerSection = sourceBetween( - COMPOSER_ACTIONS_SOURCE, - 'const openComposerForLinearItem = useCallback(', - 'const handleUseLinearItem = useCallback(' - ) - const handlerSection = sourceBetween( - COMPOSER_ACTIONS_SOURCE, - 'const handleUseLinearItem = useCallback(', - 'const handleOpenOrUseLinearItem = useCallback(' - ) - - expect(composerSection).toContain('buildLinearIssueLinkedWorkItem(issue)') - expect(composerSection).toContain("openModal('new-workspace-composer', {") - expect(composerSection).toContain('taskSourceContext: linearTaskSourceContext') - expect(composerSection).toContain('prefilledName: getLinearIssueWorkspaceName(issue)') - expect(composerSection).toContain("telemetrySource: 'sidebar'") - expect(handlerSection).toContain("recordFeatureInteraction('linear-tasks')") - expect(handlerSection).toContain('openComposerForLinearItem(issue)') - }) - - it('resumes an attachment from the primary action and composes when none exists', () => { - const section = sourceBetween( - WORKSPACE_ACTIONS_SOURCE, - 'const handleOpenOrUseGitHubWorkItem = useCallback(', - 'const openComposerForGitLabItem = useCallback(' - ) - - expect(section).toContain('findGithubWorkItemWorkspaceAttachment(') - expect(section).toContain('if (!currentAttached)') - expect(section).toContain('handleUseWorkItem(item)') - expect(section).toContain('activateAndRevealWorktree(currentAttached.id, {') - }) - - it('uses the shared composer handler from GitHub detail and start-new actions', () => { - const detail = readFileSync(join(__dirname, 'task-page/Content.tsx'), 'utf8') - const actions = readFileSync(join(__dirname, 'task-page/github/Rows.tsx'), 'utf8') - expect(detail.match(/onUse=\{\(item\) => \{/g)).toHaveLength(2) - expect(actions.match(/onSelect=\{\(\) => handleUseWorkItem\(item\)\}/g)).toHaveLength(2) - }) - - it('keeps project-view GitHub actions on the direct start-work path for issue #4756', () => { - const startAnchor = PROJECT_VIEW_SOURCE.includes('const handleStartWork') - ? 'const handleStartWork = useCallback(' - : '// Why: issue #4756 keeps project-view actions on the direct' - const endAnchor = PROJECT_VIEW_SOURCE.includes('const handleStartWork') - ? 'const closeDialogRepoItem' - : 'openModalFallback: () => {' - const section = sourceBetween(PROJECT_VIEW_SOURCE, startAnchor, endAnchor) - - expect(section).toContain('void launchWorkItemDirect({') - expect(section).toContain("launchSource: 'task_page'") - expect(section).not.toContain('createGitHubWorkItemWorkspaceInBackground') - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-listener-order-parity.test.ts b/src/renderer/src/components/terminal-pane/terminal-pane-listener-order-parity.test.ts deleted file mode 100644 index 70a214abfd5..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-pane-listener-order-parity.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { createHash } from 'node:crypto' -import { readFileSync, readdirSync } from 'node:fs' -import { join } from 'node:path' -// TypeScript 7 is a native CLI; AST tests still need the legacy JavaScript API. -import ts from 'typescript-api' -import { describe, expect, it } from 'vitest' - -const LISTENER_SOURCE_PATTERN = - /^(?:TerminalPane\.tsx|terminal-pane-paste-listeners\.ts|use-terminal-pane-(?:chat-state|close-actions|context-actions|controller|foundation|global-listeners|layout-bindings|layout-persistence|lifecycle-stage|mobile-actions|paste-listeners|projection|reconciliation|startup-actions|store-bindings|title-effects|title-state)\.ts)$/ -const PRE_REFACTOR_LISTENER_ORDER_SHA256 = - '2a2c5caaa368636d761ec819a7858f6b8010e578ccdd5c1be5960f87968c7e8a' - -type FunctionDefinition = { declaration: ts.FunctionDeclaration; sourceFile: ts.SourceFile } - -function readDefinitions(): Map { - const definitions = new Map() - for (const relativePath of readdirSync(__dirname).filter((name) => - LISTENER_SOURCE_PATTERN.test(name) - )) { - const filePath = join(__dirname, relativePath) - const sourceFile = ts.createSourceFile( - filePath, - readFileSync(filePath, 'utf8'), - ts.ScriptTarget.Latest, - true, - relativePath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS - ) - const visit = (node: ts.Node): void => { - if ( - ts.isFunctionDeclaration(node) && - node.name && - (node.name.text === 'TerminalPane' || - node.name.text === 'registerTerminalPanePasteListeners' || - node.name.text.startsWith('useTerminalPane')) - ) { - definitions.set(node.name.text, { declaration: node, sourceFile }) - } - ts.forEachChild(node, visit) - } - visit(sourceFile) - } - return definitions -} - -function readFlattenedListeners(): string[] { - const definitions = readDefinitions() - const listeners: string[] = [] - const visitDefinition = (name: string, active: ReadonlySet): void => { - const definition = definitions.get(name) - if (!definition?.declaration.body) { - throw new Error(`Missing terminal pane stage: ${name}`) - } - if (active.has(name)) { - throw new Error(`Recursive terminal pane stage: ${name}`) - } - const nextActive = new Set([...active, name]) - const visit = (node: ts.Node): void => { - if (ts.isCallExpression(node)) { - if ( - ts.isPropertyAccessExpression(node.expression) && - ['addEventListener', 'removeEventListener'].includes(node.expression.name.text) - ) { - listeners.push( - [ - node.expression.expression.getText(definition.sourceFile), - node.expression.name.text, - ...node.arguments.map((argument) => - argument.getText(definition.sourceFile).replace(/\s+/g, '') - ) - ].join('|') - ) - } - if (ts.isIdentifier(node.expression) && definitions.has(node.expression.text)) { - visitDefinition(node.expression.text, nextActive) - } - } - ts.forEachChild(node, visit) - } - visit(definition.declaration.body) - } - - visitDefinition('TerminalPane', new Set()) - return listeners -} - -describe('TerminalPane refactor listener parity', () => { - it('preserves ordered listener registration and cleanup', () => { - const listeners = readFlattenedListeners() - expect(listeners).toHaveLength(24) - expect(createHash('sha256').update(listeners.join('\n')).digest('hex')).toBe( - PRE_REFACTOR_LISTENER_ORDER_SHA256 - ) - }) -}) diff --git a/src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts b/src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts index b2cdcb5b2ad..82f686f851f 100644 --- a/src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts +++ b/src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts @@ -8,8 +8,6 @@ * Keyboard path: Cmd+W -> TerminalPane.handleRequestClosePane -> probePtyRunningWork * (split panes) or closeTerminalTab's guard (last pane) -> CloseTerminalDialog. */ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -92,21 +90,6 @@ describe('#10142 close confirmation policy is the same for keyboard and mouse', }) }) - // Control: the keyboard entry point does probe for running children. - it('keyboard Cmd+W path probes for running child processes before closing', () => { - const source = readFileSync( - join(__dirname, '../terminal-pane/use-terminal-pane-close-actions.ts'), - 'utf8' - ) - const handler = source.slice(source.indexOf('const handleRequestClosePane')) - // The shared probe, not a direct inspect: the pane path asks the same question as the tab - // guard, and routing both through one measurement is what stops them drifting on what an - // unanswered host means. - expect(handler.slice(0, handler.indexOf('useImperativeHandle'))).toContain( - 'probePtyRunningWork' - ) - }) - // Control: the harness does observe a guard when one exists — pinning blocks the same mouse close. it('mouse close routes a pinned tab through its confirmation guard', () => { const state = stateWithBusyTerminalTab(closeTab) @@ -121,13 +104,6 @@ describe('#10142 close confirmation policy is the same for keyboard and mouse', expect(closeTab).not.toHaveBeenCalled() }) - it('mouse close (X button / middle-click) consults the running-process probe', async () => { - closeTerminalTab('tab-busy') - await Promise.resolve() - - expect(inspectRuntimeTerminalProcessMock).toHaveBeenCalled() - }) - it('mouse close (X button / middle-click) does not drop a busy tab without confirmation', async () => { closeTerminalTab('tab-busy') await Promise.resolve() diff --git a/src/renderer/src/components/terminal/use-terminal-provider-snapshot-capability.test.tsx b/src/renderer/src/components/terminal/use-terminal-provider-snapshot-capability.test.tsx index b1f6e087617..c1763411586 100644 --- a/src/renderer/src/components/terminal/use-terminal-provider-snapshot-capability.test.tsx +++ b/src/renderer/src/components/terminal/use-terminal-provider-snapshot-capability.test.tsx @@ -1,6 +1,4 @@ // @vitest-environment happy-dom -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { renderHook, waitFor } from '@testing-library/react' import { @@ -195,21 +193,6 @@ describe('useTerminalProviderSnapshotCapability', () => { hook.unmount() }) - // Why source-pinned: the hook test cannot prove the quiet parking effect consumes the external revision. - it('invalidates the Terminal parking pass when a capability verdict changes', () => { - const projectionSource = readFileSync( - join(__dirname, '../use-terminal-workspace-projection.ts'), - 'utf8' - ) - const parkingSource = readFileSync(join(__dirname, '../use-terminal-parking-pass.ts'), 'utf8') - - expect(projectionSource).toContain( - 'const terminalProviderSnapshotCapabilityRevision = useTerminalProviderSnapshotCapability(' - ) - expect(projectionSource).toContain('terminalProviderSnapshotCapabilityRevision') - expect(parkingSource.match(/terminalProviderSnapshotCapabilityRevision/g)).toHaveLength(2) - }) - it('cancels an unknown-capability retry when the hook unmounts', async () => { vi.useFakeTimers() resolveCapabilities.mockResolvedValue([{ id: 'ssh:target@@pty-1', authoritative: null }]) diff --git a/src/renderer/src/components/worktree-jump-palette-sleeping-filter.test.ts b/src/renderer/src/components/worktree-jump-palette-sleeping-filter.test.ts index 73ce01b2951..56fe90c0eb2 100644 --- a/src/renderer/src/components/worktree-jump-palette-sleeping-filter.test.ts +++ b/src/renderer/src/components/worktree-jump-palette-sleeping-filter.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it } from 'vitest' import { isSleepingSweepExemptWorkspace } from './sidebar/visible-worktrees' import type { Worktree } from '../../../shared/worktree/types' -import { readWorktreeJumpPaletteSource } from './worktree-jump-palette-source.test-support' - -const worktreeSource = readWorktreeJumpPaletteSource('use-worktree-jump-palette-worktrees.ts') -const storeSource = readWorktreeJumpPaletteSource('use-worktree-jump-palette-store-state.ts') function makeWorktree(overrides: Partial = {}): Worktree { return { @@ -30,28 +26,6 @@ function makeWorktree(overrides: Partial = {}): Worktree { } describe('Cmd+J empty-query "Hide sleeping" pass (#8873)', () => { - // Why source-level: the palette re-implements the sidebar's filter pass - // inline, so the only structural guarantee that the two agree is that both - // call the shared predicate. A behavioral copy here would not catch a - // hand-rolled duplicate creeping back in. - it('routes the sleeping sweep through the shared exemption predicate', () => { - const start = worktreeSource.indexOf('const emptyQueryVisibleWorktrees = useMemo(') - expect(start).toBeGreaterThanOrEqual(0) - const end = worktreeSource.indexOf('const { visibleWorktreesForState', start) - const filterPass = worktreeSource.slice(start, end) - - expect(filterPass).toContain( - '!isSleepingSweepExemptWorkspace(worktree, alwaysShowDefaultBranchWorkspace)' - ) - expect(filterPass).toContain('alwaysShowDefaultBranchWorkspace,') - }) - - it('reads the flag from the same store field the sidebar uses', () => { - expect(storeSource).toMatch( - /const alwaysShowDefaultBranchWorkspace = useAppStore\(\s*\(state\) => state\.alwaysShowDefaultBranchWorkspace\s*\)/ - ) - }) - it('exempts a project entry point by default and honours an explicit opt-out', () => { const main = makeWorktree() diff --git a/src/renderer/src/components/worktree-jump-palette-source-context-boundary.test.ts b/src/renderer/src/components/worktree-jump-palette-source-context-boundary.test.ts deleted file mode 100644 index 0815cc7092f..00000000000 --- a/src/renderer/src/components/worktree-jump-palette-source-context-boundary.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readWorktreeJumpPaletteSource } from './worktree-jump-palette-source.test-support' - -const source = [ - readWorktreeJumpPaletteSource('use-worktree-jump-palette-create-action.ts'), - readWorktreeJumpPaletteSource('worktree-jump-palette-create-worktree.ts') -].join('\n') - -function sourceBetween(startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('WorktreeJumpPalette source-context boundaries', () => { - it('defers pasted GitHub URL resolution to the composer so cross-project detection runs', () => { - // Why: pasting a cross-project URL must surface the same "Switch project?" - // prompt as Cmd+N. The palette hands the raw URL to the composer's name - // field instead of pre-resolving it against an arbitrary repo, which - // silently linked cross-project items to the wrong project. - const githubLinkSection = sourceBetween('if (ghLink) {', 'if (ghNumber !== null) {') - expect(githubLinkSection).toContain('prefilledName: trimmed') - expect(githubLinkSection).not.toContain('lookupGitHubWorkItemByOwnerRepoForSource') - }) - - it('resolves typed raw issue/PR numbers through the lookup repo source host', () => { - expect(source).toContain('buildTaskSourceContextFromRepo') - - const rawNumberSection = sourceBetween( - 'void lookupGitHubWorkItemForSource({', - '.then((item) => {' - ) - expect(rawNumberSection).toContain('sourceContext') - }) -}) diff --git a/src/renderer/src/components/worktree-jump-palette-source.test-support.ts b/src/renderer/src/components/worktree-jump-palette-source.test-support.ts deleted file mode 100644 index 6cb92e66de6..00000000000 --- a/src/renderer/src/components/worktree-jump-palette-source.test-support.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' - -export function readWorktreeJumpPaletteSource(relativePath: string): string { - return readFileSync(join(__dirname, relativePath), 'utf8') -} diff --git a/src/renderer/src/hooks/remote-workspace-session-merge-close-tombstones.test.ts b/src/renderer/src/hooks/remote-workspace-session-merge-close-tombstones.test.ts index 57964af2e99..5fbdd00ffed 100644 --- a/src/renderer/src/hooks/remote-workspace-session-merge-close-tombstones.test.ts +++ b/src/renderer/src/hooks/remote-workspace-session-merge-close-tombstones.test.ts @@ -156,19 +156,6 @@ describe('direct-SSH pull merge: closed-tab tombstones', () => { expect(merged.tabsByWorktree[WORKTREE].map((tab) => tab.id)).toEqual(['live']) }) - it('leaves a tab alone when no tombstone names it', () => { - // The pre-existing absence-is-not-closed trade, restated: a host that still lists a tab closed - // on some other client keeps it here, because absence is all this merge would have to go on. - const agent = terminalTab('agent') - const closedElsewhere = terminalTab('closed-elsewhere') - const current = sessionState({ tabsByWorktree: { [WORKTREE]: [agent, closedElsewhere] } }) - const remote = sessionState({ tabsByWorktree: { [WORKTREE]: [agent] } }) - - const merged = merge(current, remote, { [WORKTREE]: [agent, closedElsewhere] }) - - expect(merged.tabsByWorktree[WORKTREE].map((tab) => tab.id)).toContain('closed-elsewhere') - }) - it('neither retires nor writes back a record once the host stops listing the tab', () => { // Main alone writes records; an acknowledgement used to delete them here, which made a workspace // the user emptied read as never initialized as soon as the host caught up. diff --git a/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts b/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts index 764a033275f..9d76c9f9a23 100644 --- a/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts +++ b/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts @@ -1,8 +1,5 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { - canResolveFolderSmartGitHubSubmit, getInitialAutoManagedWorkspaceName, getInitialGitHubPrStartPointSelection, getMatchingLinkedTaskSourceContext, @@ -11,54 +8,6 @@ import { resolveInitialWorkspaceRunSeed } from './useComposerState' -function readComposerModule(fileName: string): string { - return readFileSync(join(__dirname, 'composer-state', fileName), 'utf8') -} - -const COMPOSER_SOURCE = { - cardProps: readComposerModule('composer-card-props.ts'), - derived: readComposerModule('derived-composer-state.ts'), - folderSubmit: readComposerModule('folder-submit-orchestration.ts'), - fullCreation: readComposerModule('full-creation-execution.ts'), - fullCreationStartup: readComposerModule('full-creation-startup.ts'), - fullSubmitOrchestration: readComposerModule('full-submit-orchestration.ts'), - fullSubmitPreparation: readComposerModule('full-submit-preparation.ts'), - fullSubmitSourcePreparation: readComposerModule('full-submit-source-preparation.ts'), - githubProvider: readComposerModule('github-provider-selection.ts'), - githubSourceApplication: readComposerModule('github-source-application.ts'), - githubSubmit: readComposerModule('github-submit-resolution.ts'), - gitlabProvider: readComposerModule('gitlab-provider-selection.ts'), - hostRuntime: readComposerModule('host-runtime-effects.ts'), - initialTarget: readComposerModule('initial-target-state.ts'), - issueSource: readComposerModule('issue-source-actions.ts'), - linkedItemLookup: readComposerModule('linked-item-lookup-effects.ts'), - navigation: readComposerModule('composer-navigation-actions.ts'), - projectTarget: readComposerModule('project-target-actions.ts'), - providerRuntime: readComposerModule('provider-runtime-sync.ts'), - quickCreation: readComposerModule('quick-creation-execution.ts'), - quickSubmitAction: readComposerModule('quick-submit-action.ts'), - quickSubmitPreparation: readComposerModule('quick-submit-preparation.ts'), - quickSubmitSourcePreparation: readComposerModule('quick-submit-source-preparation.ts'), - runtimeTarget: readComposerModule('runtime-target-selection.ts'), - sourceContext: readComposerModule('source-context-state.ts'), - sourceIdentity: readComposerModule('source-identity-actions.ts'), - targetChange: readComposerModule('target-change-actions.ts'), - quickStartup: readComposerModule('quick-startup-plan.ts'), - workspaceIdentity: readComposerModule('workspace-identity-state.ts') -} as const -const RECIPE_OPTIONS_SOURCE = readFileSync( - join(__dirname, 'useEphemeralVmRecipeOptions.ts'), - 'utf8' -) - -function sourceBetween(source: string, startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - describe('useComposerState host-context boundaries', () => { it('seeds TaskPage pull requests as submit-time PR start points', () => { const item = { @@ -156,14 +105,6 @@ describe('useComposerState host-context boundaries', () => { ).toEqual({ workspaceName: 'title-derived-name', displayName: 'Title derived name' }) }) - it('requires pasted PR recovery to match the selected GitHub host', () => { - const recoverySection = COMPOSER_SOURCE.derived - - expect(recoverySection).toContain('githubRepoIdentityKey(fromName.slug)') - expect(recoverySection).toContain('githubRepoIdentityKey(selectedRepoSlug)') - expect(recoverySection).not.toContain('fromName.slug.owner.toLowerCase()') - }) - it('auto-owns linked-item generated prefilled names', () => { expect( getInitialAutoManagedWorkspaceName({ @@ -179,112 +120,6 @@ describe('useComposerState host-context boundaries', () => { ).toBe('fix-workspace-name') }) - it('resolves GitHub PR bases against the selected run repo, not the source item repo', () => { - const section = COMPOSER_SOURCE.githubProvider - - expect(section).toContain('const runRepo = selectedRepo ??') - expect(section).toContain('resolveGitHubPrStartPointForRepo') - expect(section).toContain('repoId: runRepo.id') - expect(section).toContain('settings: itemRepoSettings') - expect(section).toContain('smartGitHubPrStartPointSelectionRef.current = startPointSelection') - expect(section).toContain( - 'if (smartGitHubPrStartPointSelectionRef.current !== startPointSelection)' - ) - expect(section).not.toContain('repoId: repoForItem.id') - expect(section).not.toContain('repo: repoForItem.id') - }) - - it('resolves GitLab MR bases against the selected run repo, not the source item repo', () => { - const section = COMPOSER_SOURCE.gitlabProvider - - expect(section).toContain('const runRepo = selectedRepo ??') - expect(section).toContain('repoId: runRepo.id') - expect(section).toContain('getSettingsForRepoRuntimeOwner') - expect(section).toContain('worktree.resolveMrBase') - expect(section).toContain('repo: runRepo.id') - expect(section).not.toContain('repoId: repoForItem.id') - // Why (#6263): an unresolved MR base must surface a toast and clear stale - // state instead of silently dropping the worktree onto origin/master. - expect(section).toContain('toast.error(result.error)') - expect(section).toContain("'Failed to resolve MR base.'") - expect(section).toMatch(/\.catch\(\(error: unknown\) =>/) - }) - - it('clears only repo-scoped linked work items when the repo or project changes', () => { - // Why: Linear and Jira issues are workspace-scoped context — a repo or - // project switch must keep them attached. Jira used to be dropped because - // this path special-cased Linear only. - const repoChangeSection = COMPOSER_SOURCE.targetChange - expect(repoChangeSection).toContain( - '!shouldPreserveWorkspaceSourceOnRepoChange(linkedWorkItem)' - ) - - const folderSourceSection = COMPOSER_SOURCE.targetChange - expect(folderSourceSection).toContain('!shouldPreserveWorkspaceSourceOnRepoChange(current)') - - // No switch path may gate the linked-item clear on a Linear-only predicate - // again. (isLinearLinkedWorkItem itself may still appear — it drives the - // separate Linear branch-name feature — but never the preservation decision.) - expect(COMPOSER_SOURCE.targetChange).not.toContain('if (!preserveLinearLinkedWorkItem)') - }) - - it('does not use local SSH gates for runtime-owned folder targets', () => { - const targetSection = COMPOSER_SOURCE.runtimeTarget - expect(targetSection).toContain("parsedFolderTargetHost?.kind === 'runtime'") - expect(targetSection).toContain('connectionId: folderTargetConnectionId') - expect(COMPOSER_SOURCE.runtimeTarget).not.toContain('folderSourceConnectionId') - }) - - it('routes folder target runtime ownership through detection, path status, and create', () => { - const targetSection = COMPOSER_SOURCE.runtimeTarget - expect(targetSection).toContain('folderTargetRuntimeEnvironmentId') - expect(targetSection).toContain("{ kind: 'runtime' as const") - expect(targetSection).toContain('useFolderWorkspaceComposerPathStatus(') - expect(targetSection).toContain('folderTargetRuntimeEnvironmentId') - expect(targetSection).toContain('useDetectedAgents(folderTargetAgentDetectionTarget)') - - const submitSection = COMPOSER_SOURCE.folderSubmit - expect(submitSection).toContain('isRemote: folderTargetIsRemote') - expect(submitSection).toContain( - "launchSource: telemetrySource === 'onboarding' ? 'onboarding' : 'new_workspace_composer'" - ) - expect(submitSection).toContain('runtimeEnvironmentId: folderTargetRuntimeEnvironmentId') - }) - - it('detects composer agents against the repo host: SSH, then runtime, then local (#7082)', () => { - // Why: a repo owned by a paired runtime must show the runtime's agents, not - // the local machine's. SSH stays first priority; runtime falls through before - // local so an SSH repo never double-detects. Regression guard for #7082. - const selectorSection = COMPOSER_SOURCE.workspaceIdentity - expect(selectorSection).toContain('if (isRemote) {') - expect(selectorSection).toContain('s.remoteDetectedAgentIds[connectionId]') - expect(selectorSection).toContain('if (runtimeEnvironmentId) {') - expect(selectorSection).toContain('s.runtimeDetectedAgentIds[runtimeEnvironmentId]') - expect(selectorSection).toContain('return s.detectedAgentIds') - // SSH branch is checked before the runtime branch. - expect(selectorSection.indexOf('if (isRemote) {')).toBeLessThan( - selectorSection.indexOf('if (runtimeEnvironmentId) {') - ) - - expect(COMPOSER_SOURCE.workspaceIdentity).toContain( - 'const runtimeEnvironmentId = selectedRepoSettings?.activeRuntimeEnvironmentId?.trim() || null' - ) - - // Detection effect fans out to the same three hosts in the same order and - // re-runs when the runtime environment changes. - const detectSection = sourceBetween( - COMPOSER_SOURCE.hostRuntime, - 'const detect = isRemote', - '// Per-repo: load yaml hooks' - ) - expect(detectSection).toContain('ensureRemoteDetectedAgents(connectionId!)') - expect(detectSection).toContain('ensureRuntimeDetectedAgents(runtimeEnvironmentId)') - expect(detectSection).toContain('ensureDetectedAgents()') - expect(detectSection).toMatch( - /\}, \[\s*connectionId,\s*runtimeEnvironmentId,\s*isRemote,\s*selectedRepoSshStatus,\s*disabledTuiAgents/ - ) - }) - it('seeds initial workspace run target from the task source context', () => { expect( resolveInitialWorkspaceRunSeed({ @@ -316,299 +151,6 @@ describe('useComposerState host-context boundaries', () => { hostId: 'local', projectHostSetupId: 'setup-local' }) - - const section = COMPOSER_SOURCE.initialTarget - - expect(section).toContain('resolveInitialWorkspaceRunSeed') - expect(section).toContain('initialTaskSourceContext') - expect(section).toContain('projectId: initialRunSeed.projectId') - expect(section).toContain('hostId: initialRunSeed.hostId') - expect(section).toContain('projectHostSetupId: initialRunSeed.projectHostSetupId') - }) - - it('resolves typed GitHub issue/PR input through the selected repo source context', () => { - expect(COMPOSER_SOURCE.sourceContext).toContain( - 'const selectedRepoGitHubSourceContext = useMemo' - ) - - const directLookup = COMPOSER_SOURCE.linkedItemLookup - expect(directLookup).toContain('sourceContext: selectedRepoGitHubSourceContext') - expect(directLookup).toContain('lookupGitHubWorkItemByOwnerRepoForSource') - expect(directLookup).toContain('type: normalizedLinkQuery.directLink.type') - - const submitLookup = COMPOSER_SOURCE.githubSubmit - expect(submitLookup).toContain('sourceContext:') - expect(submitLookup).toContain('selectedRepoGitHubSourceContext') - }) - - it('uses submit-time GitHub PR start points for the create payload', () => { - const submitLookup = COMPOSER_SOURCE.githubSubmit - expect(submitLookup).toContain('resolveGitHubPrStartPointForRepo') - expect(submitLookup).toContain("kind: 'pr-start-point'") - expect(submitLookup).toContain("kind: 'metadata-only'") - expect(submitLookup).toContain('baseBranch: prStartPoint.baseBranch') - expect(submitLookup).toContain('branchNameOverride: prStartPoint.branchNameOverride') - const selectedPrSubmitLookup = sourceBetween( - submitLookup, - 'if (linkedWorkItem) {', - 'const intent = getSmartGitHubSubmitIntent(name)' - ) - expect(selectedPrSubmitLookup).toContain('smartGitHubPrStartPointSelectionRef.current') - expect(selectedPrSubmitLookup).toContain("linkedWorkItemIdentity?.type === 'pr'") - expect(selectedPrSubmitLookup).toContain("startPointIdentity?.type === 'pr'") - expect(selectedPrSubmitLookup).toContain( - 'startPointIdentity.number === linkedWorkItemIdentity.number' - ) - expect(selectedPrSubmitLookup).toContain('resolveGitHubPrStartPointForRepo') - expect(selectedPrSubmitLookup.indexOf('resolveGitHubPrStartPointForRepo')).toBeLessThan( - selectedPrSubmitLookup.indexOf("return { kind: 'none' }") - ) - - const fullSubmit = COMPOSER_SOURCE.fullSubmitSourcePreparation + COMPOSER_SOURCE.fullCreation - expect(fullSubmit).toContain("smartGitHubResolution.kind === 'pr-start-point'") - expect(fullSubmit).toContain("smartGitHubResolution.kind === 'metadata-only'") - expect(fullSubmit).toContain('effectiveLinkedPR !== null || linkedGitLabMR !== null') - expect(fullSubmit).toContain('selectedRepoIsGit ? submitBaseBranch : undefined') - expect(fullSubmit).toContain('submitPushTarget') - expect(fullSubmit).toContain('submitCompareBaseRef') - expect(fullSubmit).not.toContain('smartGitHubResolution?.baseBranch ?? baseBranch') - expect(fullSubmit).not.toContain('smartGitHubResolution?.compareBaseRef ?? compareBaseRef') - expect(fullSubmit).not.toContain('smartGitHubResolution?.pushTarget ?? pushTarget') - expect(fullSubmit).not.toContain( - 'smartGitHubResolution?.branchNameOverride ?? branchNameOverride' - ) - - const quickSubmit = - COMPOSER_SOURCE.quickSubmitSourcePreparation + - COMPOSER_SOURCE.quickSubmitPreparation + - COMPOSER_SOURCE.quickCreation - expect(quickSubmit).toContain("smartGitHubResolution.kind === 'pr-start-point'") - expect(quickSubmit).toContain("smartGitHubResolution.kind === 'metadata-only'") - expect(quickSubmit).toContain('effectiveLinkedPR !== null || linkedGitLabMR !== null') - expect(quickSubmit).toContain('explicitBaseBranch: smartSubmitBaseBranch') - expect(quickSubmit).toContain('pushTarget: submitPushTarget') - expect(quickSubmit).toContain('compareBaseRef: submitCompareBaseRef') - expect(quickSubmit).not.toContain('smartGitHubResolution?.baseBranch ?? baseBranch') - expect(quickSubmit).not.toContain('smartGitHubResolution?.compareBaseRef ?? compareBaseRef') - expect(quickSubmit).not.toContain('smartGitHubResolution?.pushTarget ?? pushTarget') - expect(quickSubmit).not.toContain( - 'smartGitHubResolution?.branchNameOverride ?? branchNameOverride' - ) - }) - - it('saves setup startup policy before creating a workspace', () => { - const persistSection = COMPOSER_SOURCE.providerRuntime - expect(persistSection).toContain('setupAgentStartupPolicySaveRef.current') - expect(persistSection).toContain('pendingSave?.repoId === currentRepo.id') - expect(persistSection).toContain('pendingSave.policy === policy') - expect(persistSection).toContain('await pendingSave.promise') - expect(persistSection).toContain('continue') - expect(COMPOSER_SOURCE.providerRuntime).toContain('setupAgentStartupPolicyDraftRef.current') - - const fullSubmit = COMPOSER_SOURCE.fullCreation - const fullPolicySave = fullSubmit.indexOf('persistSetupAgentStartupPolicy()') - const fullCreate = fullSubmit.indexOf('const result = await createWorktree(') - expect(fullPolicySave).toBeGreaterThanOrEqual(0) - expect(fullCreate).toBeGreaterThan(fullPolicySave) - - const quickSubmit = COMPOSER_SOURCE.quickCreation - const quickPolicySave = quickSubmit.indexOf('persistSetupAgentStartupPolicy()') - const quickCreate = quickSubmit.indexOf('const request = buildQuickCreationRequest(') - expect(quickPolicySave).toBeGreaterThanOrEqual(0) - expect(quickCreate).toBeGreaterThan(quickPolicySave) - }) - - it('resolves submit-time GitHub smart input when folder child repos exist', () => { - expect( - canResolveFolderSmartGitHubSubmit({ - hasFolderSourceRepos: true - }) - ).toBe(true) - expect( - canResolveFolderSmartGitHubSubmit({ - hasFolderSourceRepos: false - }) - ).toBe(false) - - const lookupSection = COMPOSER_SOURCE.githubSubmit - expect(lookupSection).toContain('isProjectGroupTarget') - expect(lookupSection).toContain('folderSourceRepos.filter(isGitRepoKind)') - expect(lookupSection).toContain('Promise.all') - expect(lookupSection).toContain('buildTaskSourceContextFromRepo') - - const section = COMPOSER_SOURCE.folderSubmit - expect(section).toContain('canResolveFolderSmartGitHubSubmit') - expect(section).toContain('hasFolderSourceRepos: folderSourceRepos.length > 0') - expect(section).toContain('? resolvePendingSmartGitHubSubmit()') - expect(section).toContain("Promise.resolve({ kind: 'none' } as const)") - expect(section).toContain("smartGitHubSettlement.status === 'cancelled'") - expect(section).not.toContain('folderSourceRequiresConnection') - }) - - it('clears branch reuse state when manually editing the branch name', () => { - const section = COMPOSER_SOURCE.sourceIdentity - - expect(section).toContain('resolveComposerManualBranchNameChange') - expect(section).toContain('setReuseEligibleBranch(null)') - expect(section).toContain('setReuseSelectedBranch(false)') - expect(section).toContain("branchAutoNameRef.current = ''") - }) - - it('forces repo-scoped source reset when returning from folder target to a repo with the same id', () => { - const handleRepoChange = COMPOSER_SOURCE.targetChange - expect(handleRepoChange).toContain('forceResetStartFrom?: boolean') - expect(handleRepoChange).toContain('value === repoId && !options.forceResetStartFrom') - - const handleProjectChange = COMPOSER_SOURCE.projectTarget - expect(handleProjectChange).toContain( - 'handleRepoChange(nextRepoId, { forceResetStartFrom: isProjectGroupTarget })' - ) - }) - - it('keeps a Linear branch override when its workspace-scoped issue survives a repo change', () => { - const section = COMPOSER_SOURCE.targetChange - - expect(section).toContain('const preservedLinearBranchName = preserveLinearLinkedWorkItem') - expect(section).toContain('getLinearLinkedWorkItemBranchName(linkedWorkItem)') - expect(section).toContain('setBranchNameOverride(preservedLinearBranchName)') - expect(section).toContain( - 'setBranchNameOverridePreservesNameEdits(Boolean(preservedLinearBranchName))' - ) - expect(section).toContain("branchAutoNameRef.current = preservedLinearBranchName ?? ''") - }) - - it('clears a Linear branch override when its linked issue is removed', () => { - const section = COMPOSER_SOURCE.sourceIdentity - - expect(section).toContain('const removedLinearItem = isLinearLinkedWorkItem(linkedWorkItem)') - expect(section).toContain('if (removedLinearItem)') - expect(section).toContain('setBranchNameOverride(undefined)') - expect(section).toContain('setBranchNameOverridePreservesNameEdits(false)') - expect(section).toContain("branchAutoNameRef.current = ''") - }) - - it('keeps Jira-mode URL edits synchronously blocked before lookup settles', () => { - // Why: derived on every render from the same name the submit path uses, so an in-flight - // URL cannot slip through between the keystroke and the create. - expect(COMPOSER_SOURCE.workspaceIdentity).toContain( - 'isBlockingJiraUrlIntent(smartNameMode, name)' - ) - const section = COMPOSER_SOURCE.sourceIdentity - - expect(section).not.toContain("smartNameMode === 'smart'") - expect(section).not.toContain('setSourceIntentBlocksCreate') - }) - - it('selects a project by its own host instead of pinning the current host', () => { - // Regression: passing the current host as a hard `hostId` made picking a - // project set up only on a different host a silent no-op. The current host - // must be a preference (focusedHostScope), with a fallback to any ready host. - const handleProjectChange = COMPOSER_SOURCE.projectTarget - expect(handleProjectChange).toContain('focusedHostScope: preferredHostId ?? workspaceHostScope') - expect(handleProjectChange).not.toContain('hostId: preferredHostId') - }) - - it('clears GitLab-specific linked state when clearing smart-name selection', () => { - const section = COMPOSER_SOURCE.issueSource - expect(section).toContain("setLinkedIssue('')") - expect(section).toContain('setLinkedPR(null)') - expect(section).toContain('setLinkedGitLabIssue(null)') - expect(section).toContain('setLinkedGitLabMR(null)') - expect(section).toContain('setLinkedWorkItem(null)') - }) - - it('clears stale opposite-provider review fields when selecting linked work items', () => { - const githubApply = COMPOSER_SOURCE.githubSourceApplication - expect(githubApply).toContain('setLinkedGitLabIssue(null)') - expect(githubApply).toContain('setLinkedGitLabMR(null)') - expect(githubApply).toContain('setBranchNameOverridePreservesNameEdits(false)') - expect(githubApply).toContain("branchAutoNameRef.current = ''") - - const gitlabApply = COMPOSER_SOURCE.gitlabProvider - expect(gitlabApply).toContain("setLinkedIssue('')") - expect(gitlabApply).toContain('setLinkedPR(null)') - expect(gitlabApply).toContain('setBranchNameOverridePreservesNameEdits(false)') - expect(gitlabApply).toContain("branchAutoNameRef.current = ''") - - const githubProjectGroupHandler = COMPOSER_SOURCE.githubProvider - const gitlabProjectGroupHandler = COMPOSER_SOURCE.githubProvider - expect(githubProjectGroupHandler).toContain('setLinkedGitLabIssue(null)') - expect(githubProjectGroupHandler).toContain('setLinkedGitLabMR(null)') - expect(gitlabProjectGroupHandler).toContain( - "setLinkedIssue(identity.type === 'issue' ? String(identity.number) : '')" - ) - expect(gitlabProjectGroupHandler).toContain( - "setLinkedPR(identity.type === 'pr' ? identity.number : null)" - ) - }) - - it('disables repo-backed folder smart lookup when a folder target has no source repos', () => { - const cardProps = COMPOSER_SOURCE.cardProps - expect(cardProps).toContain( - 'repoBackedSourcesDisabled: isProjectGroupTarget ? folderSourceRepos.length === 0 : false' - ) - expect(cardProps).toContain( - 'repoBackedSearchRepos: isProjectGroupTarget ? folderSourceRepos : undefined' - ) - }) - - it('surfaces folder submit smart-resolution failures through create error UI', () => { - const section = COMPOSER_SOURCE.folderSubmit - expect(section).toContain('catch (error)') - expect(section).toContain('const formattedError = formatWorkspaceCreateError(error)') - expect(section).toContain('setCreateError(formattedError)') - expect(section).toContain('toast.error(getWorkspaceCreateErrorToastMessage(formattedError))') - expect(section).toContain('if (!folderWorkspaceCreated)') - expect(section).toContain('setCreateError({') - }) - - it('uses submit-time smart metadata for both folder launch mode and startup content', () => { - const section = COMPOSER_SOURCE.folderSubmit - expect(section).toContain( - 'const submitLinkedWorkItem = smartGitHubMetadata?.linkedWorkItem ?? linkedWorkItem' - ) - expect(section).toContain('resolveFolderWorkspaceLaunchDraft(submitLinkedWorkItem, note)') - expect(section).toContain('linkedWorkItem: submitLinkedWorkItem') - }) - - it('gates every submit path on the derived source intent', () => { - // Why: derived from name+mode, so the submitted name and the gate can never disagree. - expect(COMPOSER_SOURCE.workspaceIdentity).toContain( - 'const sourceIntentBlocksCreate = !linkedWorkItem && isBlockingJiraUrlIntent(smartNameMode, name)' - ) - const submitSections = [ - COMPOSER_SOURCE.navigation, - COMPOSER_SOURCE.fullSubmitOrchestration, - COMPOSER_SOURCE.quickSubmitAction - ] - - for (const section of submitSections) { - expect(section).toContain('sourceIntentBlocksCreate') - } - }) - - it('passes folder child repos to smart lookup instead of building task source options', () => { - const cardProps = COMPOSER_SOURCE.cardProps - expect(cardProps).toContain( - 'repoBackedSearchRepos: isProjectGroupTarget ? folderSourceRepos : undefined' - ) - expect(cardProps).not.toContain('folderSourceProjectOptions') - expect(cardProps).not.toContain('handleFolderTaskSourceProjectChange') - expect(cardProps).not.toContain('getRepoIdFromNewWorkspaceFolderSourceOptionId') - }) - - it('keeps folder run repo changes inside the selected folder source set', () => { - const section = COMPOSER_SOURCE.targetChange - expect(section).toContain('folderSourceRepos.some((repo) => repo.id === value)') - expect(section).toContain('return') - - const cardProps = COMPOSER_SOURCE.cardProps - expect(cardProps).toContain('allowSmartNameAddProject: !isProjectGroupTarget') - }) - - it('preserves Jira linked items when switching from repo target to folder target', () => { - const section = COMPOSER_SOURCE.projectTarget - expect(section).toContain('!shouldPreserveWorkspaceSourceOnRepoChange(linkedWorkItem)') }) it('restores Jira draft context only when its site and issue identity agree', () => { @@ -644,139 +186,4 @@ describe('useComposerState host-context boundaries', () => { getMatchingLinkedTaskSourceContext({ ...item, jiraIdentifier: 'ORCA-999' }, context) ).toBeNull() }) - - it('resolves quick-create base refs through the worktree-create precedence helper', () => { - const section = COMPOSER_SOURCE.quickSubmitPreparation - expect(section).not.toContain('repoWorktreeBaseRef: selectedRepo.worktreeBaseRef') - expect(section).not.toContain('getRuntimeRepoBaseRefDefault') - }) - - it('plans new workspace agent startup from the selected repo runtime', () => { - expect(COMPOSER_SOURCE.runtimeTarget).toContain( - 'const selectedRepoAgentLaunchPlatform = useMemo' - ) - expect(COMPOSER_SOURCE.runtimeTarget).toContain('getLocalRepoProjectExecutionRuntimeContext') - expect(COMPOSER_SOURCE.runtimeTarget).toContain( - 'getAgentLaunchPlatformForRepo(selectedRepo, projectRuntime)' - ) - - const fullStartupPlan = sourceBetween( - COMPOSER_SOURCE.fullSubmitPreparation, - 'const startupPlan = buildAgentStartupPlan({', - 'const shouldSeedInitialAgentStatus =' - ) - expect(fullStartupPlan).toContain('platform: selectedRepoAgentLaunchPlatform') - expect(fullStartupPlan).not.toContain('platform: CLIENT_PLATFORM') - expect(COMPOSER_SOURCE.fullCreation).toContain('startupDraft: startupPlan.draftPrompt') - - const quickStartupPlan = sourceBetween( - COMPOSER_SOURCE.quickCreation, - 'buildQuickComposerStartup({', - 'const startupPolicySettlement =' - ) - expect(quickStartupPlan).toContain('platform: selectedRepoAgentLaunchPlatform') - expect(quickStartupPlan).not.toContain('platform: CLIENT_PLATFORM') - }) - - // Why: activation no longer rebuilds a startup from `createdWithAgent`, so this - // caller's own `startup` is the only thing that launches the agent it planned. - it('passes its own startup to activation when submit planned an agent', () => { - const activation = COMPOSER_SOURCE.fullCreation + COMPOSER_SOURCE.fullCreationStartup - - expect(activation).toContain('...(!structuredLaunch && startup ? { startup } : {})') - expect(activation).toContain('backendStartupTerminalSpawned: true') - expect(activation).toContain('command: args.startupPlan.launchCommand') - expect(activation).toContain('launchAgent: args.agent') - // The removed activation-time fallback must not come back through this caller. - expect(COMPOSER_SOURCE.fullCreation).not.toContain('buildCreatedAgentReopenStartup') - }) - - it('prepares linked quick-create drafts for the selected default agent', () => { - const quickSubmit = COMPOSER_SOURCE.quickCreation + COMPOSER_SOURCE.quickStartup - - expect(quickSubmit).toContain( - 'const promptLinkedWorkItem = agent === null ? null : submitLinkedWorkItem' - ) - expect(quickSubmit).toContain('resolveQuickCreateLinkedWorkItemPrompt(promptLinkedWorkItem') - expect(quickSubmit).not.toContain('explicitAgentChoice') - expect(quickSubmit).not.toContain('shouldPrepareQuickLinkedWorkItemAgentPrompt') - expect(COMPOSER_SOURCE.quickCreation).not.toContain('resolveQuickWorkspaceSubmitAgent') - }) - - it('keeps sentinel-based Jira and Linear starts out of issue-command templates', () => { - const submitSources = - COMPOSER_SOURCE.derived + - COMPOSER_SOURCE.fullSubmitSourcePreparation + - COMPOSER_SOURCE.fullSubmitPreparation + - COMPOSER_SOURCE.fullCreation + - COMPOSER_SOURCE.quickSubmitPreparation + - COMPOSER_SOURCE.quickCreation - expect(submitSources).not.toContain('isOrcaCliAvailableForLaunch') - expect(submitSources).not.toContain('hasGeneratedLinearSourceContext') - expect(submitSources).not.toContain('shouldDraftGeneratedLinearContext') - expect(COMPOSER_SOURCE.derived).toMatch( - /willApplyIssueCommandAsPrompt[\s\S]*canUseIssueCommandForLinkedItemProvider\(linkedWorkItemProvider\)/ - ) - - const previewSection = COMPOSER_SOURCE.derived - expect(previewSection).toContain( - 'canUseIssueCommandForLinkedItemProvider(linkedWorkItemProvider)' - ) - - const fullSubmit = - COMPOSER_SOURCE.fullSubmitSourcePreparation + - COMPOSER_SOURCE.fullSubmitPreparation + - COMPOSER_SOURCE.fullCreation + - COMPOSER_SOURCE.fullCreationStartup - expect(fullSubmit).toContain( - 'canUseIssueCommandForLinkedItemProvider(submitLinkedWorkItemProvider)' - ) - expect(fullSubmit).toMatch( - /submitShouldRunIssueAutomation[\s\S]*canUseIssueCommandForLinkedItemProvider\(submitLinkedWorkItemProvider\)/ - ) - expect(fullSubmit).toContain('prompt: submitStartupPrompt') - expect(fullSubmit).toContain('const shouldSeedInitialAgentStatus =') - expect(fullSubmit).toContain('...(args.shouldSeedInitialAgentStatus') - - const quickSubmit = - COMPOSER_SOURCE.quickSubmitPreparation + - COMPOSER_SOURCE.quickCreation + - COMPOSER_SOURCE.quickStartup - expect(quickSubmit).toContain('startupPlan.draftPrompt = draftPrompt') - }) - - it('selects the failed Jira source host before opening integration settings', () => { - const section = COMPOSER_SOURCE.navigation - - expect(section).toContain('getTaskSourceRuntimeSettings(') - expect(section).toContain('smartNameJiraSourceContext') - expect(section).toContain('setActiveRuntimeEnvironmentPreference(targetRuntimeEnvironmentId)') - expect(section.indexOf('setActiveRuntimeEnvironmentPreference')).toBeLessThan( - section.indexOf("openSettingsTarget({ pane: 'integrations'") - ) - expect(section).toContain('if (!selected)') - }) - - it('gates per-workspace environment recipe discovery behind the experimental setting', () => { - const recipeLoadSection = COMPOSER_SOURCE.runtimeTarget - expect(recipeLoadSection).toContain('settings?.experimentalEphemeralVms === true') - expect(recipeLoadSection).toContain('useEphemeralVmRecipeOptions') - expect(recipeLoadSection).toContain('enabled: ephemeralVmsEnabled') - expect(RECIPE_OPTIONS_SOURCE).toContain('args.enabled &&') - expect(RECIPE_OPTIONS_SOURCE).toContain('window.api.ephemeralVm') - expect(RECIPE_OPTIONS_SOURCE).toContain('window.api.plugins.onChanged') - expect(RECIPE_OPTIONS_SOURCE).toContain('requestGeneration') - - const submitSection = COMPOSER_SOURCE.quickCreation - expect(submitSection).toContain( - 'const activeEphemeralVmRecipeId = ephemeralVmsEnabled ? selectedEphemeralVmRecipeId : null' - ) - expect(submitSection).toContain('recipeId: activeEphemeralVmRecipeId') - - const cardPropsSection = COMPOSER_SOURCE.cardProps - expect(cardPropsSection).toContain('ephemeralVmRecipes:') - expect(cardPropsSection).toContain('!ephemeralVmsEnabled') - expect(cardPropsSection).toContain('selectedEphemeralVmRecipeId:') - expect(cardPropsSection).toContain('ephemeralVmRecipeError:') - }) }) diff --git a/src/renderer/src/hooks/useSettingsNavigationMetadata.test.ts b/src/renderer/src/hooks/useSettingsNavigationMetadata.test.ts index 12ca698f192..e0e4761aad0 100644 --- a/src/renderer/src/hooks/useSettingsNavigationMetadata.test.ts +++ b/src/renderer/src/hooks/useSettingsNavigationMetadata.test.ts @@ -1,5 +1,3 @@ -import { readdirSync, readFileSync } from 'node:fs' -import { basename, resolve } from 'node:path' import { describe, expect, it } from 'vitest' import { buildSettingsNavigationMetadata } from './useSettingsNavigationMetadata' import type { Repo } from '../../../shared/repo-types' @@ -405,42 +403,4 @@ describe('settings navigation metadata', () => { expect(ids({ isMac: false })).not.toContain('developer-permissions') expect(ids({ isMac: true })).toContain('developer-permissions') }) - - it('does not import Settings page or pane UI modules from the metadata hook', () => { - const testDir = import.meta.dirname - // Why: the section tables live in sibling settings-navigation-* modules, so reading only the - // hook would scan a file that no longer holds the imports this guard exists to police. - // Walk recursively so a later split that nests the modules cannot shrink this guard. - const sourceFiles = [ - 'useSettingsNavigationMetadata.ts', - ...readdirSync(testDir, { recursive: true, encoding: 'utf8' }).filter( - (name) => basename(name).startsWith('settings-navigation-') && name.endsWith('.ts') - ) - ] - expect(sourceFiles.length).toBeGreaterThan(1) - const importLines = sourceFiles - .flatMap((name) => readFileSync(resolve(testDir, name), 'utf8').split('\n')) - .filter((line) => line.trim().startsWith('import ')) - .join('\n') - - expect(importLines).not.toMatch(/components\/settings\/Settings(?:'|")/) - expect(importLines).not.toMatch(/components\/settings\/[A-Z][A-Za-z]+Pane(?:'|")/) - expect(importLines).not.toMatch(/components\/stats\/StatsPane(?:'|")/) - }) - - it('does not import Settings page or pane UI modules from the quick action registry', () => { - const testDir = import.meta.dirname - const registrySource = readFileSync( - resolve(testDir, '../components/cmd-j/quick-actions.ts'), - 'utf8' - ) - const importLines = registrySource - .split('\n') - .filter((line) => line.trim().startsWith('import ')) - .join('\n') - - expect(importLines).not.toMatch(/components\/settings\/Settings(?:'|")/) - expect(importLines).not.toMatch(/components\/settings\/[A-Z][A-Za-z]+Pane(?:'|")/) - expect(importLines).not.toMatch(/components\/stats\/StatsPane(?:'|")/) - }) }) diff --git a/src/renderer/src/lib/agent-launch-caller-profile-census.test.ts b/src/renderer/src/lib/agent-launch-caller-profile-census.test.ts deleted file mode 100644 index 0b168e66ef4..00000000000 --- a/src/renderer/src/lib/agent-launch-caller-profile-census.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -// Ties every caller profile back to the call site it characterizes. The behaviour files feed the -// profiles through the real funnel; without this census a call site could change what it passes and -// the behaviour files would keep happily pinning a shape nobody sends any more. - -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { glob } from 'tinyglobby' -import { AGENT_LAUNCH_CALLER_PROFILES } from './agent-launch-caller-profiles-test-harness' - -const REPO_ROOT = join(import.meta.dirname, '../../../..') -const FUNNEL = 'src/renderer/src/lib/launch-agent-in-new-tab.ts' - -async function productionCallers(): Promise { - const files = await glob(['src/**/*.ts', 'src/**/*.tsx'], { - cwd: REPO_ROOT, - ignore: ['**/*.test.ts', '**/*.test.tsx'] - }) - return files - .filter((file) => file !== FUNNEL) - .filter((file) => readFileSync(join(REPO_ROOT, file), 'utf8').includes('launchAgentInNewTab(')) - .sort() -} - -describe('agent launch caller profiles', () => { - it('covers every production call site of the funnel and no phantom one', async () => { - const profiled = AGENT_LAUNCH_CALLER_PROFILES.map((profile) => profile.caller).sort() - - expect(profiled).toEqual(await productionCallers()) - }) - - it('names each profile exactly once', () => { - const ids = AGENT_LAUNCH_CALLER_PROFILES.map((profile) => profile.id) - - expect(new Set(ids).size).toBe(ids.length) - expect(ids.length).toBe(13) - }) - - it.each(AGENT_LAUNCH_CALLER_PROFILES.map((profile) => [profile.id, profile] as const))( - 'keeps %s anchored to the arguments its call site still builds', - (_id, profile) => { - const source = readFileSync(join(REPO_ROOT, profile.caller), 'utf8') - - // Why: a positive control on the instrument — an unreadable or renamed file would otherwise - // make every marker below vacuously "not found" and the assertion would just be noise. - expect(source).toContain('launchAgentInNewTab(') - expect(profile.sourceMarkers.length).toBeGreaterThan(0) - for (const marker of profile.sourceMarkers) { - expect(source).toContain(marker) - } - } - ) - - it.each(AGENT_LAUNCH_CALLER_PROFILES.map((profile) => [profile.id, profile] as const))( - 'records whether %s installs launch callbacks, matching its source', - (_id, profile) => { - const source = readFileSync(join(REPO_ROOT, profile.caller), 'utf8') - - expect(source.includes('beforeSurfaceOpen:')).toBe(profile.passesBeforeSurfaceOpen) - expect(source.includes('agentSessionLaunchPlan,')).toBe(profile.passesLaunchPlan) - expect(source.includes('onPromptDelivered')).toBe(profile.passesOnPromptDelivered) - } - ) - - it('pins which call sites read a tab id straight off the synchronous result', () => { - const readers = AGENT_LAUNCH_CALLER_PROFILES.filter((profile) => - profile.readsBack.includes('surface-tab-id') - ).map((profile) => profile.id) - - // Why: this is the coupling a move to an async launch RPC threatens most directly — these - // call sites cannot tolerate a tab id that only exists after the launch settles. - expect(readers.sort()).toEqual([ - 'empty-workspace-default-chat', - 'fix-checks', - 'floating-default-agent', - 'quick-command', - 'source-control-action', - 'source-control-recovery', - 'tab-bar-create-menu', - 'tab-bar-quick-launch-button' - ]) - }) - - it('pins which call sites await the prompt-delivery promise', () => { - const awaiters = AGENT_LAUNCH_CALLER_PROFILES.filter((profile) => - profile.readsBack.includes('prompt-delivery-result') - ).map((profile) => profile.id) - - expect(awaiters.sort()).toEqual(['session-continuation', 'source-control-action']) - }) -}) diff --git a/src/renderer/src/lib/agent-launch-caller-profiles-test-harness.ts b/src/renderer/src/lib/agent-launch-caller-profiles-test-harness.ts index 5aaa913044f..a988e1673f5 100644 --- a/src/renderer/src/lib/agent-launch-caller-profiles-test-harness.ts +++ b/src/renderer/src/lib/agent-launch-caller-profiles-test-harness.ts @@ -7,42 +7,23 @@ import type { LaunchAgentInNewTabArgs } from '@/lib/launch-agent-in-new-tab' * The suite feeds these argument shapes through the real funnel instead of driving twelve caller * module graphs: a migration rewrites the funnel's internals, not what a caller hands it, so the * observable outcome of each caller's argument shape is the thing that must survive. - * - * `sourceMarkers` re-anchors each profile to its call site. A caller that stops passing what the - * profile encodes fails the census rather than silently drifting out of coverage. */ export type CallerLaunchArgs = Omit< LaunchAgentInNewTabArgs, 'beforeSurfaceOpen' | 'agentSessionLaunchPlan' | 'onPromptDelivered' > -export type CallerResultRead = - | 'surface-tab-id' - | 'prompt-delivery-result' - | 'null-only' - | 'discarded' - export type AgentLaunchCallerProfile = { /** Production module that owns this call site. */ caller: string /** Stable id used in test titles so a dropped profile is visible in the report. */ id: string - /** Literal fragments the call site must still contain for this profile to be current. */ - sourceMarkers: readonly string[] /** * The argument object this call site builds. Values the call site derives at runtime (agent, * workspace, prompt text, group) use a representative stand-in; values it fixes as a literal are * reproduced exactly. */ args: CallerLaunchArgs - /** The call site installs a `beforeSurfaceOpen` hook. */ - passesBeforeSurfaceOpen: boolean - /** The call site hands in a route plan preflighted before the workspace existed. */ - passesLaunchPlan: boolean - /** The call site installs an `onPromptDelivered` callback. */ - passesOnPromptDelivered: boolean - /** What the call site reads off the synchronous result. */ - readsBack: readonly CallerResultRead[] } const PROMPT = 'Explain the failing check and propose a fix.' @@ -51,51 +32,30 @@ export const AGENT_LAUNCH_CALLER_PROFILES: readonly AgentLaunchCallerProfile[] = { id: 'dashboard-spawn', caller: 'src/renderer/src/components/dashboard/launch-dashboard-agent.ts', - sourceMarkers: ["launchSource: 'unknown'"], - args: { agent: 'codex', worktreeId: 'wt-1', launchSource: 'unknown' }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: false, - passesOnPromptDelivered: false, - readsBack: ['null-only'] + args: { agent: 'codex', worktreeId: 'wt-1', launchSource: 'unknown' } }, { id: 'empty-workspace-default-chat', caller: 'src/renderer/src/lib/empty-workspace-default-agent-chat.ts', - sourceMarkers: ["launchSource: 'unknown'", 'pendingActivationSpawn: true'], args: { agent: 'codex', worktreeId: 'wt-1', launchSource: 'unknown', pendingActivationSpawn: true - }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: true, - passesOnPromptDelivered: false, - readsBack: ['surface-tab-id'] + } }, { id: 'floating-default-agent', caller: 'src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx', - sourceMarkers: ['worktreeId: FLOATING_TERMINAL_WORKTREE_ID', "launchSource: 'shortcut'"], args: { agent: 'codex', worktreeId: FLOATING_TERMINAL_WORKTREE_ID, launchSource: 'shortcut' - }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: false, - passesOnPromptDelivered: false, - readsBack: ['surface-tab-id'] + } }, { id: 'source-control-action', caller: 'src/renderer/src/components/right-sidebar/runSourceControlAgentActionStart.ts', - sourceMarkers: [ - 'groupId: groupId ?? worktreeId', - 'agentArgs: launchAgentArgs', - 'promptDelivery,', - 'launchPlatform,' - ], args: { agent: 'codex', worktreeId: 'wt-1', @@ -106,21 +66,11 @@ export const AGENT_LAUNCH_CALLER_PROFILES: readonly AgentLaunchCallerProfile[] = launchPlatform: 'darwin', // Caller-supplied, not fixed at the call site: one representative value stands in. launchSource: 'sidebar' - }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: false, - passesOnPromptDelivered: false, - readsBack: ['surface-tab-id', 'prompt-delivery-result'] + } }, { id: 'source-control-recovery', caller: 'src/renderer/src/components/right-sidebar/source-control/ai/recovery-launch.ts', - sourceMarkers: [ - 'groupId: activeGroupId ?? activeWorktreeId', - 'agentArgs: savedRecipe.agentArgs', - "promptDelivery: 'submit-after-ready'", - "launchSource: 'source_control_recovery'" - ], args: { agent: 'codex', worktreeId: 'wt-1', @@ -130,36 +80,22 @@ export const AGENT_LAUNCH_CALLER_PROFILES: readonly AgentLaunchCallerProfile[] = promptDelivery: 'submit-after-ready', launchPlatform: 'darwin', launchSource: 'source_control_recovery' - }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: false, - passesOnPromptDelivered: false, - readsBack: ['surface-tab-id'] + } }, { id: 'git-history-explain-commit', caller: 'src/renderer/src/components/right-sidebar/source-control/sync/use-git-history-commit-actions.ts', - sourceMarkers: ['prompt: explainPrompt', "promptDelivery: 'submit-after-ready'"], args: { agent: 'codex', worktreeId: 'wt-1', prompt: PROMPT, promptDelivery: 'submit-after-ready' - }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: false, - passesOnPromptDelivered: false, - readsBack: ['discarded'] + } }, { id: 'tab-bar-quick-launch-button', caller: 'src/renderer/src/components/tab-bar/QuickLaunchButton.tsx', - sourceMarkers: [ - '...(prompt !== undefined ? { prompt } : {})', - '...(promptDelivery !== undefined ? { promptDelivery } : {})', - '...(onPromptDelivered !== undefined ? { onPromptDelivered } : {})' - ], args: { agent: 'codex', worktreeId: 'wt-1', @@ -167,36 +103,21 @@ export const AGENT_LAUNCH_CALLER_PROFILES: readonly AgentLaunchCallerProfile[] = prompt: PROMPT, promptDelivery: 'submit-after-ready', launchSource: 'tab_bar_quick_launch' - }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: false, - passesOnPromptDelivered: true, - readsBack: ['surface-tab-id'] + } }, { id: 'tab-bar-create-menu', caller: 'src/renderer/src/components/tab-bar/use-tab-bar-create-menu-controller.ts', - sourceMarkers: ['groupId: resolvedGroupId', "launchSource: 'tab_bar_quick_launch'"], args: { agent: 'codex', worktreeId: 'wt-1', groupId: 'group-1', launchSource: 'tab_bar_quick_launch' - }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: false, - passesOnPromptDelivered: false, - readsBack: ['surface-tab-id'] + } }, { id: 'terminal-session-fork', caller: 'src/renderer/src/components/terminal-pane/terminal-agent-session-fork.ts', - sourceMarkers: [ - "promptDelivery: 'draft'", - "launchSource: 'terminal_context_menu'", - 'agentSessionLaunchPlan,', - 'beforeSurfaceOpen: (surface) =>' - ], args: { agent: 'codex', worktreeId: 'wt-1', @@ -204,30 +125,16 @@ export const AGENT_LAUNCH_CALLER_PROFILES: readonly AgentLaunchCallerProfile[] = promptDelivery: 'draft', launchSource: 'terminal_context_menu', launchPlatform: 'darwin' - }, - passesBeforeSurfaceOpen: true, - passesLaunchPlan: true, - passesOnPromptDelivered: false, - readsBack: ['null-only'] + } }, { id: 'terminal-create-shortcut', caller: 'src/renderer/src/components/use-terminal-create-actions.ts', - sourceMarkers: ['groupId: targetGroupId', "launchSource: 'shortcut'"], - args: { agent: 'codex', worktreeId: 'wt-1', groupId: 'group-1', launchSource: 'shortcut' }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: false, - passesOnPromptDelivered: false, - readsBack: ['null-only'] + args: { agent: 'codex', worktreeId: 'wt-1', groupId: 'group-1', launchSource: 'shortcut' } }, { id: 'fix-checks', caller: 'src/renderer/src/lib/fix-checks-agent-launch.ts', - sourceMarkers: [ - 'agentArgs: recipe.agentArgs', - "promptDelivery: 'submit-after-ready'", - 'beforeSurfaceOpen: () => {' - ], args: { agent: 'codex', worktreeId: 'wt-1', @@ -238,19 +145,11 @@ export const AGENT_LAUNCH_CALLER_PROFILES: readonly AgentLaunchCallerProfile[] = launchPlatform: 'darwin', // Caller-supplied, not fixed at the call site: one representative value stands in. launchSource: 'task_page' - }, - passesBeforeSurfaceOpen: true, - passesLaunchPlan: false, - passesOnPromptDelivered: false, - readsBack: ['surface-tab-id'] + } }, { id: 'session-continuation', caller: 'src/renderer/src/lib/launch-agent-session-continuation.ts', - sourceMarkers: [ - "promptDelivery: agent === 'claude' ? 'draft' : 'submit-after-ready'", - 'onPromptDelivered: () =>' - ], args: { agent: 'codex', worktreeId: 'wt-1', @@ -260,20 +159,11 @@ export const AGENT_LAUNCH_CALLER_PROFILES: readonly AgentLaunchCallerProfile[] = initialCwd: '/repo/worktree/packages/app', // Caller-supplied, not fixed at the call site: one representative value stands in. launchSource: 'command_palette' - }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: false, - passesOnPromptDelivered: true, - readsBack: ['prompt-delivery-result'] + } }, { id: 'quick-command', caller: 'src/renderer/src/lib/run-quick-command-in-new-tab.ts', - sourceMarkers: [ - "launchSource: 'quick_command'", - 'quickCommandLabel: command.label', - "{ promptDelivery: 'submit-after-ready' as const }" - ], args: { agent: 'codex', worktreeId: 'wt-1', @@ -281,11 +171,7 @@ export const AGENT_LAUNCH_CALLER_PROFILES: readonly AgentLaunchCallerProfile[] = prompt: PROMPT, launchSource: 'quick_command', quickCommandLabel: 'Review' - }, - passesBeforeSurfaceOpen: false, - passesLaunchPlan: false, - passesOnPromptDelivered: false, - readsBack: ['surface-tab-id'] + } } ] diff --git a/src/renderer/src/lib/agent-launch-routing-caller-census.test.ts b/src/renderer/src/lib/agent-launch-routing-caller-census.test.ts deleted file mode 100644 index 2c9524c9995..00000000000 --- a/src/renderer/src/lib/agent-launch-routing-caller-census.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { glob } from 'tinyglobby' - -const REPO_ROOT = join(import.meta.dirname, '../../../..') -const CENSUS_FILE = 'src/renderer/src/lib/agent-launch-routing-caller-census.test.ts' - -const LAUNCH_AGENT_IN_NEW_TAB_CALLERS = [ - 'src/renderer/src/components/dashboard/launch-dashboard-agent.ts', - // Joined the funnel rather than appearing beside it: this button used to hand-roll the helper's - // terminal arm against `queueTabStartupCommand`. A line going up here is a converged bypass. - 'src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx', - 'src/renderer/src/components/right-sidebar/runSourceControlAgentActionStart.ts', - 'src/renderer/src/components/right-sidebar/source-control/ai/recovery-launch.ts', - 'src/renderer/src/components/right-sidebar/source-control/sync/use-git-history-commit-actions.ts', - 'src/renderer/src/components/tab-bar/QuickLaunchButton.tsx', - 'src/renderer/src/components/tab-bar/use-tab-bar-create-menu-controller.ts', - 'src/renderer/src/components/terminal-pane/terminal-agent-session-fork.ts', - 'src/renderer/src/components/use-terminal-create-actions.ts', - 'src/renderer/src/lib/empty-workspace-default-agent-chat.ts', - 'src/renderer/src/lib/fix-checks-agent-launch.ts', - 'src/renderer/src/lib/launch-agent-session-continuation.ts', - 'src/renderer/src/lib/run-quick-command-in-new-tab.ts' -] - -// Why: the planner is the one production module that decides a route. A second resolver call -// site is how the seven launch sites drifted apart before it existed. -const ROUTE_RESOLVER_DEFINITION = 'src/renderer/src/lib/agent-launch-routing.ts' -const ROUTE_PLANNER = 'src/renderer/src/lib/agent-session-launch-plan.ts' -const DIRECT_ROUTE_RESOLVER_CALL = /\b(?:resolveAgentLaunchRoute|structuredAgentLaunchSupported)\(/ -// Why: adopting a verdict bypasses the resolver by design (a persisted quick-create request, a -// resume whose gate already planned), so each adopter is pinned rather than trusted by convention. -const VERDICT_ADOPTERS = [ - 'src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts', - 'src/renderer/src/lib/worktree-creation-structured-session.ts' -] - -async function productionFiles(): Promise { - return glob(['src/**/*.ts', 'src/**/*.tsx'], { - cwd: REPO_ROOT, - ignore: ['**/*.test.ts', '**/*.test.tsx', CENSUS_FILE] - }) -} - -describe('agent launch routing caller census', () => { - it('pins every production launchAgentInNewTab caller behind the shared funnel', async () => { - const callers = (await productionFiles()) - .filter((file) => file !== 'src/renderer/src/lib/launch-agent-in-new-tab.ts') - .filter((file) => - readFileSync(join(REPO_ROOT, file), 'utf8').includes('launchAgentInNewTab(') - ) - .sort() - expect(callers).toEqual([...LAUNCH_AGENT_IN_NEW_TAB_CALLERS].sort()) - }) - - it('lets only the planner decide a launch route', async () => { - const directCallers = (await productionFiles()) - .filter((file) => file !== ROUTE_RESOLVER_DEFINITION) - .filter((file) => - DIRECT_ROUTE_RESOLVER_CALL.test(readFileSync(join(REPO_ROOT, file), 'utf8')) - ) - .sort() - expect(directCallers).toEqual([ROUTE_PLANNER]) - }) - - it('pins every production adopter of a planned verdict', async () => { - const adopters = (await productionFiles()) - .filter((file) => file !== ROUTE_PLANNER) - .filter((file) => - readFileSync(join(REPO_ROOT, file), 'utf8').includes('adoptAgentSessionLaunchVerdict(') - ) - .sort() - expect(adopters).toEqual([...VERDICT_ADOPTERS].sort()) - }) - - it('keeps non-visible, resume, and floating launchers intentionally outside the route', () => { - for (const file of [ - 'src/renderer/src/lib/launch-agent-background-session.ts', - 'src/renderer/src/lib/launch-ai-vault-session.ts', - 'src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx' - ]) { - expect(readFileSync(join(REPO_ROOT, file), 'utf8')).not.toContain('resolveAgentLaunchRoute') - } - }) -}) diff --git a/src/renderer/src/lib/non-secure-context-crypto.repro.test.ts b/src/renderer/src/lib/non-secure-context-crypto.repro.test.ts index ce16d669f16..87da1737c79 100644 --- a/src/renderer/src/lib/non-secure-context-crypto.repro.test.ts +++ b/src/renderer/src/lib/non-secure-context-crypto.repro.test.ts @@ -20,19 +20,6 @@ afterEach(() => { }) describe('non-secure context (plain HTTP LAN web client)', () => { - it('crypto.randomUUID is undefined, like the browser reports', () => { - // oxlint-disable-next-line no-restricted-properties -- asserting the absence this suite exists for - expect((globalThis.crypto as Crypto).randomUUID).toBeUndefined() - // oxlint-disable-next-line no-restricted-properties -- asserting the absence this suite exists for - expect(() => (globalThis.crypto as Crypto).randomUUID()).toThrow() - }) - - it('hashOrcaHookScript does not throw when crypto.subtle is missing', async () => { - const { hashOrcaHookScript } = await import('./orca-hook-trust') - const hash = await hashOrcaHookScript('echo hi') - expect(hash).toMatch(/^[0-9a-f]+$/) - }) - // The fallback must match the secure-context hash, or the shared trust store // mismatches and the user is re-prompted to approve a hook they already // trusted on the desktop app. @@ -54,9 +41,7 @@ describe('non-secure context (plain HTTP LAN web client)', () => { it('loads the renderer agent-status authority and its store slice', async () => { vi.resetModules() const { rendererAgentStatusObservations } = await import('./renderer-agent-status-observations') - const { createAgentStatusAuthorityActions } = - await import('../store/slices/agent-status-authority-actions') - expect(typeof createAgentStatusAuthorityActions).toBe('function') + await import('../store/slices/agent-status-authority-actions') expect(rendererAgentStatusObservations.getAuthorityId()).toMatch( /^renderer:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ ) diff --git a/src/renderer/src/lib/react-commit-cascade-telemetry.test.ts b/src/renderer/src/lib/react-commit-cascade-telemetry.test.ts index 89e0456c2ce..d09337c8d0c 100644 --- a/src/renderer/src/lib/react-commit-cascade-telemetry.test.ts +++ b/src/renderer/src/lib/react-commit-cascade-telemetry.test.ts @@ -2,7 +2,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { sanitizeCrashReportDetails } from '../../../shared/crash-report-redaction' import { REACT_NESTED_UPDATE_LIMIT } from '../../../shared/react-update-depth-attribution' import { - REACT_CASCADING_LANES, setReactCommitCascadeRendererSurface, REACT_COMMIT_CASCADE_ARM_COMMITS, REACT_COMMIT_CASCADE_BREADCRUMB, @@ -67,7 +66,6 @@ describe('cascade thresholds', () => { it('derives arm and notice limits from React commit budget', () => { expect(REACT_COMMIT_CASCADE_NOTICE_LIMIT).toBeLessThan(REACT_NESTED_UPDATE_LIMIT) expect(REACT_COMMIT_CASCADE_ARM_COMMITS).toBeLessThan(REACT_COMMIT_CASCADE_NOTICE_LIMIT) - expect(REACT_CASCADING_LANES).toBe(42) }) }) diff --git a/src/renderer/src/lib/structured-agent-startup-label-census.test.ts b/src/renderer/src/lib/structured-agent-startup-label-census.test.ts deleted file mode 100644 index 888e17c46c1..00000000000 --- a/src/renderer/src/lib/structured-agent-startup-label-census.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { glob } from 'tinyglobby' - -const REPO_ROOT = join(import.meta.dirname, '../../../..') - -describe('structured launch copy', () => { - it('never exposes the removed starting-chat phase or label', async () => { - const files = await glob( - ['src/renderer/src/**/*.ts', 'src/renderer/src/**/*.tsx', 'src/renderer/src/i18n/**/*.json'], - { - cwd: REPO_ROOT, - ignore: ['**/*.test.ts', '**/*.test.tsx'] - } - ) - const offenders = files.filter((file) => { - const source = readFileSync(join(REPO_ROOT, file), 'utf8') - return ( - source.includes('starting-chat') || - source.includes('Starting chat…') || - /Starting (?:\{\{value0\}\}|Claude|Codex) chat…/.test(source) - ) - }) - - expect(offenders).toEqual([]) - }) -}) diff --git a/src/renderer/src/lib/workspace-emoji-shortcodes.lazy.test.ts b/src/renderer/src/lib/workspace-emoji-shortcodes.lazy.test.ts index eafc3e3b2b8..2e4dfac4a4a 100644 --- a/src/renderer/src/lib/workspace-emoji-shortcodes.lazy.test.ts +++ b/src/renderer/src/lib/workspace-emoji-shortcodes.lazy.test.ts @@ -1,5 +1,3 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' describe('workspace emoji shortcode index laziness', () => { @@ -20,11 +18,4 @@ describe('workspace emoji shortcode index laziness', () => { expect(shortcodeIndex.searchWorkspaceEmojiShortcodes('tada')[0]?.emoji).toBe('🎉') expect(catalog.isEmojiShortcodeCatalogBuiltForTest()).toBe(true) }) - - it('keeps the exact-shortcode index out of module scope', () => { - const indexSource = readFileSync(join(__dirname, 'workspace-emoji-shortcodes.ts'), 'utf8') - - expect(indexSource).not.toMatch(/^const \w+ = new Map\(/m) - expect(indexSource).not.toContain('STANDARD_EMOJI_SHORTCODE_ENTRIES') - }) }) diff --git a/src/renderer/src/lib/worktree-creation-flow-agent-trust-preflight.test.ts b/src/renderer/src/lib/worktree-creation-flow-agent-trust-preflight.test.ts deleted file mode 100644 index 2a960761900..00000000000 --- a/src/renderer/src/lib/worktree-creation-flow-agent-trust-preflight.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' - -const FLOW_SOURCE = readFileSync(join(__dirname, 'worktree-creation-flow-execute.ts'), 'utf8') -const PREFLIGHT_SOURCE = readFileSync(join(__dirname, 'agent-trust-preflight.ts'), 'utf8') - -function sourceBetween(source: string, startPattern: string, endPattern: string): string { - const start = source.indexOf(startPattern) - expect(start).toBeGreaterThanOrEqual(0) - const end = source.indexOf(endPattern, start + startPattern.length) - expect(end).toBeGreaterThan(start) - return source.slice(start, end) -} - -describe('worktree creation flow agent trust preflight', () => { - it('forwards the repo SSH connection id when pre-marking terminal agent trust', () => { - const preflight = PREFLIGHT_SOURCE - const createFlow = sourceBetween( - FLOW_SOURCE, - 'const backendSpawned = result.startupTerminal?.spawned === true', - '// `createWorktree` already inserted the real worktree row' - ) - - expect(preflight).toContain('connectionId?: string | null') - expect(preflight).toContain('...(args.connectionId ? { connectionId: args.connectionId } : {})') - expect(createFlow).toContain('repoConnectionId') - expect(createFlow).toContain('repo.id === worktree.repoId') - expect(createFlow).toContain('await preflightAgentTrust({') - expect(createFlow).toContain('connectionId: repoConnectionId') - }) -}) diff --git a/src/renderer/src/lib/worktree-status-spinner-launch-agent.test.ts b/src/renderer/src/lib/worktree-status-spinner-launch-agent.test.ts index 78b71ef25da..e964a9f28f1 100644 --- a/src/renderer/src/lib/worktree-status-spinner-launch-agent.test.ts +++ b/src/renderer/src/lib/worktree-status-spinner-launch-agent.test.ts @@ -55,18 +55,6 @@ describe('#9040 worktree dot attributes spinner titles to the launched agent', ( expect(status).toBe('working') }) - // Why: pins the #9647 gate — spinner attribution needs a launch identity, so a - // spinner in a tab no agent was launched in cannot spin the dot. - it('stays active for a spinner title with no launch identity', () => { - const status = getWorktreeStatus( - [{ id: 'tab-1', title: '⠐ Review branch for regressions' }], - [], - livePtyMap('tab-1') - ) - - expect(status).toBe('active') - }) - it('does not manufacture activity from a non-spinner title with a launch identity', () => { const status = getWorktreeStatus( [{ id: 'tab-1', title: 'bash', launchAgent: 'claude' }], diff --git a/src/renderer/src/runtime/browser-workspace-tab-close-census.test.ts b/src/renderer/src/runtime/browser-workspace-tab-close-census.test.ts deleted file mode 100644 index 212e9d7afe7..00000000000 --- a/src/renderer/src/runtime/browser-workspace-tab-close-census.test.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { readdirSync, readFileSync } from 'node:fs' -import { join, relative, sep } from 'node:path' -import { describe, expect, it } from 'vitest' - -// Why: who tears a browser workspace down is a policy, and every close site that decides it alone -// gets it wrong in a different way — the ambiguous multi-owner close fell through silently, the -// pageless host mirror was un-closable, and the menu's Close Tab fired at a host that had never -// heard of a staged tab. Testing planBrowserWorkspaceTabClose in isolation cannot catch the next -// site that skips it, so this census pins every renderer file that closes a browser workspace: -// how often it reaches for the store action, and whether it asks the shared plan first. Adding a -// close anywhere fails this test until it is classified here. -const BROWSER_WORKSPACE_CLOSE_SITES: { - path: string - /** - * Every mention of the identifier, not just call expressions: a renamed destructure or a - * `store['closeBrowserTab']` lookup is still a close site, and matching `closeBrowserTab(` - * walks straight past both. - */ - closeBrowserTabMentions: number - /** How many local teardowns forward the plan's cleanup reason; 0 for sites that skip the plan. */ - planReasonForwardings: number - /** How many closeBrowserTab calls actually pass that reason on; 0 for sites that skip the plan. */ - reasonCarryingCloseCalls: number - routesThroughPlan: boolean - why: string -}[] = [ - { - path: 'src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-lifecycle.ts', - closeBrowserTabMentions: 4, - reasonCarryingCloseCalls: 0, - planReasonForwardings: 0, - routesThroughPlan: false, - why: 'Mirrors a page the host already retired; a plan-driven close would echo it back.' - }, - { - path: 'src/renderer/src/components/floating-terminal/use-floating-terminal-close-actions.ts', - closeBrowserTabMentions: 6, - reasonCarryingCloseCalls: 0, - planReasonForwardings: 0, - routesThroughPlan: false, - why: 'Floating workspace tabs are local-only and have no remote owner to reconcile.' - }, - { - path: 'src/renderer/src/components/floating-terminal/use-floating-terminal-panel-store-state.ts', - closeBrowserTabMentions: 3, - reasonCarryingCloseCalls: 0, - planReasonForwardings: 0, - routesThroughPlan: false, - why: 'Passes the local floating-panel close action through its controller.' - }, - { - path: 'src/renderer/src/components/use-terminal-bulk-close-actions.ts', - closeBrowserTabMentions: 3, - reasonCarryingCloseCalls: 1, - planReasonForwardings: 1, - routesThroughPlan: true, - why: 'Bulk terminal-tab teardown plans browser ownership before local cleanup.' - }, - { - path: 'src/renderer/src/components/use-terminal-workspace-store-bindings.ts', - closeBrowserTabMentions: 3, - reasonCarryingCloseCalls: 0, - planReasonForwardings: 0, - routesThroughPlan: false, - why: 'Store binding exposes the close action to terminal controllers.' - }, - { - path: 'src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.ts', - closeBrowserTabMentions: 3, - reasonCarryingCloseCalls: 0, - planReasonForwardings: 0, - routesThroughPlan: false, - why: 'Host-requested closes are applied locally without echoing a close request.' - }, - { - path: 'src/renderer/src/hooks/ipc-events/session-tab-ipc-bridge.ts', - closeBrowserTabMentions: 2, - reasonCarryingCloseCalls: 0, - planReasonForwardings: 0, - routesThroughPlan: false, - why: 'Host session-tab requests are applied locally without echo.' - }, - { - path: 'src/renderer/src/lib/workspace-browser-tab-close.ts', - closeBrowserTabMentions: 2, - reasonCarryingCloseCalls: 1, - planReasonForwardings: 1, - routesThroughPlan: true, - why: 'All workspace browser teardown funnels through the ownership plan before local cleanup.' - }, - { - path: 'src/renderer/src/runtime/browser-workspace-tab-close.ts', - closeBrowserTabMentions: 1, - reasonCarryingCloseCalls: 0, - planReasonForwardings: 0, - routesThroughPlan: true, - why: 'The funnel disavowal fallback completes teardown when every owning host denies the tab.' - }, - { - path: 'src/renderer/src/runtime/web-runtime-browser-tab-staging.ts', - closeBrowserTabMentions: 1, - reasonCarryingCloseCalls: 0, - planReasonForwardings: 0, - routesThroughPlan: false, - why: 'Rolls back a client-staged row for a create that never reached a host page.' - }, - { - path: 'src/renderer/src/store/slices/browser/browser-close-actions.ts', - closeBrowserTabMentions: 3, - reasonCarryingCloseCalls: 0, - planReasonForwardings: 0, - routesThroughPlan: false, - why: 'Slice-owned shutdown tears down every browser row directly.' - }, - { - path: 'src/renderer/src/store/slices/browser/browser-slice-contract.ts', - closeBrowserTabMentions: 1, - reasonCarryingCloseCalls: 0, - planReasonForwardings: 0, - routesThroughPlan: false, - why: 'The extracted slice contract declares the close action consumed by browser controllers.' - } -] - -function listSourceFiles(dir: string): string[] { - return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { - const fullPath = join(dir, entry.name) - if (entry.isDirectory()) { - return listSourceFiles(fullPath) - } - // Test harnesses and fixtures stub the store action rather than closing anything. - if ( - !/\.(ts|tsx)$/.test(entry.name) || - /\.test\.(ts|tsx)$/.test(entry.name) || - /-test-(harness|fixtures)\.(ts|tsx)$/.test(entry.name) - ) { - return [] - } - return [fullPath] - }) -} - -// Why: comments are stripped first, so commenting a close call out in place must fail the census -// rather than quietly shrink the count. -function stripComments(source: string): string { - return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1') -} - -function countCloseBrowserTabMentions(source: string): number { - return stripComments(source).match(/\bcloseBrowserTab\b/g)?.length ?? 0 -} - -describe('browser workspace close census', () => { - it.each(BROWSER_WORKSPACE_CLOSE_SITES)( - '$path mentions closeBrowserTab $closeBrowserTabMentions times, plan-routed: $routesThroughPlan', - ({ path, closeBrowserTabMentions, routesThroughPlan }) => { - const source = stripComments(readFileSync(join(process.cwd(), path), 'utf8')) - expect(countCloseBrowserTabMentions(source)).toBe(closeBrowserTabMentions) - expect(/\bcloseBrowserWorkspaceTabOnHosts\(/.test(source)).toBe(routesThroughPlan) - } - ) - - it('lists every renderer file that closes a browser workspace', () => { - const root = join(process.cwd(), 'src/renderer') - const closers = listSourceFiles(root) - .filter((filePath) => countCloseBrowserTabMentions(readFileSync(filePath, 'utf8')) > 0) - .map((filePath) => relative(process.cwd(), filePath).split(sep).join('/')) - .sort() - expect(closers).toEqual(BROWSER_WORKSPACE_CLOSE_SITES.map((site) => site.path).sort()) - }) - - // Why: the plan is only an authority if its consumers actually run its local teardown. A site - // that reads the plan and then closes on its own terms is the same divergence with extra steps. - // Bound to the forwarding expression itself — merely mentioning localCloseReason is not wiring, - // and Terminal.tsx's two sites have no behavior test to catch it going missing. - it('every plan-routed site forwards the plan cleanup reason into its local teardown', () => { - const forwardsReason = - /plan\.localCloseReason\s*\?\s*\{\s*reason:\s*plan\.localCloseReason\s*\}\s*:\s*undefined/g - // Why: the expression existing somewhere in the file is not the wiring — a call that drops it on - // the floor reads identically. Both halves are pinned: the reason is computed, and the close - // calls carry it. - const carriesReason = - /closeBrowserTab\(\s*[^()]*?(?:[Cc]loseOptions|plan\.localCloseReason)[^()]*?\)/g - for (const site of BROWSER_WORKSPACE_CLOSE_SITES) { - const source = stripComments(readFileSync(join(process.cwd(), site.path), 'utf8')) - expect({ - path: site.path, - forwards: source.match(forwardsReason)?.length ?? 0, - carrying: source.match(carriesReason)?.length ?? 0 - }).toEqual({ - path: site.path, - forwards: site.planReasonForwardings, - carrying: site.reasonCarryingCloseCalls - }) - } - }) -}) diff --git a/src/renderer/src/runtime/host-session-mirror-settle-census.test.ts b/src/renderer/src/runtime/host-session-mirror-settle-census.test.ts deleted file mode 100644 index 7d6a0eadc3e..00000000000 --- a/src/renderer/src/runtime/host-session-mirror-settle-census.test.ts +++ /dev/null @@ -1,256 +0,0 @@ -/** - * Registry test for the host-session-mirror settle seam. Four review rounds - * each found a NEW call site settling the latch out of order with its store - * patch, so the seam is enforced structurally: a settle exists only as the - * receipt of a landed patch (or as the audited stale-frame exception), and a - * new patch or settle site fails this census until it adopts that contract. - */ - -import { readdirSync, readFileSync, statSync } from 'node:fs' -import { join, relative, sep } from 'node:path' -import { describe, expect, it } from 'vitest' - -const RENDERER_SRC = join(import.meta.dirname, '..') - -const SETTLE_RULE = [ - 'The mirror latch settles EXACTLY when evidence reached the store.', - 'applyWebSessionTabsStorePatch returns the settle receipt for its own patch:', - 'capture it and invoke it after the frame finishes recovery. A frame whose', - 'patch wrote nothing settles through hostSessionMirrorSettleForPatchlessFrame,', - 'and ONLY on a decision carrying settlesHostMirror — a rejection backed by the', - 'equal/newer view already accepted into the store. Never derive that from a', - 'bare boolean: "the mirror never writes this workspace" is also a rejection,', - 'and settling on it drains parked resume work against state nobody wrote.', - 'A captured receipt that is never invoked wedges its pane instead, so every', - 'receipt has to reach a call. Never call markHostSessionMirror*Hydrated from', - 'feature code, and never add a boolean that remembers "the patch landed" —', - 'that ordering bug shipped four times. If you added a legitimate new site,', - 'update this census deliberately.' -].join(' ') - -/** Receipt-minting calls. Every one owes its caller an invocation. */ -const RECEIPT_CALLS = [ - 'applyWebSessionTabsStorePatch(', - 'hostSessionMirrorSettleForPatchlessFrame(' -] as const - -/** - * The binding a receipt was captured into, read backwards from the call. - * TypeScript cannot express a must-call obligation and the invocation is - * deliberately deferred to after `finishRecovery`, so this stays textual: - * an unrecognised capture shape fails rather than passing unaudited. - */ -function receiptBindingName(before: string): string | null { - const lines = before.split('\n') - for (let line = lines.length - 1; line >= 0 && line > lines.length - 8; line -= 1) { - const match = /\b(?:const|let|var)?\s*([A-Za-z_$][\w$]*)\s*(?::[^=]*?)?=(?![=>])/.exec( - lines[line]! - ) - if (match) { - return match[1]! - } - } - return null -} - -function productionSources(): { path: string; source: string }[] { - const sources: { path: string; source: string }[] = [] - const walk = (dir: string): void => { - for (const entry of readdirSync(dir)) { - const path = join(dir, entry) - if (statSync(path).isDirectory()) { - walk(path) - continue - } - if (!/\.(ts|tsx)$/.test(entry) || /\.test\.|\.d\.ts$/.test(entry)) { - continue - } - sources.push({ - path: relative(RENDERER_SRC, path).split(sep).join('/'), - source: readFileSync(path, 'utf8') - }) - } - } - walk(RENDERER_SRC) - return sources -} - -function countOccurrences(source: string, needle: string): number { - let count = 0 - for ( - let index = source.indexOf(needle); - index !== -1; - index = source.indexOf(needle, index + 1) - ) { - count += 1 - } - return count -} - -describe('host-session-mirror settle census', () => { - const sources = productionSources() - - it('mirror marks are reachable only through the settle receipts', () => { - const markCounts: Record = {} - for (const { path, source } of sources) { - const hydrated = countOccurrences(source, 'markHostSessionMirrorHydrated(') - const worktreeHydrated = countOccurrences(source, 'markHostSessionMirrorWorktreeHydrated(') - if (hydrated + worktreeHydrated > 0) { - markCounts[path] = { hydrated, worktreeHydrated } - } - } - expect(markCounts, SETTLE_RULE).toEqual({ - // The definitions themselves. - 'runtime/host-session-mirror-hydration.ts': { hydrated: 1, worktreeHydrated: 1 }, - // Exactly the receipt constructors: the patch receipt (environment-wide - // and per-worktree) and the stale-frame receipt. The environment-wide - // mark has three audited arms, all inside the receipt: an authoritative - // empty inventory, a non-empty inventory, and an empty inventory that - // settles only after `terminal.list` says the host has no live PTY — - // `0 === 0` is not host evidence (STA-5377). - 'runtime/web-session-tabs-sync/mirror-settle.ts': { hydrated: 3, worktreeHydrated: 2 } - }) - }) - - it('every store patch call site captures its settle receipt', () => { - const needle = 'applyWebSessionTabsStorePatch(' - const callSites: Record = {} - for (const { path, source } of sources) { - let calls = 0 - for ( - let index = source.indexOf(needle); - index !== -1; - index = source.indexOf(needle, index + 1) - ) { - const before = source.slice(0, index).trimEnd() - if (before.endsWith('function')) { - continue // The definition. - } - calls += 1 - // A receipt is captured when the call is an expression consumed by an - // assignment, return, ternary, or argument — never a bare statement. - const capturedBy = before.slice(-1) - expect( - ['=', '(', ',', '?', ':', '{'].includes(capturedBy) || before.endsWith('return'), - `${path} discards the settle receipt of applyWebSessionTabsStorePatch. ${SETTLE_RULE}` - ).toBe(true) - } - if (calls > 0) { - callSites[path] = calls - } - } - expect(callSites, SETTLE_RULE).toEqual({ - // Initial listAll, visibility-resume repair, full inventory, global - // singular frame, and scoped active frame are owned by these extracted - // recovery/event modules. - 'runtime/web-session-tabs-sync/active-session-subscription.ts': 1, - 'runtime/web-session-tabs-sync/global-session-events.ts': 1, - 'runtime/web-session-tabs-sync/global-session-inventory-event.ts': 1, - 'runtime/web-session-tabs-sync/load-initial.ts': 1, - 'runtime/web-session-tabs-sync/visibility-resume-repair.ts': 1, - // The eager post-create session.tabs.list refresh. - 'runtime/web-runtime-session-snapshot.ts': 1, - // The local structured-session mirror owns two: the inventory/subscription - // frame, and the toggle-off teardown that retracts the tabs it published. - 'runtime/local-structured-session-tabs-sync/snapshot-apply.ts': 2 - }) - }) - - it('every captured settle receipt reaches an invocation', () => { - const receiptBindings: Record> = {} - for (const { path, source } of sources) { - for (const needle of RECEIPT_CALLS) { - for ( - let index = source.indexOf(needle); - index !== -1; - index = source.indexOf(needle, index + 1) - ) { - const before = source.slice(0, index).trimEnd() - if (before.endsWith('function')) { - continue // The definition. - } - const name = receiptBindingName(before) - expect( - name, - `${path} captures a settle receipt in a shape this census cannot follow. ${SETTLE_RULE}` - ).not.toBeNull() - // The obligation is discharged by the next call of the same binding — - // a fresh declaration of that name in between means the call belongs - // to another receipt, so this one was dropped. - const rest = source.slice(index + needle.length) - const invocation = new RegExp(`\\b${name}\\s*(?:\\?\\.)?\\(`).exec(rest) - const redeclared = - invocation !== null && - new RegExp(`\\b(?:let|const|var)\\s+${name}\\b`).test(rest.slice(0, invocation.index)) - expect( - invocation !== null && !redeclared, - `${path} never invokes the settle receipt it captured into \`${name}\`. ${SETTLE_RULE}` - ).toBe(true) - const bindings = (receiptBindings[path] ??= {}) - bindings[name!] = (bindings[name!] ?? 0) + 1 - } - } - } - // Pinning the resolved names keeps the rule from going vacuous: a binding - // this census misreads settles on some other identifier's invocation. - expect(receiptBindings, SETTLE_RULE).toEqual({ - // Hydration and mirror receipts remain pinned by their extracted owners: - // the global singular frame owns two hydration completions and the global - // inventory frame one, initial loading owns one, active subscription owns - // two mirror settles, and visibility resume repair owns one. The local - // structured-session apply module owns one settle per direction: the - // snapshot it mirrors in, and the teardown that retracts it. - 'runtime/web-session-tabs-sync/active-session-subscription.ts': { settle: 2 }, - 'runtime/web-session-tabs-sync/global-session-events.ts': { settleHydration: 2 }, - 'runtime/web-session-tabs-sync/global-session-inventory-event.ts': { settleHydration: 1 }, - 'runtime/web-session-tabs-sync/load-initial.ts': { settleHydration: 1 }, - 'runtime/web-session-tabs-sync/visibility-resume-repair.ts': { settle: 1 }, - 'runtime/web-runtime-session-snapshot.ts': { settleMirror: 1 }, - 'runtime/local-structured-session-tabs-sync/snapshot-apply.ts': { - settleStructuredSessionClear: 1, - settleStructuredSessionMirror: 1 - } - }) - }) - - it('the patchless settle appears only at its audited sites', () => { - const patchlessCounts: Record = {} - for (const { path, source } of sources) { - const count = countOccurrences(source, 'hostSessionMirrorSettleForPatchlessFrame(') - if (count > 0) { - patchlessCounts[path] = count - } - } - expect(patchlessCounts, SETTLE_RULE).toEqual({ - // The definition, the global singular frame, and the scoped active frame. - 'runtime/web-session-tabs-sync/active-session-subscription.ts': 1, - 'runtime/web-session-tabs-sync/global-session-events.ts': 1, - 'runtime/web-session-tabs-sync/mirror-settle.ts': 1 - }) - }) - - it('only the audited decisions grant a rejected frame a settle', () => { - const settlingCounts: Record = {} - const silentCounts: Record = {} - for (const { path, source } of sources) { - const settling = countOccurrences(source, 'settlesHostMirror: true') - const silent = countOccurrences(source, 'settlesHostMirror: false') - if (settling > 0) { - settlingCounts[path] = settling - } - if (silent > 0) { - silentCounts[path] = silent - } - } - // A new decision has to be minted here, and minting one forces its author - // to say whether the frame is host evidence — the whole point of the pair. - expect(settlingCounts, SETTLE_RULE).toEqual({ - // The applied frame (its own patch) and the outranked one (the accepted view). - 'runtime/web-session-tabs-sync/tracking-decisions.ts': 2 - }) - expect(silentCounts, SETTLE_RULE).toEqual({ - // The unmirrored frame: no accepted view of it ever reached the store. - 'runtime/web-session-tabs-sync/tracking-decisions.ts': 1 - }) - }) -}) diff --git a/src/renderer/src/runtime/remote-server-parity.test.ts b/src/renderer/src/runtime/remote-server-parity.test.ts index 7c1bcf9bb68..c9779332f66 100644 --- a/src/renderer/src/runtime/remote-server-parity.test.ts +++ b/src/renderer/src/runtime/remote-server-parity.test.ts @@ -210,29 +210,6 @@ describe('parity §3: remote terminal create appends rightmost (matches local)', toWebTerminalSurfaceTabId('host-tab-3') ]) }) - - it('preserves existing relative order when adding (no reshuffle)', () => { - const prior = stateWithLocalTerminals([ - localTerminal('host-tab-1', 0, false), - localTerminal('host-tab-2', 1, true) - ]) - recordWebSessionFocusIntent({ environmentId: ENV }, WT, `host-tab-3::${LEAF_C}`) - const patch = applyWebSessionTabsSnapshot( - prior, - makeSnapshot([ - { parentTab: 'host-tab-1', leaf: LEAF_A, active: false }, - { parentTab: 'host-tab-2', leaf: LEAF_B, active: false }, - { parentTab: 'host-tab-3', leaf: LEAF_C, active: true } - ]), - ENV, - NOW + 10 - ) as Partial - expect(groupOrder(patch)).toEqual([ - toWebTerminalSurfaceTabId('host-tab-1'), - toWebTerminalSurfaceTabId('host-tab-2'), - toWebTerminalSurfaceTabId('host-tab-3') - ]) - }) }) // ────────────────────────────────────────────────────────────────────────── @@ -422,24 +399,3 @@ describe('parity §11: remote browser create focuses the new browser tab', () => expect(nextType).toBe('terminal') }) }) - -// ────────────────────────────────────────────────────────────────────────── -// Plan §1 — Lifecycle: an emptied host snapshot does not bootstrap phantom tabs -// when local terminals already exist (sleep/disconnect must not invent state). -// ────────────────────────────────────────────────────────────────────────── -describe('parity §1: empty host snapshot does not fabricate tabs', () => { - it('an empty snapshot with existing local terminals does not add a phantom tab', () => { - const prior = stateWithLocalTerminals([localTerminal('host-tab-1', 0, true)]) - const patch = applyWebSessionTabsSnapshot( - prior, - makeSnapshot([], { activeTabId: null, activeTabType: null }), - ENV, - NOW + 10 - ) as Partial - // No new fabricated terminal ids beyond what existed. - const order = groupOrder(patch) - for (const id of order) { - expect(id).toBe(toWebTerminalSurfaceTabId('host-tab-1')) - } - }) -}) diff --git a/src/renderer/src/runtime/runtime-host-contact-parity.test.ts b/src/renderer/src/runtime/runtime-host-contact-parity.test.ts index a24e963a1d9..83e152cd899 100644 --- a/src/renderer/src/runtime/runtime-host-contact-parity.test.ts +++ b/src/renderer/src/runtime/runtime-host-contact-parity.test.ts @@ -10,16 +10,6 @@ import { runtimeHostContactFromSnapshot } from '../../../shared/runtime-host-contact' import type { RuntimeStatus } from '../../../shared/runtime-types' -import { - runtimeHostConnectionState, - runtimeHostConnectionStateForEntry, - type RuntimeHostConnectionState -} from './runtime-host-connection-state' - -// This file exists to prove the contact introduced here changes nothing. It carries a frozen copy -// of the derivation as it stood before, and asserts the shipping one agrees with it on every -// combination of the inputs it reads. A behaviour change would have to survive the whole -// cross-product to go unnoticed, which is a much harder thing to do by accident than to argue. type Entry = { status: RuntimeStatus | null @@ -27,33 +17,6 @@ type Entry = { snapshot?: RuntimeHostStatusSnapshot } -/** The derivation exactly as it read before `RuntimeHostContact` existed. Do not refactor. */ -function legacyRuntimeHostConnectionStateForEntry( - entry: Entry | null | undefined -): RuntimeHostConnectionState { - const snapshot = entry?.snapshot - if (snapshot) { - if (snapshot.retired || snapshot.verification === 'blocked') { - return 'disconnected' - } - if (snapshot.transport === 'disconnected') { - return 'reconnecting' - } - if (snapshot.verification === 'checking' && !entry?.status) { - return 'checking' - } - if (snapshot.transport === 'ready' && snapshot.verification !== 'verified') { - return 'runtime-unavailable' - } - } - return runtimeHostConnectionState({ - hasStatusEntry: Boolean(entry), - status: entry?.status ?? null, - ...(snapshot?.transport === 'connecting' ? { transportStatus: 'checking' as const } : {}), - remoteControl: entry?.remoteControl ?? entry?.status?.remoteControl ?? null - }) -} - const VERIFICATIONS = ['checking', 'verified', 'unavailable', 'blocked'] as const const TRANSPORTS = ['unknown', 'connecting', 'ready', 'disconnected'] as const const RETIRED = [false, true] as const @@ -138,38 +101,7 @@ function* everySnapshotEntry(): Generator<{ label: string; entry: Entry }> { } } -describe('the host contact changes no verdict', () => { - it('agrees with the frozen derivation on every snapshot combination', () => { - const cases = [...everySnapshotEntry()] - // Guard against the enumeration silently collapsing: 4 x 4 x 2 x 2 x 6. - expect(cases).toHaveLength(384) - const disagreements = cases - .map(({ label, entry }) => ({ - label, - now: runtimeHostConnectionStateForEntry(entry), - before: legacyRuntimeHostConnectionStateForEntry(entry) - })) - .filter(({ now, before }) => now !== before) - expect(disagreements).toEqual([]) - }) - - it('agrees for entries that carry no snapshot at all', () => { - const entries: (Entry | null | undefined)[] = [ - null, - undefined, - { status: null }, - { status: makeStatus() }, - { status: null, remoteControl: makeRemoteControl('closed') }, - { status: null, remoteControl: makeRemoteControl('ready') }, - { status: makeStatus({ remoteControl: makeRemoteControl('reconnecting') }) } - ] - for (const entry of entries) { - expect(runtimeHostConnectionStateForEntry(entry)).toBe( - legacyRuntimeHostConnectionStateForEntry(entry) - ) - } - }) - +describe('the revoked predicate and the contact verdict stay in step', () => { it('keeps the revoked predicate and the contact verdict in step', () => { for (const { label, entry } of everySnapshotEntry()) { expect( diff --git a/src/renderer/src/store/slices/github-pr-comments.test.ts b/src/renderer/src/store/slices/github-pr-comments.test.ts index 8432f944fd4..b78fe1589f6 100644 --- a/src/renderer/src/store/slices/github-pr-comments.test.ts +++ b/src/renderer/src/store/slices/github-pr-comments.test.ts @@ -234,62 +234,6 @@ describe('createGitHubSlice.fetchPRComments', () => { vi.useRealTimers() } }) - - it('preserves cached checks when the checks IPC fails', async () => { - const store = createTestStore() - const repoPath = '/repo' - const branch = 'feature/test' - const checksCacheKey = `${repoPath}::pr-checks::12` - const cachedChecks = [ - { name: 'build', status: 'completed', conclusion: 'failure', url: null } as const - ] - - store.setState({ - checksCache: { - [checksCacheKey]: { - data: cachedChecks, - fetchedAt: 1, - headSha: 'abc123head' - } - } - } as unknown as Partial) - mockApi.gh.prChecks.mockRejectedValueOnce(new Error('rate limited')) - - await expect( - store.getState().fetchPRChecks(repoPath, 12, branch, 'abc123head', null, { force: true }) - ).resolves.toEqual(cachedChecks) - - expect(store.getState().checksCache[checksCacheKey]?.data).toEqual(cachedChecks) - expect(store.getState().checksCache[checksCacheKey]?.fetchedAt).toBe(1) - }) - - it('does not return cached checks for a different requested head SHA after IPC failure', async () => { - const store = createTestStore() - const repoPath = '/repo' - const branch = 'feature/test' - const checksCacheKey = `${repoPath}::pr-checks::12` - const oldHeadChecks = [ - { name: 'build', status: 'completed', conclusion: 'success', url: null } as const - ] - - store.setState({ - checksCache: { - [checksCacheKey]: { - data: oldHeadChecks, - fetchedAt: 1, - headSha: 'old-head' - } - } - } as unknown as Partial) - mockApi.gh.prChecks.mockRejectedValueOnce(new Error('rate limited')) - - await expect( - store.getState().fetchPRChecks(repoPath, 12, branch, 'new-head', null, { force: true }) - ).resolves.toEqual([]) - - expect(store.getState().checksCache[checksCacheKey]?.data).toEqual(oldHeadChecks) - expect(store.getState().checksCache[checksCacheKey]?.headSha).toBe('old-head') - }) }) describe('createGitHubSlice PR comment mutations', () => { diff --git a/src/renderer/src/store/slices/github-work-items-query-bounds.test.ts b/src/renderer/src/store/slices/github-work-items-query-bounds.test.ts deleted file mode 100644 index 40b89fdd4d5..00000000000 --- a/src/renderer/src/store/slices/github-work-items-query-bounds.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { - GITHUB_WORK_ITEMS_QUERY_MAX_BYTES, - isGitHubWorkItemsQueryTooLarge -} from './github-work-items-query-bounds' - -describe('GitHub work item query bounds', () => { - it('allows normal GitHub search syntax', () => { - expect(isGitHubWorkItemsQueryTooLarge('is:pr is:open label:bug')).toBe(false) - }) - - it('rejects oversized pasted work item queries', () => { - expect(isGitHubWorkItemsQueryTooLarge('x'.repeat(GITHUB_WORK_ITEMS_QUERY_MAX_BYTES))).toBe( - false - ) - expect(isGitHubWorkItemsQueryTooLarge('x'.repeat(GITHUB_WORK_ITEMS_QUERY_MAX_BYTES + 1))).toBe( - true - ) - }) - - it('measures UTF-8 bytes for non-ASCII query text', () => { - expect(isGitHubWorkItemsQueryTooLarge(String.fromCodePoint(0x1f600).repeat(3_000))).toBe(true) - }) -}) diff --git a/src/renderer/src/store/slices/linear-invalidation.test.ts b/src/renderer/src/store/slices/linear-invalidation.test.ts index febf6bc222f..59c0bd666c6 100644 --- a/src/renderer/src/store/slices/linear-invalidation.test.ts +++ b/src/renderer/src/store/slices/linear-invalidation.test.ts @@ -136,35 +136,6 @@ describe('createLinearSlice invalidation', () => { ).toMatchObject({ items: [{ id: 'LIST' }] }) }) - it('caches teams by workspace and dedupes fresh reads', async () => { - const store = createTestStore() - linearListTeams.mockResolvedValueOnce([team('team-1')]) - - await expect(store.getState().listLinearTeams('workspace-1')).resolves.toMatchObject([ - { id: 'team-1' } - ]) - await expect(store.getState().listLinearTeams('workspace-1')).resolves.toMatchObject([ - { id: 'team-1' } - ]) - - expect(linearListTeams).toHaveBeenCalledTimes(1) - expect(store.getState().getCachedLinearTeams('workspace-1')).toMatchObject([{ id: 'team-1' }]) - }) - - it('patches issue-cache entries keyed by workspace-qualified ids', () => { - const store = createTestStore() - store.setState({ - linearIssueCache: { - 'workspace-1::issue-id': { data: issue('issue-id'), fetchedAt: Date.now() } - } - }) - - store.getState().patchLinearIssue('issue-id', { title: 'Updated' }) - - expect(store.getState().linearIssueCache['workspace-1::issue-id'].data?.title).toBe('Updated') - expect(store.getState().linearIssueCache['workspace-1::issue-id'].fetchedAt).toBe(0) - }) - it('refreshing a linked Linear issue invalidates stale issue collection caches', async () => { const store = createTestStore() linearGetIssue.mockResolvedValueOnce(issue('issue-id')) diff --git a/src/renderer/src/store/slices/repo-identity-reconcile.test.ts b/src/renderer/src/store/slices/repo-identity-reconcile.test.ts index 43afafe717f..703ff483306 100644 --- a/src/renderer/src/store/slices/repo-identity-reconcile.test.ts +++ b/src/renderer/src/store/slices/repo-identity-reconcile.test.ts @@ -1,5 +1,4 @@ import { describe, expect, it } from 'vitest' -import fs from 'node:fs' import type { Repo } from '../../../../shared/repo-types' import { reconcileFetchedRepos, reuseEqualRecordMap } from './repo-identity-reconcile' @@ -119,8 +118,6 @@ describe('reconcileFetchedRepos', () => { expect(result).toBe(previous) expect(result.every((repo, index) => repo === previous[index])).toBe(true) - const source = fs.readFileSync(new URL('./repo-identity-reconcile.ts', import.meta.url), 'utf8') - expect(source).not.toMatch(/previous\.find|next\.find|findIndex/) }) }) diff --git a/src/renderer/src/store/slices/runtime-host-status-entry-parity.test.ts b/src/renderer/src/store/slices/runtime-host-status-entry-parity.test.ts deleted file mode 100644 index 63c3de2e708..00000000000 --- a/src/renderer/src/store/slices/runtime-host-status-entry-parity.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -// The store's host-status entry is one shape, and every reader of the map has to accept exactly -// it. A narrower local copy still typechecks against the store — the fields it is missing are all -// optional — so it freezes at the vintage it was written at and never fails. #17710 added -// `remoteControl` and #20003 added `snapshot`; the copies these assertions cover were not updated -// either time. Like the other typed-contract tests, they fail at typecheck, not at runtime. -import { describe, expectTypeOf, it } from 'vitest' -import type { buildExecutionHostRegistry } from '../../../../shared/execution-host-registry' -import type { buildSidebarHostOptions } from '@/components/sidebar/sidebar-host-options' -import type { getRuntimeAutomationAvailability } from '@/components/automations/automation-target-availability' -import type { getRuntimeSourceHostAvailability } from '@/components/automations/automation-source-context' -import type { AutomationListLocalRowProps } from '@/components/automations/AutomationListLocalRow' -import type { AutomationsListPanelProps } from '@/components/automations/AutomationsListPanel' -import type { RuntimeEnvironmentStatus } from './runtime-status-types' - -// Compare the entry each reader accepts rather than the surrounding map, so a mismatch names the -// field that drifted instead of every ReadonlyMap method signature. -type AcceptedEntry = NonNullable extends ReadonlyMap ? TEntry : never - -type RegistryEntry = AcceptedEntry< - Parameters[0]['runtimeStatusByEnvironmentId'] -> -type SidebarEntry = AcceptedEntry< - Parameters[0]['runtimeStatusByEnvironmentId'] -> -type AutomationEntry = AcceptedEntry[1]> -type SourceContextEntry = AcceptedEntry[1]> -type LocalRowEntry = AcceptedEntry -type ListPanelEntry = AcceptedEntry - -describe('every reader of the runtime host status map accepts the store entry', () => { - it('holds for the execution-host registry', () => { - expectTypeOf().toEqualTypeOf() - }) - - it('holds for the sidebar host options', () => { - expectTypeOf().toEqualTypeOf() - }) - - it('holds for runtime automation availability', () => { - expectTypeOf().toEqualTypeOf() - }) - - // These three only forward the map, which is exactly how a stale copy survives: nothing they - // do with it can fail, so the drift surfaces in whatever they hand it to. - it('holds for the automation source-context reader', () => { - expectTypeOf().toEqualTypeOf() - }) - - it('holds for the automation list row', () => { - expectTypeOf().toEqualTypeOf() - }) - - it('holds for the automations list panel', () => { - expectTypeOf().toEqualTypeOf() - }) -}) diff --git a/src/renderer/src/web/web-runtime-client-export-parity.test.ts b/src/renderer/src/web/web-runtime-client-export-parity.test.ts deleted file mode 100644 index 6ba87eaad36..00000000000 --- a/src/renderer/src/web/web-runtime-client-export-parity.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { expect, expectTypeOf, it } from 'vitest' -import type { WebPairingOffer } from './web-pairing' -import * as WebClient from './web-runtime-client' - -it('keeps the paired-web client public export surface exact', () => { - expectTypeOf().toEqualTypeOf() - expectTypeOf().toEqualTypeOf() - expectTypeOf>().toEqualTypeOf< - [ - pairing: WebPairingOffer, - options?: ConstructorParameters[1] - ] - >() - expectTypeOf().toEqualTypeOf< - 'call' | 'close' | 'subscribe' | 'statusOwner' - >() - expect(Object.keys(WebClient)).toEqual(['WebRuntimeClient']) -}) diff --git a/src/shared/child-process/child-process-import-boundary.test.ts b/src/shared/child-process/child-process-import-boundary.test.ts index e5c1d362112..f7d78c9f84b 100644 --- a/src/shared/child-process/child-process-import-boundary.test.ts +++ b/src/shared/child-process/child-process-import-boundary.test.ts @@ -23,14 +23,6 @@ const CHILD_PROCESS_IMPORT_ALLOWLIST: readonly string[] = readFileSync( .map((line) => line.trim()) .filter((line) => line.length > 0 && !line.startsWith('#')) -/** - * The true count of files importing child_process directly. - * - * May only ever be DECREASED, and only by migrating a file off - * `node:child_process`. Raising it is never the fix. - */ -const DIRECT_IMPORTER_PIN = 149 - const IMPORT_PATTERN = /(?:from\s+['"]node:child_process['"]|from\s+['"]child_process['"]|require\(\s*['"]node:child_process['"]|require\(\s*['"]child_process['"])/ @@ -118,23 +110,4 @@ describe('child_process import boundary', () => { const stale = CHILD_PROCESS_IMPORT_ALLOWLIST.filter((path) => !offenders.includes(path)) expect(stale, 'Allowlist entry no longer imports child_process — delete the line.').toEqual([]) }) - - it('holds the offender count at the pin', () => { - // Bounding by the allowlist's own length proves nothing: the two move - // together, so a swap (one file migrated off, one new file added with its - // entry) kept the bound satisfied. The pin is a literal for that reason. - expect( - offenders.length, - `${offenders.length} files import child_process directly; the pin is ${DIRECT_IMPORTER_PIN}. ` + - 'Never raise the pin -- migrate the file to runProcess/spawnProcess from ' + - 'src/shared/child-process instead.' - ).toBeLessThanOrEqual(DIRECT_IMPORTER_PIN) - // A pin left above reality is how a ratchet rots: it re-opens room for the - // next direct import to land for free. - expect( - offenders.length, - `Only ${offenders.length} files import child_process directly. Lower DIRECT_IMPORTER_PIN to ` + - `${offenders.length} to keep the ground you just took.` - ).toBeGreaterThanOrEqual(DIRECT_IMPORTER_PIN) - }) }) diff --git a/src/shared/emoji-shortcode-catalog.lazy.test.ts b/src/shared/emoji-shortcode-catalog.lazy.test.ts index dc05160696b..f46e0e742aa 100644 --- a/src/shared/emoji-shortcode-catalog.lazy.test.ts +++ b/src/shared/emoji-shortcode-catalog.lazy.test.ts @@ -1,5 +1,3 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' import emojiShortcodes from 'emojibase-data/en/shortcodes/emojibase.json' @@ -29,37 +27,4 @@ describe('emoji shortcode catalog laziness', () => { expect(catalog.replaceKnownEmojiWithShortcodes('ship \u{1F389}')).toBe('ship party ') expect(catalog.isEmojiShortcodeCatalogBuiltForTest()).toBe(true) }) - - it('leaves the main-process worktree namer importing only the deferred entry points', () => { - // A cross-project import would drag src/main into the shared tsconfig, so assert on source. - const worktreeLogic = readFileSync(join(__dirname, '../main/ipc/worktree-logic.ts'), 'utf8') - const catalogImport = worktreeLogic.match( - /import \{([^}]*)\} from '[^']*emoji-shortcode-catalog'/ - ) - - expect(catalogImport?.[1].split(',').map((name) => name.trim())).toEqual([ - 'replaceKnownEmojiWithShortcodes', - 'setEmojiShortcodeDatasetLoader' - ]) - }) - - it('keeps the catalog build out of module scope', () => { - const sharedSource = readFileSync(join(__dirname, 'emoji-shortcode-catalog.ts'), 'utf8') - - // A module-scope `const X = ` is the regression this guards. - expect(sharedSource).not.toMatch(/^const \w+ = Object\.entries\(/m) - expect(sharedSource).not.toMatch(/^const \w+ = new (?:Map|Intl\.Segmenter)\(/m) - expect(sharedSource).toContain('function loadCatalog()') - }) - - it('keeps the 166 KB dataset off every module main statically imports', () => { - const sharedSource = readFileSync(join(__dirname, 'emoji-shortcode-catalog.ts'), 'utf8') - const worktreeLogic = readFileSync(join(__dirname, '../main/ipc/worktree-logic.ts'), 'utf8') - - // A static `emojibase-data` import anywhere main reaches inlines the dataset into - // out/main/index.js and JSON.parses it on every launch. - const staticDatasetImport = /\bfrom '[^']*emojibase-data[^']*'/ - expect(sharedSource).not.toMatch(staticDatasetImport) - expect(worktreeLogic).not.toMatch(staticDatasetImport) - }) }) diff --git a/src/shared/network/manual-address.test.ts b/src/shared/network/manual-address.test.ts index 6ef59536129..0260eeb7d72 100644 --- a/src/shared/network/manual-address.test.ts +++ b/src/shared/network/manual-address.test.ts @@ -1,16 +1,8 @@ import { describe, it, expect } from 'vitest' -import { readFileSync } from 'node:fs' -import { resolve } from 'node:path' import { parseManualNetworkAddress } from './manual-address' import { PAIRING_ENDPOINT_MAX_CHARACTERS } from '../mobile-pairing-protocol-limits' describe('parseManualNetworkAddress', () => { - it('keeps renderer validation off the Zod schema import path', () => { - const source = readFileSync(resolve('src/shared/network/manual-address.ts'), 'utf8') - expect(source).not.toContain('mobile-relay-pairing-offer') - expect(source).not.toContain("from 'zod'") - }) - describe('IPv4', () => { it('accepts canonical IPv4', () => { expect(parseManualNetworkAddress('192.168.1.24')).toEqual({ diff --git a/src/shared/pane-agent-identity-inventory.test.ts b/src/shared/pane-agent-identity-inventory.test.ts deleted file mode 100644 index 028207cdfb9..00000000000 --- a/src/shared/pane-agent-identity-inventory.test.ts +++ /dev/null @@ -1,488 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { glob } from 'tinyglobby' -import { - blankStringContents, - blankStringContentsDesynced, - isTestFile, - stripComments -} from './source-scan/source-tree-scan' - -const HELPERS = [ - 'getAgentLabel', - 'isClaudeAgent', - 'titleHasAgentName', - 'buildAgentNameRe', - 'resolveTerminalTitleAgentType', - 'resolveExplicitTerminalTitleAgentType', - 'resolveCommittedTitleAgentType', - 'resolvePaneAgentOwner', - 'resolveCompatibleAgentTypeForOwner', - 'classifyTitleActivity', - 'detectAgentStatusFromTitle', - 'resolveAgentTypeFromTerminalTitle', - 'resolvePaneAgentIdentity', - 'resolveCanonicalPaneAgentIdentity', - 'resolvePublishedPaneAgentIdentity' -] as const - -const TEST_SUPPORT_PATHS = new Set([ - 'src/renderer/src/components/terminal-pane/pty-connection-test-environment.ts' -]) - -type Helper = (typeof HELPERS)[number] -type InventoryPath = string | readonly [path: string, occurrences: number] -type Classification = - | 'parser-implementation' - | 'activity-only' - | 'enum-formatter' - | 'evidence-producer' - | 'identity-consumer' - | 'action-consumer' - -type InventoryGroup = { - helper: Helper - classification: Classification - paths: readonly InventoryPath[] -} - -const INVENTORY: readonly InventoryGroup[] = [ - { - helper: 'getAgentLabel', - classification: 'enum-formatter', - paths: [ - [ - 'src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx', - 2 - ], - ['src/renderer/src/components/automations/AutomationListLocalRow.tsx', 2], - 'src/renderer/src/components/automations/automation-draft-model.ts', - ['src/renderer/src/components/automations/automation-list-search-rows.ts', 2], - ['src/renderer/src/components/settings/NativeChatSupportedAgents.tsx', 2], - ['src/renderer/src/components/settings/QuickCommandsList.tsx', 2], - ['src/renderer/src/components/tab-bar/TabBarQuickCommandItem.tsx', 2], - ['src/renderer/src/components/tab-bar/TabBarQuickCommandsMenu.tsx', 2], - 'src/renderer/src/lib/agent-catalog.tsx', - ['src/renderer/src/lib/launch-agent-session-continuation.ts', 3], - ['src/renderer/src/lib/orchestration-skill-coverage.ts', 2] - ] - }, - { - helper: 'getAgentLabel', - classification: 'activity-only', - paths: [['src/renderer/src/lib/pane-agent-evidence.ts', 2]] - }, - { - helper: 'getAgentLabel', - classification: 'parser-implementation', - paths: [ - 'src/renderer/src/lib/agent-status.ts', - 'src/shared/agent-detection.ts', - 'src/shared/agent-title-identity.ts', - ['src/shared/agent-title-owner.ts', 2], - ['src/shared/terminal-title-agent-type.ts', 2] - ] - }, - { - helper: 'isClaudeAgent', - classification: 'action-consumer', - paths: [ - ['src/renderer/src/components/terminal-pane/cache-timer-seeding.ts', 2], - ['src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts', 2], - ['src/renderer/src/components/terminal-pane/pty-connection/agent-task-complete-notify.ts', 2], - ['src/renderer/src/store/terminals/terminal-ephemeral-state.ts', 2] - ] - }, - { - helper: 'isClaudeAgent', - classification: 'action-consumer', - paths: [ - ['src/renderer/src/components/terminal-pane/pty-connection/command-inferred-pane-agent.ts', 2] - ] - }, - { - helper: 'isClaudeAgent', - classification: 'parser-implementation', - paths: [ - 'src/renderer/src/lib/agent-status.ts', - 'src/shared/agent-detection.ts', - ['src/shared/agent-title-identity.ts', 2], - ['src/shared/terminal-title-agent-type.ts', 2] - ] - }, - { - helper: 'titleHasAgentName', - classification: 'parser-implementation', - paths: [ - 'src/shared/agent-detection.ts', - 'src/shared/agent-name-token-match.ts', - ['src/shared/agent-title-core.ts', 4], - ['src/shared/agent-title-evidence.ts', 2], - ['src/shared/agent-title-identity.ts', 11], - ['src/shared/terminal-title-agent-type.ts', 15] - ] - }, - { - helper: 'titleHasAgentName', - classification: 'evidence-producer', - paths: [['src/renderer/src/hooks/ipc-events/agent-status-routing.ts', 2]] - }, - { - helper: 'buildAgentNameRe', - classification: 'parser-implementation', - paths: [['src/shared/agent-name-token-match.ts', 2]] - }, - { - helper: 'resolveTerminalTitleAgentType', - classification: 'identity-consumer', - paths: [['src/renderer/src/lib/notes-send-agent-targets.ts', 2]] - }, - { - helper: 'resolveTerminalTitleAgentType', - classification: 'parser-implementation', - paths: [['src/shared/terminal-title-agent-type.ts', 2]] - }, - { - helper: 'resolveExplicitTerminalTitleAgentType', - classification: 'identity-consumer', - paths: [ - ['mobile/src/session/mobile-terminal-tab-agent.ts', 2], - ['src/main/runtime/tui-idle-evidence.ts', 2], - ['src/renderer/src/lib/open-tab-occupant-agent.ts', 2], - ['src/renderer/src/lib/use-tab-agent.ts', 3] - ] - }, - { - helper: 'resolveExplicitTerminalTitleAgentType', - classification: 'parser-implementation', - paths: [ - ['src/renderer/src/lib/pane-agent-evidence.ts', 2], - ['src/renderer/src/lib/tab-agent-from-signals.ts', 2], - 'src/shared/terminal-title-agent-type.ts' - ] - }, - { - helper: 'resolveCommittedTitleAgentType', - classification: 'action-consumer', - paths: [ - ['src/renderer/src/components/tab-bar/native-chat-tab-agent-evidence.ts', 3], - ['src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts', 2], - ['src/renderer/src/components/terminal-pane/terminal-ctrl-enter.ts', 2], - ['src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.ts', 2], - ['src/renderer/src/components/terminal-pane/use-notification-dispatch.ts', 2] - ] - }, - { - helper: 'resolveCommittedTitleAgentType', - classification: 'identity-consumer', - paths: [ - ['src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.ts', 4], - ['src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts', 2] - ] - }, - { - helper: 'resolveCommittedTitleAgentType', - classification: 'parser-implementation', - paths: ['src/renderer/src/lib/pane-agent-evidence.ts'] - }, - { - helper: 'resolveCommittedTitleAgentType', - classification: 'action-consumer', - paths: [ - ['src/renderer/src/components/terminal-pane/pty-connection/command-inferred-pane-agent.ts', 2] - ] - }, - { - helper: 'resolvePaneAgentOwner', - classification: 'parser-implementation', - paths: ['src/shared/pane-agent-owner.ts'] - }, - { - helper: 'resolvePaneAgentOwner', - classification: 'evidence-producer', - paths: [['src/renderer/src/components/terminal-pane/parked-terminal-command-status.ts', 2]] - }, - { - helper: 'resolvePaneAgentOwner', - classification: 'identity-consumer', - paths: [ - ['src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts', 2], - ['src/renderer/src/components/terminal-pane/pty-connection/shell-command-inference.ts', 2], - ['src/renderer/src/lib/use-tab-agent.ts', 2] - ] - }, - { - helper: 'resolveCompatibleAgentTypeForOwner', - classification: 'parser-implementation', - paths: [['src/shared/agent-title-owner.ts', 2]] - }, - { - helper: 'resolveCompatibleAgentTypeForOwner', - classification: 'identity-consumer', - paths: [ - ['src/renderer/src/components/sidebar/worktree-agent-row-type.ts', 2], - ['src/main/runtime/runtime-mobile-session-projection.ts', 3], - ['src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts', 2], - ['src/renderer/src/lib/tab-agent-from-signals.ts', 2], - ['src/renderer/src/lib/use-tab-agent.ts', 2] - ] - }, - { - helper: 'resolveCompatibleAgentTypeForOwner', - classification: 'action-consumer', - paths: [ - ['src/renderer/src/components/terminal-pane/pty-connection/agent-task-complete-notify.ts', 2], - [ - 'src/renderer/src/components/terminal-pane/pty-connection/command-inferred-pane-agent.ts', - 3 - ], - ['src/renderer/src/components/terminal-pane/pty-connection/terminal-keydown-fit.ts', 3] - ] - }, - { - helper: 'resolveCompatibleAgentTypeForOwner', - classification: 'evidence-producer', - paths: [ - ['src/renderer/src/components/terminal-pane/pty-connection/direct-ssh-retry-status.ts', 2], - ['src/renderer/src/components/terminal-pane/pty-connection/title-spawn-bell.ts', 2] - ] - }, - { - helper: 'classifyTitleActivity', - classification: 'identity-consumer', - paths: [ - ['src/renderer/src/components/sidebar/smart-attention.ts', 3], - ['src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts', 2], - ['src/renderer/src/components/status-bar/workspace-space-presentation.ts', 3], - ['src/renderer/src/lib/active-agent-note-target.ts', 2], - ['src/renderer/src/lib/worktree-status.ts', 3], - ['src/renderer/src/store/slices/terminal-helpers.ts', 2] - ] - }, - { - helper: 'classifyTitleActivity', - classification: 'action-consumer', - paths: [ - ['src/renderer/src/components/terminal-pane/cache-timer-seeding.ts', 2], - ['src/renderer/src/lib/agent-ready-wait.ts', 2], - ['src/renderer/src/store/terminals/terminal-ephemeral-state.ts', 2] - ] - }, - { - helper: 'classifyTitleActivity', - classification: 'activity-only', - paths: [ - ['src/renderer/src/store/slices/workspace-cleanup-local-evidence.ts', 3], - ['src/renderer/src/store/terminals/terminal-tab-presentation.ts', 4] - ] - }, - { - helper: 'classifyTitleActivity', - classification: 'evidence-producer', - paths: [ - ['src/renderer/src/lib/agent-send-title-status.ts', 2], - ['src/renderer/src/lib/agent-status-terminal-title.ts', 2] - ] - }, - { - helper: 'classifyTitleActivity', - classification: 'parser-implementation', - paths: [ - ['src/renderer/src/lib/agent-status.ts', 5], - 'src/renderer/src/lib/pane-agent-evidence.ts' - ] - }, - { - helper: 'detectAgentStatusFromTitle', - classification: 'evidence-producer', - paths: [ - ['src/main/runtime/orca-runtime-apply-tracked-pty-title.ts', 2], - ['src/main/runtime/orca-runtime-get-pty-record-for-pane-key.ts', 2], - ['src/main/runtime/orca-runtime-get-unpersisted-tracked-title-for-pty.ts', 2], - ['src/main/runtime/orca-runtime-maybe-hydrate-headless-from-renderer.ts', 2], - ['src/main/runtime/orca-runtime-record-agent-prompt-lifecycle-state.ts', 2], - ['src/main/runtime/runtime-terminal-agent-status-query.ts', 3], - ['src/main/runtime/runtime-worktree-status-projection.ts', 4], - ['src/main/runtime/terminal-wait-detection.ts', 2], - ['src/renderer/src/components/terminal-pane/agent-completion-title-observer.ts', 2], - ['src/renderer/src/components/terminal-pane/pty-connection/shell-command-inference.ts', 4], - ['src/renderer/src/components/terminal-pane/pty-output-title-observer.ts', 2], - ['src/shared/terminal-output-side-effects.ts', 3], - ['src/shared/tui-agent-rest-signal.ts', 2] - ] - }, - { - helper: 'detectAgentStatusFromTitle', - classification: 'action-consumer', - paths: [ - ['src/renderer/src/components/terminal-pane/pty-connection/agent-task-complete-notify.ts', 2], - [ - 'src/renderer/src/components/terminal-pane/pty-connection/command-inferred-pane-agent.ts', - 3 - ], - ['src/renderer/src/components/terminal-pane/pty-connection/interrupt-input-intent.ts', 3] - ] - }, - { - helper: 'detectAgentStatusFromTitle', - classification: 'parser-implementation', - paths: [ - ['src/renderer/src/components/terminal-pane/title-agent-identity.ts', 2], - 'src/renderer/src/lib/agent-status.ts', - ['src/renderer/src/lib/pane-agent-evidence.ts', 3], - ['src/shared/agent-decorative-title-signature.ts', 2], - 'src/shared/agent-detection.ts', - ['src/shared/agent-title-owner.ts', 2], - ['src/shared/agent-title-status.ts', 6] - ] - }, - { - helper: 'resolveAgentTypeFromTerminalTitle', - classification: 'identity-consumer', - paths: [ - ['src/renderer/src/components/sidebar/worktree-agent-row-type.ts', 2], - 'src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts', - ['src/renderer/src/lib/worktree-status.ts', 2] - ] - }, - { - helper: 'resolvePaneAgentIdentity', - classification: 'parser-implementation', - paths: ['src/shared/pane-agent-identity-resolver.ts'] - }, - { - helper: 'resolvePaneAgentIdentity', - classification: 'identity-consumer', - paths: [['src/shared/published-pane-agent-identity.ts', 2]] - }, - { - helper: 'resolveCanonicalPaneAgentIdentity', - classification: 'parser-implementation', - paths: ['src/shared/pane-agent-identity-adapter.ts'] - }, - { - helper: 'resolveCanonicalPaneAgentIdentity', - classification: 'identity-consumer', - paths: [['src/shared/agent-status-identity.ts', 2]] - }, - { - helper: 'resolveCanonicalPaneAgentIdentity', - classification: 'identity-consumer', - paths: [['src/shared/terminal-title-agent-type.ts', 2]] - }, - { - helper: 'resolvePublishedPaneAgentIdentity', - classification: 'parser-implementation', - paths: [ - 'src/shared/published-pane-agent-identity.ts', - ['src/main/runtime/orca-runtime-write-orchestration-pointer-pty.ts', 2] - ] - } -] - -const DIRECT_SINGLE_SOURCE_SURFACES: readonly { - path: string - classification: Classification - marker: string -}[] = [ - { - path: 'src/renderer/src/components/terminal-pane/terminal-renderer-policy.ts', - classification: 'identity-consumer', - marker: 'resolveGeminiCompatFallback' - }, - { - path: 'src/renderer/src/components/terminal-pane/terminal-title-evidence.ts', - classification: 'identity-consumer', - marker: 'resolvePaneTitleDecision' - }, - { - path: 'src/renderer/src/components/terminal/terminal-close-copy-kind.ts', - classification: 'identity-consumer', - marker: 'resolveLeafCloseCopyKind' - }, - { - path: 'src/main/runtime/orchestration/mailbox-pointer-stage.ts', - classification: 'action-consumer', - marker: 'isCursorAgentTitle' - }, - { - path: 'src/main/providers/local-pty-session-activation.ts', - classification: 'action-consumer', - marker: 'launchAgent' - }, - { - path: 'src/renderer/src/components/terminal-pane/pty-connection/pane-serializer-settle.ts', - classification: 'action-consumer', - marker: 'sendStartupDraftPaste' - }, - { - path: 'src/renderer/src/lib/active-agent-note-send.ts', - classification: 'action-consumer', - marker: 'sendNotesToActiveAgentSession' - }, - { - path: 'src/renderer/src/components/native-chat/native-chat-runtime-send.ts', - classification: 'action-consumer', - marker: 'sendNativeChatMessage' - }, - { - path: 'mobile/src/session/mobile-native-chat-send.ts', - classification: 'action-consumer', - marker: 'sendMobileNativeChatMessageWithOutcome' - }, - { - path: 'mobile/src/session/mobile-native-chat-image-send.ts', - classification: 'action-consumer', - marker: 'pasteMobileNativeChatImagePaths' - } -] - -describe('pane agent identity inventory ratchet', () => { - it('classifies every legacy helper definition, import, and callsite in src and mobile/src', async () => { - const files = await glob(['src/**/*.{ts,tsx}', 'mobile/src/**/*.{ts,tsx}'], { - ignore: ['**/*.test.*', '**/*.spec.*'] - }) - const actual: { helper: Helper; path: string; occurrences: number }[] = [] - for (const path of files) { - if (isTestFile(path) || TEST_SUPPORT_PATHS.has(path)) { - continue - } - const rawSource = readFileSync(join(process.cwd(), path), 'utf8') - if (!HELPERS.some((helper) => rawSource.includes(helper))) { - continue - } - const decommentedSource = stripComments(rawSource) - if (blankStringContentsDesynced(decommentedSource)) { - throw new Error(`String scanner desynchronized while inventorying ${path}`) - } - const source = blankStringContents(decommentedSource) - for (const helper of HELPERS) { - const occurrences = source.match(new RegExp(`\\b${helper}\\b`, 'g'))?.length ?? 0 - if (occurrences > 0) { - actual.push({ helper, path, occurrences }) - } - } - } - const expected = INVENTORY.flatMap(({ helper, paths }) => - paths.map((site) => { - const [path, occurrences] = typeof site === 'string' ? [site, 1] : site - return { helper, path, occurrences } - }) - ) - const byHelperAndPath = (left: (typeof actual)[number], right: (typeof actual)[number]) => - left.helper.localeCompare(right.helper) || left.path.localeCompare(right.path) - expect(actual.sort(byHelperAndPath)).toEqual(expected.sort(byHelperAndPath)) - }, 30_000) - - it('pins direct single-source identity and action branches outside named helpers', () => { - for (const site of DIRECT_SINGLE_SOURCE_SURFACES) { - const source = stripComments(readFileSync(join(process.cwd(), site.path), 'utf8')) - expect({ - path: site.path, - classification: site.classification, - hasMarker: source.includes(site.marker) - }).toEqual({ path: site.path, classification: site.classification, hasMarker: true }) - } - }) -}) diff --git a/src/shared/pane-agent-identity-surface-inventory.test.ts b/src/shared/pane-agent-identity-surface-inventory.test.ts deleted file mode 100644 index 77d9edb3b84..00000000000 --- a/src/shared/pane-agent-identity-surface-inventory.test.ts +++ /dev/null @@ -1,284 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { glob } from 'tinyglobby' -import { isTestFile, stripComments } from './source-scan/source-tree-scan' - -/** - * Surface half of the identity inventory ratchet: every consumer decision point from the closed - * 65-row inventory (rows 32–65 — the direct title/native-chat selectors, tab projections, mobile - * sync graph, lifecycle selectors, status/OSC ingress, worktree status, attention, and - * title-reset paths) is pinned to a marker symbol in its file. The helper-name census - * (`pane-agent-identity-inventory.test.ts`) is necessary but not sufficient — these files reach - * identity through direct reads a name census cannot see. Moving or renaming a marker means the - * inventory row must be re-classified, deliberately, before review. - */ - -type SurfaceRow = { - /** Row number in the closed consumer inventory. */ - row: number - path: string - marker: string -} - -const SURFACE_ROWS: readonly SurfaceRow[] = [ - { - row: 32, - path: 'src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.ts', - marker: 'resolveNativeChatLeafTitleAgent' - }, - { - row: 32, - path: 'src/renderer/src/components/terminal-pane/use-terminal-pane-chat-state.ts', - marker: 'resolveNativeChatLeafTitleAgent' - }, - { - row: 33, - path: 'src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts', - marker: 'installPaneAgentIdentity' - }, - { row: 34, path: 'src/main/runtime/orchestration/groups.ts', marker: 'terminalIsAgent' }, - { - row: 35, - path: 'src/renderer/src/lib/active-agent-note-target.ts', - marker: 'getActiveTerminalNoteTarget' - }, - { - row: 36, - path: 'src/renderer/src/components/terminal-pane/terminal-agent-paste-bracketing.ts', - marker: 'resolveProtectedMultilinePasteOptionsForPane' - }, - { - row: 37, - path: 'src/renderer/src/components/terminal-pane/command-code-output-ownership.ts', - marker: 'canCommandCodeOutputOwnPane' - }, - { row: 38, path: 'src/renderer/src/lib/agent-ready-wait.ts', marker: 'waitForAgentReady' }, - { - row: 39, - path: 'src/renderer/src/lib/agent-paste-draft.ts', - marker: 'getSettingsForAgentTabRuntimeOwner' - }, - { - row: 40, - path: 'src/renderer/src/lib/agent-followup-delivery.ts', - marker: 'sendFollowupPromptWhenAgentReady' - }, - { - row: 41, - path: 'src/renderer/src/lib/codex-session-restart.ts', - marker: 'markLiveCodexSessionsForRestart' - }, - { - row: 41, - path: 'src/renderer/src/lib/codex-pane-restart-eligibility.ts', - marker: 'isCodexForegroundProcess' - }, - { - row: 42, - path: 'src/renderer/src/components/native-chat/native-chat-availability.ts', - marker: 'canToggleNativeChat' - }, - { - row: 43, - path: 'src/renderer/src/components/native-chat/native-chat-pane-resolution.ts', - marker: 'resolveNativeChatSession' - }, - { - row: 44, - path: 'src/renderer/src/components/terminal-pane/terminal-agent-session-continuation.ts', - marker: 'canContinueAgentSessionInNewSession' - }, - { - row: 45, - path: 'src/renderer/src/components/terminal-pane/terminal-agent-session-fork.ts', - marker: 'prepareAgentSessionForkFromPane' - }, - { - row: 46, - path: 'src/renderer/src/components/terminal-pane/agent-interrupt-inference.ts', - marker: 'isPlainEscapeKeyEvent' - }, - { - row: 46, - path: 'src/renderer/src/components/terminal-pane/agent-question-answered-inference.ts', - marker: 'inferQuestionAnsweredFromCurrentStatus' - }, - { - row: 47, - path: 'src/renderer/src/components/terminal-pane/terminal-keyboard-protocol-pane-agent.ts', - marker: 'resolvePaneKeyboardProtocolAgent' - }, - { - row: 47, - path: 'src/renderer/src/components/terminal-pane/terminal-pane-manager-options.ts', - marker: 'resolvePaneKeyboardProtocolAgent' - }, - { - row: 48, - path: 'src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.ts', - marker: 'selectTabAgentTypesByTabId' - }, - { - row: 49, - path: 'src/renderer/src/components/terminal-pane/terminal-tab-agent-type-index.ts', - marker: 'createTerminalTabAgentTypeSelector' - }, - { - row: 50, - path: 'src/renderer/src/lib/tab-agent-status-index.ts', - marker: 'selectLiveTabAgentPanes' - }, - { - row: 51, - path: 'src/renderer/src/components/tab-bar/terminal-tab-activity-status.ts', - marker: 'resolveTerminalTabActivityStatus' - }, - { - row: 52, - path: 'src/renderer/src/lib/workspace-tab-agent-metadata.ts', - marker: 'maxAgentActivityAt' - }, - { - row: 52, - path: 'src/renderer/src/lib/workspace-tab-palette-entry-builder.ts', - marker: 'buildSearchableWorkspaceTabEntries' - }, - { - row: 53, - path: 'src/renderer/src/lib/running-agent-targets.ts', - marker: 'deriveRunningAgentSendTargets' - }, - { - row: 54, - path: 'src/renderer/src/runtime/sync-runtime-graph.ts', - marker: 'buildMobileSessionTabSnapshots' - }, - { - row: 55, - path: 'src/renderer/src/lib/agent-hibernation-pane-eligibility.ts', - marker: 'toRuntimePtyId' - }, - { - row: 56, - path: 'src/renderer/src/lib/resume-sleeping-agent-session.ts', - marker: 'resumeSleepingAgentSessionsForWorktree' - }, - { - row: 57, - path: 'src/renderer/src/lib/automation-session-reuse.ts', - marker: 'findReusableAutomationSession' - }, - { - row: 58, - path: 'src/renderer/src/components/terminal-pane/pty-connection/cold-restore-resume-startup.ts', - marker: 'bindBuildColdRestoreAgentResumeStartup' - }, - { - row: 59, - path: 'src/main/agent-hooks/server/server-authority-evidence.ts', - marker: 'recordCurrentAuthorityObservation' - }, - { - row: 59, - path: 'src/main/runtime/orca-runtime-write-orchestration-pointer-pty.ts', - marker: 'resolvePaneAgentIdentityField' - }, - { - row: 59, - path: 'src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts', - marker: 'createAgentStatusEventApplicator' - }, - { - row: 59, - path: 'src/renderer/src/store/slices/agent-status-authority-actions.ts', - marker: 'transferAgentPaneAuthority' - }, - { - row: 59, - path: 'src/renderer/src/store/slices/pane-foreground-agent.ts', - marker: 'createPaneForegroundAgentSlice' - }, - { - row: 59, - path: 'src/renderer/src/hooks/ipc-events/agent-status-routing.ts', - marker: 'isAgentStatusForRecentlyClosedTab' - }, - { - row: 60, - path: 'src/renderer/src/components/terminal-pane/pty-connection/title-spawn-bell.ts', - marker: 'installTitleSpawnBell' - }, - { row: 61, path: 'src/renderer/src/lib/worktree-status.ts', marker: 'getWorktreeStatus' }, - { - row: 62, - path: 'src/main/runtime/runtime-worktree-status-projection.ts', - marker: 'getLeafWorktreeStatus' - }, - { - row: 63, - path: 'src/renderer/src/components/sidebar/smart-attention.ts', - marker: 'buildAttentionByWorktree' - }, - { - row: 64, - path: 'src/renderer/src/components/status-bar/workspace-space-presentation.ts', - marker: 'countWorkspaceSpaceActiveAgents' - }, - { row: 65, path: 'src/renderer/src/store/slices/terminal-helpers.ts', marker: 'getResetTitle' }, - { - row: 6, - path: 'src/renderer/src/runtime/web-session-tabs-sync.ts', - marker: 'applyWebSessionTabs' - } -] - -describe('pane agent identity surface inventory (rows 6, 32–65)', () => { - it('every pinned surface still carries its marker symbol', () => { - for (const row of SURFACE_ROWS) { - const source = stripComments(readFileSync(join(process.cwd(), row.path), 'utf8')) - expect({ row: row.row, path: row.path, hasMarker: source.includes(row.marker) }).toEqual({ - row: row.row, - path: row.path, - hasMarker: true - }) - } - }) -}) - -/** - * Identity-observation rebind audit. Advancing a pane incarnation without a positive replacement - * proof is how a legitimate reclaim and a stale-hook bug get conflated (see - * `PaneReplacementProof` in pane-agent-identity-adapter.ts). Every existing sequencer `rebind` - * call is pinned here by file and count: today they are the retired-pane `restart` disposition - * (three ingress paths) and the renderer pane-key transfer. Adding a rebind call, or changing - * these, requires updating this audit — and per the migration plan, a `replacementProof`. - */ -const IDENTITY_SEQUENCER_REBIND_RE = /\b(?:observations|rendererAgentStatusObservations)\.rebind\(/g - -const EXPECTED_REBIND_SITES: readonly (readonly [path: string, occurrences: number])[] = [ - ['src/main/agent-hooks/server/server-ingest-normalization.ts', 1], - ['src/main/agent-hooks/server/server-ingest-remote.ts', 1], - ['src/main/agent-hooks/server/server-lifecycle.ts', 1], - ['src/renderer/src/store/slices/agent-status-authority-actions.ts', 1] -] - -describe('identity observation rebind audit', () => { - it('pins every identity-sequencer rebind call site by file and count', async () => { - const files = await glob(['src/**/*.{ts,tsx}', 'mobile/src/**/*.{ts,tsx}'], { - ignore: ['**/*.test.*', '**/*.spec.*'] - }) - const actual: [string, number][] = [] - for (const path of files.sort()) { - if (isTestFile(path)) { - continue - } - const source = stripComments(readFileSync(join(process.cwd(), path), 'utf8')) - const occurrences = source.match(IDENTITY_SEQUENCER_REBIND_RE)?.length ?? 0 - if (occurrences > 0) { - actual.push([path, occurrences]) - } - } - expect(actual).toEqual(EXPECTED_REBIND_SITES.map((site) => [...site])) - }, 30_000) -}) diff --git a/src/shared/priority-semaphore.test.ts b/src/shared/priority-semaphore.test.ts index aeeacda94ef..5cfbe898bdc 100644 --- a/src/shared/priority-semaphore.test.ts +++ b/src/shared/priority-semaphore.test.ts @@ -2,19 +2,6 @@ import { describe, expect, it } from 'vitest' import { PrioritySemaphore } from './priority-semaphore' describe('PrioritySemaphore', () => { - it('allows up to N concurrent acquires', async () => { - const sem = new PrioritySemaphore(2) - const r1 = await sem.acquire(0) - const r2 = await sem.acquire(0) - - // Both acquired immediately - expect(typeof r1).toBe('function') - expect(typeof r2).toBe('function') - - r1() - r2() - }) - it('blocks when concurrency limit is reached', async () => { const sem = new PrioritySemaphore(1) const r1 = await sem.acquire(0) @@ -129,23 +116,6 @@ describe('PrioritySemaphore', () => { expect(order[0]).toBe('B-high') }) - it('works with zero waiters', async () => { - const sem = new PrioritySemaphore(3) - const r1 = await sem.acquire(0) - r1() - // No crash, no hanging - }) - - it('release is idempotent', async () => { - const sem = new PrioritySemaphore(1) - const r1 = await sem.acquire(0) - r1() - r1() // double release should not throw or corrupt state - - const r2 = await sem.acquire(0) - r2() - }) - it('removes an aborted waiter without consuming the next permit', async () => { const sem = new PrioritySemaphore(1) const release = await sem.acquire(0) diff --git a/src/shared/runtime-client-export-parity.test.ts b/src/shared/runtime-client-export-parity.test.ts deleted file mode 100644 index 2b86d2e6e99..00000000000 --- a/src/shared/runtime-client-export-parity.test.ts +++ /dev/null @@ -1,242 +0,0 @@ -import { describe, expect, expectTypeOf, it } from 'vitest' -import type { PairingOffer } from './pairing' -import type { RuntimeCapability } from './protocol-version' -import * as RemoteClient from './remote-runtime-client' -import type { RuntimeOrchestrationEnvelope, RuntimeRpcResponse } from './runtime-rpc-envelope' -import * as Runtime from './runtime-types' - -type RuntimeTypeInventory = [ - Runtime.BrowserBackResult, - Runtime.BrowserCaptureStartResult, - Runtime.BrowserCaptureStopResult, - Runtime.BrowserCheckResult, - Runtime.BrowserClearResult, - Runtime.BrowserClickResult, - Runtime.BrowserConsoleEntry, - Runtime.BrowserConsoleResult, - Runtime.BrowserCookie, - Runtime.BrowserCookieDeleteResult, - Runtime.BrowserCookieGetResult, - Runtime.BrowserCookieSetResult, - Runtime.BrowserDetectedInfo, - Runtime.BrowserDetectedProfileInfo, - Runtime.BrowserDetectProfilesResult, - Runtime.BrowserDragResult, - Runtime.BrowserErrorCode, - Runtime.BrowserEvalResult, - Runtime.BrowserFillResult, - Runtime.BrowserFocusResult, - Runtime.BrowserGeolocationResult, - Runtime.BrowserGotoResult, - Runtime.BrowserHoverResult, - Runtime.BrowserInterceptDisableResult, - Runtime.BrowserInterceptedRequest, - Runtime.BrowserInterceptEnableResult, - Runtime.BrowserKeypressResult, - Runtime.BrowserNetworkEntry, - Runtime.BrowserNetworkLogResult, - Runtime.BrowserPdfResult, - Runtime.BrowserProfileClearDefaultCookiesResult, - Runtime.BrowserProfileCreateResult, - Runtime.BrowserProfileDeleteResult, - Runtime.BrowserProfileImportFromBrowserResult, - Runtime.BrowserProfileListResult, - Runtime.BrowserReloadResult, - Runtime.BrowserScreencastDialogClosedResult, - Runtime.BrowserScreencastDialogResult, - Runtime.BrowserScreencastEndResult, - Runtime.BrowserScreencastErrorResult, - Runtime.BrowserScreencastReadyResult, - Runtime.BrowserScreencastResult, - Runtime.BrowserScreenshotResult, - Runtime.BrowserScrollResult, - Runtime.BrowserSelectAllResult, - Runtime.BrowserSelectResult, - Runtime.BrowserSnapshotRef, - Runtime.BrowserSnapshotResult, - Runtime.BrowserTabCreateResult, - Runtime.BrowserTabCurrentResult, - Runtime.BrowserTabInfo, - Runtime.BrowserTabListResult, - Runtime.BrowserTabProfileCloneResult, - Runtime.BrowserTabProfileShowResult, - Runtime.BrowserTabSetProfileResult, - Runtime.BrowserTabShowResult, - Runtime.BrowserTabSwitchResult, - Runtime.BrowserTypeResult, - Runtime.BrowserUploadResult, - Runtime.BrowserViewportResult, - Runtime.BrowserWaitResult, - Runtime.CliRuntimeState, - Runtime.CliStatusResult, - Runtime.ComputerActionMetadata, - Runtime.ComputerActionResult, - Runtime.ComputerActionVerification, - Runtime.ComputerAppInfo, - Runtime.ComputerAppQuery, - Runtime.ComputerErrorCode, - Runtime.ComputerListAppsResult, - Runtime.ComputerListWindowsResult, - Runtime.ComputerProviderCapabilities, - Runtime.ComputerScreenshotData, - Runtime.ComputerScreenshotMetadata, - Runtime.ComputerScreenshotStatus, - Runtime.ComputerSnapshotData, - Runtime.ComputerSnapshotResult, - Runtime.ComputerWindowInfo, - Runtime.ComputerWindowListWindow, - Runtime.DeviceScope, - Runtime.RuntimeBrowserDriverState, - Runtime.RuntimeBrowserUnavailableReason, - Runtime.RuntimeDegradation, - Runtime.RuntimeDesktopWindowStatus, - Runtime.RuntimeFileListEntry, - Runtime.RuntimeFileListResult, - Runtime.RuntimeFileOpenResult, - Runtime.RuntimeFilePreviewResult, - Runtime.RuntimeFileReadChunkResult, - Runtime.RuntimeFileReadResult, - Runtime.RuntimeGitCheckoutResult, - Runtime.RuntimeGitLocalBranches, - Runtime.RuntimeGraphStatus, - Runtime.RuntimeMarkdownReadTabResult, - Runtime.RuntimeMarkdownSaveTabResult, - Runtime.RuntimeMobileSessionBrowserTab, - Runtime.RuntimeMobileSessionClientTab, - Runtime.RuntimeMobileSessionCreateTerminalResult, - Runtime.RuntimeMobileSessionFileTab, - Runtime.RuntimeMobileSessionMarkdownTab, - Runtime.RuntimeMobileSessionSnapshotTab, - Runtime.RuntimeMobileSessionTabCloseResult, - Runtime.RuntimeMobileSessionTabGroup, - Runtime.RuntimeMobileSessionTabMove, - Runtime.RuntimeMobileSessionTabMoveResult, - Runtime.RuntimeMobileSessionTabsRemovedResult, - Runtime.RuntimeMobileSessionTabsResult, - Runtime.RuntimeMobileSessionTabsSnapshot, - Runtime.RuntimeMobileSessionTerminalClientTab, - Runtime.RuntimeMobileSessionTerminalTab, - Runtime.RuntimeMobileTerminalTheme, - Runtime.RuntimeNativeChatFileContext, - Runtime.RuntimeNativeChatLaunchDraftResolution, - Runtime.RuntimeRendererSyncWindowGraph, - Runtime.RuntimeRepoList, - Runtime.RuntimeRepoSearchRefs, - Runtime.RuntimeSessionTabCloseReason, - Runtime.RuntimeSpeechModelSummary, - Runtime.RuntimeSpeechSetupState, - Runtime.RuntimeStatus, - Runtime.RuntimeSyncedLeaf, - Runtime.RuntimeSyncedTab, - Runtime.RuntimeSyncWindowGraph, - Runtime.RuntimeSyncWindowGraphResult, - Runtime.RuntimeTerminalAgentStatus, - Runtime.RuntimeTerminalAgentStatusState, - Runtime.RuntimeTerminalClose, - Runtime.RuntimeTerminalCreate, - Runtime.RuntimeTerminalCreateRequestPayload, - Runtime.RuntimeTerminalDriverState, - Runtime.RuntimeTerminalFocus, - Runtime.RuntimeTerminalInteractiveWait, - Runtime.RuntimeTerminalInteractiveWaitSource, - Runtime.RuntimeTerminalListHostScope, - Runtime.RuntimeTerminalListResult, - Runtime.RuntimeTerminalOrphanAdoptionClaim, - Runtime.RuntimeTerminalOrphanAdoptionRequest, - Runtime.RuntimeTerminalOrphanAdoptionResult, - Runtime.RuntimeTerminalOrphanTopology, - Runtime.RuntimeTerminalOrphanTopologyGroup, - Runtime.RuntimeTerminalOrphanTopologyTab, - Runtime.RuntimeTerminalPathOpenTarget, - Runtime.RuntimeTerminalPathResolution, - Runtime.RuntimeTerminalPresentation, - Runtime.RuntimeTerminalRead, - Runtime.RuntimeTerminalRename, - Runtime.RuntimeTerminalResolvePane, - Runtime.RuntimeTerminalSend, - Runtime.RuntimeTerminalShow, - Runtime.RuntimeTerminalSplit, - Runtime.RuntimeTerminalState, - Runtime.RuntimeTerminalSummary, - Runtime.RuntimeTerminalUnavailableReason, - Runtime.RuntimeTerminalVisualGroupNode, - Runtime.RuntimeTerminalVisualLayout, - Runtime.RuntimeTerminalVisualLayoutNode, - Runtime.RuntimeTerminalVisualPaneNode, - Runtime.RuntimeTerminalVisualTab, - Runtime.RuntimeTerminalVisualTerminalNode, - Runtime.RuntimeTerminalWait, - Runtime.RuntimeTerminalWaitBlockedReason, - Runtime.RuntimeTerminalWaitCondition, - Runtime.RuntimeWorktreeAgentRow, - Runtime.RuntimeWorktreeCreateResult, - Runtime.RuntimeWorktreeListResult, - Runtime.RuntimeWorktreePsConditionalResult, - Runtime.RuntimeWorktreePsResult, - Runtime.RuntimeWorktreePsSnapshotResult, - Runtime.RuntimeWorktreePsSummary, - Runtime.RuntimeWorktreePsUnchangedResult, - Runtime.RuntimeWorktreeRecord, - Runtime.RuntimeWorktreeRemoveResult, - Runtime.RuntimeWorktreeStatus, - Runtime.RuntimeWorktreeTerminalSleepResult -] - -describe('runtime client public export parity', () => { - it('keeps the runtime type inventory compile-visible', () => { - expectTypeOf().toEqualTypeOf() - expectTypeOf().toEqualTypeOf() - expectTypeOf().toEqualTypeOf() - expectTypeOf(RemoteClient.sendRemoteRuntimeRequest).toEqualTypeOf< - ( - pairing: PairingOffer, - method: string, - params: unknown, - timeoutMs: number, - envelope?: RuntimeOrchestrationEnvelope, - signal?: AbortSignal, - clientCapabilities?: readonly RuntimeCapability[] - ) => Promise> - >() - expectTypeOf(RemoteClient.sendRemoteRuntimeRequestWithStatusPreflight).toEqualTypeOf< - ( - pairing: PairingOffer, - method: string, - params: unknown, - timeoutMs: number, - validateStatus: (response: RuntimeRpcResponse) => void, - envelope?: RuntimeOrchestrationEnvelope, - clientCapabilities?: readonly RuntimeCapability[] - ) => Promise> - >() - expectTypeOf(RemoteClient.subscribeRemoteRuntimeRequest).toEqualTypeOf< - ( - pairing: PairingOffer, - method: string, - params: unknown, - timeoutMs: number, - callbacks: RemoteClient.RemoteRuntimeSubscriptionCallbacks, - options?: RemoteClient.RemoteRuntimeSubscriptionOptions - ) => Promise - >() - }) - - it('keeps the runtime and transport value exports exact', () => { - expect(Object.keys(Runtime).sort()).toEqual([ - 'BROWSER_UNAVAILABLE_ERROR_CODE', - 'COMPUTER_ERROR_CODES', - 'HEADLESS_RUNTIME_WINDOW_ID', - 'TERMINAL_PTY_DEGRADATION_CAPABILITY', - 'TERMINAL_UNAVAILABLE_ERROR_CODE', - 'UNPUBLISHED_WORKTREE_PUBLICATION_EPOCH', - 'browserUnavailableMessage', - 'terminalUnavailableMessage' - ]) - expect(Object.keys(RemoteClient).sort()).toEqual([ - 'RemoteRuntimeClientError', - 'sendRemoteRuntimeRequest', - 'sendRemoteRuntimeRequestWithStatusPreflight', - 'subscribeRemoteRuntimeRequest' - ]) - }) -}) diff --git a/tests/tools/windows-pty-native-capability-smoke/run.test.mjs b/tests/tools/windows-pty-native-capability-smoke/run.test.mjs index bb8ab525da6..27439cb498e 100644 --- a/tests/tools/windows-pty-native-capability-smoke/run.test.mjs +++ b/tests/tools/windows-pty-native-capability-smoke/run.test.mjs @@ -1,10 +1,7 @@ -import { readFileSync } from 'node:fs' import path from 'node:path' import { describe, expect, it } from 'vitest' import { checkoutRunProcessPath, formatProbeFailure, packagedProbeInvocation } from './run.mjs' -const runnerSource = readFileSync(new URL('./run.mjs', import.meta.url), 'utf8') - describe('packaged Windows native smoke runner boundary', () => { it('uses one checkout-owned runner for current and affected package paths', () => { const current = packagedProbeInvocation('/ci/current/dist/win-unpacked/Orca.exe') @@ -36,12 +33,4 @@ describe('packaged Windows native smoke runner boundary', () => { expect(failure).toContain('stdout-tail') expect(failure).toContain('stage=target-spawn:start') }) - - it('does not import child_process or resolve the runner from the artifact', () => { - expect(runnerSource).not.toContain('node:child_process') - expect(runnerSource).not.toMatch( - /path\.join\(resourcesDir[\s\S]*?app\.asar\.unpacked[\s\S]*?run-process\.js/ - ) - expect(runnerSource).toContain("'../../../out/shared/child-process/run-process.js'") - }) }) From 4da485cac1c308243fc22f5ee9c9c15058eee7ea Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:30:54 -0700 Subject: [PATCH 06/83] fix(native-chat): render the terminal-backed chat through the structured chat's turn status (#22090) * fix(native-chat): render the terminal-backed chat through the structured chat's turn status A terminal-backed chat (grok and omp always; Claude and Codex whenever the structured lane is refused) could not say what its agent was doing. A working agent drew three bouncing dots with no elapsed time, and an agent stopped on a prompt that only its terminal showed drew nothing, so it looked idle. A pending AskUserQuestion row read "Asked:" while the agent was still waiting, because the pane treated the wait as the end of the turn. The pane already held the facts: the host-stamped working epoch and the hook's waiting/blocked state. It now feeds them to the same message list props and components the structured lane uses, instead of opting out with showTurnStatus={false}: - The turn runs on while the agent waits on the reader, as a structured turn does behind its prompt card, so the "Working for" bar keeps counting and the live line yields to the wait. - A wait the pane can draw as a card (approval or question) is shown by the card; a wait only the terminal shows is reported by the tail row the structured lane already uses for a pending question (NativeChatAwaitingInputRow). - The hook wait is reconciled against the transcript's terminal marker, like hook 'working' is, because an interrupt at the prompt fires no hook. showTurnStatus meant nothing once both lanes passed it, so it is gone, along with showLiveTurnActivity (replaced by the awaitingInput fact), the structuredActivityUi flag it fed to tool rows, and the transcript-guessing typing indicator (native-chat-typing-indicator.ts, NativeChatTypingIndicatorRow.tsx), which had no other consumer. The interactive card's derivation moved into useNativeChatInteractivePromptCard so the view can tell a wait the card answers from one it cannot. * test(native-chat): seed the hook wait through the store instead of a cast * fix(native-chat): say "Awaiting user input" as a whole phrase when no question is named A wait the pane cannot draw as a card, and a question whose text could not be parsed, both drew "Awaiting user input:" with nothing after the colon. The row now reads "Awaiting user input" when it has no question to name, in both chat lanes. The pending-question view test now counts awaiting rows by attribute so a second, unnamed row cannot slip past it. * perf(native-chat): read the prompt's tool name only while a prompt is pending Deriving the prompt card moved from the card into the pane's view, and with it a store read of the status row's tool name, which changes on every tool call. Every tool call therefore re-rendered the whole terminal-backed pane and its transcript list, where before only the card re-rendered. The tool name only matters beside a prompt, so read it only then. * fix(native-chat): keep the terminal lane's turn clock and folds across a remount Answering a prompt only the terminal shows means switching the pane to its terminal, which unmounts the chat. On return the "Working for" clock restarted from the agent's current state (seconds after the answer), and every turn the pane had folded behind "Worked for N" came back unfolded with no bar. - The running turn now counts from the start of the hook's unbroken run of mid-turn states under the current prompt (read from the status row's state history), not the current state's own start. - Finished turns take their duration from the transcript's own timestamps (prompt to the agent's last row or its interruption), so history turns fold like a structured chat's. The latest turn still relies on what the pane saw. * fix(native-chat): date the terminal lane's turns by the main agent and skip harness notices Two ways the terminal-backed chat showed a wrong turn status: - A background task or subagent keeps the status row 'working' after the main agent finishes, so the row's own start time carries into the next turn. A prompt sent while a background dev server ran showed "Working for" counted from the earlier turn. The clock now reads the main agent's own state and start time where the row carries them. - Harness notices (task notifications, reminders) are user-role rows in the transcript that the chat does not draw. The finished-turn derivation treated them as new prompts, so a running turn was reported settled and folded its steps while it still ran, and a finished turn's "Worked for" stopped at the notice. They no longer start or end a turn. * feat(agent-status): stamp each turn's start on the host The hook server now records turnStartedAt on a status row when the main agent's own turn-opening event arrives (the per-provider new-turn classifier the observation boundary already uses; not a replay, a child event or an identity-only row). Other events carry it; a session boundary clears it, and a settled main agent running again with no opening event drops it rather than count from the finished turn. It rides the snapshot and the live push as an optional field, persists with the row, lands on the renderer entry (kept within one state for writers with no turn clock), and is part of the paired-client projection key and equality. Old hosts send nothing; readers fall back to stateStartedAt. * fix(native-chat): time the terminal lane's turns from the host's turn stamp The running clock reads the host's turnStartedAt, so a remount, a reload (which starts with no state history) and child work holding the row open no longer move it, and the same prompt sent again is a new turn. The stateHistory walk and its prompt-equality rule are gone; an old host falls back to the current state's start. The latest turn is settled from host facts: once the main agent is done (outside a session boundary) its duration is the done stamp minus the turn start, so it folds after a remount. When the host went quiet mid-turn (the store's staleness dropped the row) the pane passes null, so a still-waiting turn no longer reads "Worked for 30m" and folds. Older turns keep their transcript durations. * test(agent-status): pin the host's turn start on the live status push * fix(native-chat): keep omp's turn working while its latest row is a tool call The terminal-backed chat settles a hook 'working' turn when the transcript's last row is an assistant row written after the turn began, a recovery for a Stop hook the host can miss. omp writes a timestamp on every row and has no transcript turn markers, so every tool call mid-turn tripped it: the pane dropped its "Working for" bar and showed Send instead of Stop while the command ran. omp's own runtime delivers its turn end (agent_end, retried until the host takes it and held back while the run continues), so its hook 'working' is never a dropped Stop. The prose recovery now skips it. * test(native-chat): read the clock once in the host-ended remount test The test stamped the row's done time and the turn start from two separate Date.now() reads, so whenever a millisecond passed between them the expected "Worked for 1m 30s" came out as 1m 29s. It failed that way once under load. * test(sync-runtime-graph): carry the turn stamp in the hot-path projection reference The hot-path suite compares the agent-status projection against its own copy of the serializer; that copy lacked the new turnStartedAt key. --- .../server-turn-started-at.test.ts | 185 ++++++++ .../server/server-persistence-validation.ts | 6 +- .../server/server-status-application.ts | 41 +- .../server/server-status-identity.ts | 1 + src/main/agent-hooks/server/server-types.ts | 3 + src/main/startup/main-window-agent-status.ts | 2 + ...in-window-structured-status-filter.test.ts | 8 + .../NativeChatAwaitingInputRow.tsx | 12 +- .../NativeChatInteractiveCard.test.tsx | 32 +- .../native-chat/NativeChatInteractiveCard.tsx | 50 +-- ...eChatMessageList.task-list-frames.test.tsx | 1 - ...eChatMessageList.tool-stream-cost.test.tsx | 10 +- .../native-chat/NativeChatMessageList.tsx | 51 +-- ...iveChatMessageList.turn-indicator.test.tsx | 72 ++-- .../native-chat/NativeChatMessageRow.tsx | 3 - .../native-chat/NativeChatResolvedView.tsx | 30 +- ...ativeChatResolvedView.turn-status.test.tsx | 401 ++++++++++++++++++ ...tiveChatStructuredSession.test-harness.tsx | 3 +- .../NativeChatStructuredSession.test.tsx | 15 +- .../NativeChatStructuredSession.tsx | 3 +- ...tiveChatStructuredSessionDelivery.test.tsx | 1 - .../NativeChatToolRun.ask-row.test.tsx | 2 +- .../native-chat/NativeChatToolRun.tsx | 12 +- .../native-chat/NativeChatTranscriptRow.tsx | 2 - .../NativeChatTypingIndicatorRow.tsx | 21 - .../native-chat-live-session-contract.ts | 3 + .../native-chat-live-status.test.ts | 79 +++- .../native-chat/native-chat-live-status.ts | 32 +- .../native-chat-message-rail-items.test.ts | 1 - .../native-chat-rail-outline-parity.test.ts | 1 - .../native-chat-terminal-turn.test.ts | 243 +++++++++++ .../native-chat/native-chat-terminal-turn.ts | 132 ++++++ .../native-chat-transcript-slots.test.ts | 1 - .../native-chat-transcript-slots.ts | 12 +- .../native-chat-typing-indicator.test.ts | 154 ------- .../native-chat-typing-indicator.ts | 34 -- ...ative-chat-interactive-prompt-card.test.ts | 68 +++ ...use-native-chat-interactive-prompt-card.ts | 48 +++ .../use-native-chat-live-session.test.ts | 36 ++ .../use-native-chat-live-session.ts | 7 +- .../use-native-chat-message-rail.test.ts | 1 - .../use-native-chat-terminal-turn-timing.ts | 45 ++ ...use-native-chat-transcript-scroll.test.tsx | 2 +- .../use-native-chat-transcript-scroll.ts | 7 +- .../use-native-chat-turn-status.ts | 2 +- ...events-agent-status-store-test-fixtures.ts | 1 + .../agent-status-event-applicator.ts | 3 +- ...vents-agent-status-snapshot-replay.test.ts | 10 +- .../src/i18n/en-runtime-required.json | 1 + src/renderer/src/i18n/locales/en.json | 1 + src/renderer/src/i18n/locales/fr.json | 1 + src/renderer/src/i18n/locales/ja.json | 1 + src/renderer/src/i18n/locales/ko.json | 1 + src/renderer/src/i18n/locales/zh.json | 1 + ...time-graph-agent-status-projection.test.ts | 3 + ...-runtime-graph-projection-hot-path.test.ts | 1 + .../agent-status-projection.ts | 1 + .../state-equality-core.test.ts | 24 +- .../state-equality-core.ts | 1 + .../src/store/slices/agent-status-contract.ts | 2 + .../slices/agent-status-live-entry-builder.ts | 6 + .../agent-status-turn-started-at.test.ts | 50 +++ src/shared/agent-status-ipc-payload.ts | 4 + src/shared/agent-status-types.ts | 3 + src/shared/native-chat-ask-row.ts | 1 + 65 files changed, 1593 insertions(+), 398 deletions(-) create mode 100644 src/main/agent-hooks/server-turn-started-at.test.ts create mode 100644 src/renderer/src/components/native-chat/NativeChatResolvedView.turn-status.test.tsx delete mode 100644 src/renderer/src/components/native-chat/NativeChatTypingIndicatorRow.tsx create mode 100644 src/renderer/src/components/native-chat/native-chat-terminal-turn.test.ts create mode 100644 src/renderer/src/components/native-chat/native-chat-terminal-turn.ts delete mode 100644 src/renderer/src/components/native-chat/native-chat-typing-indicator.test.ts delete mode 100644 src/renderer/src/components/native-chat/native-chat-typing-indicator.ts create mode 100644 src/renderer/src/components/native-chat/use-native-chat-interactive-prompt-card.test.ts create mode 100644 src/renderer/src/components/native-chat/use-native-chat-interactive-prompt-card.ts create mode 100644 src/renderer/src/components/native-chat/use-native-chat-terminal-turn-timing.ts create mode 100644 src/renderer/src/store/slices/agent-status-turn-started-at.test.ts diff --git a/src/main/agent-hooks/server-turn-started-at.test.ts b/src/main/agent-hooks/server-turn-started-at.test.ts new file mode 100644 index 00000000000..63ebd136be6 --- /dev/null +++ b/src/main/agent-hooks/server-turn-started-at.test.ts @@ -0,0 +1,185 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { AgentHookServer, _internals } from './server' +import { buildBody, postHookEvent, PANE } from './server.test-fixtures' + +const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ + getCohortAtEmitMock: vi.fn(), + trackMock: vi.fn() +})) + +vi.mock('../telemetry/client', () => ({ track: trackMock })) +vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) + +beforeEach(() => { + _internals.resetCachesForTests() + getCohortAtEmitMock.mockReturnValue({}) +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +// Distinct host stamps: each event lands on a later millisecond than the one before it. +async function nextMillisecond(): Promise { + await new Promise((resolve) => setTimeout(resolve, 5)) +} + +// The execution host stamps when the main agent's turn began, so every reader (and a reload, which +// starts the renderer with no state history) gets the turn start rather than rebuilding it. +describe('the host-stamped turn start', () => { + const servers: AgentHookServer[] = [] + let userDataPath: string + + beforeEach(() => { + userDataPath = mkdtempSync(join(tmpdir(), 'orca-turn-started-at-')) + }) + + afterEach(() => { + for (const server of servers) { + server.stop() + } + servers.length = 0 + rmSync(userDataPath, { recursive: true, force: true }) + }) + + async function startServer(): Promise { + const server = new AgentHookServer() + servers.push(server) + await server.start({ env: 'production', userDataPath }) + return server + } + + async function post(server: AgentHookServer, payload: Record): Promise { + const response = await postHookEvent(server, buildBody(payload)) + expect(response.status).toBe(204) + await nextMillisecond() + } + + function turnStartedAt(server: AgentHookServer): number | undefined { + return server.getStatusSnapshot()[0]?.turnStartedAt + } + + it('stamps a new main-agent turn and carries it across tools, a wait and its answer', async () => { + const server = await startServer() + await post(server, { hook_event_name: 'UserPromptSubmit', prompt: 'Rename the module' }) + const started = turnStartedAt(server) + expect(started).toBe(server.getStatusSnapshot()[0]?.stateStartedAt) + + const bash = { tool_name: 'Bash', tool_input: { command: 'pnpm build' }, tool_use_id: 'tu-1' } + await post(server, { hook_event_name: 'PreToolUse', ...bash }) + await post(server, { hook_event_name: 'PermissionRequest', ...bash }) + expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'waiting' }) + await post(server, { hook_event_name: 'PostToolUse', ...bash }) + // The answer restarted the state clock, not the turn's. + expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'working' }) + expect(server.getStatusSnapshot()[0]?.stateStartedAt).toBeGreaterThan(started!) + expect(turnStartedAt(server)).toBe(started) + + await post(server, { hook_event_name: 'Stop' }) + // Kept on the finished turn, so a reader can time it from the host's own facts. + expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'done', turnStartedAt: started }) + }) + + it('is not stamped by a child agent, and the same prompt sent again is a new turn', async () => { + const server = await startServer() + await post(server, { hook_event_name: 'UserPromptSubmit', prompt: 'Rename the module' }) + const started = turnStartedAt(server) + + await post(server, { + hook_event_name: 'UserPromptSubmit', + prompt: 'child task', + agent_id: 'child-1' + }) + expect(turnStartedAt(server)).toBe(started) + + // Esc at a permission prompt fires no hook, so the resend follows the stale wait directly. + await post(server, { hook_event_name: 'PermissionRequest', tool_name: 'Bash', tool_input: {} }) + await post(server, { hook_event_name: 'UserPromptSubmit', prompt: 'Rename the module' }) + expect(turnStartedAt(server)).toBeGreaterThan(started!) + }) + + it('is not stamped by a relayed replay', async () => { + const server = await startServer() + const envelope = { + paneKey: PANE, + tabId: 'tab-1', + source: 'claude' as const, + hookEventName: 'UserPromptSubmit', + payload: { state: 'working' as const, prompt: 'relayed', agentType: 'claude' as const } + } + server.ingestRemote(envelope, 'ssh-turn') + const started = turnStartedAt(server) + expect(started).toEqual(expect.any(Number)) + await nextMillisecond() + + server.ingestRemote({ ...envelope, isReplay: true }, 'ssh-turn') + expect(turnStartedAt(server)).toBe(started) + }) + + // A session start lands an idle boundary row: no turn is open until the next prompt. + it('clears on a session boundary', async () => { + const server = await startServer() + await post(server, { hook_event_name: 'UserPromptSubmit', prompt: 'Rename the module' }) + expect(turnStartedAt(server)).toEqual(expect.any(Number)) + + await post(server, { hook_event_name: 'SessionStart', source: 'clear' }) + expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'done', sessionBoundary: true }) + expect(server.getStatusSnapshot()[0]).not.toHaveProperty('turnStartedAt') + }) + + // An OSC repaint can land before the prompt hook; it must not count from the finished turn. + it('drops the stamp when a finished main agent runs again with no turn-opening event', async () => { + const server = await startServer() + await post(server, { hook_event_name: 'UserPromptSubmit', prompt: 'Rename the module' }) + await post(server, { hook_event_name: 'Stop' }) + expect(turnStartedAt(server)).toEqual(expect.any(Number)) + + server.ingestTerminalStatus({ + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'working', prompt: 'Rename the module', agentType: 'claude' } + }) + expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'working' }) + expect(server.getStatusSnapshot()[0]).not.toHaveProperty('turnStartedAt') + }) + + it('cannot be declared by a producer', async () => { + const server = await startServer() + await post(server, { + hook_event_name: 'UserPromptSubmit', + prompt: 'Rename the module', + turnStartedAt: 1 + }) + await post(server, { hook_event_name: 'PreToolUse', tool_name: 'Bash', turnStartedAt: 1 }) + expect(turnStartedAt(server)).toBeGreaterThan(1) + }) + + it('reaches the live push and survives a restart through the status file', async () => { + const server = await startServer() + const pushed: (number | undefined)[] = [] + server.setListener((status) => pushed.push(status.turnStartedAt)) + await post(server, { hook_event_name: 'UserPromptSubmit', prompt: 'Rename the module' }) + await post(server, { hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: {} }) + const started = turnStartedAt(server) + expect(pushed.at(-1)).toBe(started) + server.flushStatusPersistSync() + server.stop() + const file = JSON.parse( + readFileSync(join(userDataPath, 'agent-hooks', 'last-status.json'), 'utf8') + ) + expect(file.entries[PANE].turnStartedAt).toBe(started) + + const restarted = await startServer() + expect(restarted.getStatusSnapshot()[0]).toMatchObject({ + restoredUnconfirmed: true, + turnStartedAt: started + }) + // The turn goes on after the restart: the next event carries the restored stamp. + await post(restarted, { hook_event_name: 'PostToolUse', tool_name: 'Bash', tool_input: {} }) + expect(turnStartedAt(restarted)).toBe(started) + }) +}) diff --git a/src/main/agent-hooks/server/server-persistence-validation.ts b/src/main/agent-hooks/server/server-persistence-validation.ts index f88766217c1..7203f174a0e 100644 --- a/src/main/agent-hooks/server/server-persistence-validation.ts +++ b/src/main/agent-hooks/server/server-persistence-validation.ts @@ -149,6 +149,7 @@ export function sanitizeHydratedEntry( source === 'claude' && (record.compactTrigger === 'manual' || record.compactTrigger === 'auto') ? record.compactTrigger : undefined + const turnStartedAt = record.turnStartedAt return { paneKey, source, @@ -170,7 +171,10 @@ export function sanitizeHydratedEntry( retainedForLiveness: retainedForLiveness ? true : undefined, payload, receivedAt, - stateStartedAt + stateStartedAt, + ...(typeof turnStartedAt === 'number' && Number.isFinite(turnStartedAt) && turnStartedAt > 0 + ? { turnStartedAt } + : {}) } } diff --git a/src/main/agent-hooks/server/server-status-application.ts b/src/main/agent-hooks/server/server-status-application.ts index 8863dc178b9..674fa8a0760 100644 --- a/src/main/agent-hooks/server/server-status-application.ts +++ b/src/main/agent-hooks/server/server-status-application.ts @@ -10,6 +10,7 @@ import type { AgentStatusObservationOrigin } from '../../../shared/agent-status-observation' import { AGENT_STATUS_2A_CURRENT_PRODUCER_MODE } from '../../../shared/agent-status-legacy-adapter' +import type { AgentStatusState, ParsedAgentStatusPayload } from '../../../shared/agent-status-types' import { admitLegacyAgentStatus } from '../../../shared/agent-hook-listener/listener-state' import type { EnrichedAgentHookEventPayload } from './server-types' import { agentTypeToPromptSentAgentKind } from './server-status-identity' @@ -18,6 +19,41 @@ import { AgentHookServerStatusDisposition } from './server-status-disposition' /** Bounds the retained observation clock; eviction only degrades a replay to `now`. */ const MAX_REMEMBERED_EVIDENCE_OBSERVATIONS = 1024 +function mainAgentState(payload: ParsedAgentStatusPayload): AgentStatusState { + return payload.mainAgent?.state ?? payload.state +} + +/** + * When the main agent's current turn began. Its own turn-opening event stamps it (the same + * classifier the observation boundary uses), except a session boundary, which lands idle with no + * turn open. Replays, child events and identity-only rows restate a turn rather than open one. + */ +function resolveTurnStartedAt( + previous: EnrichedAgentHookEventPayload | undefined, + payload: AgentHookEventPayload, + at: number +): number | undefined { + if ( + payload.source !== undefined && + payload.toolAgentId === undefined && + payload.isReplay !== true && + payload.providerSessionOnly !== true && + isNewTurnEvent(payload.source, payload.hookEventName) + ) { + return payload.payload.sessionBoundary === true ? undefined : at + } + // Why: a settled main agent running again with no opening event (an OSC repaint racing the + // prompt hook) is a turn edge nothing dated; carrying the old stamp would count from that turn. + if ( + previous && + mainAgentState(previous.payload) === 'done' && + mainAgentState(payload.payload) !== 'done' + ) { + return undefined + } + return previous?.turnStartedAt +} + export abstract class AgentHookServerStatusApplication extends AgentHookServerStatusDisposition { protected refreshTerminalStatusEvidence( previous: EnrichedAgentHookEventPayload, @@ -113,12 +149,15 @@ export abstract class AgentHookServerStatusApplication extends AgentHookServerSt previous && previous.payload.state === payload.payload.state && !commandCodeNewTurn ? previous.stateStartedAt : (observedAt ?? now) + const turnStartedAt = resolveTurnStartedAt(previous, payload, observedAt ?? now) // Why: `stateStartedAt` tracks the current state, while `receivedAt` tracks every arrival. return { ...payload, receivedAt: now, evidenceObservedAt: observedAt ?? this.resolveEvidenceObservedAt(payload, previous, now), - stateStartedAt + stateStartedAt, + // Always written here, so a producer can never declare it. + turnStartedAt } } diff --git a/src/main/agent-hooks/server/server-status-identity.ts b/src/main/agent-hooks/server/server-status-identity.ts index 1694c4b1b67..4400b43efee 100644 --- a/src/main/agent-hooks/server/server-status-identity.ts +++ b/src/main/agent-hooks/server/server-status-identity.ts @@ -63,6 +63,7 @@ export function toAgentStatusIpcPayload( ? { evidenceObservedAt: entry.evidenceObservedAt } : {}), stateStartedAt: entry.stateStartedAt, + ...(entry.turnStartedAt !== undefined ? { turnStartedAt: entry.turnStartedAt } : {}), ...(entry.providerSession ? { providerSession: entry.providerSession } : {}), ...(entry.providerSessionOnly ? { providerSessionOnly: true } : {}), ...(entry.promptInteractionKey ? { promptInteractionKey: entry.promptInteractionKey } : {}), diff --git a/src/main/agent-hooks/server/server-types.ts b/src/main/agent-hooks/server/server-types.ts index d1466797798..79b4e569cdd 100644 --- a/src/main/agent-hooks/server/server-types.ts +++ b/src/main/agent-hooks/server/server-types.ts @@ -19,6 +19,9 @@ export type EnrichedAgentHookEventPayload = AgentHookEventPayload & { * main restart; absent means "never separately observed" and consumers use `receivedAt`. */ evidenceObservedAt?: number stateStartedAt: number + /** When the main agent's current turn began, on this server's clock. Stamped only here, from the + * main agent's own turn-opening event; absent when no such event was seen. */ + turnStartedAt?: number /** Provenance/ordering stamped by this server as the pane authority (STA-4293). Read by nothing yet. */ observation?: AgentStatusObservation /** Stamped at hydrate for nonterminal states; never persisted (hydrate re-stamps) and cleared by any accepted live event replacing the entry. */ diff --git a/src/main/startup/main-window-agent-status.ts b/src/main/startup/main-window-agent-status.ts index 5899b2fe6bd..38bb380d724 100644 --- a/src/main/startup/main-window-agent-status.ts +++ b/src/main/startup/main-window-agent-status.ts @@ -35,6 +35,7 @@ export function installMainWindowAgentStatusListeners(options: MainWindowAgentSt receivedAt, evidenceObservedAt, stateStartedAt, + turnStartedAt, launchToken, providerSession, providerSessionOnly, @@ -89,6 +90,7 @@ export function installMainWindowAgentStatusListeners(options: MainWindowAgentSt receivedAt, ...(evidenceObservedAt !== undefined ? { evidenceObservedAt } : {}), stateStartedAt, + ...(turnStartedAt !== undefined ? { turnStartedAt } : {}), ...(providerSession ? { providerSession } : {}), ...(promptInteractionKey ? { promptInteractionKey } : {}), ...(restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), diff --git a/src/main/startup/main-window-structured-status-filter.test.ts b/src/main/startup/main-window-structured-status-filter.test.ts index c7fe55da626..da26a593d00 100644 --- a/src/main/startup/main-window-structured-status-filter.test.ts +++ b/src/main/startup/main-window-structured-status-filter.test.ts @@ -94,3 +94,11 @@ it('forwards retirement acknowledgement only on live status delivery', () => { expect(sent[0].event).toHaveProperty('authorityRestartId', 'retirement-id') expect(sent[1].event).not.toHaveProperty('authorityRestartId') }) + +// The live push picks fields one by one; the host's turn start must be one of them. +it("forwards the host's turn start, and nothing when the host stamped none", () => { + hooks.listener!(statusPayload({ turnStartedAt: 1 })) + hooks.listener!(statusPayload({})) + expect(sent[0].event).toHaveProperty('turnStartedAt', 1) + expect(sent[1].event).not.toHaveProperty('turnStartedAt') +}) diff --git a/src/renderer/src/components/native-chat/NativeChatAwaitingInputRow.tsx b/src/renderer/src/components/native-chat/NativeChatAwaitingInputRow.tsx index 8e621a8a441..9549fc933e7 100644 --- a/src/renderer/src/components/native-chat/NativeChatAwaitingInputRow.tsx +++ b/src/renderer/src/components/native-chat/NativeChatAwaitingInputRow.tsx @@ -72,9 +72,15 @@ export function NativeChatAwaitingInputRow({ const questions = subject?.kind === 'questions' && listsQuestions ? subject.questions : null // A count always hides its questions, so the list needs no clipping measurement. const toggles = questions !== null || (question !== null && (open || clipped)) - const label = pending - ? translate('components.native-chat.ask.awaiting', NATIVE_CHAT_ASK_ROW_COPY.awaiting) - : translate('components.native-chat.ask.asked', NATIVE_CHAT_ASK_ROW_COPY.asked) + // With nothing to name, the label must read as a whole phrase, not end on a colon. + const label = !pending + ? translate('components.native-chat.ask.asked', NATIVE_CHAT_ASK_ROW_COPY.asked) + : subject === null + ? translate( + 'components.native-chat.ask.awaitingUnnamed', + NATIVE_CHAT_ASK_ROW_COPY.awaitingUnnamed + ) + : translate('components.native-chat.ask.awaiting', NATIVE_CHAT_ASK_ROW_COPY.awaiting) const text = subject === null ? null diff --git a/src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx b/src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx index cd08f779e71..303ab2472c7 100644 --- a/src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx @@ -33,6 +33,7 @@ vi.mock('../../store', () => ({ })) import { NativeChatInteractiveCard } from './NativeChatInteractiveCard' +import { useNativeChatInteractivePromptCard } from './use-native-chat-interactive-prompt-card' const mocks = { sendAnswer: vi.fn(), @@ -45,6 +46,8 @@ function renderCard(canSend = true): ReturnType { return render(cardElement(canSend)) } +const NO_MESSAGES: readonly NativeChatMessage[] = [] + function cardElement( canSend = true, messages?: readonly NativeChatMessage[], @@ -52,11 +55,36 @@ function cardElement( transcriptSettled = true ): React.JSX.Element { return ( - + ) +} + +// The view derives the card and hands it over; this stands in for that view. +function CardHarness({ + canSend, + messages, + onShowingQuestionChange, + transcriptSettled +}: { + canSend: boolean + messages?: readonly NativeChatMessage[] + onShowingQuestionChange?: (showing: boolean) => void + transcriptSettled: boolean +}): React.JSX.Element | null { + const card = useNativeChatInteractivePromptCard({ + paneKey: 'tab-1:leaf-1', + messages: messages ?? NO_MESSAGES, + transcriptSettled: transcriptSettled && messages !== undefined + }) + return ( + void @@ -51,26 +36,7 @@ export function NativeChatInteractiveCard({ * a target while the composer is unmounted. */ answerInputRef?: React.RefObject }): React.JSX.Element | null { - const interactivePrompt = useAppStore( - (s) => s.agentStatusByPaneKey[paneKey]?.interactivePrompt ?? null - ) - // Thread the sibling `toolName` from the same status entry so the question - // parser can dispatch through the tool's registered parser (mobile parity). - const interactiveToolName = useAppStore((s) => s.agentStatusByPaneKey[paneKey]?.toolName ?? null) const { sendAnswer, sendRaw, cancelPending, cancel } = send - - const card = useMemo(() => { - const statusCard = parseInteractivePrompt(interactivePrompt, interactiveToolName ?? undefined) - if (statusCard?.kind === 'approval') { - return statusCard - } - const prompt = resolveNativeChatAsk({ - liveAsk: statusCard?.prompt ?? null, - messages: messages ?? [], - transcriptSettled: transcriptSettled && messages != null - }) - return prompt ? { kind: 'question' as const, prompt } : null - }, [interactivePrompt, interactiveToolName, messages, transcriptSettled]) const cardKey = useMemo(() => nativeChatCardDismissKey(card), [card]) const [dismissedKey, setDismissedKey] = useState(null) // A question answer is a paced multi-step write (body→Enter per question); keep diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.task-list-frames.test.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.task-list-frames.test.tsx index 4be1ea7cdb3..82b2c43d468 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.task-list-frames.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.task-list-frames.test.tsx @@ -70,7 +70,6 @@ function transcript(messages: NativeChatMessage[], sessionId = 'live-codex') { isWorking={false} expandSignal fontScale={1} - showTurnStatus={false} /> ) } diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.tool-stream-cost.test.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.tool-stream-cost.test.tsx index 2a2401bea52..a77d2907b6a 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.tool-stream-cost.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.tool-stream-cost.test.tsx @@ -44,15 +44,7 @@ function Transcript({ items }: { items: AgentJournalRenderItem[] }) { loadEarlier, readPhase: 'ready' } - return ( - - ) + return } function row(index: number, body: AgentJournalRenderItem['body']): AgentJournalRenderItem { diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx index ee697732671..6e0c29d9d71 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx @@ -10,9 +10,8 @@ import { nativeChatTaskListPredecessors } from './native-chat-task-list-history' import { NativeChatTaskList } from './NativeChatTaskList' import { projectNativeChatTaskListFrames } from './native-chat-task-list-frames' import { omitNativeChatThreadGoalRows } from './native-chat-thread-goal-rows' -import { shouldShowNativeChatTypingIndicator } from './native-chat-typing-indicator' import { useNativeChatTurnStatus } from './use-native-chat-turn-status' -import { NativeChatTypingIndicatorRow } from './NativeChatTypingIndicatorRow' +import { NativeChatAwaitingInputRow } from './NativeChatAwaitingInputRow' import type { RuntimeFileOperationArgs } from '@/runtime/runtime-file-client' import type { NativeChatTurnActivity } from '../../../../shared/native-chat-turn-activity' import { NativeChatTurnActivityLine } from './NativeChatTurnActivityLine' @@ -59,6 +58,10 @@ export { ProviderFrameRow } from './NativeChatTranscriptChrome' const MAX_EXPANDED_TURNS = 128 +/** The turn is blocked on the reader. `shown`: the pane draws the prompt itself, as a card; + * `unshown`: it cannot (the prompt is only in the agent's terminal). */ +export type NativeChatAwaitingInput = 'shown' | 'unshown' + type NativeChatNavigationRequest = | { kind: 'diff'; target: NativeChatDiffReveal } | { kind: 'rail'; messageId: string; requestId: number } @@ -78,8 +81,7 @@ export function NativeChatMessageList({ activeTurnOpenedBy, turnKeysByItemId = null, deliveryNotices, - showTurnStatus = true, - showLiveTurnActivity = true, + awaitingInput = null, turnActivity, runtimeContext }: { @@ -94,7 +96,8 @@ export function NativeChatMessageList({ /** Chat-only text multiplier (1 = default), driven by the zoom shortcuts. */ fontScale: number workingStartedAt?: number | null - /** Host-recorded turn durations keyed by user message id (structured lane). */ + /** Recorded turn durations keyed by user message id (the host's, or the transcript's). + * A turn missing here shows the duration this list observed, if it saw the turn run. */ settledTurns?: NativeChatSettledTurns /** The key the host says anchors the running turn's bar (structured lane). */ activeTurnOpenedBy?: string | null @@ -104,10 +107,8 @@ export function NativeChatMessageList({ onLinkClick?: CommentMarkdownLinkClickHandler allowFileUriLinks?: boolean deliveryNotices?: ReadonlyMap - /** Turn timing and disclosure are available on structured agent sessions. */ - showTurnStatus?: boolean - /** Whether the active turn's foreground activity row should be visible. */ - showLiveTurnActivity?: boolean + /** Set while the turn waits on the reader; the live activity line yields to it. */ + awaitingInput?: NativeChatAwaitingInput | null turnActivity?: NativeChatTurnActivity | null runtimeContext?: RuntimeFileOperationArgs | null }): React.JSX.Element { @@ -162,14 +163,11 @@ export function NativeChatMessageList({ const subagentLabels = useMemo(() => nativeChatSubagentLabels(messages), [messages]) const taskListPredecessors = useMemo(() => nativeChatTaskListPredecessors(messages), [messages]) const taskListState = useMemo(() => nativeChatTaskListState(messages), [messages]) - const showTypingIndicator = showTurnStatus - ? isWorking - : shouldShowNativeChatTypingIndicator({ messages, isWorking }) // Resolve each row's owning turn once. Prefix slice/findLast in the render // loop becomes quadratic for long transcripts. const turnKeys = useMemo( - () => nativeChatRowTurnKeys(messages, showTurnStatus ? turnKeysByItemId : null), - [messages, showTurnStatus, turnKeysByItemId] + () => nativeChatRowTurnKeys(messages, turnKeysByItemId), + [messages, turnKeysByItemId] ) const turnDiffs = useMemo( () => @@ -188,11 +186,19 @@ export function NativeChatMessageList({ const turnStatuses = useNativeChatTurnStatus({ messages, activeTurnKey, - isWorking: showTurnStatus && isWorking, - workingStartedAt: showTurnStatus ? workingStartedAt : null, - settledTurns: showTurnStatus ? settledTurns : null, + isWorking, + workingStartedAt, + settledTurns, thinking }) + // The transcript tail: what the running turn is doing, or that it waits on a + // prompt nothing else on screen shows. A prompt card says so itself. + const tailRow = + awaitingInput === 'unshown' + ? 'awaiting-input' + : isWorking && awaitingInput === null + ? 'activity' + : null const lifecycleWorking = session.transcriptLifecycle?.state === 'working' const slots = useMemo( () => @@ -203,7 +209,6 @@ export function NativeChatMessageList({ receipts, turnStatuses, turnDiffs, - showTurnStatus, expandedTurnKeys: expandedTurnIds, isWorking, lifecycleWorking, @@ -216,7 +221,6 @@ export function NativeChatMessageList({ lifecycleWorking, messages, receipts, - showTurnStatus, subagentLabels, turnDiffs, turnKeys, @@ -236,7 +240,7 @@ export function NativeChatMessageList({ contentRef, itemCount: slots.length, isWorking, - showTypingIndicator, + showsTailRow: tailRow !== null, isVisible, alignToViewportTop: transcriptWindow.alignToViewportTop, scrollToEnd: transcriptWindow.scrollToEnd, @@ -331,7 +335,6 @@ export function NativeChatMessageList({ const rowContext = useMemo( () => ({ expandSignal, - showTurnStatus, revealedDiff, taskListPredecessors, expandedTurnIds, @@ -353,7 +356,6 @@ export function NativeChatMessageList({ revealedDiff, runtimeContext, scrollMessageToTop, - showTurnStatus, taskListPredecessors, toggleExpandedTurn ] @@ -398,13 +400,14 @@ export function NativeChatMessageList({ context={rowContext} window={transcriptWindow} /> - {showTurnStatus && showLiveTurnActivity && isWorking ? ( + {tailRow === 'activity' ? ( + ) : tailRow === 'awaiting-input' ? ( + ) : null} - {!showTurnStatus && showTypingIndicator ? : null}
diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.turn-indicator.test.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.turn-indicator.test.tsx index 8400b592e7d..e8d714fad1a 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.turn-indicator.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.turn-indicator.test.tsx @@ -166,7 +166,7 @@ describe('NativeChatMessageList turn indicator', () => { }} journalItems={[journalItem(1, turnItem), journalItem(2, reasoningRow)]} isWorking - showLiveTurnActivity={false} + awaitingInput="shown" expandSignal={false} fontScale={1} /> @@ -178,6 +178,38 @@ describe('NativeChatMessageList turn indicator', () => { expect(screen.getByText('Running 1 command')).toHaveClass('animate-pulse') }) + // A terminal-backed pane can learn its agent is waiting without being handed + // the prompt; the tail then says so, in the row a question uses. + it('says the turn waits on the reader when no card shows the prompt', () => { + const { container } = render( + + ) + + expect(container.querySelector('[data-native-chat-ask-row="awaiting"]')).toHaveTextContent( + /^Awaiting user input$/ + ) + expect(container.querySelector('[data-native-chat-turn-activity]')).toBeNull() + expect(screen.getByText('Working for 5s')).toBeInTheDocument() + }) + it('keeps the live row up after a tool settles', () => { render( { expect(liveRun?.querySelector('.lucide-check')).toBeInTheDocument() }) - it('keeps bridge chats on the legacy activity chrome', () => { - render( - - ) - - expect(screen.queryByText('Thinking')).toBeNull() - expect(screen.queryByRole('button', { name: 'Toggle turn details' })).toBeNull() - expect(screen.queryByText('Running sleep 5')).toBeNull() - expect(document.querySelectorAll('.animate-bounce')).toHaveLength(3) - }) - it('replaces a bridge ask row and settles it from the FIFO tool result', () => { const user = { id: 'bridge-user', @@ -355,7 +351,6 @@ describe('NativeChatMessageList turn indicator', () => { isWorking={false} expandSignal={false} fontScale={1} - showTurnStatus={false} /> ) @@ -382,7 +377,6 @@ describe('NativeChatMessageList turn indicator', () => { isWorking={false} expandSignal={false} fontScale={1} - showTurnStatus={false} /> ) diff --git a/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx b/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx index 59e70cfc7e1..e43a758051b 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx @@ -47,7 +47,6 @@ export const MessageRow = memo(function MessageRow({ onLinkClick, allowFileUriLinks = false, deliveryNotice, - structuredActivityUi = true, folded = false, subagentLabel, runtimeContext @@ -65,7 +64,6 @@ export const MessageRow = memo(function MessageRow({ onLinkClick?: CommentMarkdownLinkClickHandler allowFileUriLinks?: boolean deliveryNotice?: NativeChatDeliveryNotice - structuredActivityUi?: boolean /** Behind a folded turn: the row keeps only what outlives the turn. */ folded?: boolean /** The roster's name for the subagent that wrote this row, when one names it. */ @@ -269,7 +267,6 @@ export const MessageRow = memo(function MessageRow({ expandSignal={expandSignal} activeTurnIsWorking={activeTurnIsWorking} trailing={trailingRun} - structuredActivityUi={structuredActivityUi} disclosureId={message.id} /> ) : null} diff --git a/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx b/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx index fb432e1e5b4..786ade25ebc 100644 --- a/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx +++ b/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx @@ -11,12 +11,12 @@ import { NativeChatComposer, type NativeChatComposerHandle } from './NativeChatC import { useNativeChatFontScale } from './use-native-chat-font-scale' import { useNativeChatCanSend } from './use-native-chat-can-send' import { NativeChatInteractiveCard } from './NativeChatInteractiveCard' +import { useNativeChatInteractivePromptCard } from './use-native-chat-interactive-prompt-card' import { NativeChatEmptyState } from './NativeChatEmptyState' import { useNativeChatInteractiveSend } from './use-native-chat-interactive-send' -import { - shouldClearNativeChatWorkingSuppression, - shouldShowNativeChatWorking -} from './native-chat-working-suppression' +import { shouldClearNativeChatWorkingSuppression } from './native-chat-working-suppression' +import { resolveNativeChatTerminalTurn } from './native-chat-terminal-turn' +import { useNativeChatTerminalTurnTiming } from './use-native-chat-terminal-turn-timing' import { appendPendingSendCache, launchPromptAsMessage, @@ -251,6 +251,11 @@ export function NativeChatResolvedView({ paneLaunchPrompt?.failed ? launchPromptMessage?.id : null, sessionAfterCommandBoundaries.messages ) + const promptCard = useNativeChatInteractivePromptCard({ + paneKey, + messages: sessionAfterCommandBoundaries.messages, + transcriptSettled: session.readPhase === 'ready' + }) // The streaming preview bubble (if any) sits after the transcript but before // the optimistic user echoes — same order mobile uses. @@ -313,11 +318,14 @@ export function NativeChatResolvedView({ previousWorkingEpochRef.current = null } }, [liveWorking, workingInterrupted, hookWorkingEpoch]) - const isWorking = shouldShowNativeChatWorking({ + const { isWorking, turnActive, awaitingInput } = resolveNativeChatTerminalTurn({ isConversation, working: liveWorking, - interrupted: workingInterrupted + hookAwaitingInput: session.hookAwaitingInput === true, + interrupted: workingInterrupted, + hasPromptCard: promptCard !== null }) + const turnTiming = useNativeChatTerminalTurnTiming(paneKey, session.messages, turnActive) const stopAgent = useCallback(() => { setWorkingInterrupted(true) @@ -399,11 +407,11 @@ export function NativeChatResolvedView({ diff --git a/src/renderer/src/components/native-chat/NativeChatResolvedView.turn-status.test.tsx b/src/renderer/src/components/native-chat/NativeChatResolvedView.turn-status.test.tsx new file mode 100644 index 00000000000..ba2a7c00de2 --- /dev/null +++ b/src/renderer/src/components/native-chat/NativeChatResolvedView.turn-status.test.tsx @@ -0,0 +1,401 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, render, screen } from '@testing-library/react' +import type { AgentStatusEntry, AgentStatusPayload } from '../../../../shared/agent-status-types' +import type { NativeChatMessage } from '../../../../shared/native-chat-types' +import type { NativeChatLiveSession } from './use-native-chat-live-session' + +// The transcript source and the composer are stubbed; the wire under test is +// store status -> resolved view -> the shared message list and prompt card. +const retained = vi.hoisted((): { session: NativeChatLiveSession | null } => ({ session: null })) +vi.mock('./use-native-chat-retained-session', () => ({ + useNativeChatRetainedSession: () => retained.session +})) +vi.mock('./NativeChatComposer', () => ({ NativeChatComposer: () => null })) + +const { NativeChatResolvedView } = await import('./NativeChatResolvedView') +const { useAppStore } = await import('../../store') +const { installNativeChatMessageListTestViewport } = + await import('./native-chat-message-list-test-viewport') + +const paneKey = 'tab-state:leaf-state' +let restoreViewport = (): void => {} + +const userTurn: NativeChatMessage = { + id: 'user-1', + role: 'user', + blocks: [{ type: 'text', text: 'Rename the module' }], + timestamp: 1, + source: 'transcript' +} + +const askCall: NativeChatMessage = { + id: 'ask-1', + role: 'assistant', + blocks: [ + { + type: 'tool-call', + name: 'AskUserQuestion', + input: { + questions: [ + { + question: 'Which name?', + multiSelect: false, + options: [{ label: 'core' }, { label: 'base' }] + } + ] + } + } + ], + timestamp: 2, + source: 'transcript' +} + +const stepCall: NativeChatMessage = { + id: 'step-1', + role: 'assistant', + blocks: [{ type: 'tool-call', name: 'Bash', input: { command: 'pnpm build' } }], + timestamp: 3, + source: 'transcript' +} + +// `status` and `hookAwaitingInput` are what the live session reconciles from the +// same hook row; the test states both so the view is fed a consistent session. +function transcript( + status: NativeChatLiveSession['status'], + hookAwaitingInput: boolean, + messages: NativeChatMessage[] = [userTurn] +): NativeChatLiveSession { + return { + messages, + status, + sessionId: 'session-state', + agent: 'claude', + hookAwaitingInput, + hasMore: false, + loadingEarlier: false, + olderHistoryGeneration: 0, + loadEarlier: vi.fn(), + readPhase: 'ready' + } +} + +function setStatus(payload: Omit, age = 0): void { + useAppStore + .getState() + .setAgentStatus(paneKey, { prompt: 'Rename the module', agentType: 'claude', ...payload }) + const live = useAppStore.getState().agentStatusByPaneKey[paneKey] + if (!live) { + throw new Error('the store dropped the status row this test depends on') + } + useAppStore.setState((store) => ({ + agentStatusByPaneKey: { + ...store.agentStatusByPaneKey, + [paneKey]: { ...live, stateStartedAt: Date.now() - age } + } + })) +} + +function patchStatus(fields: Partial): void { + useAppStore.setState((store) => ({ + agentStatusByPaneKey: { + ...store.agentStatusByPaneKey, + [paneKey]: { ...store.agentStatusByPaneKey[paneKey]!, ...fields } + } + })) +} + +function renderPane(): void { + render( + + ) +} + +function liveActivityLine(): Element | null { + return document.querySelector('[data-native-chat-turn-activity]') +} + +beforeEach(() => { + restoreViewport = installNativeChatMessageListTestViewport() + useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} }) +}) + +afterEach(() => { + cleanup() + restoreViewport() + useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} }) +}) + +// A terminal-backed pane renders through the structured chat's own turn-status +// UI: the clock bar under the prompt, the live line at the tail, and the row a +// question uses when the agent waits on the reader. +describe('NativeChatResolvedView turn status', () => { + it('counts the working turn from the host-stamped epoch, with the live line at the tail', () => { + retained.session = transcript('working', false) + setStatus({ state: 'working' }, 75_000) + + renderPane() + + expect(screen.getByText('Working for 1m 15s')).toBeInTheDocument() + expect(liveActivityLine()).toHaveTextContent('Working…') + expect(document.querySelectorAll('.animate-bounce')).toHaveLength(0) + }) + + it.each(['waiting', 'blocked'] as const)( + 'says a %s agent waits on the reader when only its terminal shows the prompt', + (state) => { + retained.session = transcript('ready', true) + setStatus({ state }, 20_000) + + renderPane() + + // A whole phrase: there is no question to name after a colon. + expect(screen.getByText('Awaiting user input')).toBeInTheDocument() + expect(liveActivityLine()).toBeNull() + // The turn runs on behind the wait, as a structured turn does behind its card. + expect(screen.getByText('Working for 20s')).toBeInTheDocument() + } + ) + + it('lets the approval card speak for the wait', () => { + retained.session = transcript('ready', true) + setStatus({ + state: 'waiting', + interactivePrompt: JSON.stringify({ approval: { tool: 'Bash', summary: 'rm -rf dist' } }) + }) + + renderPane() + + expect(screen.getByText('Allow Bash?')).toBeInTheDocument() + expect(screen.queryByText(/Awaiting user input/)).toBeNull() + expect(liveActivityLine()).toBeNull() + expect(screen.getByText('Working for 0s')).toBeInTheDocument() + }) + + it("keeps a pending question's transcript row awaiting while the agent waits", () => { + retained.session = transcript('ready', true, [userTurn, askCall]) + setStatus({ state: 'waiting' }) + + renderPane() + + // One row says it: the question's own, not a second one at the tail. + expect(document.querySelectorAll('[data-native-chat-ask-row="awaiting"]')).toHaveLength(1) + expect(screen.getByText('Awaiting user input:')).toBeInTheDocument() + expect(screen.getAllByText('Which name?').length).toBeGreaterThan(0) + expect(screen.queryByText('Asked:')).toBeNull() + }) + + // Answering a terminal-only prompt means leaving the chat, which remounts it on return; a reload + // also starts the store with no state history. The host's stamp covers both. + it("counts a turn it first sees after a wait from the host's turn start, not the last state", () => { + retained.session = transcript('working', false) + setStatus({ state: 'working' }, 5_000) + patchStatus({ turnStartedAt: Date.now() - 90_000, stateHistory: [] }) + + renderPane() + + expect(screen.getByText('Working for 1m 30s')).toBeInTheDocument() + }) + + // A background task holds the row 'working' past the last turn's end, so the row's own epoch is + // that turn's; the host stamps the new turn from the main agent's own prompt. + it('counts a new turn from its stamp, not a row held open by background work', () => { + retained.session = transcript('working', false) + setStatus({ state: 'working' }) + const now = Date.now() + patchStatus({ + stateStartedAt: now - 45 * 60_000, + turnStartedAt: now - 5_000, + mainAgent: { state: 'working', stateStartedAt: now - 5_000 }, + stateHistory: [] + }) + + renderPane() + + expect(screen.getByText('Working for 5s')).toBeInTheDocument() + }) + + it("falls back to the main agent's own clock on a host that stamps no turn", () => { + retained.session = transcript('working', false) + setStatus({ state: 'working' }) + const now = Date.now() + patchStatus({ + stateStartedAt: now - 45 * 60_000, + mainAgent: { state: 'working', stateStartedAt: now - 5_000 }, + stateHistory: [] + }) + + renderPane() + + expect(screen.getByText('Working for 5s')).toBeInTheDocument() + }) + + // An Esc at a permission prompt fires no hook, then the same text is sent again: a new turn. + it('counts the same prompt sent again as a new turn', () => { + retained.session = transcript('working', false) + setStatus({ state: 'working' }, 5_000) + const now = Date.now() + patchStatus({ + turnStartedAt: now - 5_000, + stateHistory: [ + { state: 'working', prompt: 'Rename the module', startedAt: now - 600_000 }, + { state: 'waiting', prompt: 'Rename the module', startedAt: now - 500_000 } + ] + }) + + renderPane() + + expect(screen.getByText('Working for 5s')).toBeInTheDocument() + }) + + // The reader no longer rebuilds a turn from the history, so an old host reads the state's start. + it('falls back to the current state start on a host that stamps no turn', () => { + retained.session = transcript('working', false) + setStatus({ state: 'working' }, 20_000) + const now = Date.now() + patchStatus({ + stateHistory: [ + { state: 'working', prompt: 'Rename the module', startedAt: now - 90_000 }, + { state: 'waiting', prompt: 'Rename the module', startedAt: now - 40_000 } + ] + }) + + renderPane() + + expect(screen.getByText('Working for 20s')).toBeInTheDocument() + }) + + // The host recorded the turn's end, so a pane mounted after it (a switch to the terminal and + // back) folds it behind its duration instead of drawing it unfinished. + it('shows the host-ended latest turn with its host duration after a remount', () => { + retained.session = transcript('ready', false, [userTurn, stepCall]) + setStatus({ state: 'done' }) + // One clock read: the duration is the difference of these two stamps. + const now = Date.now() + patchStatus({ stateStartedAt: now - 10_000, turnStartedAt: now - 100_000 }) + + renderPane() + + expect(screen.getByText('Worked for 1m 30s')).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Toggle turn details' })).toBeInTheDocument() + }) + + // The store's staleness drops a silent row after 30 minutes. A wait left unanswered that long + // must not read as a finished turn: nothing says it ended. + it('does not settle a turn the host went quiet on', () => { + retained.session = transcript('ready', true, [userTurn, stepCall]) + setStatus({ state: 'waiting' }, 60_000) + patchStatus({ turnStartedAt: Date.now() - 60_000 }) + + renderPane() + expect(screen.getByText('Working for 1m 0s')).toBeInTheDocument() + + // The live session reads no hook state once the row is stale, so the wait no longer holds the turn. + retained.session = transcript('ready', false, [userTurn, stepCall]) + act(() => { + patchStatus({ updatedAt: Date.now() - 31 * 60_000 }) + }) + + expect(screen.queryByText(/Work(ing|ed) for/)).toBeNull() + expect(screen.queryByRole('button', { name: 'Toggle turn details' })).toBeNull() + expect(screen.getByText('pnpm build')).toBeInTheDocument() + }) + + it('folds finished turns from history behind their transcript duration', () => { + const at = Date.parse('2026-09-28T10:00:00.000Z') + retained.session = transcript('ready', false, [ + { ...userTurn, timestamp: at }, + { + id: 'answer-1', + role: 'assistant', + blocks: [{ type: 'text', text: 'Renamed.' }], + timestamp: at + 45_000, + source: 'transcript' + }, + { + id: 'user-2', + role: 'user', + blocks: [{ type: 'text', text: 'Now add tests' }], + timestamp: at + 100_000, + source: 'transcript' + } + ]) + setStatus({ state: 'done' }, 60_000) + + renderPane() + + expect(screen.getByText('Worked for 45s')).toBeInTheDocument() + // The latest turn has no recorded end, and this pane never watched it. + expect(screen.getAllByText(/Work(ing|ed) for/)).toHaveLength(1) + }) + + // The transcript draws no row for harness notices, so they cannot end a turn either. + it('keeps a running turn open across a harness notice injected mid-turn', () => { + const at = Date.parse('2026-09-28T10:00:00.000Z') + retained.session = transcript('working', false, [ + { ...userTurn, timestamp: at }, + { + id: 'progress-1', + role: 'assistant', + blocks: [{ type: 'text', text: 'Starting the build.' }], + timestamp: at + 10_000, + source: 'transcript' + }, + { + id: 'notice-1', + role: 'user', + blocks: [{ type: 'text', text: '\nb1' }], + timestamp: at + 20_000, + source: 'transcript' + }, + { + id: 'progress-2', + role: 'assistant', + blocks: [{ type: 'text', text: 'Build finished, checking output.' }], + timestamp: at + 25_000, + source: 'transcript' + } + ]) + setStatus({ state: 'working' }, 30_000) + + renderPane() + + expect(screen.getByText('Working for 30s')).toBeInTheDocument() + expect(screen.getByText('Starting the build.')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Toggle turn details' })).toBeNull() + }) + + it('stays quiet on a settled turn it never watched', () => { + retained.session = transcript('ready', false) + setStatus({ state: 'done' }, 60_000) + + renderPane() + + expect(screen.queryByText(/Awaiting user input/)).toBeNull() + expect(screen.queryByText(/Work(ing|ed) for/)).toBeNull() + expect(liveActivityLine()).toBeNull() + }) + + it('stays quiet when the pane has no status at all', () => { + retained.session = transcript('ready', false) + + renderPane() + + expect(screen.queryByText(/Awaiting user input/)).toBeNull() + expect(screen.queryByText(/Work(ing|ed) for/)).toBeNull() + expect(liveActivityLine()).toBeNull() + }) +}) diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.test-harness.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.test-harness.tsx index 5689cf9689f..1f97046363c 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.test-harness.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.test-harness.tsx @@ -52,8 +52,7 @@ type StructuredSessionMessageListProps = { allowFileUriLinks?: boolean isVisible?: boolean onLinkClick?: (...args: unknown[]) => void - showTurnStatus?: boolean - showLiveTurnActivity?: boolean + awaitingInput?: 'shown' | 'unshown' | null isWorking?: boolean runtimeContext?: unknown session?: { hasMore: boolean; loadingEarlier: boolean; loadEarlier: () => Promise } diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx index e766955b83e..9a40f63530d 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx @@ -177,8 +177,8 @@ describe('NativeChatStructuredSession', () => { expect(mocks.loadOlder).toHaveBeenCalledOnce() }) - // Turn status and transcript image previews shipped Codex-first. Every - // structured session renders through the same list, so neither is agent-gated. + // Transcript image previews shipped Codex-first. Every structured session + // renders through the same list, so they are not agent-gated. it.each(['codex', 'claude'] as const)( 'renders the same structured transcript chrome for %s', (agent) => { @@ -193,7 +193,6 @@ describe('NativeChatStructuredSession', () => { /> ) - expect(mocks.messageListProps?.showTurnStatus).toBe(true) expect(mocks.messageListProps?.runtimeContext).not.toBeUndefined() } ) @@ -216,7 +215,7 @@ describe('NativeChatStructuredSession', () => { expect(mocks.messageListProps).toMatchObject({ isWorking: true, - showLiveTurnActivity: false + awaitingInput: 'shown' }) expect( document @@ -231,13 +230,13 @@ describe('NativeChatStructuredSession', () => { itemId: 'legacy-question-item', expectedRevision: 1 }) - expect(mocks.messageListProps?.showLiveTurnActivity).toBe(false) + expect(mocks.messageListProps?.awaitingInput).toBe('shown') mocks.promptItems = [] rerender(view()) expect(mocks.messageListProps).toMatchObject({ isWorking: true, - showLiveTurnActivity: true + awaitingInput: null }) expect(screen.getByTestId('structured-composer')).toBeTruthy() expect(mocks.composerProps?.isWorking).toBe(true) @@ -285,7 +284,7 @@ describe('NativeChatStructuredSession', () => { expect(mocks.messageListProps).toMatchObject({ isWorking: true, - showLiveTurnActivity: false + awaitingInput: 'shown' }) expect(mocks.approvalCardProps?.approval.title).toBe('Allow command?') expect(screen.queryByTestId('structured-composer')).toBeNull() @@ -296,7 +295,7 @@ describe('NativeChatStructuredSession', () => { kind: 'option', optionId: 'allow' }) - expect(mocks.messageListProps?.showLiveTurnActivity).toBe(false) + expect(mocks.messageListProps?.awaitingInput).toBe('shown') act(() => mocks.approvalCardProps?.onCancel?.()) expect(mocks.cancel).toHaveBeenCalledWith('turn-approval', { diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index 26f04ae2e3c..a6bb8ad8d28 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -281,8 +281,7 @@ export function NativeChatStructuredSession( settledTurns={controller.settledTurns} activeTurnOpenedBy={controller.activeTurnOpenedBy} turnKeysByItemId={controller.turnKeysByItemId} - showTurnStatus - showLiveTurnActivity={prompt === null} + awaitingInput={prompt === null ? null : 'shown'} turnActivity={controller.turnActivity} onLinkClick={onLinkClick} allowFileUriLinks={onLinkClick !== undefined} diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsx index 0e6994a7b8b..81a8f53300f 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSessionDelivery.test.tsx @@ -18,7 +18,6 @@ const mocks = vi.hoisted(() => ({ messageListProps: null as null | { allowFileUriLinks?: boolean onLinkClick?: (...args: unknown[]) => void - showTurnStatus?: boolean runtimeContext?: unknown }, composerProps: null as null | { diff --git a/src/renderer/src/components/native-chat/NativeChatToolRun.ask-row.test.tsx b/src/renderer/src/components/native-chat/NativeChatToolRun.ask-row.test.tsx index 870bf39a409..b4257648efa 100644 --- a/src/renderer/src/components/native-chat/NativeChatToolRun.ask-row.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatToolRun.ask-row.test.tsx @@ -231,7 +231,7 @@ describe('NativeChatToolRun awaiting-input row', () => { /> ) - expect(screen.getByText('Awaiting user input:')).toBeInTheDocument() + expect(screen.getByText('Awaiting user input')).toBeInTheDocument() expect(screen.queryByText(/request_user_input/)).toBeNull() }) }) diff --git a/src/renderer/src/components/native-chat/NativeChatToolRun.tsx b/src/renderer/src/components/native-chat/NativeChatToolRun.tsx index 141ae739886..a6cb100ff58 100644 --- a/src/renderer/src/components/native-chat/NativeChatToolRun.tsx +++ b/src/renderer/src/components/native-chat/NativeChatToolRun.tsx @@ -58,7 +58,6 @@ export function NativeChatToolRun({ activeTurnIsWorking, trailing, expandOverride, - structuredActivityUi = true, disclosureId, onLinkClick }: { @@ -81,7 +80,6 @@ export function NativeChatToolRun({ * the agent has already moved past reads as settled even mid-call. Left * unset, a working turn's run is taken to be its last. */ trailing?: boolean - structuredActivityUi?: boolean /** Message this run belongs to. Windowing unmounts rows, so a run the reader * opened has to be remembered somewhere that outlives the row. */ disclosureId?: string @@ -130,10 +128,9 @@ export function NativeChatToolRun({ // caller with no turn state, or a turn blocked on the reader's answer, falls // back to the calls themselves. const live = - structuredActivityUi && - (activeTurnIsWorking === true && !askIsActive + activeTurnIsWorking === true && !askIsActive ? trailing !== false - : selectActiveToolCall(headerBlocks, { activeTurnIsWorking }) !== null) + : selectActiveToolCall(headerBlocks, { activeTurnIsWorking }) !== null // One sentence for the whole run, or the command itself when the run is one // call — the reader recognizes `git push` faster than "Ran 1 command". const runSentence = nativeChatToolRunSentence(headerBlocks, { live }) @@ -199,7 +196,6 @@ export function NativeChatToolRun({ // the grouped row visible here made a failed child command look like the // whole response was still running (or had failed) even while collapsed. if ( - structuredActivityUi && expandOverride === false && !(revealedDiff && open) && !live && @@ -237,7 +233,7 @@ export function NativeChatToolRun({ aria-live="polite" data-native-chat-tool-run-state={live ? 'live' : 'settled'} > - {structuredActivityUi && settledHeaderIcon ? ( + {settledHeaderIcon ? ( ) : null} {/* The run in words, in the transcript's own type. Present tense while @@ -278,7 +274,7 @@ export function NativeChatToolRun({ {/* Only a stated success is marked done — see nativeChatToolRunOutcome — and never while live: between two calls nothing is running, and a mark that appeared then would flash on every call. */} - {structuredActivityUi && !live && runSucceeded ? ( + {!live && runSucceeded ? ( ) : null} {latestCallLabel ? ( diff --git a/src/renderer/src/components/native-chat/NativeChatTranscriptRow.tsx b/src/renderer/src/components/native-chat/NativeChatTranscriptRow.tsx index 54499e3dc31..91e71df2140 100644 --- a/src/renderer/src/components/native-chat/NativeChatTranscriptRow.tsx +++ b/src/renderer/src/components/native-chat/NativeChatTranscriptRow.tsx @@ -13,7 +13,6 @@ import type { NativeChatDiffReveal, NativeChatDiffTarget } from './native-chat-t * object so a row's props change only when that row's own slot does. */ export type NativeChatTranscriptRowContext = { expandSignal: boolean - showTurnStatus: boolean revealedDiff: NativeChatDiffReveal | null taskListPredecessors: ReadonlyMap expandedTurnIds: ReadonlySet @@ -74,7 +73,6 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ onLinkClick={context.onLinkClick} allowFileUriLinks={context.allowFileUriLinks} deliveryNotice={context.deliveryNotices?.get(message.id)} - structuredActivityUi={context.showTurnStatus} folded={slot.folded} subagentLabel={slot.subagentLabel} runtimeContext={context.runtimeContext} diff --git a/src/renderer/src/components/native-chat/NativeChatTypingIndicatorRow.tsx b/src/renderer/src/components/native-chat/NativeChatTypingIndicatorRow.tsx deleted file mode 100644 index 59969c1dece..00000000000 --- a/src/renderer/src/components/native-chat/NativeChatTypingIndicatorRow.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { translate } from '@/i18n/i18n' - -export function NativeChatTypingIndicatorRow(): React.JSX.Element { - return ( -
-
- {[0, 1, 2].map((i) => ( - - ))} -
-
- ) -} diff --git a/src/renderer/src/components/native-chat/native-chat-live-session-contract.ts b/src/renderer/src/components/native-chat/native-chat-live-session-contract.ts index e3097ca085f..d61d11b9ac1 100644 --- a/src/renderer/src/components/native-chat/native-chat-live-session-contract.ts +++ b/src/renderer/src/components/native-chat/native-chat-live-session-contract.ts @@ -27,6 +27,9 @@ export function isNativeChatTranscriptUnsettled(phase: ReadState['phase']): bool export type NativeChatLiveSession = NativeChatSession & { /** Latest provider turn boundary, used to settle orphaned running tool rows. */ transcriptLifecycle?: NativeChatTurnLifecycle + /** The pane's hook says the agent stopped mid-turn for the reader, and the transcript + * has not since ended that turn. Absent on lanes with no hook status. */ + hookAwaitingInput?: boolean /** True when an older page may still exist (the last read filled the window). */ hasMore: boolean /** Whether an older-history page is currently loading. */ diff --git a/src/renderer/src/components/native-chat/native-chat-live-status.test.ts b/src/renderer/src/components/native-chat/native-chat-live-status.test.ts index ce8a2875df0..9dcd683dcd9 100644 --- a/src/renderer/src/components/native-chat/native-chat-live-status.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-live-status.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest' import type { NativeChatMessage } from '../../../../shared/native-chat-types' -import { mergeNativeChatLiveSession } from './native-chat-live-status' +import { mergeNativeChatLiveSession, nativeChatHookAwaitsInput } from './native-chat-live-status' import { selectNativeChatViewState } from './native-chat-view-state' import { shouldShowNativeChatWorking } from './native-chat-working-suppression' @@ -154,6 +154,36 @@ describe('mergeNativeChatLiveSession', () => { expect(session.status).toBe('ready') }) + it("keeps omp working while its latest row is a tool call written after the turn's start", () => { + // Shaped as decodeOmpTranscriptLine emits them: every omp row carries its timestamp. + const turnStartedAt = Date.parse('2026-09-28T10:00:00.000Z') + const toolCall: NativeChatMessage = { + id: 'rec-2', + role: 'assistant', + blocks: [ + { type: 'text', text: 'Running the suite.' }, + { type: 'tool-call', name: 'bash', input: { command: 'pnpm test' } } + ], + timestamp: turnStartedAt + 4_000, + source: 'transcript' + } + const session = mergeNativeChatLiveSession({ + messages: [{ ...user('rec-1', 'run the tests'), timestamp: turnStartedAt }, toolCall], + sessionId: 'sess', + agent: 'omp', + hookState: 'working', + stateStartedAt: turnStartedAt + }) + expect(session.status).toBe('working') + expect( + shouldShowNativeChatWorking({ + isConversation: true, + working: session.status === 'working', + interrupted: false + }) + ).toBe(true) + }) + it('keeps working while the hook reports a live background child', () => { const session = mergeNativeChatLiveSession({ messages: [assistant('a-1', 'lead done')], @@ -201,7 +231,7 @@ describe('mergeNativeChatLiveSession', () => { }).status ).toBe('working') // Regression: a non-null sessionId used to force 'loading' over live work, - // so the pane rendered idle mid-turn — Send instead of Stop, no typing + // so the pane rendered idle mid-turn — Send instead of Stop, no working // indicator, no streaming preview. The empty-transcript loading SURFACE is // selectNativeChatViewState's job; the status must stay 'working'. expect( @@ -249,7 +279,7 @@ describe('mergeNativeChatLiveSession', () => { // The whole chain the defect broke: a fresh Claude session reports its id // before the transcript flushes, so the pane rendered Send (not Stop) with no - // typing indicator while the agent was working. + // working indicator while the agent was working. it('keeps the Stop affordance for a working known session mid-flush', () => { const session = mergeNativeChatLiveSession({ messages: [user('u-1', 'run it')], @@ -271,3 +301,46 @@ describe('mergeNativeChatLiveSession', () => { ).toBe(true) }) }) + +describe('nativeChatHookAwaitsInput', () => { + it.each(['waiting', 'blocked'] as const)('reads a %s hook as a wait on the reader', (state) => { + expect(nativeChatHookAwaitsInput(state, 5, undefined)).toBe(true) + expect( + nativeChatHookAwaitsInput(state, 5, { state: 'working', turnId: 'turn-1', timestamp: 1 }) + ).toBe(true) + }) + + it('reads no other hook state as a wait', () => { + expect(nativeChatHookAwaitsInput('working', 5, undefined)).toBe(false) + expect(nativeChatHookAwaitsInput('done', 5, undefined)).toBe(false) + expect(nativeChatHookAwaitsInput(null, 5, undefined)).toBe(false) + }) + + // An interrupt at the prompt fires no hook; the transcript's marker is the only end. + it('ends a wait the transcript closed after it began', () => { + expect( + nativeChatHookAwaitsInput('waiting', 5, { + state: 'interrupted', + turnId: 'turn-1', + timestamp: 6 + }) + ).toBe(false) + expect( + nativeChatHookAwaitsInput('waiting', 5, { + state: 'completed', + turnId: 'turn-1', + timestamp: 6 + }) + ).toBe(false) + }) + + it('keeps a wait that began after the last closed turn', () => { + expect( + nativeChatHookAwaitsInput('waiting', 5, { + state: 'interrupted', + turnId: 'turn-1', + timestamp: 2 + }) + ).toBe(true) + }) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-live-status.ts b/src/renderer/src/components/native-chat/native-chat-live-status.ts index eefd7fcbeca..f3d2bb58be9 100644 --- a/src/renderer/src/components/native-chat/native-chat-live-status.ts +++ b/src/renderer/src/components/native-chat/native-chat-live-status.ts @@ -63,14 +63,15 @@ export function mergeNativeChatLiveSession(input: NativeChatLiveMergeInput): Nat } const status = liveStatusOverride( + agent, hookState, statusTailMessage ?? messages.at(-1), stateStartedAt, transcriptLifecycle, hookHasWorkingSubagents ?? false ) - // Why live work still wins: 'working' is what drives Stop-vs-Send, the typing - // indicator and the streaming preview, so forcing 'loading' over it renders an + // Why live work still wins: 'working' is what drives Stop-vs-Send, the turn + // status and the streaming preview, so forcing 'loading' over it renders an // idle pane while the agent works. A known session with nothing to show yet is // held on the loading surface by selectNativeChatViewState instead. if (loading && status !== 'working') { @@ -84,10 +85,36 @@ export function mergeNativeChatLiveSession(input: NativeChatLiveMergeInput): Nat } } +/** + * Whether the agent stopped mid-turn for the reader (`blocked` and `waiting` both mean a human + * must decide). Reconciled like 'working': an interrupt at the prompt fires no hook, so only the + * transcript's terminal marker can end a wait the hook never cleared. + */ +export function nativeChatHookAwaitsInput( + hookState: AgentStatusState | null, + stateStartedAt: number | null | undefined, + transcriptLifecycle: NativeChatTurnLifecycle | undefined +): boolean { + return ( + (hookState === 'blocked' || hookState === 'waiting') && + !lifecycleTerminatesCurrentTurn(transcriptLifecycle, stateStartedAt) + ) +} + /** Slack for comparing transcript timestamps to hook receipt times across hosts. */ export const LIFECYCLE_CLOCK_SKEW_SLACK_MS = 2_000 +/** + * Agents whose own runtime reports the turn end: omp posts `agent_end` from inside the agent, + * retried until the host takes it and held back while the run continues. Their hook 'working' + * is never a dropped Stop, so a trailing assistant row (a tool call mid-run) cannot end it. + */ +function hookDeliversTurnEnd(agent: AgentType): boolean { + return agent === 'omp' +} + function liveStatusOverride( + agent: AgentType, hookState: AgentStatusState | null, statusTailMessage: NativeChatMessage | undefined, stateStartedAt: number | null | undefined, @@ -121,6 +148,7 @@ function liveStatusOverride( // do not settle early on capable providers. if ( transcriptLifecycle?.state !== 'working' && + !hookDeliversTurnEnd(agent) && trailingAssistantPostDates(statusTailMessage, stateStartedAt) ) { return undefined diff --git a/src/renderer/src/components/native-chat/native-chat-message-rail-items.test.ts b/src/renderer/src/components/native-chat/native-chat-message-rail-items.test.ts index fa4995b4755..3a08c6a503e 100644 --- a/src/renderer/src/components/native-chat/native-chat-message-rail-items.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-message-rail-items.test.ts @@ -47,7 +47,6 @@ function slotsOf(messages: NativeChatMessage[]) { receipts: new Map(), turnStatuses: { active: null, completedByTurn: {} }, turnDiffs: new Map(), - showTurnStatus: false, expandedTurnKeys: new Set(), isWorking: false, lifecycleWorking: false diff --git a/src/renderer/src/components/native-chat/native-chat-rail-outline-parity.test.ts b/src/renderer/src/components/native-chat/native-chat-rail-outline-parity.test.ts index ba8e6fa8f21..b1efe034acd 100644 --- a/src/renderer/src/components/native-chat/native-chat-rail-outline-parity.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-rail-outline-parity.test.ts @@ -86,7 +86,6 @@ function loadedRailItems(items: AgentJournalRenderItem[], submissions: AgentJour receipts: new Map(), turnStatuses: { active: null, completedByTurn: {} }, turnDiffs: new Map(), - showTurnStatus: true, expandedTurnKeys: new Set(), isWorking: false, lifecycleWorking: false diff --git a/src/renderer/src/components/native-chat/native-chat-terminal-turn.test.ts b/src/renderer/src/components/native-chat/native-chat-terminal-turn.test.ts new file mode 100644 index 00000000000..4e77c18ace6 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-terminal-turn.test.ts @@ -0,0 +1,243 @@ +import { describe, expect, it } from 'vitest' +import { + NATIVE_CHAT_INTERRUPTED_STATUS_TEXT, + type NativeChatMessage +} from '../../../../shared/native-chat-types' +import { + nativeChatHookLatestTurnWorkedSeconds, + nativeChatHookTurnStartedAt, + nativeChatLatestTurnId, + nativeChatTranscriptSettledTurns, + resolveNativeChatTerminalTurn +} from './native-chat-terminal-turn' + +const idle = { + isConversation: true, + working: false, + hookAwaitingInput: false, + interrupted: false, + hasPromptCard: false +} + +describe('resolveNativeChatTerminalTurn', () => { + it('keeps the turn running while the agent waits, without calling it generating', () => { + expect(resolveNativeChatTerminalTurn({ ...idle, hookAwaitingInput: true })).toEqual({ + isWorking: false, + turnActive: true, + awaitingInput: 'unshown' + }) + }) + + it('lets a prompt card speak for the wait', () => { + expect( + resolveNativeChatTerminalTurn({ ...idle, hookAwaitingInput: true, hasPromptCard: true }) + ).toEqual({ isWorking: false, turnActive: true, awaitingInput: 'shown' }) + }) + + it('reports a generating turn with nothing awaited', () => { + expect(resolveNativeChatTerminalTurn({ ...idle, working: true })).toEqual({ + isWorking: true, + turnActive: true, + awaitingInput: null + }) + }) + + // Stop is the reader's word that the turn is over, whatever the hook still says. + it('ends the turn on local Stop, wait included', () => { + expect( + resolveNativeChatTerminalTurn({ + ...idle, + working: true, + hookAwaitingInput: true, + interrupted: true + }) + ).toEqual({ isWorking: false, turnActive: false, awaitingInput: null }) + }) + + it('stays quiet with no turn at all', () => { + expect(resolveNativeChatTerminalTurn(idle)).toEqual({ + isWorking: false, + turnActive: false, + awaitingInput: null + }) + }) +}) + +describe('nativeChatHookTurnStartedAt', () => { + const entry = { state: 'working' as const, stateStartedAt: 3_000 } + + // Answered in the terminal: the current state began at 3s, the turn at 1s. + it("dates the turn by the host's stamp, not the state it came back from", () => { + expect(nativeChatHookTurnStartedAt({ ...entry, turnStartedAt: 1_000 })).toBe(1_000) + }) + + // A background task held the row 'working' since 500; the main agent's turn began at 8s. + it('keeps the stamp when child work holds the row open', () => { + expect( + nativeChatHookTurnStartedAt({ + ...entry, + stateStartedAt: 500, + turnStartedAt: 8_000, + mainAgent: { state: 'working', stateStartedAt: 8_000 } + }) + ).toBe(8_000) + }) + + it("falls back to the main agent's own state start on a host that stamps no turn", () => { + expect( + nativeChatHookTurnStartedAt({ + ...entry, + stateStartedAt: 500, + mainAgent: { state: 'working', stateStartedAt: 8_000 } + }) + ).toBe(8_000) + }) + + it('falls back to the row once the main agent is done, or where it has none', () => { + expect( + nativeChatHookTurnStartedAt({ ...entry, mainAgent: { state: 'done', stateStartedAt: 2_500 } }) + ).toBe(3_000) + expect(nativeChatHookTurnStartedAt(entry)).toBe(3_000) + }) + + it('knows nothing without a status row', () => { + expect(nativeChatHookTurnStartedAt(undefined)).toBeNull() + }) +}) + +describe('nativeChatHookLatestTurnWorkedSeconds', () => { + const done = { state: 'done' as const, stateStartedAt: 91_000, turnStartedAt: 1_000 } + + it("times a turn the host ended from its turn start to the main agent's done", () => { + expect(nativeChatHookLatestTurnWorkedSeconds(done, false)).toBe(90) + // Child work still holds the row; the main agent's own end closes the turn. + expect( + nativeChatHookLatestTurnWorkedSeconds( + { ...done, state: 'working', mainAgent: { state: 'done', stateStartedAt: 31_000 } }, + false + ) + ).toBe(30) + }) + + // Staleness ages the row out of the pane, not the host's record that the turn finished. + it('keeps a host-ended duration once the row is stale', () => { + expect(nativeChatHookLatestTurnWorkedSeconds(done, true)).toBe(90) + }) + + it('hides a local end while the host went quiet mid-turn', () => { + expect( + nativeChatHookLatestTurnWorkedSeconds( + { ...done, state: 'waiting', stateStartedAt: 2_000 }, + true + ) + ).toBeNull() + }) + + // A pane-side end (Stop, the transcript's end marker) is the pane's own word; keep what it saw. + it('keeps the local reading while the host is fresh and the turn not host-ended', () => { + expect( + nativeChatHookLatestTurnWorkedSeconds( + { ...done, state: 'waiting', stateStartedAt: 2_000 }, + false + ) + ).toBeUndefined() + }) + + it('invents no duration without the host turn stamp, or across a session boundary', () => { + expect( + nativeChatHookLatestTurnWorkedSeconds({ state: 'done', stateStartedAt: 91_000 }, false) + ).toBeUndefined() + expect( + nativeChatHookLatestTurnWorkedSeconds({ ...done, sessionBoundary: true }, false) + ).toBeUndefined() + expect(nativeChatHookLatestTurnWorkedSeconds(undefined, true)).toBeUndefined() + }) +}) + +function row( + id: string, + role: NativeChatMessage['role'], + timestamp: number | null +): NativeChatMessage { + return { id, role, blocks: [{ type: 'text', text: id }], timestamp, source: 'transcript' } +} + +describe('nativeChatTranscriptSettledTurns', () => { + it('times each finished turn from its prompt to its last row, leaving the latest out', () => { + const settled = nativeChatTranscriptSettledTurns([ + row('u1', 'user', 10_000), + row('a1', 'assistant', 20_000), + row('a2', 'assistant', 55_900), + row('u2', 'user', 70_000), + row('a3', 'assistant', 80_000) + ]) + expect([...settled]).toEqual([['u1', { startedAt: 10_000, workedSeconds: 45 }]]) + }) + + it('ends an interrupted turn at its interruption', () => { + const settled = nativeChatTranscriptSettledTurns([ + row('u1', 'user', 0), + row('a1', 'assistant', 5_000), + { + ...row('stop', 'system', 12_000), + blocks: [{ type: 'text', text: NATIVE_CHAT_INTERRUPTED_STATUS_TEXT }] + }, + row('u2', 'user', 60_000) + ]) + expect(settled.get('u1')).toEqual({ startedAt: 0, workedSeconds: 12 }) + }) + + // An attachment row sits beside the next prompt; it does not stretch the turn before it. + it('does not end a turn at a system row the agent did not write', () => { + const settled = nativeChatTranscriptSettledTurns([ + row('u1', 'user', 0), + row('a1', 'assistant', 5_000), + row('@src/index.ts', 'system', 3_600_000), + row('u2', 'user', 3_601_000) + ]) + expect(settled.get('u1')).toEqual({ startedAt: 0, workedSeconds: 5 }) + }) + + // A harness notice (task notification, reminder) is user-role in the transcript but not a prompt. + it('times a turn across a harness notice injected mid-turn', () => { + const settled = nativeChatTranscriptSettledTurns([ + row('u1', 'user', 0), + row('a1', 'assistant', 5_000), + { + ...row('notice', 'user', 10_000), + blocks: [{ type: 'text', text: '\nb1' }] + }, + row('a2', 'assistant', 30_000), + row('u2', 'user', 60_000) + ]) + expect([...settled]).toEqual([['u1', { startedAt: 0, workedSeconds: 30 }]]) + }) + + // Absent, not null: null would also hide the duration the pane measured itself. + it('leaves out a turn missing either end', () => { + const settled = nativeChatTranscriptSettledTurns([ + row('u1', 'user', null), + row('a1', 'assistant', 5_000), + row('u2', 'user', 10_000), + row('a2', 'assistant', null), + row('u3', 'user', 20_000) + ]) + expect(settled.size).toBe(0) + }) +}) + +describe('nativeChatLatestTurnId', () => { + it('names the last prompt, not a harness notice after it', () => { + expect( + nativeChatLatestTurnId([ + row('u1', 'user', 0), + row('a1', 'assistant', 5_000), + { + ...row('notice', 'user', 10_000), + blocks: [{ type: 'text', text: '\nb1' }] + } + ]) + ).toBe('u1') + expect(nativeChatLatestTurnId([row('a1', 'assistant', 0)])).toBeNull() + }) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-terminal-turn.ts b/src/renderer/src/components/native-chat/native-chat-terminal-turn.ts new file mode 100644 index 00000000000..2926c5d75f2 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-terminal-turn.ts @@ -0,0 +1,132 @@ +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import { + isInterruptedStatusMessage, + type NativeChatMessage +} from '../../../../shared/native-chat-types' +import type { + NativeChatSettledTurn, + NativeChatSettledTurns +} from '../../../../shared/native-chat-turn-status' +import { isNoiseMessage } from '../../../../shared/native-chat-noise' +import type { NativeChatAwaitingInput } from './NativeChatMessageList' +import { shouldShowNativeChatWorking } from './native-chat-working-suppression' + +export type NativeChatTerminalTurn = { + /** The agent is generating: drives Stop-vs-Send and the streaming preview. */ + isWorking: boolean + /** The turn is running, including while its agent waits on the reader, as a + * structured turn runs on behind its prompt card: its clock keeps counting. */ + turnActive: boolean + awaitingInput: NativeChatAwaitingInput | null +} + +/** The turn facts a terminal-backed pane feeds the shared turn-status UI. */ +export function resolveNativeChatTerminalTurn(args: { + isConversation: boolean + /** Hook 'working', reconciled with the transcript's turn boundaries. */ + working: boolean + /** Hook 'waiting'/'blocked', reconciled the same way. */ + hookAwaitingInput: boolean + /** Local Stop suppression. */ + interrupted: boolean + /** The pane draws the agent's prompt as a card. */ + hasPromptCard: boolean +}): NativeChatTerminalTurn { + const { isConversation, working, hookAwaitingInput, interrupted, hasPromptCard } = args + const turnActive = shouldShowNativeChatWorking({ + isConversation, + working: working || hookAwaitingInput, + interrupted + }) + return { + isWorking: shouldShowNativeChatWorking({ isConversation, working, interrupted }), + turnActive, + // A prompt only the terminal shows is the one wait the transcript has to report. + awaitingInput: hasPromptCard ? 'shown' : turnActive && hookAwaitingInput ? 'unshown' : null + } +} + +type NativeChatHookTurnEntry = Pick< + AgentStatusEntry, + 'state' | 'stateStartedAt' | 'turnStartedAt' | 'mainAgent' | 'sessionBoundary' +> + +/** + * When the pane's current turn began: the host's stamp from the main agent's own turn-opening + * event, which survives a remount, a reload and child work holding the row open. A host too old to + * stamp it leaves the current state's start, the main agent's while it is mid-turn. + */ +export function nativeChatHookTurnStartedAt( + entry: NativeChatHookTurnEntry | undefined +): number | null { + if (!entry) { + return null + } + if (entry.turnStartedAt !== undefined) { + return entry.turnStartedAt + } + return entry.mainAgent && entry.mainAgent.state !== 'done' + ? entry.mainAgent.stateStartedAt + : entry.stateStartedAt +} + +/** + * The latest turn's duration by the host, for a turn the pane is not running: a number once the + * main agent is done (its done stamp minus the host's turn start), null when the host went quiet + * mid-turn (nothing says the turn ended, so a locally measured end would be a false claim), and + * undefined to keep what the pane observed (an old host, a session boundary, a pane-side end). + */ +export function nativeChatHookLatestTurnWorkedSeconds( + entry: NativeChatHookTurnEntry | undefined, + hookSilent: boolean +): number | null | undefined { + if (!entry) { + return undefined + } + const mainAgent = entry.mainAgent ?? entry + if (mainAgent.state === 'done') { + return entry.sessionBoundary === true || entry.turnStartedAt === undefined + ? undefined + : Math.max(0, Math.floor((mainAgent.stateStartedAt - entry.turnStartedAt) / 1000)) + } + return hookSilent ? null : undefined +} + +/** The transcript's latest turn: its last prompt, harness notices aside. */ +export function nativeChatLatestTurnId(messages: readonly NativeChatMessage[]): string | null { + const latest = messages.findLast((message) => message.role === 'user' && !isNoiseMessage(message)) + return latest?.id ?? null +} + +/** + * Durations of the transcript's finished turns, from its own timestamps (one clock): a turn runs + * from its prompt to the agent's last timestamped row or its interruption. Other system rows (file + * mentions, extension notes) can land long after, next to the following prompt. The latest turn is + * left out, since nothing here says it has ended, and so is a turn missing either end, which keeps + * what the pane observed. + */ +export function nativeChatTranscriptSettledTurns( + messages: readonly NativeChatMessage[] +): NativeChatSettledTurns { + const settled = new Map() + let turn: { id: string; startedAt: number | null; endedAt: number | null } | null = null + for (const message of messages) { + // A harness notice is user-role but draws no row, so it neither starts nor extends a turn. + if (message.role !== 'user' || isNoiseMessage(message)) { + const agentRow = + message.role === 'system' ? isInterruptedStatusMessage(message) : message.role !== 'user' + if (turn && agentRow && message.timestamp != null) { + turn.endedAt = Math.max(turn.endedAt ?? message.timestamp, message.timestamp) + } + continue + } + if (turn?.startedAt != null && turn.endedAt != null) { + settled.set(turn.id, { + startedAt: turn.startedAt, + workedSeconds: Math.max(0, Math.floor((turn.endedAt - turn.startedAt) / 1000)) + }) + } + turn = { id: message.id, startedAt: message.timestamp, endedAt: null } + } + return settled +} diff --git a/src/renderer/src/components/native-chat/native-chat-transcript-slots.test.ts b/src/renderer/src/components/native-chat/native-chat-transcript-slots.test.ts index 21e48166e9c..4c908375576 100644 --- a/src/renderer/src/components/native-chat/native-chat-transcript-slots.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-transcript-slots.test.ts @@ -43,7 +43,6 @@ function build( receipts: new Map(), turnStatuses: NO_STATUSES, turnDiffs: new Map(), - showTurnStatus: true, expandedTurnKeys: new Set(), isWorking: false, lifecycleWorking: false, diff --git a/src/renderer/src/components/native-chat/native-chat-transcript-slots.ts b/src/renderer/src/components/native-chat/native-chat-transcript-slots.ts index 1b20671ce24..b3631fb8012 100644 --- a/src/renderer/src/components/native-chat/native-chat-transcript-slots.ts +++ b/src/renderer/src/components/native-chat/native-chat-transcript-slots.ts @@ -75,7 +75,6 @@ export type NativeChatTranscriptSlotsInput = { completedByTurn: Readonly> } turnDiffs: ReadonlyMap - showTurnStatus: boolean /** Turns the reader opened. Everything else with a duration stays folded. */ expandedTurnKeys: ReadonlySet isWorking: boolean @@ -95,7 +94,6 @@ export function buildNativeChatTranscriptSlots( receipts, turnStatuses, turnDiffs, - showTurnStatus, expandedTurnKeys, isWorking, lifecycleWorking, @@ -141,11 +139,9 @@ export function buildNativeChatTranscriptSlots( } } const settledTurnKeys = new Set( - showTurnStatus - ? Object.entries(turnStatuses.completedByTurn) - .filter(([, status]) => status.workedSeconds != null) - .map(([turnKey]) => turnKey) - : [] + Object.entries(turnStatuses.completedByTurn) + .filter(([, status]) => status.workedSeconds != null) + .map(([turnKey]) => turnKey) ) const { foldedRows, foldableTurnKeys } = nativeChatTurnFold({ rows: foldRows, @@ -180,7 +176,7 @@ export function buildNativeChatTranscriptSlots( : turnStatuses.completedByTurn[turnKey] : undefined // The live turn's bar carries its running clock; it settles in place. - const status = showTurnStatus ? (candidateStatus ?? undefined) : undefined + const status = candidateStatus ?? undefined const turnDiff = turnKey && lastRowByTurn.get(turnKey) === index ? turnDiffs.get(turnKey) : undefined const folded = foldedRows.has(index) diff --git a/src/renderer/src/components/native-chat/native-chat-typing-indicator.test.ts b/src/renderer/src/components/native-chat/native-chat-typing-indicator.test.ts deleted file mode 100644 index b53b217eb15..00000000000 --- a/src/renderer/src/components/native-chat/native-chat-typing-indicator.test.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { NATIVE_CHAT_STREAMING_ID } from '../../../../shared/native-chat-streaming' -import type { NativeChatMessage } from '../../../../shared/native-chat-types' -import type { AgentJournalRenderItem } from '../../../../shared/agent-session-journal-types' -import { projectStructuredItemsToNativeChat } from '../../../../shared/structured-agent-session-projection' -import { shouldShowNativeChatTypingIndicator } from './native-chat-typing-indicator' - -function message(id: string, role: NativeChatMessage['role'], text = id): NativeChatMessage { - return { id, role, blocks: [{ type: 'text', text }], timestamp: null, source: 'transcript' } -} - -describe('shouldShowNativeChatTypingIndicator', () => { - it('stays hidden when the session is idle', () => { - expect( - shouldShowNativeChatTypingIndicator({ - messages: [message('u1', 'user')], - isWorking: false - }) - ).toBe(false) - }) - - it('shows once a send lands and no assistant row exists yet', () => { - expect( - shouldShowNativeChatTypingIndicator({ - messages: [message('a0', 'assistant'), message('u1', 'user')], - isWorking: true - }) - ).toBe(true) - }) - - it('hides as soon as the structured reply row arrives, before working clears', () => { - expect( - shouldShowNativeChatTypingIndicator({ - messages: [message('u1', 'user'), message('orca-item', 'assistant')], - isWorking: true - }) - ).toBe(false) - }) - - it('hides behind the PTY streaming bubble', () => { - expect( - shouldShowNativeChatTypingIndicator({ - messages: [message('u1', 'user'), message(NATIVE_CHAT_STREAMING_ID, 'assistant')], - isWorking: true - }) - ).toBe(false) - }) - - it('does not flicker back on when a system row interleaves mid-turn', () => { - expect( - shouldShowNativeChatTypingIndicator({ - messages: [ - message('u1', 'user'), - message('a1', 'assistant'), - message('s1', 'system', 'Ran /status') - ], - isWorking: true - }) - ).toBe(false) - }) - - it('shows again for the next send even though an earlier turn replied', () => { - expect( - shouldShowNativeChatTypingIndicator({ - messages: [message('u1', 'user'), message('a1', 'assistant'), message('u2', 'user')], - isWorking: true - }) - ).toBe(true) - }) - - it('does not let an unresolved tool from an earlier turn hide the next send indicator', () => { - const earlierRunningTool: NativeChatMessage = { - id: 'tool-old', - role: 'assistant', - blocks: [ - { type: 'tool-call', name: 'shell', input: { command: 'sleep 1' }, state: 'running' } - ], - timestamp: null, - source: 'transcript' - } - expect( - shouldShowNativeChatTypingIndicator({ - messages: [earlierRunningTool, message('a1', 'assistant'), message('u2', 'user')], - isWorking: true - }) - ).toBe(true) - }) - - it('shows after a slash-command marker even though an earlier turn replied', () => { - expect( - shouldShowNativeChatTypingIndicator({ - messages: [ - message('a1', 'assistant'), - message('command:compact', 'system', 'Ran /compact') - ], - isWorking: true - }) - ).toBe(true) - }) - - it('shows on a session whose transcript is still empty', () => { - expect(shouldShowNativeChatTypingIndicator({ messages: [], isWorking: true })).toBe(true) - }) -}) - -// These build rows through the REAL structured projection instead of hand-made -// `command:` marker ids. The hand-made ids only exist on the PTY transport, so -// tests using them were blind to how the shipping transport actually looks. -describe('with rows projected from the structured journal', () => { - function toolCallItem(sequence: number): AgentJournalRenderItem { - return { - itemId: `codex:thread-1:turn-1:${sequence}`, - revision: 1, - sequence, - observedAt: 1_800_000_000_000, - body: { - kind: 'tool-call', - name: 'shell', - state: 'running', - input: { command: 'sed -n 1,240p README.md' } - } - } as AgentJournalRenderItem - } - - function assistantTextItem(sequence: number): AgentJournalRenderItem { - return { - itemId: `codex:thread-1:turn-1:${sequence}`, - revision: 1, - sequence, - observedAt: 1_800_000_000_000, - body: { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: "I'm checking PR 14696's metadata." }] - } - } as AgentJournalRenderItem - } - - it('stays visible beside the structured live tool row while a command runs', () => { - const messages = projectStructuredItemsToNativeChat([assistantTextItem(1), toolCallItem(2)]) - expect(messages.at(-1)?.role).toBe('assistant') - expect(shouldShowNativeChatTypingIndicator({ messages, isWorking: true })).toBe(true) - }) - - it('hides once prose is the newest row', () => { - const messages = projectStructuredItemsToNativeChat([toolCallItem(1), assistantTextItem(2)]) - expect(shouldShowNativeChatTypingIndicator({ messages, isWorking: true })).toBe(false) - }) - - it('stays hidden when the turn is not working, command row or not', () => { - const messages = projectStructuredItemsToNativeChat([toolCallItem(1)]) - expect(shouldShowNativeChatTypingIndicator({ messages, isWorking: false })).toBe(false) - }) -}) diff --git a/src/renderer/src/components/native-chat/native-chat-typing-indicator.ts b/src/renderer/src/components/native-chat/native-chat-typing-indicator.ts deleted file mode 100644 index 144560278a2..00000000000 --- a/src/renderer/src/components/native-chat/native-chat-typing-indicator.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { NativeChatMessage } from '../../../../shared/native-chat-types' -import { NATIVE_CHAT_STREAMING_ID } from '../../../../shared/native-chat-streaming' -import { isCommandMarkerId } from './native-chat-command-marker' - -function isToolActivityOnlyRow(message: NativeChatMessage): boolean { - const blocks = message.blocks - if (!blocks || blocks.length === 0) { - return false - } - return blocks.every((block) => block.type === 'tool-call' || block.type === 'tool-result') -} - -export function shouldShowNativeChatTypingIndicator(args: { - messages: readonly NativeChatMessage[] - isWorking: boolean -}): boolean { - if (!args.isWorking) { - return false - } - const { messages } = args - for (let index = messages.length - 1; index >= 0; index -= 1) { - const message = messages[index] - if (!message || message.role === 'user' || isCommandMarkerId(message.id)) { - return true - } - if (isToolActivityOnlyRow(message)) { - return true - } - if (message.role === 'assistant' || message.id === NATIVE_CHAT_STREAMING_ID) { - return false - } - } - return true -} diff --git a/src/renderer/src/components/native-chat/use-native-chat-interactive-prompt-card.test.ts b/src/renderer/src/components/native-chat/use-native-chat-interactive-prompt-card.test.ts new file mode 100644 index 00000000000..a13df87c3e8 --- /dev/null +++ b/src/renderer/src/components/native-chat/use-native-chat-interactive-prompt-card.test.ts @@ -0,0 +1,68 @@ +// @vitest-environment happy-dom + +import { afterEach, describe, expect, it } from 'vitest' +import { act, cleanup, renderHook } from '@testing-library/react' +import type { AgentStatusPayload } from '../../../../shared/agent-status-types' +import type { NativeChatMessage } from '../../../../shared/native-chat-types' + +const { useAppStore } = await import('../../store') +const { useNativeChatInteractivePromptCard } = + await import('./use-native-chat-interactive-prompt-card') + +const paneKey = 'tab-card:leaf-card' +const NO_MESSAGES: readonly NativeChatMessage[] = [] + +function setStatus(payload: Omit): void { + useAppStore + .getState() + .setAgentStatus(paneKey, { prompt: 'Rename', agentType: 'claude', ...payload }) +} + +afterEach(() => { + cleanup() + useAppStore.setState({ agentStatusByPaneKey: {} }) +}) + +describe('useNativeChatInteractivePromptCard', () => { + // The hook runs in the pane's view, so each render here re-renders the whole transcript. + it('does not re-render for a tool call that carries no prompt', () => { + setStatus({ state: 'working', toolName: 'Read' }) + let renders = 0 + renderHook(() => { + renders += 1 + return useNativeChatInteractivePromptCard({ + paneKey, + messages: NO_MESSAGES, + transcriptSettled: true + }) + }) + const settled = renders + + act(() => setStatus({ state: 'working', toolName: 'Bash' })) + act(() => setStatus({ state: 'working', toolName: 'Edit' })) + + expect(renders).toBe(settled) + }) + + it('still reads the prompt that arrives with a tool call', () => { + setStatus({ state: 'working', toolName: 'Read' }) + const { result } = renderHook(() => + useNativeChatInteractivePromptCard({ + paneKey, + messages: NO_MESSAGES, + transcriptSettled: true + }) + ) + expect(result.current).toBeNull() + + act(() => + setStatus({ + state: 'waiting', + toolName: 'Bash', + interactivePrompt: JSON.stringify({ approval: { tool: 'Bash', summary: 'rm -rf dist' } }) + }) + ) + + expect(result.current).toMatchObject({ kind: 'approval' }) + }) +}) diff --git a/src/renderer/src/components/native-chat/use-native-chat-interactive-prompt-card.ts b/src/renderer/src/components/native-chat/use-native-chat-interactive-prompt-card.ts new file mode 100644 index 00000000000..243fea0ac57 --- /dev/null +++ b/src/renderer/src/components/native-chat/use-native-chat-interactive-prompt-card.ts @@ -0,0 +1,48 @@ +import { useMemo } from 'react' +import { useAppStore } from '../../store' +import { resolveNativeChatAsk } from '../../../../shared/native-chat-ask' +import type { NativeChatMessage } from '../../../../shared/native-chat-types' +import { + parseInteractivePrompt, + type InteractivePromptCard +} from './native-chat-interactive-prompt' + +/** + * The prompt a terminal-backed pane can draw as a card: a tool approval from the + * live status, else a question from the live status or, failing that, from the + * transcript's unresolved ask (headless host, relay gap, replay, reconnect — a + * pane parked on a selector must not take the next message as its answer, #11761). + */ +export function useNativeChatInteractivePromptCard({ + paneKey, + messages, + transcriptSettled +}: { + paneKey: string + /** Pass the command-boundary-trimmed messages so an ask abandoned via `/clear` stays gone. */ + messages: readonly NativeChatMessage[] + transcriptSettled: boolean +}): InteractivePromptCard { + const interactivePrompt = useAppStore( + (s) => s.agentStatusByPaneKey[paneKey]?.interactivePrompt ?? null + ) + // The sibling `toolName` lets the question parser dispatch through the tool's + // registered parser (mobile parity). Read only beside a prompt: it changes on + // every tool call, and this hook re-renders the whole pane. + const interactiveToolName = useAppStore((s) => { + const entry = s.agentStatusByPaneKey[paneKey] + return entry?.interactivePrompt ? (entry.toolName ?? null) : null + }) + return useMemo(() => { + const statusCard = parseInteractivePrompt(interactivePrompt, interactiveToolName ?? undefined) + if (statusCard?.kind === 'approval') { + return statusCard + } + const prompt = resolveNativeChatAsk({ + liveAsk: statusCard?.prompt ?? null, + messages, + transcriptSettled + }) + return prompt ? { kind: 'question' as const, prompt } : null + }, [interactivePrompt, interactiveToolName, messages, transcriptSettled]) +} diff --git a/src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts b/src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts index cd4b701e270..4c7f784eb31 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts @@ -547,6 +547,42 @@ describe('useNativeChatLiveSession — transport routing', () => { expect(latest?.status).toBe('ready') }) + // Declining a prompt with an interrupt fires no hook, so the row keeps saying + // `waiting`; the transcript's marker is what ends the wait. + it('ends a hook wait once the transcript records the turn interrupted', async () => { + const waitStartedAt = Date.now() - 1_000 + useAppStore.getState().setAgentStatus(PANE, { state: 'waiting', prompt: '', agentType: AGENT }) + const row = useAppStore.getState().agentStatusByPaneKey[PANE] + if (!row) { + throw new Error('the store dropped the status row this test depends on') + } + useAppStore.setState({ + agentStatusByPaneKey: { [PANE]: { ...row, stateStartedAt: waitStartedAt } } + }) + const transport = getMockTransport('env-1') + await render({ paneKey: PANE, agent: AGENT, sessionId: SESSION, runtimeEnvironmentId: 'env-1' }) + await act(async () => + transport.emit({ + type: 'snapshot', + messages: [user('u-1', 'go')], + hasMore: false, + lifecycle: { state: 'working', turnId: 'turn-1', timestamp: waitStartedAt - 500 } + }) + ) + expect(latest?.hookAwaitingInput).toBe(true) + expect(latest?.status).toBe('ready') + + await act(async () => + transport.emit({ + type: 'appended', + messages: [], + lifecycle: { state: 'interrupted', turnId: 'turn-1', timestamp: Date.now() } + }) + ) + + expect(latest?.hookAwaitingInput).toBe(false) + }) + it('does not let an older pagination read rewind a live completion', async () => { useAppStore.setState({ agentStatusByPaneKey: { diff --git a/src/renderer/src/components/native-chat/use-native-chat-live-session.ts b/src/renderer/src/components/native-chat/use-native-chat-live-session.ts index a62237f1b35..0f4a4058155 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-live-session.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-live-session.ts @@ -9,7 +9,7 @@ import { createNativeChatMerger, replaceList } from '../../../../shared/native-chat-merge' -import { mergeNativeChatLiveSession } from './native-chat-live-status' +import { mergeNativeChatLiveSession, nativeChatHookAwaitsInput } from './native-chat-live-status' import { hasMoreNativeChatHistory, NATIVE_CHAT_INITIAL_LIMIT, @@ -342,6 +342,11 @@ export function useNativeChatLiveSession( }) return { ...session, + hookAwaitingInput: nativeChatHookAwaitsInput( + hookState, + hookStateStartedAt, + transcriptLifecycle + ), hasMore, loadingEarlier, olderHistoryGeneration, diff --git a/src/renderer/src/components/native-chat/use-native-chat-message-rail.test.ts b/src/renderer/src/components/native-chat/use-native-chat-message-rail.test.ts index cbbd819ce22..6772eec7a47 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-message-rail.test.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-message-rail.test.ts @@ -36,7 +36,6 @@ function slotsOf(messages: NativeChatMessage[]) { receipts: new Map(), turnStatuses: { active: null, completedByTurn: {} }, turnDiffs: new Map(), - showTurnStatus: false, expandedTurnKeys: new Set(), isWorking: false, lifecycleWorking: false diff --git a/src/renderer/src/components/native-chat/use-native-chat-terminal-turn-timing.ts b/src/renderer/src/components/native-chat/use-native-chat-terminal-turn-timing.ts new file mode 100644 index 00000000000..13aa5a93977 --- /dev/null +++ b/src/renderer/src/components/native-chat/use-native-chat-terminal-turn-timing.ts @@ -0,0 +1,45 @@ +import { useMemo } from 'react' +import { useAppStore } from '../../store' +import type { NativeChatMessage } from '../../../../shared/native-chat-types' +import type { NativeChatSettledTurns } from '../../../../shared/native-chat-turn-status' +import { + nativeChatHookLatestTurnWorkedSeconds, + nativeChatHookTurnStartedAt, + nativeChatLatestTurnId, + nativeChatTranscriptSettledTurns +} from './native-chat-terminal-turn' +import { resolveNativeChatHookState } from './use-native-chat-hook-status' + +/** The terminal-backed pane's turn timing for the message list: when its running turn began, by + * the host, and each finished turn's duration (the host's for the latest, the transcript's for + * history). All of it survives a remount of the pane. */ +export function useNativeChatTerminalTurnTiming( + paneKey: string, + messages: readonly NativeChatMessage[], + turnActive: boolean +): { workingStartedAt: number | null; settledTurns: NativeChatSettledTurns } { + // Freshness is time-based: re-read when the scheduler says a silent row aged out. + const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) + void agentStatusEpoch + const turnStartedAt = useAppStore((s) => + nativeChatHookTurnStartedAt(s.agentStatusByPaneKey[paneKey]) + ) + const latestWorkedSeconds = useAppStore((s) => { + const entry = s.agentStatusByPaneKey[paneKey] + return nativeChatHookLatestTurnWorkedSeconds(entry, resolveNativeChatHookState(entry) === null) + }) + const transcriptSettled = useMemo(() => nativeChatTranscriptSettledTurns(messages), [messages]) + const latestTurnId = useMemo(() => nativeChatLatestTurnId(messages), [messages]) + const settledTurns = useMemo(() => { + if (turnActive || latestWorkedSeconds === undefined || latestTurnId === null) { + return transcriptSettled + } + return new Map(transcriptSettled).set( + latestTurnId, + latestWorkedSeconds === null || turnStartedAt === null + ? null + : { startedAt: turnStartedAt, workedSeconds: latestWorkedSeconds } + ) + }, [latestTurnId, latestWorkedSeconds, transcriptSettled, turnActive, turnStartedAt]) + return { workingStartedAt: turnActive ? turnStartedAt : null, settledTurns } +} diff --git a/src/renderer/src/components/native-chat/use-native-chat-transcript-scroll.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-transcript-scroll.test.tsx index 1f08a51299a..948b83c5dbb 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-transcript-scroll.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-transcript-scroll.test.tsx @@ -23,7 +23,7 @@ function TranscriptHarness({ contentRef, itemCount, isWorking: false, - showTypingIndicator: false, + showsTailRow: false, isVisible, alignToViewportTop: vi.fn(), scrollToEnd, diff --git a/src/renderer/src/components/native-chat/use-native-chat-transcript-scroll.ts b/src/renderer/src/components/native-chat/use-native-chat-transcript-scroll.ts index 23bebf0f1e8..6df6d3eb562 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-transcript-scroll.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-transcript-scroll.ts @@ -52,7 +52,7 @@ export function useNativeChatTranscriptScroll({ contentRef, itemCount, isWorking, - showTypingIndicator, + showsTailRow, isVisible, alignToViewportTop, scrollToEnd, @@ -64,7 +64,8 @@ export function useNativeChatTranscriptScroll({ contentRef: React.RefObject itemCount: number isWorking: boolean - showTypingIndicator: boolean + /** Whether the list draws a row after the transcript (live activity or a wait). */ + showsTailRow: boolean isVisible: boolean alignToViewportTop: (element: HTMLElement) => void scrollToEnd: () => void @@ -156,7 +157,7 @@ export function useNativeChatTranscriptScroll({ itemCount, isWorking, restoreScrollOffset, - showTypingIndicator, + showsTailRow, scrollToEndWhenMeasurable ]) diff --git a/src/renderer/src/components/native-chat/use-native-chat-turn-status.ts b/src/renderer/src/components/native-chat/use-native-chat-turn-status.ts index 95db05141d2..33a795b8b9d 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-turn-status.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-turn-status.ts @@ -23,7 +23,7 @@ export function useNativeChatTurnStatus({ activeTurnKey: string isWorking: boolean workingStartedAt?: number | null - /** Host-recorded durations; they outrank whatever this client observed. */ + /** Recorded durations (the host's journal or the transcript); they outrank what this client observed. */ settledTurns?: NativeChatSettledTurns | null /** Whether the turn is reasoning right now, derived from its journal content. */ thinking?: boolean diff --git a/src/renderer/src/hooks/ipc-events-agent-status-store-test-fixtures.ts b/src/renderer/src/hooks/ipc-events-agent-status-store-test-fixtures.ts index 7cabf081db9..8f676cada26 100644 --- a/src/renderer/src/hooks/ipc-events-agent-status-store-test-fixtures.ts +++ b/src/renderer/src/hooks/ipc-events-agent-status-store-test-fixtures.ts @@ -47,6 +47,7 @@ export type AgentStatusSetData = { connectionId?: string | null receivedAt: number stateStartedAt: number + turnStartedAt?: number } export type StoreLike = Record export type StoreSubscribeListener = (state: StoreLike, previousState: StoreLike) => void diff --git a/src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts b/src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts index 47aa5521a26..41957078f41 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts @@ -227,7 +227,8 @@ export function createAgentStatusEventApplicator(args: { ...(data.evidenceObservedAt !== undefined ? { evidenceObservedAt: data.evidenceObservedAt } : {}), - stateStartedAt: data.stateStartedAt + stateStartedAt: data.stateStartedAt, + ...(Number.isFinite(data.turnStartedAt) ? { turnStartedAt: data.turnStartedAt } : {}) }, routing: { tabId: ownerTabId, diff --git a/src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-replay.test.ts b/src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-replay.test.ts index e26448f0b63..f8f77eced61 100644 --- a/src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-replay.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-replay.test.ts @@ -79,7 +79,9 @@ describe('useIpcEvents agent status snapshot integration', () => { toolInput: 'pnpm test', terminalHandle: 'term-future', receivedAt: 1_700_000_000_000, - stateStartedAt: 1_699_999_999_000 + stateStartedAt: 1_699_999_999_000, + // A reload starts with no state history; the host's turn start must arrive with the row. + turnStartedAt: 1_699_999_990_000 } ]) await Promise.resolve() @@ -113,7 +115,11 @@ describe('useIpcEvents agent status snapshot integration', () => { toolInput: 'pnpm test' }), 'SSH Tab', - { updatedAt: 1_700_000_000_000, stateStartedAt: 1_699_999_999_000 }, + { + updatedAt: 1_700_000_000_000, + stateStartedAt: 1_699_999_999_000, + turnStartedAt: 1_699_999_990_000 + }, expectWorktreeRouting('wt-1'), undefined ) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 90fc6192a11..4f72d98bb17 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2674,6 +2674,7 @@ "ask": { "asked": "Asked:", "awaiting": "Awaiting user input:", + "awaitingUnnamed": "Awaiting user input", "questionCount": "{{value0}} questions" }, "composer": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 5db365466e6..30ac3af4db9 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -17800,6 +17800,7 @@ }, "ask": { "awaiting": "Awaiting user input:", + "awaitingUnnamed": "Awaiting user input", "asked": "Asked:", "questionCount": "{{value0}} questions" }, diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 04e9bb284ab..f378465a943 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -17745,6 +17745,7 @@ "railEmptyMessage": "Message", "ask": { "awaiting": "En attente de la saisie de l'utilisateur :", + "awaitingUnnamed": "En attente de la saisie de l'utilisateur", "asked": "Demandé:", "questionCount": "{{value0}} questions" }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 90f55805342..bcb68593d90 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -17681,6 +17681,7 @@ "railEmptyMessage": "メッセージ", "ask": { "awaiting": "ユーザー入力を待っています:", + "awaitingUnnamed": "ユーザー入力を待っています", "asked": "質問:", "questionCount": "{{value0}} の質問" }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index dd0dbdfa8a7..8aa0335d891 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -17681,6 +17681,7 @@ "railEmptyMessage": "메시지", "ask": { "awaiting": "사용자 입력을 기다리는 중:", + "awaitingUnnamed": "사용자 입력을 기다리는 중", "asked": "질문:", "questionCount": "{{value0}} 질문" }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 1514dd25697..70cbc25bdc5 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -17646,6 +17646,7 @@ "railEmptyMessage": "信息", "ask": { "awaiting": "等待用户输入:", + "awaitingUnnamed": "等待用户输入", "asked": "问:", "questionCount": "{{value0}} 问题" }, diff --git a/src/renderer/src/runtime/sync-runtime-graph-agent-status-projection.test.ts b/src/renderer/src/runtime/sync-runtime-graph-agent-status-projection.test.ts index 5bd9460041a..b78bb317585 100644 --- a/src/renderer/src/runtime/sync-runtime-graph-agent-status-projection.test.ts +++ b/src/renderer/src/runtime/sync-runtime-graph-agent-status-projection.test.ts @@ -29,6 +29,8 @@ function referenceProjection(map: AppState['agentStatusByPaneKey']): string { prompt: entry.prompt, updatedAtBucket: Math.floor(entry.updatedAt / BUCKET_MS), stateStartedAt: entry.stateStartedAt, + // A new turn can keep the state (child work held it open); its stamp alone must republish. + turnStartedAt: entry.turnStartedAt ?? null, agentType: entry.agentType ?? null, terminalTitle: entry.terminalTitle ?? null, stateHistory: entry.stateHistory.map((history) => ({ @@ -77,6 +79,7 @@ describe('mobile agent-status projection equivalence', () => { statusMaps.push({}) statusMaps.push({ 'tab-0:leaf-0': makeEntry(0) }) statusMaps.push({ 'tab-0:leaf-0': makeEntry(0, { workingMode: 'monitoring' }) }) + statusMaps.push({ 'tab-0:leaf-0': makeEntry(0, { turnStartedAt: 1740000000500 }) }) const many: AppState['agentStatusByPaneKey'] = {} for (let index = 0; index < 12; index += 1) { many[`tab-${index}:leaf-0`] = makeEntry(index) diff --git a/src/renderer/src/runtime/sync-runtime-graph-projection-hot-path.test.ts b/src/renderer/src/runtime/sync-runtime-graph-projection-hot-path.test.ts index 0adbd768fe5..587e30a769e 100644 --- a/src/renderer/src/runtime/sync-runtime-graph-projection-hot-path.test.ts +++ b/src/renderer/src/runtime/sync-runtime-graph-projection-hot-path.test.ts @@ -111,6 +111,7 @@ function referenceAgentStatusProjection(map: AppState['agentStatusByPaneKey']): prompt: entry.prompt, updatedAtBucket: Math.floor(entry.updatedAt / AGENT_STATUS_SYNC_UPDATED_AT_BUCKET_MS), stateStartedAt: entry.stateStartedAt, + turnStartedAt: entry.turnStartedAt ?? null, agentType: entry.agentType ?? null, terminalTitle: entry.terminalTitle ?? null, stateHistory: entry.stateHistory.map((history) => ({ diff --git a/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts b/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts index ba41d169e8c..25b65573839 100644 --- a/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts +++ b/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts @@ -19,6 +19,7 @@ function serializeAgentStatusEntry( prompt: entry.prompt, updatedAtBucket: Math.floor(entry.updatedAt / AGENT_STATUS_SYNC_UPDATED_AT_BUCKET_MS), stateStartedAt: entry.stateStartedAt, + turnStartedAt: entry.turnStartedAt ?? null, agentType: entry.agentType ?? null, terminalTitle: entry.terminalTitle ?? null, stateHistory: entry.stateHistory.map((history) => ({ diff --git a/src/renderer/src/runtime/web-session-tabs-sync/state-equality-core.test.ts b/src/renderer/src/runtime/web-session-tabs-sync/state-equality-core.test.ts index ae51553ea7b..aa466c0f9b5 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/state-equality-core.test.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/state-equality-core.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest' -import type { AgentStateHistoryEntry } from '../../../../shared/agent-status-types' -import { sameAgentStateHistory } from './state-equality-core' +import type { + AgentStateHistoryEntry, + AgentStatusEntry +} from '../../../../shared/agent-status-types' +import { agentStatusEntryEqual, sameAgentStateHistory } from './state-equality-core' function doneEntry(mainAgent?: AgentStateHistoryEntry['mainAgent']): AgentStateHistoryEntry { return { state: 'done', prompt: 'ship it', startedAt: 1_000, ...(mainAgent ? { mainAgent } : {}) } @@ -25,3 +28,20 @@ describe('sameAgentStateHistory', () => { ).toBe(false) }) }) + +describe('agentStatusEntryEqual', () => { + // A paired client must take a host row whose only change is a new turn under the same state. + it('sees a new host turn start under an unchanged state', () => { + const entry: AgentStatusEntry = { + state: 'working', + prompt: 'ship it', + updatedAt: 2_000, + stateStartedAt: 1_000, + turnStartedAt: 1_000, + paneKey: 'tab-1:leaf-1', + stateHistory: [] + } + expect(agentStatusEntryEqual(entry, { ...entry })).toBe(true) + expect(agentStatusEntryEqual(entry, { ...entry, turnStartedAt: 1_500 })).toBe(false) + }) +}) diff --git a/src/renderer/src/runtime/web-session-tabs-sync/state-equality-core.ts b/src/renderer/src/runtime/web-session-tabs-sync/state-equality-core.ts index 197fb698137..407b7f6c2f3 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/state-equality-core.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/state-equality-core.ts @@ -48,6 +48,7 @@ export function agentStatusEntryEqual( a.prompt === b.prompt && a.updatedAt === b.updatedAt && a.stateStartedAt === b.stateStartedAt && + a.turnStartedAt === b.turnStartedAt && a.agentType === b.agentType && a.paneKey === b.paneKey && a.worktreeId === b.worktreeId && diff --git a/src/renderer/src/store/slices/agent-status-contract.ts b/src/renderer/src/store/slices/agent-status-contract.ts index afff64d3303..64ff3e10dcf 100644 --- a/src/renderer/src/store/slices/agent-status-contract.ts +++ b/src/renderer/src/store/slices/agent-status-contract.ts @@ -88,6 +88,8 @@ export type AgentStatusTiming = { /** Observation clock for staleness; see `AgentStatusEntry.evidenceObservedAt`. */ evidenceObservedAt?: number stateStartedAt?: number + /** The host's turn start; see `AgentStatusEntry.turnStartedAt`. */ + turnStartedAt?: number } export type AgentStatusRouting = { diff --git a/src/renderer/src/store/slices/agent-status-live-entry-builder.ts b/src/renderer/src/store/slices/agent-status-live-entry-builder.ts index 28bf952460c..ec80692f95e 100644 --- a/src/renderer/src/store/slices/agent-status-live-entry-builder.ts +++ b/src/renderer/src/store/slices/agent-status-live-entry-builder.ts @@ -113,6 +113,11 @@ export function buildAgentStatusLiveEntry( : existing && existing.state === payload.state ? existing.stateStartedAt : updatedAt) + // Why: a writer with no turn clock (an OSC repaint) keeps the host's stamp only within one state; + // a state change it cannot date must not inherit another turn's start. + const turnStartedAt = + timing?.turnStartedAt ?? + (existing && existing.state === payload.state ? existing.turnStartedAt : undefined) if ( existing && shouldSuppressInheritedTerminalStatus({ @@ -205,6 +210,7 @@ export function buildAgentStatusLiveEntry( ...(metadata?.structuredHostOwned === true ? { structuredHostOwned: true as const } : {}), stateStartedAt, stateObservedAt, + ...(turnStartedAt !== undefined ? { turnStartedAt } : {}), agentType: identity.agentType, model: payload.model ?? (existing?.agentType === identity.agentType ? existing.model : undefined), diff --git a/src/renderer/src/store/slices/agent-status-turn-started-at.test.ts b/src/renderer/src/store/slices/agent-status-turn-started-at.test.ts new file mode 100644 index 00000000000..324b70e075f --- /dev/null +++ b/src/renderer/src/store/slices/agent-status-turn-started-at.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest' +import { createTestStore } from './store-test-helpers' + +const PANE = 'tab-1:11111111-1111-4111-8111-111111111111' + +describe("the host's turn start on a renderer status entry", () => { + it('lands on the entry from the host timing and follows each host write', () => { + const store = createTestStore() + store + .getState() + .setAgentStatus(PANE, { state: 'working', prompt: 'go', agentType: 'claude' }, undefined, { + updatedAt: 1_000, + stateStartedAt: 1_000, + turnStartedAt: 900 + }) + expect(store.getState().agentStatusByPaneKey[PANE]?.turnStartedAt).toBe(900) + + // The same prompt sent again: the state never left working, the host stamped a new turn. + store + .getState() + .setAgentStatus(PANE, { state: 'working', prompt: 'go', agentType: 'claude' }, undefined, { + updatedAt: 2_000, + stateStartedAt: 1_000, + turnStartedAt: 1_900 + }) + expect(store.getState().agentStatusByPaneKey[PANE]?.turnStartedAt).toBe(1_900) + }) + + it('keeps the stamp behind an unchanged state when a writer carries none, and drops it on a state edge', () => { + const store = createTestStore() + store + .getState() + .setAgentStatus(PANE, { state: 'working', prompt: 'go', agentType: 'claude' }, undefined, { + updatedAt: 1_000, + stateStartedAt: 1_000, + turnStartedAt: 900 + }) + // A renderer-side OSC repaint has no turn clock of its own. + store.getState().setAgentStatus(PANE, { + state: 'working', + prompt: 'go', + agentType: 'claude', + toolName: 'Bash' + }) + expect(store.getState().agentStatusByPaneKey[PANE]?.turnStartedAt).toBe(900) + + store.getState().setAgentStatus(PANE, { state: 'done', prompt: 'go', agentType: 'claude' }) + expect(store.getState().agentStatusByPaneKey[PANE]?.turnStartedAt).toBeUndefined() + }) +}) diff --git a/src/shared/agent-status-ipc-payload.ts b/src/shared/agent-status-ipc-payload.ts index a15282b0018..68398a6d0de 100644 --- a/src/shared/agent-status-ipc-payload.ts +++ b/src/shared/agent-status-ipc-payload.ts @@ -55,6 +55,10 @@ export type AgentStatusIpcPayload = ParsedAgentStatusPayload & { evidenceObservedAt?: number /** Timestamp (ms) when the current state first appeared for this pane. */ stateStartedAt: number + /** When the main agent's current turn began, stamped by the hook server from the main agent's + * own turn-opening event. Optional: old hosts and turns opened unseen omit it, and readers fall + * back to `stateStartedAt`. */ + turnStartedAt?: number orchestration?: AgentStatusOrchestrationContext providerSession?: AgentProviderSessionMetadata /** Resume identity update only; the status-shaped fields are transport placeholders. */ diff --git a/src/shared/agent-status-types.ts b/src/shared/agent-status-types.ts index acc7e4f4255..5a9d34ae7d3 100644 --- a/src/shared/agent-status-types.ts +++ b/src/shared/agent-status-types.ts @@ -95,6 +95,9 @@ export type AgentStatusEntry = { stateStartedAt: number /** `updatedAt` of the write that switched into `state`; see AgentStateHistoryEntry.observedAt. */ stateObservedAt?: number + /** When the main agent's current turn began, as the hook server stamped it. Absent from old hosts + * and writers without a turn clock; readers fall back to `stateStartedAt`. */ + turnStartedAt?: number agentType?: AgentType /** Provider model currently used by this session. */ model?: string diff --git a/src/shared/native-chat-ask-row.ts b/src/shared/native-chat-ask-row.ts index 11900c5c4ea..6d92f244f8e 100644 --- a/src/shared/native-chat-ask-row.ts +++ b/src/shared/native-chat-ask-row.ts @@ -9,6 +9,7 @@ import { pairToolBlocks } from './native-chat-tool-fold' export const NATIVE_CHAT_ASK_ROW_COPY = { awaiting: 'Awaiting user input:', + awaitingUnnamed: 'Awaiting user input', asked: 'Asked:', questionCount: '{{value0}} questions' } as const From c49388cd33917a828b63997537c9710b4f1aec3a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:39:49 -0700 Subject: [PATCH 07/83] fix(native-chat): Stop is there from the moment a message is sent (#23026) * refactor(native-chat): remove the unused terminal handoff No client ever called agentSession.requestHandoff or mounted the handoff chrome. Delete the handoff coordinator, the terminal-owner runtime, the proof write path and the unmounted UI. Keep agentSession.handoffStatus, which released desktop clients read for worktree activation, and let records an older build left mid handoff reconcile through the ordinary restart and recovery paths. * fix(native-chat): never let the pre-stop snapshot hold a chat's stop Eviction now drains delivered events before quit's resume-offer snapshot. An unbounded wait there sits ahead of the provider stop, so a sink whose journal write stalls kept the child running until the step deadline aborted the eviction. The offer is advisory: bound the drain and stop the child regardless. Co-Authored-By: Claude * refactor(native-chat): drop helpers only the terminal handoff called `claudeAuthEnvCarriedForward`, `isPathWithinDirectory` and `queryWindowsProcessRowsFresh` lost their last caller with the handoff. The fresh-scan tests now go through `queryWindowsProcessDescendants({ fresh: true })`, the teardown path that still depends on that contract. Co-Authored-By: Claude * docs(native-chat): stop citing the removed handoff in lifecycle comments Six comments still named the handoff coordinator, a handoff suspend, or a terminal-owned session as live participants in the flows they describe. Co-Authored-By: Claude * test(native-chat): type the stalled snapshot drain without a cast Co-Authored-By: Claude * test(native-chat): pin that a start dead before proving owes no settlement The removed restart handoff test pinned this branch; nothing else did. Co-Authored-By: Claude * fix(native-chat): keep the owner-status read behind an in-flight attach The handoff removal dropped the per-session queue from `handoffStatus`, so a read landing mid-start reported the reservation (no owner) instead of the settled chat owner, and shipped desktop clients blocked worktree activation on it. The read is queued again, as it was before the removal. Co-Authored-By: Claude * refactor(terminal): remove the agent-session PTY write gate The gate only refused a write when a PTY had been bound to a chat session, and the only code that ever bound one was the terminal handoff this branch removes. With it gone, every admit/readmit returned "admitted" unconditionally, so the checks on the renderer write path, the runtime controller backstop, terminal.send, agent prompts, preview input and orchestration pointers, the refusal fields on terminal.send and worker-start receipts, the plugin and CLI refusal copy, and the adopted-pane orchestration routing could no longer run. Ordinary writes take the same path in the same order as before. Co-Authored-By: Claude * refactor(native-chat): drop the transcript helpers only the handoff called appendLegacyTranscriptMessages fed the terminal transcript catch-up and proveClaudeTranscriptBranch backed the terminal owner's exit proof. Both lost their last caller with the handoff. Their tests now go through the live entry points instead: the roster bounds through the legacy import, the pinned-read and growth tests through the ancestry replay the history window uses, and the marker rules through the string proof in their own file rather than the session-file resolver's. Co-Authored-By: Claude * fix(native-chat): stop calling a starting chat "mid-handoff" A send refused because the chat's owner is not settled showed "The session is mid-handoff ()." in the composer. With the handoff gone, the stages that reach it are a chat that is still starting, or one whose previous agent process has not yet been confirmed stopped. The message now says which of the two it is. The refusal code is unchanged. Co-Authored-By: Claude * test(native-chat): type the stand-in roster decoder without a cast Co-Authored-By: Claude * refactor(codex): name the pinned rollout lookup for what it does With the terminal handoff gone, the module named codex-tui-rollout-proof holds only the pinned rollout lookup that structured Codex launches use to resume a thread, so the name described code that no longer exists. Rename the module and its options type. Also drop a mobile allowlist assertion that pinned the removed agentSession.requestHandoff method, which no longer exists to allow. * refactor(native-chat): type the owner-status reply as the host sends it The handoffStatus reply type still listed the terminal handoff's fields and states (terminal placement, host label, proof retry, queued and waiting phases, the to-terminal direction). No host writes them any more and the only client reader parses the reply as unknown, so they described nothing. The reply on the wire is unchanged. * refactor(native-chat): normalize terminal-handoff lease values once at decode Nothing in this build writes a terminal owner (`runtimeKind: 'tui'`) or the handoff's `preparing` / `old-owner-stopped` stages, but the in-memory types still admitted them, so readers across the host kept branches for values no path produces and the compiler could not point at them. The store now validates the on-disk shape, which still accepts those values so an older record is not quarantined, and maps them once while parsing: - `preparing` and `old-owner-stopped` become `recovering` - a `tui` lease becomes `native`; when it records a process it also becomes `conflicted`, the claim every build probes but never stops. A plain native owner would be stopped by restart recovery, here and in older builds. Revisions are taken over the normalized state on both sides of every compare, and the mapped record reaches disk with the store's first transaction, the same way the tab-id backfill does. The in-memory types narrow to what this build writes, and the branches that existed only for the removed values go. Structured-worker identity keeps its verdict for a former terminal owner by refusing a conflicted claim rather than a non-native kind. * refactor(native-chat): stop threading the owner kind through a reservation A reservation only ever names a native owner now, so the request no longer carries a kind and the reserved lease records `native` directly. The attach params keep `runtimeKind`: agentSession.ensure and create accept it, and the operation fingerprint stored in the ledger covers it. * test(native-chat): pin the legacy-lease rewrite with a transaction that changes nothing else Hiding a tab also committed the visibility index, so the no-op transaction wrote the file even when its open-time revision was wrong. Committing the index first leaves the pending rewrite as the only reason to write. * fix(native-chat): name a chat write by its target, not the owner generation A write carried the fence of the last frame the pane read, and the host refused it unless that fence was still current. An idle release and the restart after it each move the fence, and the release publishes nothing, so a send after a release was refused "Expected runtime fence 1; the session is at 3", and a Stop queued behind a cold start was refused as stale. Every write already names what it acts on: a send its conversation, a cancel its turn, a prompt answer its item revision, a rewind its epoch; an option is last-writer-wins. So admission stops comparing the client's fence, and the rebase that papered over one restart (admitAtResumedFence, resumedFromFence) goes with it. The writer-lease check stays, and so does the attach's compare-and-swap. Frames now stamp the fence read when each frame is sent instead of a copy each subscriber kept, which went stale on the same release. * fix(native-chat): every journal append reaches the chats that are open A journal write and its delivery to open readers were two calls, and some writers made only the first. A failed start whose lease could not be handed back, a provider revision with no frame behind it, and eviction's settlement were all journaled without reaching an open chat. A journal handle now reports every durable change, and the host's session map binds that report to the session's readers when the handle is set. Writers no longer publish what they append; the per-writer publish calls are deleted. * test(native-chat): an epoch replacement reaches the open chat * test(native-chat): each row reaches an open chat once, and a live handle enters only through the map * test(native-chat): give the legacy-lease store test a tab id so the backfill cannot supply its rewrite The seeded record had no surface tab id, so the next open backfilled one and that rewrite alone made the no-op transaction write. The test passed with the legacy-lease rewrite signal removed. * test(worktree-activation): restore the OMP surfaced-agent resume test The handoff removal deleted it alongside the terminal-owner tests, but it covers the surfaced-PTY block that still guards resume, including an agent whose ownership is unknown. * perf(native-chat): a publish behind a delivered commit reads nothing Each commit now delivers itself, so the publish a provider frame still sends afterwards found every reader caught up but still read rows and rebuilt the timeline for each one. A caught-up reader now skips the read. * test(native-chat): state why the teardown test's fake journal is safe to cast * docs(native-chat): say mutation admission checks only the writer lease * docs(native-chat): drop the send rebase from comments that still described it * fix(native-chat): a message is accepted, then delivered A send to a chat with no running agent restarted the agent inside the send call, before the message was recorded, so the client waited for the whole start and a failed restart refused the message. Claude held prompts sent during startup, and those could settle as "unconfirmed". A send is now accepted inside the session's serialized queue: one ledger row and one submission row marked handoverRecorded, published, answered pending. A per-session delivery loop exists while a message is queued. It starts the agent through the same serialized attach a hold uses, waits outside the queue for a Claude child to prove its start, and hands the oldest queued message over as its own serialized step, writing dispatch{pending} before the adapter call. A start it needed and did not get writes one error-tone row and rejects every queued message with the same words; a start Stop cancelled writes none. Settlement follows from the rows. A queued message is provably unwritten, so a close, an eviction or an exit rejects it. A handed-over message stays in doubt. A queued row at or below the sequence a handle found when it opened was left by an earlier process and is rejected at open, with no latch. Stop withdraws queued messages with no writer lease and no fence. An attach failure keeps the conversation open, and the attach adopts its journal. Owed work counts the loop and queued rows. A compaction or rewind found prepared when a conversation opens was started under a child this process no longer has, so the open settles it rather than leaving it to refuse every send until a view attaches. The open cursor is scoped to its epoch, because sequences restart when an epoch is replaced. Deleted: restart-before-admission, recordFailedRestart, the fence rebase, Claude's startup gate, the attach's forget on failure and its own crash boundary. Clients without agent-session.accepted-send.v1 get their reply held until the handover; the desktop and paired desktop lists advertise it. * fix(native-chat): settle queued messages only for the child that ended A child that proved its start and then exited before its message was handed over left the message queued: the exit settlement returned early when nothing else was in flight. Delivery then started another child for it, and a child that died the same way started another, without end and without a row. A retried settlement for an earlier generation, run by the attach that delivery started, did the opposite: with that generation's turn unfinished it rejected the message queued for the child being attached. The settlement now takes the rejection for queued messages from its caller. The unexpected exit and the eviction pass one, and it applies even with no other work in flight; the retry for an earlier generation passes none. * fix(native-chat): an adoption that fails to import keeps the conversation open The attach now writes into the conversation's own open journal, but a failed transcript import still closed it as if it were the attach's provisional one. The conversation stayed indexed with a closed journal, so every later send answered "could not be recorded" and every attach failed again until the app restarted. The import now closes only a journal the attach opened for itself. * perf(native-chat): the recovering open reads the journal once Every conversation open now goes through the recovering open, including the read restore of every chat at startup, which used to replay its journal once. The recovering open replayed it twice: once to probe it and again inside the open. The probe is now handed to the open as its load. * fix(native-chat): an attach that fails after indexing its child leaves no child behind A failed attach now keeps the conversation open, but a failure after `onAttached` indexed the child (the rewind or compaction recovery, or the attach's own success record) left that entry claiming a child the failure path had already released. The next send found the phantom, skipped the start, and wrote at a fence the journal had moved past, so the message stayed queued for good. The entry now drops the released child and its event sink, and follows the record's fence, as a failure before indexing already did. * fix(native-chat): a withdrawn message shows no error, and a rejection outlasts the send's answer The error strip for a message the host accepted and then did not deliver matched the entry before the outbox reconciled, so a Stop's withdrawal, which the reconcile drops, showed "Orca could not send your message" with nothing to retry. It now reads the reconciled entry. A rejection the journal records before the send's own pending answer lands is final as well: that answer no longer puts the entry back to dispatching with no Retry. * fix(orchestration): a structured worker whose agent outlasts the preamble wait is left unknown, not torn down The preamble waits for its submission to be delivered while the worker's agent starts. When that wait ran out it threw operation_unknown, and the failed-start teardown then closed the session, which rejected the very preamble the host was about to deliver. It now reports a turn start nobody observed yet: the worker is start-unknown with its session kept, the host delivers the preamble when the agent starts, and the worker's report settles the dispatch as for any unobserved start. The receipt no longer suggests reading a screen a structured worker lacks. * fix(native-chat): a message rejected while its chat was closed reads as not sent A remount reads an entry it left dispatching as unconfirmed. When the journal had rejected it meanwhile, as a failed start or a quit now does, the reconcile left it unconfirmed: it blocked every later message behind a Retry and no reason, and the delivery probe, seeing the journal already answered, never ran. The reconcile now settles it as rejected like a dispatching one. * test(orchestration): name why the readiness settlement fakes are cast * fix(native-chat): keep each pane's own fence on frames so a failed restart is not resent * docs(native-chat): drop the fence from the admission the send effects run behind * docs(native-chat): give the fence move on release the reason that still holds * docs(native-chat): stop citing a write fence check in launch and mailbox comments Three places still gave the removed fence check as a reason: the launch replay said admission puts the ledger ahead of the fence, the launch surface said a send must name the lease it was admitted against, and the direct-mailbox path said the lease fence decides whether delivery is safe. Admission now checks only the writer lease. * refactor(native-chat): the provider child is its own record A conversation now outlives any number of provider children, so the child is one record on the conversation's entry instead of five loose fields beside its journal. It is written in one place: indexed only once an attach has fully succeeded, and ended through one function that an exit, a failed re-attach, a Stop and an eviction all share, matched on the child's generation and fence. - A failed attach writes no child, so there is nothing to unwind: the field unwind and the fence patch after it are gone. - Conversation writes read the record's fence, the way mutation admission already does; a child's own writes use its fence. The four stored-fence patches, and the settlement retry's overwrite of the conversation's fence, are gone. - The owed wind-down is its own tombstone, carrying the child it is owed for, and is no longer dropped when an attach replaced the whole entry. - Stop on a child still proving its start stops only the child: its lease goes back and the chat is told it is idle, but the journal, the holders and the readers stay. Close is that stop plus the conversation's close. - The settlement retry uses the conversation's own journal, opened through the host's one open. * fix(native-chat): the delivery loop alone settles a message its start or child failed A queued message was settled by whichever path happened to end the child first: the loop, the unexpected exit, eviction's work settlement, the open's leftover rule, and the startup branch that rejected every pending row. That gave two failure rows with different tones for one start, a loop that could hand over to a different child than the one it waited on, and a Claude start that died while starting reading unlike every other failed start. - The loop remembers the child it waited on. At handover, if that child is gone or replaced, it reads how it ended: a Stop continues; anything else writes one failure row and rejects every queued message with the same words, then stops. A child still starting whose start the adapter says did not land fails the same way. The exit, eviction and the settlement retry only settle the handed-over and legacy rows of the child that ended. - One failure row, always an error, keyed by the start. A start a view began that dies with nothing queued writes the same row through the same builder, so a second report revises it. - The open no longer rejects leftovers; the loop's first step does, and the open wakes it. - `awaitStarted` answers why a start did not land, so the row says it even when the loop sees the failure before the exit is processed. - Quit closes every conversation the way closing a chat does: what is still queued is rejected as closed, with or without a child, and a start the loop already has in flight is waited for so the child it produces is stopped rather than left behind. * refactor(native-chat): a stopped child ends on the one reading of its stop The eviction step reads a stop's result through `stopAgentSessionProviderRoot` and hands that verdict to the child's ending, so the host never forms a second view of whether the root is gone. Every ending carries it: a stop's comes from that reading, an exit's root is gone by definition, and a failed re-attach passes what its release saw. The end-of-child record can therefore also carry a stop whose root was not seen to go, which nothing ends on yet. * feat(native-chat): the host says it accepts a send before any agent has it The host now lists agent-session.accepted-send.v1 among its own runtime capabilities, the same string capable clients already send. A client can then tell a host that answers a send at acceptance, and admits a Stop with no writer before a turn starts, from an older one that still restarts the agent inside the send. Additive: an older client ignores a capability it does not know. * refactor(native-chat): an attach never opens a journal of its own The attach adopts the conversation's open journal, which outlives it, so it no longer opens one for a direct caller either. That leaves nothing for a failed adopted import to close, and the flag that told the two cases apart is gone. Tests that attach without a host open the conversation the way a host does. * fix(native-chat): a moved fence resends nothing on a host that accepts first The outbox treated any fence change as a new owner: it dropped the answer of a send in flight, queued that send to go out again under the same id, and unblocked a refused head. On an older host that is how a send the restart refused, unrecorded, gets another try. On a host that records every send before it starts an agent, a fence moves because that start ran, so the same rule resent into every failed start. With a fence stamped on every frame, that became a loop. The outbox now reacts to a fence change only when the host has not advertised that it accepts a send before any agent has it. On such a host, only a Retry or a new send goes out, and a failed start reaches the client as a rejected message it keeps with its Retry. Against an older host, or before one has answered, the outbox behaves as it did. Desktop and paired web share this hook. * refactor(native-chat): a child's end says whether the user or the host stopped it The end-of-child record's cause now tells a user's Stop from the host stopping the child for a cause of its own: `user-stop` and `host-stop` replace `stop`. The delivery loop goes on after a user's Stop, as before, and fails the start it was waiting on after a host stop, with the one error row and every queued message rejected, in the stop's reason when it gave one. The reason stays description only. Stop passes `user-stop`; nothing passes `host-stop` yet. * fix(native-chat): a chat whose only work is a queued message is not offered for resume A message accepted while the agent was starting counts as working in the chat, and quit rejects it as never sent. The teardown snapshot read the same working rule, so a relaunch offered to resume a chat whose agent never had the message. The snapshot now reads only what was handed over. * test(native-chat): type the queued-message fixtures in the resume-offer tests * fix(native-chat): a start that dies while a message waits on it is that message's failed start Opening a chat's tab starts an agent for the view, and a send accepted meanwhile waits on it. When that start died, its exit wrote the start's error row and left the message queued, so the delivery loop started a second agent into the same failure and wrote a second row. A child's end now records where the conversation's journal stood, and the loop settles a message accepted before a failed start ended with that start: one row, under its key, and no second start. A message sent after the failure still gets a fresh start. * docs(native-chat): say what an attach's open conversation and unconfirmed ids are now * test(native-chat): pin what a failed start settles, and what a resume offer names A view's child that dies while a sent message waits settles that message only when it died starting and no child has taken its place: a proven child's crash, or a second start since, gets the message delivered. The resume offer names the handed-over message, never a newer one still queued. * test(native-chat): the failed-start pins fail on what the message became, not on a timeout * test(orchestration): the preamble's host stub is typed, not cast The preamble send now takes only what it reads of the host, the send, the settlement wait and the record's fence, so its test builds that host with real types instead of `as never`. * fix(native-chat): a Stop that names no turn stops what the conversation has in flight Between handing a message to the agent and the agent opening its turn, there is no turn id a client could name, so a Stop in that gap was refused as "already finished" while the agent went on to answer. A cancel's turn id is now an optional precondition instead of its target: with none, the host withdraws what is queued and, when the journal still reads working, asks the adapter to stop whatever the child has in flight. Claude's interrupt is session-scoped, so it is guarded by fence and acquisition generation rather than a turn identity. Codex interrupts the turn its latest turn/start answered with until the journal shows one. A cancel that names its turn behaves exactly as before. * fix(native-chat): Stop is there from the moment a message is sent The composer showed Stop only once the agent had opened a turn, so for the second or two after a send the chat read "thinking" with no way to stop it. Against a host that takes a Stop naming no turn, Stop now shows whenever the chat reads working (a turn, a queued message, or a handed-over one still unanswered) or this client still has a message on its way. Pressing it, or Escape, first drops every outbox entry the journal does not hold yet, so nothing goes out after the Stop, then sends the conversation-wide cancel. A send already on its way reaches the host ahead of the cancel, which withdraws it there. Against an older host Stop still needs a running turn. The unconfirmed-send probe moves into its own hook so the outbox hook stays in budget. * fix(native-chat): Stop before a turn is gated on its own host capability A host that accepts sends first (agent-session.accepted-send.v1) can still predate the cancel that names no turn and would refuse it as invalid, since clients and hosts ship independently. Hosts that take that cancel now advertise agent-session.conversation-stop.v1, and the renderer shows Stop before a turn opens, and sends the no-turn cancel, only to a host advertising it. Every other host keeps a Stop that needs, and names, a running turn. The host capability probe the accepted-send hook used is generalized so both read one path. * test(native-chat): a build advertises conversation stop exactly where its cancel may name no turn * fix(native-chat): a view never restarts a chat whose last start failed A Claude chat whose CLI exits during startup left one red row per start, and every time a view bound to it (the chat opening right after its create died, or the user switching back to it) the hold started the CLI again, so the same launch-failure row repeated. Only a send retries a failed start now, the same rule provider-exit recovery already applied; the rule lives in one predicate the hold, exit recovery and the delivery loop share. * test(native-chat): start the child the loop waits on with an attach, not a second view A view no longer starts a child whose last start failed, so the R2 case that waits on a child started since the failure now gets that child from a client attach, the one non-send starter left. * fix(native-chat): settle a gone generation's turn wherever a conversation opens A send that opens a chat this process had not read yet (after a crash, from a phone or the CLI) went through the delivery open, which never settled what the dead generation left running; only the read restore and a successful acquire did. When the send's start then failed, the turn stayed running for every reader. The settlement now runs in the one journal open, at the crash boundary, for every opener except an acquisition, which settles from the evidence it read before its reserve; the read restore's separate step is gone. * test(native-chat): prove the next child's start settles the turn an earlier child left The R1 case lost its only settlement assertion when the latch it checked was deleted. It now seeds the running turn the earlier child left and asserts it ends at the exit's receipt, with the exit's row, before the message is handed to the new child. * test(native-chat): count a failed start's rows by row, not by text Comparing the set of texts passed when two different rows carried the same words, which is the duplicate the test exists to catch. * test(native-chat): give the failed-start and stale-turn waits a loaded runner's budget * test(native-chat): pin the open's and the send's start and row counts, however the view binds Opening a fresh chat whose starts fail makes one start and one row, with two views bound before or after the create's child died; one send makes one more of each. * fix(native-chat): settle a gone generation's turn at every open but an acquisition's The journal open skipped the settlement whenever the lease read reserved or live, to leave an acquisition's own open to the acquisition. But a lease a crashed process left in recovery also reads live, until the next acquire resolves it. A send that opened such a chat, from a phone or the CLI after a crash on a host that could not prove the old owner gone, skipped the settlement; when its start then failed, the dead turn stayed running for every reader. The acquisition now says it is the opener, and every other open settles, whatever the lease still claims. * test(native-chat): hold the create's start open until the views bind The "view binds while the create is still starting" case gave the create a 300 ms head start and asserted the views bound before it died. On a loaded runner the holds took longer, the create's exit landed first, and the case failed its own precondition. The create's initialize now waits on a gate the test releases once the views are bound. * fix(native-chat): Stop reads the one working rule every session list reads While Claude retries a rate-limited request it never echoes the message, so no turn opens: the sidebar read Working from the unanswered send while the composer showed Send. The chat's working state, the host's session-list status and the host's no-turn Stop check now call one shared rule instead of three copies. * test(native-chat): a rate-limit retry pins only that no turn opens, not how its rows are kept * fix(native-chat): Stop leaves a message waiting on its Retry, and does not show for one A send that failed holds the queue until the user retries it, and one the host restarted under is parked the same way. Stop counted both as still on their way, so it showed in an idle chat and could never go away, and pressing it dropped the failed message along with its Retry. * test(native-chat): the chat's Stop and a session list read the main agent alike over their own copies The chat reduces its stream and a list reads the status feed. Driven through the real host for a rate-limit retry with no turn, a subagent still running after the main turn, and the handed-over child exiting. * refactor(mobile): the chat reads the main agent's working state through the shared rule Behaviour is unchanged: the same two terms, now from the one function the host projection and the desktop chat read. * fix(codex): a Stop naming no turn never interrupts an earlier turn It fell back to the id an earlier turn/start answered with when the latest start went unanswered, or when the journal showed a compaction Codex had not started, and reported that as stopped. * fix(native-chat): a Stop naming no turn never says a turn had already finished When the provider found nothing left to stop, for instance a turn that ended between the host's check and the interrupt, the chat got "The provider had already finished this turn." for a turn the Stop never named. It now ends quietly, as a Stop with nothing in flight does. * fix(native-chat): one Stop the host could not settle no longer refuses every later one A Stop naming no turn has one operation key per session. When the host could not settle one, it answered every later Stop under the same id as unknown until the id expired. Once the host says so, the next press is a new Stop; transport doubt still replays the same id. * refactor(native-chat): drop the composer's second error formatter After the merge with main, every chat write in the composer path reports its failure as a typed outcome worded by the refusal-notice table, so the send's catch sees only a local throw. The {code, message} formatter this branch added for it has no payload left to format, and its claim to be the one way a chat words a failure is no longer true. The composer send is main's again. * test(native-chat): pin the reason on a message rejected while its chat was closed The reopen test checked only that the message reads as not sent; it now also checks the Retry row carries the host's reason. * test(native-chat): read Stop operation ids without a cast * fix(native-chat): a Stop whose answer was lost no longer swallows the next one A Stop that names no turn has one operation key per chat. When its answer was lost in transit, the chat kept the id, so every later Stop replayed it; the host answers a replay as already handled, so for up to a day Stop stopped nothing. The id is now dropped once the call settles, however it settles. A second press while the first is still on its way still shares its id. * refactor(native-chat): a Stop naming no target keeps its operation id only for its own call The chat kept each write's operation id per payload across calls, and dropped it only on some settle paths. That is right for a write naming what it acts on, but a Stop naming no turn, and a stop of every background task, share one payload with every later one, so any path that kept the id made the next Stop replay as already handled and stop nothing. One path was still open: an answer that arrived after the chat moved to a new fence. Whether a write names its target is now decided once, before its id is picked. One that names none keeps its id only while its call is in flight, so a press made meanwhile joins it, and releases it when the call settles, however it settles. The release runs only while the key still holds that call's id, so a joined call settling late cannot drop a newer one's. This replaces the per-path exceptions for a thrown call. * test(native-chat): read the Stop fences without a cast * test(native-chat): pin the new id for a named cancel the host could not settle After the Stop naming no turn moved to a per-call id, the only test of the unknown-refusal release was gone, and the half that stays, for a cancel naming its turn, could be removed with every test green. * fix(native-chat): a Stop pressed after a new message stops it, even while the last Stop is unanswered A Stop naming no turn shared its operation id with any press made while it was still in flight. The host runs a chat's writes in order, so a message sent between two presses was accepted after the first Stop ran, and the second press replayed that Stop as already handled and left the message running, although the chat had already withdrawn it from the outbox. A write naming no target now gets a new id on every press and is never kept, so each Stop acts on whatever is running when the host reaches it. A write naming its target keeps its id exactly as before. A double press can ask the provider to stop the same turn twice, which it tolerates. * fix(native-chat): Stop no longer blinks off as Claude opens the turn for a message Claude's echo of a sent message both answers the send and opens its turn. The echo settled the send first, so the host published the message as answered one frame before the turn it opened, and for that frame the chat read nothing running: Stop turned back into Send, and Working blinked off in every session list, for tens of milliseconds on each turn. The echo now settles the send after the turn it opens has been emitted, so the running turn is published first. * fix(native-chat): a message a Stop withdrew comes back to its sender's composer A Stop withdraws every message the host holds but has not run, and S also drops the ones this client had not handed over yet. Either way the message left the chat and its text survived only in a hidden journal row and the in-memory ArrowUp history. The sending client now puts the withdrawn text and images back in that pane's composer, after whatever is typed there. Withdrawn is read from the rejection reason through one shared check, which the outbox reconcile now uses too. The composer is written before the entry leaves storage, so a failure between the two repeats the text instead of losing it, and an entry storage no longer holds is never given back again, so a replay, a second view or a remount restores it once. Only this client's outbox holds the entry, so other viewers still see the message disappear. A failed Stop withdraws nothing on the host and gives nothing back. * fix(native-chat): withdrawn text put back during an IME composition is not lost While the IME owns the field, the composer ignores a programmatic draft, and the next composed keystroke wrote the draft without the restored text, after its outbox entry had already been dropped. The composer now holds text appended mid-composition, keeps it in the cache after each composed write, and shows it once the composition settles, the way attachments that land mid-composition already wait for it. * test(native-chat): pin that only a withdrawn message comes back to the composer * test(native-chat): set up the composer's window API for every describe in the composition-race file * docs(native-chat): note that the withdrawn check reads the legacy reason until a typed category lands * test(native-chat): pin that text put back mid-composition shows once, even beside a mid-composition clear * fix(native-chat): land a late settlement from a streamed turn's end after that turn's rows A settlement that says a streamed turn ended waits for the session's event sink to drain before writing its dispatch row. The journal reducer still refuses to overwrite an accepted or rejected send. * fix(codex): settle a send from the end of the turn Codex answered it into The turn/start answer names the turn that holds a send. The send's echo entry now keeps that binding, in memory only. If the bound turn is interrupted without echoing the send, the send is withdrawn: Codex clears a turn's pending input on interrupt, so the model never saw it. If the turn fails first, the send is rejected in Codex's words. A completed turn settles nothing, since Codex records pending input when it finishes and the echo is still due. An answer read after its turn already ended is settled by that end. The echo is still the acceptance and carries the item key. * test(codex): a send settles from the end of the turn Codex answered it into The fake Codex keeps 0.157's turn bookkeeping, and can deliver the turn/start answer after turn/started or after turn/completed. The tests cover: - a Stop before any echo withdraws the send, and the working rule reads idle; - a steered follow-up is withdrawn when the turn is interrupted; - a failed turn rejects the send in Codex's words; - a completed turn leaves the send to its echo; - a normal echo and a late echo; - two steered sends in one turn; - an answer read after the turn ended; - a timed-out answer; - child-thread turns; - how a binding dies. * refactor(native-chat): drop the stream flush before a late turn-end settlement Nothing reads the order of a dispatch row against the turn's terminal row: the reducer keeps a settled send terminal and the working state is derived from both. The echo acceptance on the same path never waited either, and the wait could drop the settlement on a failed sink barrier. * fix(codex): settle a failed turn's sends at its end, not at its error Codex keeps a failed turn's pending input and records it after the error frame, before turn/completed. Settling at the error rejected a steered follow-up the model had in fact received, so a Retry would send it twice. * docs(codex): say a completed turn echoes what it took before it ends Codex records a completed turn's pending input before `turn/completed`, so a bound send that turn never echoed is left for recovery, not awaiting an echo. The comments and one test title said the echo was still due. * test(codex): settle a send whose answer is read after its turn failed or completed A failed turn that ended before the answer rejects the send in Codex's words, once; a completed one leaves it admitted and still armed for its echo. * refactor(codex): read a failed turn's reason with the typed thread-fact reader * fix(native-chat): a Stop that names no turn and ends nothing says why The host sends a Stop naming no turn to the agent only while the chat reads working. When the agent ended nothing, the Stop wrote no row, so it looked ignored. It now writes one: Stop could not reach the agent, in the agent's own words when it refused the interrupt. * fix(codex): hold a cold send until Codex opens its turn, and stop the turn it opened Codex answers turn/start before it opens the turn, and refuses an interrupt until then. A Stop queued behind a cold send ran in that gap, named the answered turn, and was refused. The send's handover now lasts until Codex opens that turn, or provably will not: the turn ended, the primary thread stopped running, or the child ended, bounded by the turn/start deadline. A steered send, whose turn is already open, does not wait. A Stop naming no turn now interrupts the turn the journal shows, else the primary-thread turn Codex reported started and not yet ended. The per-start answered id is gone: it was never cleared at a turn's end. * fix(native-chat): give back a send already on its way only when the host withdraws it Stop took the in-flight send out of the outbox and put its text back in the composer at once. The send still landed ahead of the Stop, so the chat read working for a moment before the host withdrew it, and a send the agent had already taken came back as well. The in-flight send now stays until the host answers it, and the withdrawn-message restore gives it back from that answer. * refactor(native-chat): read a Stop's withdrawal through the rejection classifier dispatchWasWithdrawn matched the legacy reason string. It now asks the classifier, which reads the typed fact first and keeps that string only as its own fallback, so a withdrawal written as a fact with a sentence is still given back to the composer. * fix(native-chat): a Stop Codex took but Orca could not confirm is not reported as reaching nothing When Codex acknowledged the interrupt but Orca could not verify the turn's processes ended, a Stop naming no turn wrote "it had no turn running to stop", though the turn then ended as interrupted. The adapter now says the Stop was taken but unconfirmed, and the row says Cancellation was not confirmed. * fix(codex): a held cold send never delays closing the chat or quitting A cold send's handover waits for Codex to open its turn, and that wait sat in the session queue ahead of the close and quit eviction, so either could wait out the 30 s request deadline. The host now releases those waits before it queues a close or starts quit teardown, and the adapter releases them when it is asked to close the child and on every exit, including one whose end publication is backpressured. * fix(native-chat): a refused Stop says the agent declined, and names it "Stop could not reach the agent" was wrong: the agent was reached and declined. The row now reads "Codex had no turn running to stop." or "Codex didn't stop: .", naming the chat's agent. * fix(codex): a Stop waits for the turn Codex answered to open; the send no longer does Codex answers turn/start before it opens the turn and refuses turn/interrupt until then, so a Stop naming no turn in that window was lost. The send's handover used to wait for the turn to open, and a close or quit needed its own release to get past that wait. Now only the Stop waits. A Stop naming no turn, finding no journal turn and no open one, reads the turn Codex answered the latest pending send into and has neither opened nor ended, and waits for it: bounded at 5 s, under the quit eviction budget, and ended by that turn opening or ending, the thread going idle or failing, or the child exiting. If the turn opened it is stopped; otherwise the Stop reports that Codex had no turn running. The send returns at Codex's answer, so a close or quit with no Stop pending is never delayed, and the release plumbing through the adapter, router, close and quit is gone. * fix(codex): the Stop's wait reads a stopped thread from the thread-facts reader main kept --------- Co-authored-by: Claude --- .../use-mobile-structured-agent-session.ts | 6 +- ...laude-structured-conversation-stop.test.ts | 101 ++++ .../claude-structured-prompt-ownership.ts | 37 +- ...claude-structured-rate-limit-retry.test.ts | 50 ++ .../claude/claude-structured-real-cli.test.ts | 74 +++ .../claude-structured-session-acquisition.ts | 8 +- .../codex-requested-close-turn-timing.test.ts | 2 + ...codex-structured-conversation-stop.test.ts | 94 +++ ...odex-structured-dispatch-admission.test.ts | 18 +- .../codex-structured-dispatch-echo.test.ts | 41 ++ .../codex/codex-structured-dispatch-echo.ts | 27 +- .../codex-structured-dispatch-test-support.ts | 51 +- .../codex/codex-structured-fast-mode.test.ts | 14 +- .../codex-structured-prompt-ownership.test.ts | 2 +- .../codex-structured-prompt-ownership.ts | 62 +- .../codex/codex-structured-provider-events.ts | 1 + ...odex-structured-session-adapter-fixture.ts | 13 + .../codex-structured-session-adapter.test.ts | 8 +- .../codex-structured-session-cancel.test.ts | 16 +- .../codex-structured-session-close.test.ts | 37 +- .../codex/codex-structured-session-close.ts | 2 + ...structured-session-options-catalog.test.ts | 2 + .../codex-structured-session-options.test.ts | 2 + .../codex/codex-structured-session-state.ts | 21 +- .../codex-structured-turn-cancellation.ts | 13 +- ...dex-structured-turn-end-settlement.test.ts | 33 +- .../codex-structured-turn-open-wait.test.ts | 147 +++++ .../codex/codex-structured-turn-open-wait.ts | 54 ++ .../structured-agent-session-adapter.ts | 20 +- ...-agent-session-claude-echo-working.test.ts | 146 +++++ ...ed-agent-session-conversation-stop.test.ts | 277 +++++++++ ...structured-agent-session-host-mutations.ts | 26 +- ...ssion-main-agent-working-agreement.test.ts | 229 ++++++++ ...structured-agent-session-mutation-plans.ts | 11 +- .../structured-agent-session-turns.ts | 76 ++- .../methods/structured-agent-session.test.ts | 3 + ...-session-codex-turn-end-settlement.test.ts | 117 +++- .../native-chat/NativeChatComposer.test.tsx | 2 +- .../native-chat/NativeChatComposer.tsx | 8 +- ...tiveChatStructuredSession.test-harness.tsx | 12 +- .../NativeChatStructuredSession.test.tsx | 27 + .../NativeChatStructuredSession.tsx | 19 +- .../native-chat/NativeChatView.test.tsx | 4 +- .../native-chat/native-chat-draft-cache.ts | 34 ++ ...structured-send-composition-clear.test.tsx | 86 ++- ...session-withdrawn-message-restore.test.tsx | 475 +++++++++++++++ ...agent-session-withdrawn-message-restore.ts | 76 +++ .../use-native-chat-composer-attachments.ts | 46 +- .../native-chat/use-native-chat-draft.ts | 53 +- .../use-structured-agent-session-mutate.ts | 23 +- ...-agent-session-outbox-unconfirmed-probe.ts | 77 +++ ...d-agent-session-outbox-withdrawal.test.tsx | 168 ++++++ .../use-structured-agent-session-outbox.ts | 93 ++- ...use-structured-agent-session-stop.test.tsx | 541 ++++++++++++++++++ ...tructured-agent-session-transport-state.ts | 10 +- .../use-structured-agent-session.ts | 31 +- ...-agent-session-accepted-send-capability.ts | 56 +- ...red-agent-session-host-capability.test.tsx | 53 ++ ...tructured-agent-session-host-capability.ts | 63 ++ .../agent-session-failure-words.test.ts | 17 + src/shared/agent-session-failure-words.ts | 5 + src/shared/agent-session-failure.ts | 3 + src/shared/agent-session-wire.ts | 4 +- src/shared/protocol-version.ts | 6 + .../structured-agent-session-params.ts | 6 +- ...ctured-agent-session-dispatch-rejection.ts | 10 + ...ctured-agent-session-main-agent-working.ts | 14 + ...d-agent-session-operation-identity.test.ts | 39 ++ ...ctured-agent-session-operation-identity.ts | 17 + ...ed-agent-session-outbox-stop-withdrawal.ts | 52 ++ .../structured-agent-session-owed-work.ts | 11 +- ...tured-agent-session-unanswered-dispatch.ts | 7 +- ...ss-version-agent-session-wire.unit.test.ts | 35 ++ 73 files changed, 3758 insertions(+), 266 deletions(-) create mode 100644 src/main/claude/claude-structured-conversation-stop.test.ts create mode 100644 src/main/claude/claude-structured-rate-limit-retry.test.ts create mode 100644 src/main/codex/codex-structured-conversation-stop.test.ts create mode 100644 src/main/codex/codex-structured-turn-open-wait.test.ts create mode 100644 src/main/codex/codex-structured-turn-open-wait.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-claude-echo-working.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-conversation-stop.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-main-agent-working-agreement.test.ts create mode 100644 src/renderer/src/components/native-chat/structured-agent-session-withdrawn-message-restore.test.tsx create mode 100644 src/renderer/src/components/native-chat/structured-agent-session-withdrawn-message-restore.ts create mode 100644 src/renderer/src/components/native-chat/use-structured-agent-session-outbox-unconfirmed-probe.ts create mode 100644 src/renderer/src/components/native-chat/use-structured-agent-session-outbox-withdrawal.test.tsx create mode 100644 src/renderer/src/components/native-chat/use-structured-agent-session-stop.test.tsx create mode 100644 src/renderer/src/runtime/structured-agent-session-host-capability.test.tsx create mode 100644 src/renderer/src/runtime/structured-agent-session-host-capability.ts create mode 100644 src/shared/structured-agent-session-main-agent-working.ts create mode 100644 src/shared/structured-agent-session-operation-identity.test.ts create mode 100644 src/shared/structured-agent-session-operation-identity.ts create mode 100644 src/shared/structured-agent-session-outbox-stop-withdrawal.ts diff --git a/mobile/src/session/use-mobile-structured-agent-session.ts b/mobile/src/session/use-mobile-structured-agent-session.ts index f04d78cc9a7..2fa5c2b2a96 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.ts +++ b/mobile/src/session/use-mobile-structured-agent-session.ts @@ -7,7 +7,7 @@ import { import { encodeNativeChatTranscriptIdentity } from '../../../src/shared/native-chat-transcript-retention' import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send' import { projectStructuredAgentSessionMessages } from '../../../src/shared/structured-agent-session-message-projection' -import { hasUnansweredStructuredAgentSessionDispatch } from '../../../src/shared/structured-agent-session-projection' +import { isStructuredAgentSessionMainAgentWorking } from '../../../src/shared/structured-agent-session-main-agent-working' import { activeStructuredAgentSessionTurnId, isStructuredAgentSessionThinking @@ -292,9 +292,7 @@ export function useMobileStructuredAgentSession(args: { loadingEarlier: loadingOlder, loadEarlier }, - isWorking: - turnId !== null || - hasUnansweredStructuredAgentSessionDispatch(state.submissions, state.fence), + isWorking: isStructuredAgentSessionMainAgentWorking(turnId, state.submissions, state.fence), turnId, turnIndicator, ...turnTiming, diff --git a/src/main/claude/claude-structured-conversation-stop.test.ts b/src/main/claude/claude-structured-conversation-stop.test.ts new file mode 100644 index 00000000000..840125853ba --- /dev/null +++ b/src/main/claude/claude-structured-conversation-stop.test.ts @@ -0,0 +1,101 @@ +// A Stop that names no turn, against the Claude adapter: the gap between writing a message and +// Claude echoing it back is exactly where no turn id exists yet, and the interrupt must still land. + +import { describe, expect, it } from 'vitest' +import { acquired, fakeClaude, USER_MESSAGE } from './claude-structured-session-test-support' + +function interrupts(claude: ReturnType): number { + return claude.connections[0]!.calls.filter((call) => call.subtype === 'interrupt').length +} + +async function written(claude: ReturnType) { + const adapter = await acquired(claude) + // No replay: the message is written and Claude has not opened its turn. + await expect( + adapter.dispatch({ + sessionId: 'session-1', + clientMessageId: 'client-1', + body: USER_MESSAGE, + fence: 7 + }) + ).resolves.toEqual({ state: 'admitted' }) + return adapter +} + +describe('Claude Stop that names no turn', () => { + it('interrupts a written message before its turn opens', async () => { + const claude = fakeClaude({ replayUuid: null }) + const adapter = await written(claude) + + await expect(adapter.cancelTurn({ sessionId: 'session-1', fence: 7 })).resolves.toEqual({ + cancelled: true + }) + expect(interrupts(claude)).toBe(1) + }) + + it('still refuses the placeholder a client used to name for that gap', async () => { + const claude = fakeClaude({ replayUuid: null }) + const adapter = await written(claude) + + await expect( + adapter.cancelTurn({ sessionId: 'session-1', turnId: 'turn-none', fence: 7 }) + ).resolves.toEqual({ cancelled: false }) + expect(interrupts(claude)).toBe(0) + }) + + it('interrupts a turn Claude opened on its own echo', async () => { + const claude = fakeClaude({ replayUuid: 'turn-T' }) + const adapter = await written(claude) + + await expect(adapter.cancelTurn({ sessionId: 'session-1', fence: 7 })).resolves.toEqual({ + cancelled: true + }) + expect(interrupts(claude)).toBe(1) + }) + + it('does nothing for another fence, or with nothing in flight', async () => { + const claude = fakeClaude({ replayUuid: null }) + const adapter = await acquired(claude) + + await expect(adapter.cancelTurn({ sessionId: 'session-1', fence: 7 })).resolves.toEqual({ + cancelled: false + }) + await adapter.dispatch({ + sessionId: 'session-1', + clientMessageId: 'client-1', + body: USER_MESSAGE, + fence: 7 + }) + await expect(adapter.cancelTurn({ sessionId: 'session-1', fence: 6 })).resolves.toEqual({ + cancelled: false + }) + expect(interrupts(claude)).toBe(0) + }) + + it('ends a turn that opens while the interrupt is on its way once, and the next send lands', async () => { + const claude = fakeClaude({ replayUuid: null }) + const adapter = await written(claude) + const connection = claude.connections[0]! + // The echo that opens the turn arrives after Orca wrote the interrupt, before Claude answers it. + claude.routes.interrupt = () => { + connection.handlers.onMessage?.({ ...connection.sent[0]!, uuid: 'turn-late' }) + return undefined + } + + await expect(adapter.cancelTurn({ sessionId: 'session-1', fence: 7 })).resolves.toEqual({ + cancelled: true + }) + expect(interrupts(claude)).toBe(1) + + delete claude.routes.interrupt + await expect( + adapter.dispatch({ + sessionId: 'session-1', + clientMessageId: 'client-2', + body: USER_MESSAGE, + fence: 7 + }) + ).resolves.toEqual({ state: 'admitted' }) + expect(connection.sent).toHaveLength(2) + }) +}) diff --git a/src/main/claude/claude-structured-prompt-ownership.ts b/src/main/claude/claude-structured-prompt-ownership.ts index e1c1aa371bf..01af8ec9fc0 100644 --- a/src/main/claude/claude-structured-prompt-ownership.ts +++ b/src/main/claude/claude-structured-prompt-ownership.ts @@ -90,6 +90,29 @@ function waitForClaudeDispatchAdmission( }) } +/** + * A Stop that names no turn: the conversation asked to stop whatever this child has in flight. + * Claude's interrupt is session-scoped, so there is no turn identity to check — only that this is + * still the child the host judged, and that it has a turn open or a written message whose turn has + * not opened yet (the gap before its echo, which no client can name). + */ +function cancelClaudeConversation( + session: ClaudeSession, + sessions: Map, + request: CancelInput, + timeoutMs: number | undefined, + onDispatchSettledLate: ClaudeLateDispatchSettlement | undefined +): Promise<{ cancelled: boolean }> { + const acquisitionGeneration = session.acquisitionGeneration + const isCurrent = (): boolean => + sessions.get(request.sessionId) === session && + session.fence === request.fence && + session.acquisitionGeneration === acquisitionGeneration && + ((request.resolveLiveTurnId?.() ?? session.translator?.currentTurnId ?? null) !== null || + session.dispatchWaiters.length > 0) + return cancelClaudeTurn(session, timeoutMs, isCurrent, onDispatchSettledLate) +} + export async function cancelClaudeStructuredTurn(input: { request: CancelInput sessions: Map @@ -106,10 +129,16 @@ export async function cancelClaudeStructuredTurn(input: { if (!prompt && session.startup.state === 'pending') { return { cancelled: false } } + const requestedTurnId = request.turnId + if (requestedTurnId === undefined) { + return prompt + ? { cancelled: false } + : cancelClaudeConversation(session, sessions, request, timeoutMs, input.onDispatchSettledLate) + } if (prompt && session.fence !== request.fence) { return { cancelled: false } } - const claim = prompt ? session.prompts.claimBound(prompt.itemId, request.turnId) : null + const claim = prompt ? session.prompts.claimBound(prompt.itemId, requestedTurnId) : null if (prompt && !claim) { return { cancelled: false } } @@ -125,7 +154,7 @@ export async function cancelClaudeStructuredTurn(input: { // means nothing has published an identity this request can contradict. const ownsRequestedTurn = (): boolean => { const liveTurnId = request.resolveLiveTurnId?.() ?? session.translator?.currentTurnId ?? null - return liveTurnId === null ? session.dispatchSequence === 0 : liveTurnId === request.turnId + return liveTurnId === null ? session.dispatchSequence === 0 : liveTurnId === requestedTurnId } // The host supplies the durable latest submission; direct adapter callers fall back to // the current in-memory waiter so an unknown dispatch remains fenced without a latch. @@ -143,7 +172,7 @@ export async function cancelClaudeStructuredTurn(input: { const dispatchAdmissionAllowsCancellation = (): boolean => dispatchAdmissionIsCurrent() || (Boolean(prompt) && supportsClaudeQueuedInterruptCancellation(session)) - const compactionOwnsTurn = (): boolean => compactions.ownsTurn(request.sessionId, request.turnId) + const compactionOwnsTurn = (): boolean => compactions.ownsTurn(request.sessionId, requestedTurnId) const currentDispatchHasRetiredWaiter = (): boolean => session.retiredDispatchWaiters.some( (waiter) => waiter.dispatchSequence === session.dispatchSequence @@ -165,7 +194,7 @@ export async function cancelClaudeStructuredTurn(input: { session.acquisitionGeneration === acquisitionGeneration && (claim && prompt ? ownsRequestedTurn() && - session.prompts.ownsBoundClaim(claim, prompt.itemId, request.turnId) && + session.prompts.ownsBoundClaim(claim, prompt.itemId, requestedTurnId) && (dispatchAdmissionAllowsCancellation() || dispatchAdmissionExpired) : compactionOwnsTurn() || (ownsRequestedTurn() && diff --git a/src/main/claude/claude-structured-rate-limit-retry.test.ts b/src/main/claude/claude-structured-rate-limit-retry.test.ts new file mode 100644 index 00000000000..d7b0d5277fc --- /dev/null +++ b/src/main/claude/claude-structured-rate-limit-retry.test.ts @@ -0,0 +1,50 @@ +// Claude retrying a rate-limited request: the frames below follow Claude Code 2.1.280 against an +// HTTP 429 stub, captured with `--replay-user-messages --include-partial-messages`. The CLI writes +// only `api_retry` frames, and echoes the message only once a request gets through or is +// interrupted, so no turn opens: the send itself is all that says the session is working. + +import { describe, expect, it, vi } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity +} from '../../shared/agent-session-journal-types' +import { readAgentJournalTurn } from '../../shared/agent-session-turn-record' +import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { createClaudeJournalTranslator } from './claude-structured-journal-translation' + +function apiRetry(attempt: number, observedAt: number) { + return { + type: 'message' as const, + sessionId: 'orca-session', + observedAt, + message: { + type: 'system', + subtype: 'api_retry', + attempt, + max_retries: 10, + retry_delay_ms: 1_000 * 2 ** (attempt - 1), + error_status: 429, + error: 'rate_limit', + uuid: `retry-${attempt}`, + session_id: 'claude-session' + } + } +} + +describe('Claude retrying a rate-limited request', () => { + it('opens no turn while it retries', () => { + const appended: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] + const sink: StructuredAgentSessionEventSink = { + appendItem: (identity, body) => appended.push({ identity, body }), + appendTombstone: vi.fn(), + publish: vi.fn() + } + const translator = createClaudeJournalTranslator({ sink }) + + for (let attempt = 1; attempt <= 6; attempt += 1) { + translator.handle(apiRetry(attempt, 1_000 * attempt)) + } + + expect(appended.filter(({ body }) => readAgentJournalTurn(body) !== null)).toEqual([]) + }) +}) diff --git a/src/main/claude/claude-structured-real-cli.test.ts b/src/main/claude/claude-structured-real-cli.test.ts index 20670147ca0..73bec7986c8 100644 --- a/src/main/claude/claude-structured-real-cli.test.ts +++ b/src/main/claude/claude-structured-real-cli.test.ts @@ -279,6 +279,80 @@ describe.skipIf(!realClaudeAvailable)('Claude structured real CLI handshake', () 90_000 ) + // The window a Stop naming no turn exists for: Orca has written the message, and Claude has not + // started its reply, so no turn id exists. Only the live binary can say the interrupt lands there. + it.skipIf(!realClaudeAuthenticated)( + 'stops a message interrupted before its reply starts, and takes the next one', + async () => { + const providerSessionId = randomUUID() + const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude') + const events: ClaudeStructuredSessionEvent[] = [] + const adapter = realAdapter(providerSessionId, claudeConfigDir, events) + const frames = (from: number) => + events.slice(from).flatMap((event) => (event.type === 'message' ? [event.message] : [])) + const replyStarted = (from: number) => + frames(from).some( + (frame) => + frame.type === 'stream_event' && + typeof frame.event === 'object' && + frame.event !== null && + 'type' in frame.event && + frame.event.type === 'message_start' + ) + const result = async (from: number) => { + const deadline = Date.now() + 60_000 + for (;;) { + const found = frames(from).find((frame) => frame.type === 'result') + if (found || Date.now() >= deadline) { + return found + } + await new Promise((resolve) => setTimeout(resolve, 100)) + } + } + const send = (clientMessageId: string, text: string) => + adapter.dispatch({ + sessionId: 'real-cli-handshake', + clientMessageId, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] }, + fence: 1 + }) + + try { + await adapter.acquire({ + identity: identity(providerSessionId), + fence: 1, + spawnToken: 'real-cli-stop' + }) + const first = events.length + await expect( + send('real-cli-stop-1', 'Count from 1 to 300, one number per line, and nothing else.') + ).resolves.toEqual({ state: 'admitted' }) + const startedBeforeStop = replyStarted(first) + + await expect( + adapter.cancelTurn({ sessionId: 'real-cli-handshake', fence: 1 }) + ).resolves.toEqual({ + cancelled: true + }) + const stopped = await result(first) + + expect(startedBeforeStop).toBe(false) + // Claude 2.1.280 echoes the message, then ends that turn as interrupted without replying. + expect(stopped).toMatchObject({ subtype: 'error_during_execution' }) + expect(replyStarted(first)).toBe(false) + + const second = events.length + await expect(send('real-cli-stop-2', 'Reply with the single word ok.')).resolves.toEqual({ + state: 'admitted' + }) + await expect(result(second)).resolves.toMatchObject({ subtype: 'success' }) + } finally { + await adapter.closeAll() + } + }, + 150_000 + ) + // Orca installs a SessionStart hook, so its frame proves most real starts before the turn's // system/init, the only frame that says this CLI can cancel what it queued. it.skipIf(!realClaudeAuthenticated)( diff --git a/src/main/claude/claude-structured-session-acquisition.ts b/src/main/claude/claude-structured-session-acquisition.ts index b5a7a5d3061..cd8836e4b82 100644 --- a/src/main/claude/claude-structured-session-acquisition.ts +++ b/src/main/claude/claude-structured-session-acquisition.ts @@ -118,9 +118,12 @@ export async function acquireClaudeSession({ persistClaudeTurnResumePoint(sessionId, liveSession, deps) } } + // Settled after the turn this echo opens is emitted: a send read as answered before its turn + // lands reads as nothing running, and Stop and Working blink off in between. + const settlements: (() => void)[] = [] const turnOrigin = liveSession ? resolveClaudeReplayTurn(liveSession, message, (settlement) => - deps.onDispatchSettledLate?.({ sessionId, ...settlement }) + settlements.push(() => deps.onDispatchSettledLate?.({ sessionId, ...settlement })) ) : null const startsTurn = turnOrigin !== null @@ -138,6 +141,9 @@ export async function acquireClaudeSession({ ...observedAt }) ) + for (const settle of settlements) { + settle() + } } const { canUseTool, onUserDialog } = buildClaudePermissionCallbacks({ sessionId, diff --git a/src/main/codex/codex-requested-close-turn-timing.test.ts b/src/main/codex/codex-requested-close-turn-timing.test.ts index fbf50badaef..a7baf6a14b5 100644 --- a/src/main/codex/codex-requested-close-turn-timing.test.ts +++ b/src/main/codex/codex-requested-close-turn-timing.test.ts @@ -1,4 +1,5 @@ import { createCodexDispatchEchoes } from './codex-structured-dispatch-echo' +import { createCodexTurnOpenWaits } from './codex-structured-turn-open-wait' import { afterEach, describe, expect, it, vi } from 'vitest' import type { AgentJournalItemBody } from '../../shared/agent-session-journal-types' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' @@ -72,6 +73,7 @@ describe('requested-close durable turn timing', () => { reportedOptions: {}, fastModeTierByModel: new Map(), dispatchEchoes: createCodexDispatchEchoes(), + turnOpenWaits: createCodexTurnOpenWaits(), translator } const sessions = new Map([['session-1', session]]) diff --git a/src/main/codex/codex-structured-conversation-stop.test.ts b/src/main/codex/codex-structured-conversation-stop.test.ts new file mode 100644 index 00000000000..1842afada72 --- /dev/null +++ b/src/main/codex/codex-structured-conversation-stop.test.ts @@ -0,0 +1,94 @@ +// A Codex Stop that names no turn. The fake keeps Codex 0.157's turn bookkeeping: it answers +// `turn/start` before it opens the turn, and refuses an interrupt until then. + +import { describe, expect, it, vi } from 'vitest' +import { + CODEX_TEST_THREAD_ID, + codexTurnLifecycleRig +} from './codex-structured-dispatch-test-support' + +type Rig = Awaited> + +async function openedTurn(rig: Rig): Promise { + const sending = rig.send('client-1') + await vi.waitFor(() => expect(rig.turns.turnId).toBe('turn-1')) + rig.turns.start() + await sending +} + +const stop = (rig: Rig, resolveLiveTurnId?: () => string | null) => + rig.adapter.cancelTurn({ + sessionId: 'session-1', + fence: 7, + ...(resolveLiveTurnId ? { resolveLiveTurnId } : {}) + }) + +describe('a Codex Stop that names no turn', () => { + it('interrupts the turn Codex opened when the journal shows none yet', async () => { + const rig = await codexTurnLifecycleRig() + await openedTurn(rig) + + await expect(stop(rig, () => null)).resolves.toEqual({ cancelled: true }) + expect(rig.interrupts().map((call) => call.params?.turnId)).toEqual(['turn-1']) + }) + + it('interrupts no turn that already ended', async () => { + const rig = await codexTurnLifecycleRig() + await openedTurn(rig) + rig.turns.end('completed') + + await expect(stop(rig)).resolves.toEqual({ cancelled: false }) + expect(rig.interrupts()).toEqual([]) + }) + + it("names the journal's turn over the one it saw open, and carries Codex's refusal", async () => { + const rig = await codexTurnLifecycleRig() + await openedTurn(rig) + + await expect(stop(rig, () => 'turn-journal')).resolves.toEqual({ + cancelled: false, + refusal: { + detail: { + text: 'expected active turn id turn-journal but found turn-1', + audience: 'person' + } + } + }) + expect(rig.interrupts().map((call) => call.params?.turnId)).toEqual(['turn-journal']) + }) + + it('interrupts nothing for another fence', async () => { + const rig = await codexTurnLifecycleRig() + await openedTurn(rig) + + await expect(rig.adapter.cancelTurn({ sessionId: 'session-1', fence: 6 })).resolves.toEqual({ + cancelled: false + }) + expect(rig.interrupts()).toEqual([]) + }) + + it('interrupts no earlier turn while a compaction the journal shows has not started', async () => { + const rig = await codexTurnLifecycleRig() + await openedTurn(rig) + rig.turns.end('completed') + const compaction = rig.adapter.compact({ + turnId: 'compact:operation-1', + sessionId: 'session-1', + fence: 7 + }) + await vi.waitFor(() => + expect(rig.codex.connections[0]!.calls.at(-1)?.method).toBe('thread/compact/start') + ) + + await expect(stop(rig, () => 'compact:operation-1')).resolves.toEqual({ cancelled: false }) + expect(rig.interrupts()).toEqual([]) + + rig.notify('turn/started', { threadId: CODEX_TEST_THREAD_ID, turn: { id: 'turn-compact' } }) + rig.notify('thread/compacted', { threadId: CODEX_TEST_THREAD_ID }) + rig.notify('turn/completed', { + threadId: CODEX_TEST_THREAD_ID, + turn: { id: 'turn-compact', status: 'completed' } + }) + await expect(compaction).resolves.toEqual({ outcome: 'compacted' }) + }) +}) diff --git a/src/main/codex/codex-structured-dispatch-admission.test.ts b/src/main/codex/codex-structured-dispatch-admission.test.ts index b8ea81d592c..b3c8a3fefeb 100644 --- a/src/main/codex/codex-structured-dispatch-admission.test.ts +++ b/src/main/codex/codex-structured-dispatch-admission.test.ts @@ -7,6 +7,7 @@ import { acquiredCodexAdapter, echoUserMessage, fakeCodexAppServer, + openAfterTurnStarts, startTurn, CODEX_TEST_THREAD_ID, CODEX_TEST_USER_MESSAGE, @@ -215,8 +216,9 @@ describe('codex dispatch admission', () => { await expect(send(adapter, 'client-unknown', 1_700_000_000_100)).rejects.toThrow( 'request timed out after write' ) - await send(adapter, 'client-later', 1_700_000_000_400) - startTurn(connection, 'turn-later') + const later = send(adapter, 'client-later', 1_700_000_000_400) + await openAfterTurnStarts(connection, 2, () => startTurn(connection, 'turn-later')) + await later echoUserMessage(connection, { turnId: 'turn-later', itemId: 'item-later', @@ -279,9 +281,10 @@ describe('codex dispatch admission', () => { const adapter = await acquiredCodexAdapter({ codex, settlements, sink: recorded.sink }) const connection = codex.connections[0]! - await send(adapter, 'client-opening', 1_700_000_000_600) - await send(adapter, 'client-queued', 1_700_000_000_200) - startTurn(connection, 'turn-1') + const opening = send(adapter, 'client-opening', 1_700_000_000_600) + const queued = send(adapter, 'client-queued', 1_700_000_000_200) + await openAfterTurnStarts(connection, 2, () => startTurn(connection, 'turn-1')) + await Promise.all([opening, queued]) await send(adapter, 'client-mid-turn', 1_700_000_000_100) echoUserMessage(connection, { @@ -325,8 +328,9 @@ describe('codex dispatch admission', () => { const adapter = await acquiredCodexAdapter({ codex, settlements, sink: recorded.sink }) const connection = codex.connections[0]! - await send(adapter, 'client-late-echo', 1_700_000_000_100) - startTurn(connection, 'turn-1') + const sending = send(adapter, 'client-late-echo', 1_700_000_000_100) + await openAfterTurnStarts(connection, 1, () => startTurn(connection, 'turn-1')) + await sending connection.handlers.onNotification?.('turn/completed', { threadId: CODEX_TEST_THREAD_ID, turn: { id: 'turn-1' } diff --git a/src/main/codex/codex-structured-dispatch-echo.test.ts b/src/main/codex/codex-structured-dispatch-echo.test.ts index 94826c1df12..a6791e5e788 100644 --- a/src/main/codex/codex-structured-dispatch-echo.test.ts +++ b/src/main/codex/codex-structured-dispatch-echo.test.ts @@ -126,3 +126,44 @@ describe('readCodexDispatchEcho', () => { ).toBeNull() }) }) + +describe('the turn Codex answered a send into but has not opened', () => { + const NONE_OPEN = new Set() + + it('is the turn the latest armed send was answered into', () => { + const echoes = createCodexDispatchEchoes() + echoes.arm('client-1') + echoes.bindTurn('client-1', 'thread-1', 'turn-1') + echoes.arm('client-2') + echoes.bindTurn('client-2', 'thread-1', 'turn-2') + + expect(echoes.answeredUnopenedTurn('thread-1', NONE_OPEN)).toBe('turn-2') + }) + + it('is none once Codex opened that turn', () => { + const echoes = createCodexDispatchEchoes() + echoes.arm('client-1') + echoes.bindTurn('client-1', 'thread-1', 'turn-1') + + expect(echoes.answeredUnopenedTurn('thread-1', new Set(['turn-1']))).toBeNull() + }) + + it('is none once that turn ended, even with its send still armed for an echo', () => { + const echoes = createCodexDispatchEchoes() + echoes.arm('client-1') + echoes.bindTurn('client-1', 'thread-1', 'turn-1') + // A completed end leaves its unechoed send armed. + expect(echoes.endTurn('thread-1', 'turn-1', { status: 'completed' })).toEqual([]) + + expect(echoes.answeredUnopenedTurn('thread-1', NONE_OPEN)).toBeNull() + }) + + it('is none for a send not yet answered, or answered on another thread', () => { + const echoes = createCodexDispatchEchoes() + echoes.arm('client-1') + echoes.arm('client-2') + echoes.bindTurn('client-2', 'thread-2', 'turn-2') + + expect(echoes.answeredUnopenedTurn('thread-1', NONE_OPEN)).toBeNull() + }) +}) diff --git a/src/main/codex/codex-structured-dispatch-echo.ts b/src/main/codex/codex-structured-dispatch-echo.ts index c1a020b2c1f..0d3794b5136 100644 --- a/src/main/codex/codex-structured-dispatch-echo.ts +++ b/src/main/codex/codex-structured-dispatch-echo.ts @@ -38,6 +38,9 @@ export type CodexDispatchEchoes = { * read after it; a send that end settles is no longer armed. */ bindTurn: (clientMessageId: string, threadId: string, turnId: string) => CodexTurnEnd | null + /** The turn the latest armed send was answered into that is neither in `openTurnIds` nor ended: + * one Codex has picked for the send but not opened. */ + answeredUnopenedTurn: (threadId: string, openTurnIds: ReadonlySet) => string | null /** * Records a turn's end and returns the sends bound to it that it settles: all of them unless it * completed, which echoes its pending input first, so one it never echoed waits for recovery. @@ -52,7 +55,10 @@ export type CodexDispatchEchoes = { } export function createCodexDispatchEchoes(): CodexDispatchEchoes { - const armed = new Map() + const armed = new Map< + string, + { requestedAt: number | null; sequence: number; turn?: { threadId: string; turnId: string } } + >() const endedTurns = new Map() let nextSequence = 0 const turnKey = (threadId: string, turnId: string): string => JSON.stringify([threadId, turnId]) @@ -79,14 +85,23 @@ export function createCodexDispatchEchoes(): CodexDispatchEchoes { if (!entry) { return null } - const turn = turnKey(threadId, turnId) - entry.turn = turn - const end = endedTurns.get(turn) ?? null + entry.turn = { threadId, turnId } + const end = endedTurns.get(turnKey(threadId, turnId)) ?? null if (end && settles(end)) { armed.delete(clientMessageId) } return end }, + answeredUnopenedTurn: (threadId, openTurnIds) => { + const answered = [...armed.values()].flatMap(({ turn }) => + turn?.threadId === threadId && + !openTurnIds.has(turn.turnId) && + !endedTurns.has(turnKey(threadId, turn.turnId)) + ? [turn.turnId] + : [] + ) + return answered.at(-1) ?? null + }, endTurn: (threadId, turnId, end) => { const turn = turnKey(threadId, turnId) endedTurns.delete(turn) @@ -101,7 +116,9 @@ export function createCodexDispatchEchoes(): CodexDispatchEchoes { return [] } const settled = [...armed].flatMap(([clientMessageId, entry]) => - entry.turn === turn ? [clientMessageId] : [] + entry.turn && turnKey(entry.turn.threadId, entry.turn.turnId) === turn + ? [clientMessageId] + : [] ) for (const clientMessageId of settled) { armed.delete(clientMessageId) diff --git a/src/main/codex/codex-structured-dispatch-test-support.ts b/src/main/codex/codex-structured-dispatch-test-support.ts index 566922d7422..86f19349ee2 100644 --- a/src/main/codex/codex-structured-dispatch-test-support.ts +++ b/src/main/codex/codex-structured-dispatch-test-support.ts @@ -1,3 +1,4 @@ +import { expect, vi } from 'vitest' import type { AgentJournalMessageItem, AgentSessionJournalIdentity @@ -10,6 +11,7 @@ import type { } from './codex-app-server-connection' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import { CodexStructuredSessionAdapter } from './codex-structured-session-adapter' +import { codexTurnLifecycleFake } from './codex-turn-lifecycle-fake' import type { CodexStructuredSessionAdapterDeps } from './codex-structured-session-state' export const CODEX_TEST_THREAD_ID = 'thread-abc' @@ -83,6 +85,7 @@ export async function acquiredCodexAdapter(input: { settlements: LateSettlement[] sink?: StructuredAgentSessionEventSink captureTurnProcesses?: CodexStructuredSessionAdapterDeps['captureTurnProcesses'] + requestTimeoutMs?: number }): Promise { const adapter = new CodexStructuredSessionAdapter({ resolveLaunch: async () => ({ @@ -95,8 +98,11 @@ export async function acquiredCodexAdapter(input: { openConnection: input.codex.openConnection, readProcessStartTime: async () => 1_700_000_000_000, captureTurnProcesses: input.captureTurnProcesses ?? (async () => null), + // A Stop must never reach for real processes on this machine under the fake pid. + terminateTurnProcesses: async () => true, now: () => 1_700_000_000_500, - onDispatchSettledLate: (settlement) => input.settlements.push(settlement) + onDispatchSettledLate: (settlement) => input.settlements.push(settlement), + ...(input.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: input.requestTimeoutMs }) }) const identity: AgentSessionJournalIdentity = { sessionId: 'session-1', @@ -130,9 +136,50 @@ export function echoUserMessage( }) } -export function startTurn(connection: FakeConnection, turnId: string): void { +export function startTurn(connection: Pick, turnId: string): void { connection.handlers.onNotification?.('turn/started', { threadId: CODEX_TEST_THREAD_ID, turn: { id: turnId } }) } + +/** Runs `open` once `count` sends reached Codex, which opens a turn only after it answers. */ +export async function openAfterTurnStarts( + connection: Pick, + count: number, + open: () => void +): Promise { + await vi.waitFor(() => + expect(connection.calls.filter((call) => call.method === 'turn/start')).toHaveLength(count) + ) + open() +} + +/** An acquired adapter over a fake Codex that keeps Codex's own turn bookkeeping. */ +export async function codexTurnLifecycleRig(options: { requestTimeoutMs?: number } = {}) { + const codex = fakeCodexAppServer() + const notify = (method: string, params: unknown): void => + codex.connections.at(-1)?.handlers.onNotification?.(method, params) + const turns = codexTurnLifecycleFake(CODEX_TEST_THREAD_ID, () => notify) + Object.assign(codex.routes, turns.routes) + const settlements: LateSettlement[] = [] + const adapter = await acquiredCodexAdapter({ codex, settlements, ...options }) + const send = (clientMessageId: string) => + adapter.dispatch({ + sessionId: 'session-1', + clientMessageId, + body: CODEX_TEST_USER_MESSAGE, + fence: 7 + }) + const interrupts = () => + codex.connections[0]!.calls.filter((call) => call.method === 'turn/interrupt') + return { codex, turns, adapter, send, settlements, notify, interrupts } +} + +/** The promise's value, or `held` when it has not settled `withinMs` after every earlier task. */ +export function settledWithin(promise: Promise, withinMs = 50): Promise { + return Promise.race([ + promise, + new Promise<'held'>((resolve) => setTimeout(() => resolve('held'), withinMs)) + ]) +} diff --git a/src/main/codex/codex-structured-fast-mode.test.ts b/src/main/codex/codex-structured-fast-mode.test.ts index 3029bff280b..73f279bd2c0 100644 --- a/src/main/codex/codex-structured-fast-mode.test.ts +++ b/src/main/codex/codex-structured-fast-mode.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { USER_MESSAGE, adapterFor, + answerWithOpenedTurn, fakeCodex, identityFor, type Route @@ -19,9 +20,9 @@ describe('Codex structured Fast mode dispatch', () => { } ], nextCursor: null - }), - 'turn/start': () => ({ turn: { id: 'turn-fast' } }) + }) }) + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'turn-fast') const adapter = adapterFor(codex) await adapter.acquire({ identity: identityFor('session-1'), @@ -43,7 +44,8 @@ describe('Codex structured Fast mode dispatch', () => { }) it('uses Standard on the first turn after acquisition with Fast explicitly off', async () => { - const codex = fakeCodex({ 'turn/start': () => ({ turn: { id: 'turn-standard' } }) }) + const codex = fakeCodex() + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'turn-standard') const adapter = adapterFor(codex) await adapter.acquire({ identity: identityFor('session-1'), @@ -91,10 +93,8 @@ describe('Codex structured Fast mode dispatch', () => { ], nextCursor: null })) - const codex = fakeCodex({ - 'model/list': listModels, - 'turn/start': () => ({ turn: { id: 'turn-recovered' } }) - }) + const codex = fakeCodex({ 'model/list': listModels }) + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'turn-recovered') const adapter = adapterFor(codex) await expect( adapter.acquire({ diff --git a/src/main/codex/codex-structured-prompt-ownership.test.ts b/src/main/codex/codex-structured-prompt-ownership.test.ts index ecdc4c9a4be..7dd048dd08a 100644 --- a/src/main/codex/codex-structured-prompt-ownership.test.ts +++ b/src/main/codex/codex-structured-prompt-ownership.test.ts @@ -261,7 +261,7 @@ describe('Codex live prompt ownership', () => { fence: 7, prompt: { itemId: 'journal-prompt' } }) - ).resolves.toEqual({ cancelled: false }) + ).resolves.toEqual({ cancelled: false, refusal: {} }) await adapter.answerPrompt({ sessionId: 'session-1', itemId: 'journal-prompt', diff --git a/src/main/codex/codex-structured-prompt-ownership.ts b/src/main/codex/codex-structured-prompt-ownership.ts index d58f08e731d..1742d5ced69 100644 --- a/src/main/codex/codex-structured-prompt-ownership.ts +++ b/src/main/codex/codex-structured-prompt-ownership.ts @@ -1,6 +1,7 @@ import { AgentSessionPromptAnswerRejectedError, AgentSessionPromptUnavailableError, + type AgentSessionCancelOutcome, type StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/structured-agent-session-adapter' import type { StructuredSessionCompaction } from '../native-chat/agent-session-wire/structured-session-compaction' @@ -16,19 +17,72 @@ import type { CodexStructuredTurnCancellation } from './codex-structured-turn-ca type CancelInput = Parameters[0] type AnswerInput = Parameters[0] +/** How long a Stop waits for Codex to open the turn it answered a send into. Under the quit + * path's eviction budget, which a close or quit queued behind the Stop spends. */ +export const CODEX_STOP_TURN_OPEN_WAIT_MS = 5_000 + +/** + * A Stop that names no turn: interrupt the turn the journal shows, or else the one Codex reported + * started and not yet ended, which the journal can trail by a publish, or else the one Codex + * answered a send into, once it opens. + */ +async function cancelCodexConversation( + input: Parameters[0], + session: CodexSession +): Promise { + const { request, sessions, compactions, cancellation } = input + const liveTurnId = request.resolveLiveTurnId?.() ?? null + // A turn the journal shows that Codex has not started yet (a compaction's) has nothing to stop. + const turnId = + liveTurnId === null + ? ([...(session.activeTurnIds ?? [])].at(-1) ?? (await openedAnsweredTurn(session))) + : compactions.providerTurnId(request.sessionId, liveTurnId) + if (!turnId) { + return { cancelled: false } + } + const acquisitionGeneration = session.acquisitionGeneration + return cancellation.cancel( + session, + session.threadId, + turnId, + () => + sessions.get(request.sessionId) === session && + !session.ended && + session.fence === request.fence && + session.acquisitionGeneration === acquisitionGeneration + ) +} + +/** The turn Codex answered a send into and has not opened yet, once it opens; null when it ends, + * the thread stops running or the child exits first, or the wait runs out. */ +async function openedAnsweredTurn(session: CodexSession): Promise { + const openTurnIds = session.activeTurnIds ?? new Set() + const answered = session.dispatchEchoes.answeredUnopenedTurn(session.threadId, openTurnIds) + if (!answered) { + return null + } + // Codex refuses an interrupt before it opens the turn. + await session.turnOpenWaits.wait(answered, CODEX_STOP_TURN_OPEN_WAIT_MS) + return session.activeTurnIds?.has(answered) ? answered : null +} + export async function cancelCodexStructuredTurn(input: { request: CancelInput sessions: Map compactions: StructuredSessionCompaction cancellation: CodexStructuredTurnCancellation -}): Promise<{ cancelled: boolean }> { +}): Promise { const { request, sessions, compactions, cancellation } = input const session = requireLiveCodexSession(sessions, request.sessionId) - const turnId = compactions.providerTurnId(request.sessionId, request.turnId) + const prompt = request.prompt + const requestedTurnId = request.turnId + if (requestedTurnId === undefined) { + return prompt ? { cancelled: false } : cancelCodexConversation(input, session) + } + const turnId = compactions.providerTurnId(request.sessionId, requestedTurnId) if (!turnId) { return { cancelled: false } } - const prompt = request.prompt if (!prompt) { return cancellation.cancel(session, session.threadId, turnId) } @@ -49,7 +103,7 @@ export async function cancelCodexStructuredTurn(input: { !session.ended && session.fence === request.fence && session.acquisitionGeneration === acquisitionGeneration && - compactions.providerTurnId(request.sessionId, request.turnId) === turnId && + compactions.providerTurnId(request.sessionId, requestedTurnId) === turnId && session.prompts.ownsBoundClaim(claim, prompt.itemId, claim.prompt.threadId, promptTurnId) let interruptConfirmed = false try { diff --git a/src/main/codex/codex-structured-provider-events.ts b/src/main/codex/codex-structured-provider-events.ts index 06563cad748..5dc608fbb59 100644 --- a/src/main/codex/codex-structured-provider-events.ts +++ b/src/main/codex/codex-structured-provider-events.ts @@ -24,6 +24,7 @@ export function translateCodexNotification(input: { }): CodexJournalTranslationAdmission { const { sessionId, session, method, params, observedAt, dispatchSequenceAtReceipt } = input codexRewind.observeCodexRewindActivity(session, method, params) + session.turnOpenWaits.observe(session.threadId, method, params) if (input.turnCancellation.handleNotification(sessionId, session, method, params, observedAt)) { return { accepted: true } } diff --git a/src/main/codex/codex-structured-session-adapter-fixture.ts b/src/main/codex/codex-structured-session-adapter-fixture.ts index 3f2d32ee2eb..27e6eadb6c5 100644 --- a/src/main/codex/codex-structured-session-adapter-fixture.ts +++ b/src/main/codex/codex-structured-session-adapter-fixture.ts @@ -89,6 +89,19 @@ export function fakeCodex(routes: Record = {}): { return { connections, openConnection, routes } } +/** A `turn/start` route for a Codex that opened the turn before its answer was read. */ +export function answerWithOpenedTurn( + codex: Pick, 'connections'>, + turnId: string +): Route { + return () => { + codex.connections + .at(-1) + ?.handlers.onNotification?.('turn/started', { threadId: THREAD_ID, turn: { id: turnId } }) + return { turn: { id: turnId } } + } +} + export function adapterFor( codex: ReturnType, launch: Partial = {}, diff --git a/src/main/codex/codex-structured-session-adapter.test.ts b/src/main/codex/codex-structured-session-adapter.test.ts index 2fa337b6001..70b2ecd7147 100644 --- a/src/main/codex/codex-structured-session-adapter.test.ts +++ b/src/main/codex/codex-structured-session-adapter.test.ts @@ -16,6 +16,7 @@ import { USER_MESSAGE, acquired, adapterFor, + answerWithOpenedTurn, fakeCodex, identityFor } from './codex-structured-session-adapter-fixture' @@ -371,7 +372,8 @@ describe('CodexStructuredSessionAdapter.acquire', () => { describe('CodexStructuredSessionAdapter.dispatch', () => { it('admits a send as soon as Codex owns it', async () => { - const codex = fakeCodex({ 'turn/start': () => ({ turn: { id: 'turn-1' } }) }) + const codex = fakeCodex() + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'turn-1') const adapter = await acquired(codex) const outcome = await adapter.dispatch({ @@ -512,9 +514,9 @@ describe('CodexStructuredSessionAdapter.dispatch', () => { } ], nextCursor: null - }), - 'turn/start': () => ({ turn: { id: 'turn-1' } }) + }) }) + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'turn-1') const adapter = await acquired(codex) await adapter.setOption({ sessionId: 'session-1', key: 'model', value: 'gpt-5', fence: 7 }) diff --git a/src/main/codex/codex-structured-session-cancel.test.ts b/src/main/codex/codex-structured-session-cancel.test.ts index 1ac807a5ccd..2d6c50adae4 100644 --- a/src/main/codex/codex-structured-session-cancel.test.ts +++ b/src/main/codex/codex-structured-session-cancel.test.ts @@ -142,14 +142,14 @@ describe('CodexStructuredSessionAdapter.cancelTurn', () => { turnId: 'turn-1', fence: 7 }) - ).resolves.toEqual({ cancelled: false }) + ).resolves.toEqual({ cancelled: false, refusal: {} }) await expect( (await acquired(absent)).cancelTurn({ sessionId: 'session-1', turnId: 'turn-1', fence: 7 }) - ).resolves.toEqual({ cancelled: false }) + ).resolves.toEqual({ cancelled: false, refusal: {} }) }) it('rethrows an unsettled interrupt so the turn is not shown as cancelled', async () => { @@ -228,14 +228,22 @@ describe('CodexStructuredSessionAdapter.cancelTurn', () => { await expect( adapter.cancelTurn({ sessionId: 'session-1', turnId: 'turn-1', fence: 7 }) - ).resolves.toEqual({ cancelled: false }) + ).resolves.toEqual({ cancelled: false, unconfirmed: true }) expect(events).toContainEqual(expect.objectContaining({ method: 'turn/completed' })) }) it('accepts an immediate resend after verified interruption', async () => { let nextTurn = 0 const codex = fakeCodex() - codex.routes['turn/start'] = () => ({ turn: { id: `turn-${++nextTurn}` } }) + codex.routes['turn/start'] = () => { + // Codex opens each turn it answers; a send's dispatch waits for that. + const turnId = `turn-${++nextTurn}` + codex.connections[0].handlers.onNotification?.('turn/started', { + threadId: THREAD_ID, + turn: { id: turnId } + }) + return { turn: { id: turnId } } + } codex.routes['turn/interrupt'] = () => { completeTurn(codex) return {} diff --git a/src/main/codex/codex-structured-session-close.test.ts b/src/main/codex/codex-structured-session-close.test.ts index dffa7157dd6..9d80a0fa982 100644 --- a/src/main/codex/codex-structured-session-close.test.ts +++ b/src/main/codex/codex-structured-session-close.test.ts @@ -1,4 +1,5 @@ import { createCodexDispatchEchoes } from './codex-structured-dispatch-echo' +import { createCodexTurnOpenWaits } from './codex-structured-turn-open-wait' import { describe, expect, it, vi } from 'vitest' import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-types' import type { @@ -76,7 +77,7 @@ function claudeAdapterStub(): StructuredAgentSessionAdapter { } describe('Codex structured session close lifecycle', () => { - it('forwards a one-shot exit when lifecycle admission is rejected', () => { + function backpressuredSession(requestedClose: boolean) { const connection: CodexAppServerConnection = { pid: 4321, closed: true, @@ -87,7 +88,6 @@ describe('Codex structured session close lifecycle', () => { close: async () => true } const prompts = new CodexPromptRegistry() - const clearPrompts = vi.spyOn(prompts, 'clear') const translator = { handle: vi.fn().mockReturnValueOnce({ accepted: false, reason: 'backpressure' as const }), dispose: vi.fn() @@ -96,7 +96,7 @@ describe('Codex structured session close lifecycle', () => { connection, backgroundTasks: new CodexBackgroundTaskTracker('thread-1'), ended: false, - requestedClose: false, + requestedClose, fence: 7, acquisitionGeneration: 'generation-1', threadId: THREAD, @@ -106,9 +106,15 @@ describe('Codex structured session close lifecycle', () => { reportedOptions: {}, fastModeTierByModel: new Map(), dispatchEchoes: createCodexDispatchEchoes(), + turnOpenWaits: createCodexTurnOpenWaits(), translator } - const sessions = new Map([['session-1', session]]) + return { connection, prompts, translator, session, sessions: new Map([['session-1', session]]) } + } + + it('forwards a one-shot exit when lifecycle admission is rejected', () => { + const { connection, prompts, translator, session, sessions } = backpressuredSession(false) + const clearPrompts = vi.spyOn(prompts, 'clear') const onEvent = vi.fn() expect( @@ -129,6 +135,29 @@ describe('Codex structured session close lifecycle', () => { expect(translator.handle).toHaveBeenCalledOnce() }) + it("ends a Stop's wait for its turn to open when a requested close cannot publish its end yet", async () => { + const { connection, prompts, session, sessions } = backpressuredSession(true) + let released = false + void session.turnOpenWaits.wait('turn-1', 60_000).then(() => { + released = true + }) + + expect( + handleCodexSessionExit({ + sessions, + sessionId: 'session-1', + connection, + error: new Error('codex session closed'), + closedByOrca: true, + prompts + }) + ).toBe(false) + await Promise.resolve() + // Left for the retry, but the child is gone: nothing waits on a turn it would open. + expect(session.ended).toBe(false) + expect(released).toBe(true) + }) + it('mints a distinct child generation even when acquisitions share one fence', async () => { const { adapter } = adapterFixture() const input = { identity: identity('session-1'), fence: 7, spawnToken: 'spawn-1' } diff --git a/src/main/codex/codex-structured-session-close.ts b/src/main/codex/codex-structured-session-close.ts index 91d6c8ff04d..5bf973308b1 100644 --- a/src/main/codex/codex-structured-session-close.ts +++ b/src/main/codex/codex-structured-session-close.ts @@ -29,6 +29,8 @@ export function handleCodexSessionExit(input: { return false } session.exitObservedAt ??= Date.now() + // Before the admission check: the child is gone whether or not its end was admitted. + session.turnOpenWaits.releaseAll() const event: StructuredAgentSessionEndedEvent = { type: 'ended', sessionId: input.sessionId, diff --git a/src/main/codex/codex-structured-session-options-catalog.test.ts b/src/main/codex/codex-structured-session-options-catalog.test.ts index a9fd420eb0a..aac9e2946cf 100644 --- a/src/main/codex/codex-structured-session-options-catalog.test.ts +++ b/src/main/codex/codex-structured-session-options-catalog.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { createCodexDispatchEchoes } from './codex-structured-dispatch-echo' +import { createCodexTurnOpenWaits } from './codex-structured-turn-open-wait' import type { CodexAppServerConnection } from './codex-app-server-connection' import { CodexAcquisitionWindow } from './codex-structured-acquisition-window' import { @@ -62,6 +63,7 @@ function storeSession( reportedOptions: { model: 'gpt-live', effort: 'high' }, fastModeTierByModel: new Map(), dispatchEchoes: createCodexDispatchEchoes(), + turnOpenWaits: createCodexTurnOpenWaits(), translator: null, catalogAccess: { store, fingerprint: FINGERPRINT, accountHomePath: '/homes/a' } } diff --git a/src/main/codex/codex-structured-session-options.test.ts b/src/main/codex/codex-structured-session-options.test.ts index 47ed8b50e3a..d99ecc0305e 100644 --- a/src/main/codex/codex-structured-session-options.test.ts +++ b/src/main/codex/codex-structured-session-options.test.ts @@ -1,4 +1,5 @@ import { createCodexDispatchEchoes } from './codex-structured-dispatch-echo' +import { createCodexTurnOpenWaits } from './codex-structured-turn-open-wait' import { describe, expect, it, vi } from 'vitest' import type { CodexAppServerConnection } from './codex-app-server-connection' import { CodexAcquisitionWindow } from './codex-structured-acquisition-window' @@ -36,6 +37,7 @@ function optionSession(request: CodexAppServerConnection['request']): CodexSessi reportedOptions: { model: 'gpt-live', effort: 'high' }, fastModeTierByModel: new Map(), dispatchEchoes: createCodexDispatchEchoes(), + turnOpenWaits: createCodexTurnOpenWaits(), translator: null } } diff --git a/src/main/codex/codex-structured-session-state.ts b/src/main/codex/codex-structured-session-state.ts index 7f40407e3ff..02c56b419bd 100644 --- a/src/main/codex/codex-structured-session-state.ts +++ b/src/main/codex/codex-structured-session-state.ts @@ -10,6 +10,10 @@ import type { openCodexAppServerConnection } from './codex-app-server-connection' import { CodexAcquisitionWindow } from './codex-structured-acquisition-window' +import { + createCodexTurnOpenWaits, + type CodexTurnOpenWaits +} from './codex-structured-turn-open-wait' import type { CodexDispatchEchoes } from './codex-structured-dispatch-echo' import type { AgentSessionBackgroundTaskState } from '../../shared/agent-session-wire' import type { AgentChildWorkEvidence } from '../../shared/agent-status-child-work-evidence' @@ -118,7 +122,11 @@ export type CodexSession = { threadId: string historyPath: string | null historyMode?: 'legacy' | 'paginated' + /** Primary-thread turns Codex reported started and not yet ended, as read off the wire: what + * rewind waits out and what a Stop naming no turn interrupts when the journal shows none. */ activeTurnIds?: Set + /** Stops waiting for the turn Codex answered a send into to open. */ + turnOpenWaits: CodexTurnOpenWaits dispatchPending?: boolean prompts: CodexAcquisitionWindow['prompts'] options: Map @@ -149,8 +157,17 @@ export function mintCodexAcquisitionGeneration(deps: CodexStructuredSessionAdapt export function codexSessionLifecycle( fence: number, acquisitionGeneration: string -): Pick { - return { ended: false, requestedClose: false, fence, acquisitionGeneration } +): Pick< + CodexSession, + 'ended' | 'requestedClose' | 'fence' | 'acquisitionGeneration' | 'turnOpenWaits' +> { + return { + ended: false, + requestedClose: false, + fence, + acquisitionGeneration, + turnOpenWaits: createCodexTurnOpenWaits() + } } export function requireLiveCodexSession( diff --git a/src/main/codex/codex-structured-turn-cancellation.ts b/src/main/codex/codex-structured-turn-cancellation.ts index 4418da81057..524ab252e4f 100644 --- a/src/main/codex/codex-structured-turn-cancellation.ts +++ b/src/main/codex/codex-structured-turn-cancellation.ts @@ -3,6 +3,8 @@ import { type CodexAppServerConnection } from './codex-app-server-connection' import { isCodexAppServerUnsupportedError } from './codex-app-server-session' +import { providerDiagnosticOf } from '../../shared/agent-session-failure' +import type { AgentSessionCancelOutcome } from '../native-chat/agent-session-wire/structured-agent-session-adapter' import type { CodexSession, CodexStructuredSessionAdapterDeps, @@ -91,7 +93,7 @@ export class CodexStructuredTurnCancellation { turnId: string, isCurrent: () => boolean = () => true, onConfirmed?: () => CodexJournalTranslationAdmission - ): Promise<{ cancelled: boolean }> { + ): Promise { const state = this.state(session) const key = turnKey(threadId, turnId) state.blockedCompletions.add(key) @@ -151,7 +153,14 @@ export class CodexStructuredTurnCancellation { // A failed cancellation must not permanently divert the provider's later // completion for this turn. Let the normal completion path settle it. this.releaseCompletion(session, key) - return { cancelled: false } + if (acknowledged) { + return { cancelled: false, unconfirmed: true } + } + if (!requestError) { + return { cancelled: false } + } + const detail = providerDiagnosticOf(requestError) + return { cancelled: false, refusal: detail ? { detail } : {} } } private capture(pid: number | undefined): Promise { diff --git a/src/main/codex/codex-structured-turn-end-settlement.test.ts b/src/main/codex/codex-structured-turn-end-settlement.test.ts index 60f5a3c5f38..38cc648f79d 100644 --- a/src/main/codex/codex-structured-turn-end-settlement.test.ts +++ b/src/main/codex/codex-structured-turn-end-settlement.test.ts @@ -36,17 +36,23 @@ async function turnEndRig() { body: CODEX_TEST_USER_MESSAGE, fence: 7 }) + // Codex answers a cold send before it opens the turn. + const sendAndOpen = async (clientMessageId: string) => { + const sending = send(clientMessageId) + await vi.waitFor(() => expect(turns.turnId).not.toBeNull()) + turns.start() + return sending + } const settledIds = () => settlements.map(({ clientMessageId }) => clientMessageId) const categoryOf = (settlement: LateSettlement | undefined) => settlement && 'state' in settlement ? classifyDispatchRejection(settlement).category : null - return { codex, turns, adapter, send, settlements, settledIds, categoryOf, bodies } + return { codex, turns, adapter, send, sendAndOpen, settlements, settledIds, categoryOf, bodies } } describe('a Codex send its turn ended without echoing', () => { it('is withdrawn when the turn is interrupted, once', async () => { const rig = await turnEndRig() - await expect(rig.send('client-1')).resolves.toEqual({ state: 'admitted' }) - rig.turns.start() + await expect(rig.sendAndOpen('client-1')).resolves.toEqual({ state: 'admitted' }) rig.turns.end('interrupted') @@ -62,8 +68,7 @@ describe('a Codex send its turn ended without echoing', () => { it('is rejected in Codex words when its failed turn ends without echoing it', async () => { const rig = await turnEndRig() - await rig.send('client-1') - rig.turns.start() + await rig.sendAndOpen('client-1') rig.codex.connections[0]!.handlers.onNotification?.('error', { threadId: CODEX_TEST_THREAD_ID, @@ -87,8 +92,7 @@ describe('a Codex send its turn ended without echoing', () => { it('is accepted when Codex records it after the error that fails its turn', async () => { const rig = await turnEndRig() - await rig.send('client-1') - rig.turns.start() + await rig.sendAndOpen('client-1') rig.turns.echo('client-1') await rig.send('client-2') @@ -113,8 +117,7 @@ describe('a Codex send its turn ended without echoing', () => { it('stays pending, still armed, when its turn completes without echoing it', async () => { const rig = await turnEndRig() - await rig.send('client-1') - rig.turns.start() + await rig.sendAndOpen('client-1') rig.turns.end('completed') expect(rig.settlements).toEqual([]) @@ -131,8 +134,7 @@ describe('a Codex send its turn ended without echoing', () => { it('accepts a send its turn echoed, with its key, exactly once', async () => { const rig = await turnEndRig() - await rig.send('client-1') - rig.turns.start() + await rig.sendAndOpen('client-1') rig.turns.echo('client-1') rig.turns.end('interrupted') @@ -153,8 +155,7 @@ describe('a Codex send its turn ended without echoing', () => { it('ignores an echo that arrives after the withdrawal', async () => { const rig = await turnEndRig() - await rig.send('client-1') - rig.turns.start() + await rig.sendAndOpen('client-1') rig.turns.end('interrupted') rig.turns.echo('client-1') @@ -165,8 +166,7 @@ describe('a Codex send its turn ended without echoing', () => { it('settles each of two sends steered into one interrupted turn once', async () => { const rig = await turnEndRig() - await rig.send('client-1') - rig.turns.start() + await rig.sendAndOpen('client-1') await rig.send('client-2') expect(rig.turns.turnId).toBe('turn-1') @@ -275,8 +275,7 @@ describe('a Codex send its turn ended without echoing', () => { it('ignores a turn end on a child thread', async () => { const rig = await turnEndRig() - await rig.send('client-1') - rig.turns.start() + await rig.sendAndOpen('client-1') rig.codex.connections[0]!.handlers.onNotification?.('turn/completed', { threadId: 'thread-child', diff --git a/src/main/codex/codex-structured-turn-open-wait.test.ts b/src/main/codex/codex-structured-turn-open-wait.test.ts new file mode 100644 index 00000000000..125be2bba0b --- /dev/null +++ b/src/main/codex/codex-structured-turn-open-wait.test.ts @@ -0,0 +1,147 @@ +// A Codex Stop that names no turn, sent after Codex answered a cold send and before it opened that +// turn, waits for the turn to open, or provably not to, and never the send itself. The fake keeps +// Codex 0.157's turn bookkeeping: it answers before it opens the turn, and refuses an interrupt +// until then. + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + CODEX_TEST_THREAD_ID, + codexTurnLifecycleRig, + settledWithin +} from './codex-structured-dispatch-test-support' +import { CODEX_STOP_TURN_OPEN_WAIT_MS } from './codex-structured-prompt-ownership' + +type Rig = Awaited> + +const ADMITTED = { state: 'admitted' } +const REFUSED = { cancelled: false } + +const stop = (rig: Rig) => rig.adapter.cancelTurn({ sessionId: 'session-1', fence: 7 }) + +/** A cold send Codex answered into `turn-1` and has not opened. */ +async function answeredColdSend(rig: Rig): Promise { + const sending = rig.send('client-1') + await vi.waitFor(() => expect(rig.turns.turnId).toBe('turn-1')) + // The send is not held for the turn to open: its handover ends at the answer. + expect(await settledWithin(sending)).toEqual(ADMITTED) +} + +/** A Stop sent in the window, which Codex would refuse if it reached Codex now. */ +async function waitingStop(rig: Rig) { + await answeredColdSend(rig) + const stopping = stop(rig) + expect(await settledWithin(stopping)).toBe('held') + expect(rig.interrupts()).toEqual([]) + // Wrapped: an async function returning the promise itself would wait for it. + return { stopping } +} + +afterEach(() => { + vi.useRealTimers() +}) + +describe('a Codex send answered before its turn opens', () => { + it('is admitted at the answer when no Stop is pending', async () => { + const rig = await codexTurnLifecycleRig() + + await answeredColdSend(rig) + + expect(rig.turns.turnId).toBe('turn-1') + }) +}) + +describe("a no-turn Stop in the window between Codex's answer and its turn opening", () => { + it('waits for the turn to open, then stops it', async () => { + const rig = await codexTurnLifecycleRig() + const { stopping } = await waitingStop(rig) + + rig.turns.start() + + expect(await settledWithin(stopping)).toEqual({ cancelled: true }) + expect(rig.interrupts().map((call) => call.params?.turnId)).toEqual(['turn-1']) + expect(rig.turns.turnId).toBeNull() + }) + + it('does not wait when Codex opened the turn before its answer was read', async () => { + const rig = await codexTurnLifecycleRig() + const release = rig.turns.holdNextAnswer() + const sending = rig.send('client-1') + await vi.waitFor(() => expect(rig.turns.turnId).toBe('turn-1')) + rig.turns.start() + release() + await sending + + expect(await settledWithin(stop(rig))).toEqual({ cancelled: true }) + }) + + it('does not wait for a send Codex steered into the running turn', async () => { + const rig = await codexTurnLifecycleRig() + await answeredColdSend(rig) + rig.turns.start() + expect(await settledWithin(rig.send('client-2'))).toEqual(ADMITTED) + + expect(await settledWithin(stop(rig))).toEqual({ cancelled: true }) + expect(rig.interrupts().map((call) => call.params?.turnId)).toEqual(['turn-1']) + }) + + it('stops nothing when the turn ends without opening', async () => { + const rig = await codexTurnLifecycleRig() + const { stopping } = await waitingStop(rig) + + rig.turns.end('interrupted') + + expect(await settledWithin(stopping)).toEqual(REFUSED) + expect(rig.interrupts()).toEqual([]) + }) + + it.each(['idle', 'systemError'])( + 'stops nothing when Codex reports the thread %s', + async (type) => { + const rig = await codexTurnLifecycleRig() + const { stopping } = await waitingStop(rig) + + rig.notify('thread/status/changed', { threadId: CODEX_TEST_THREAD_ID, status: { type } }) + + expect(await settledWithin(stopping)).toEqual(REFUSED) + expect(rig.interrupts()).toEqual([]) + } + ) + + it('keeps waiting when a child thread stops running', async () => { + const rig = await codexTurnLifecycleRig() + const { stopping } = await waitingStop(rig) + + rig.notify('thread/status/changed', { threadId: 'thread-child', status: { type: 'idle' } }) + + expect(await settledWithin(stopping)).toBe('held') + rig.turns.start() + expect(await settledWithin(stopping)).toEqual({ cancelled: true }) + }) + + it('stops nothing when the child exits', async () => { + const rig = await codexTurnLifecycleRig() + const { stopping } = await waitingStop(rig) + + rig.codex.connections[0]!.handlers.onExit?.(new Error('codex app-server exited')) + + expect(await settledWithin(stopping)).toEqual(REFUSED) + expect(rig.interrupts()).toEqual([]) + }) + + it('stops nothing once its bound runs out', async () => { + const rig = await codexTurnLifecycleRig() + await answeredColdSend(rig) + vi.useFakeTimers() + let outcome: unknown = 'held' + void stop(rig).then((value) => { + outcome = value + }) + + await vi.advanceTimersByTimeAsync(CODEX_STOP_TURN_OPEN_WAIT_MS - 1) + expect(outcome).toBe('held') + await vi.advanceTimersByTimeAsync(1) + + expect(outcome).toEqual(REFUSED) + expect(rig.interrupts()).toEqual([]) + }) +}) diff --git a/src/main/codex/codex-structured-turn-open-wait.ts b/src/main/codex/codex-structured-turn-open-wait.ts new file mode 100644 index 00000000000..63e37294005 --- /dev/null +++ b/src/main/codex/codex-structured-turn-open-wait.ts @@ -0,0 +1,54 @@ +// A Stop's wait for the turn Codex answered a send into to open, or provably not to: it ended, +// the thread stopped running, or the child is gone. Held in memory only. + +import { + codexThreadStoppedRunning, + readCodexThreadId, + readCodexTurnId +} from './codex-structured-thread-facts' + +export type CodexTurnOpenWaits = { + /** Resolves once `turnId` opens or can no longer, and after `withinMs` at the latest. */ + wait: (turnId: string, withinMs: number) => Promise + /** Ends the waits a notification on the session's own thread answers. */ + observe: (threadId: string, method: string, params: unknown) => void + /** Ends every wait: the child that would open their turns is gone. */ + releaseAll: () => void +} + +export function createCodexTurnOpenWaits(): CodexTurnOpenWaits { + const waits = new Map<() => void, string>() + const release = (turnId?: string): void => { + for (const [endWait, waitedTurnId] of waits) { + if (turnId === undefined || waitedTurnId === turnId) { + endWait() + } + } + } + return { + wait: (turnId, withinMs) => + new Promise((resolve) => { + const endWait = (): void => { + clearTimeout(bound) + waits.delete(endWait) + resolve() + } + const bound = setTimeout(endWait, withinMs) + waits.set(endWait, turnId) + }), + observe: (threadId, method, params) => { + if ((readCodexThreadId(params) ?? threadId) !== threadId) { + return + } + if (method === 'thread/status/changed' && codexThreadStoppedRunning(params)) { + release() + return + } + const turnId = readCodexTurnId(params) + if (turnId && (method === 'turn/started' || method === 'turn/completed')) { + release(turnId) + } + }, + releaseAll: () => release() + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts index bc3c27ca5b1..e4ef8eb85f8 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts @@ -33,7 +33,10 @@ import { isAgentSessionWireRefusalCode, type AgentSessionRefusalReason } from '../../../shared/agent-session-wire-refusals' -import type { SubmissionRejectionFact } from '../../../shared/agent-session-failure' +import type { + ProviderDiagnostic, + SubmissionRejectionFact +} from '../../../shared/agent-session-failure' import type { AgentJournalDispatchRejection } from '../../../shared/agent-session-failure-words' import type { AgentSessionPromptResponse } from '../../../shared/agent-session-question-answer' import type { ProviderHistoryWindow } from '../agent-session-journal/journal-submission-reconciler' @@ -216,6 +219,14 @@ export type StructuredAgentSessionSetOptionInput = { fence: number } +/** `refusal`: the provider answered the Stop and declined it, in its own words when it gave any. + * `unconfirmed`: the provider took the Stop, but Orca could not confirm the turn's work ended. */ +export type AgentSessionCancelOutcome = { + cancelled: boolean + refusal?: { detail?: ProviderDiagnostic } + unconfirmed?: true +} + export type StructuredAgentSessionAdapter = { /** Provider-aware capability check for hosts that route more than one adapter. */ supportsCreate?(location: AgentSessionExecutionLocation, agent: string): boolean @@ -270,10 +281,11 @@ export type StructuredAgentSessionAdapter = { onLateResult?: (result: StructuredSessionCompactionResult) => Promise }): Promise /** Cancels one turn, not the session: a session-wide interrupt would also kill - * a turn the client never asked to stop. */ + * a turn the client never asked to stop. With no `turnId` the conversation asked to stop + * everything it has in flight — a running turn, or a dispatch whose turn has not opened yet. */ cancelTurn(input: { sessionId: string - turnId: string + turnId?: string fence: number prompt?: { itemId: string } /** Latest journal submission for this fence, when the host has one. */ @@ -282,7 +294,7 @@ export type StructuredAgentSessionAdapter = { * could have named. A function, not a value, because the guard re-checks after the * delivery fence may have waited. Absent for direct callers with no journal. */ resolveLiveTurnId?: () => string | null - }): Promise<{ cancelled: boolean }> + }): Promise /** Changes the provider thread's goal. `rejected` is the provider refusing the * change; a throw leaves its effect unknown. Absent where no goal exists. */ changeThreadGoal?(input: { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-echo-working.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-echo-working.test.ts new file mode 100644 index 00000000000..0fe20620160 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-echo-working.test.ts @@ -0,0 +1,146 @@ +// Claude's echo of a sent message both answers the send and opens its turn. Whatever order the +// host publishes those in, a chat reading its frames one at a time must read working throughout: +// Stop and every session list's Working come from that one rule. + +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import type { AgentJournalSubmission } from '../../../shared/agent-session-journal-types' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { isStructuredAgentSessionMainAgentWorking } from '../../../shared/structured-agent-session-main-agent-working' +import { ClaudeStructuredSessionAdapter } from '../../claude/claude-structured-session-adapter' +import { + fakeClaude, + PROVIDER_SESSION_ID +} from '../../claude/claude-structured-session-test-support' +import { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' +import { structuredClaudeLifecycleEvent } from '../../runtime/structured-claude-runtime-adapter' +import { StructuredAgentSessionHost } from './structured-agent-session-host' +import { + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + hostTestAttachParams, + hostTestMessage, + hostTestOperationId, + resetHostTestOperationIds +} from './structured-agent-session-host-test-data' + +const CALLER = { callerKey: 'client-1' } + +let root: string +let host: StructuredAgentSessionHost +let adapter: ClaudeStructuredSessionAdapter +let store: AgentSessionRecordStore +const claude = { current: fakeClaude({ replayUuid: null }) } + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-claude-echo-working-')) + resetHostTestOperationIds() + claude.current = fakeClaude({ replayUuid: null }) + const lifecycle: Promise[] = [] + adapter = new ClaudeStructuredSessionAdapter({ + resolveLaunch: async () => ({ + pathToClaudeCodeExecutable: 'claude', + options: {}, + cwd: root, + claudeConfigDir: join(root, 'claude-home'), + providerSessionId: PROVIDER_SESSION_ID, + resumeLeafUuid: null, + resumesTranscript: false, + continuesChain: false + }), + onEvent: (event) => { + const mapped = structuredClaudeLifecycleEvent(event) + if (mapped) { + lifecycle.push(host.handleAdapterEvent(mapped)) + } + }, + // As the runtime wires it. + onDispatchSettledLate: (settlement) => void host.settleLateDispatch(settlement), + openConnection: claude.current.openConnection, + readProcessStartTime: async () => 1_700_000_000_000, + now: () => NOW + }) + store = await AgentSessionRecordStore.open({ directory: join(root, 'store'), hostId: 'local' }) + host = new StructuredAgentSessionHost({ + store, + adapter: Object.assign(adapter, { supportsCreate: () => true }), + journalRoot: root, + claimKeyId: 'key-1', + mintSpawnToken: () => 'spawn-a', + now: () => NOW + }) + const params = hostTestAttachParams(null, { + provider: 'claude', + agent: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root, 'claude-home') }, + providerHandle: { kind: 'claude', sessionId: PROVIDER_SESSION_ID, leafUuid: null } + }) + expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) + await adapter.awaitStarted(SESSION) + await Promise.all(lifecycle) +}) + +afterEach(async () => { + await adapter.closeAll() + await host.flushAllStreamedEvents() + await rm(root, { recursive: true, force: true }) +}) + +function settled(): Promise { + return new Promise((resolve) => setTimeout(resolve, 20)) +} + +it('reads working at every published frame from the send through the echo that opens its turn', async () => { + const submissions = new Map() + const turns = new Map() + const working: boolean[] = [] + const fence = store.getRecord(SESSION)!.lease.runtimeFence + host.subscribe({ + id: 'chat-1', + sessionId: SESSION, + emit: (event) => { + if (event.type !== 'batch') { + return + } + for (const submission of event.batch.submissions) { + submissions.set(submission.clientMessageId, submission) + } + for (const item of event.batch.items) { + if (item.body.kind === 'turn') { + turns.set(item.itemId, item.body.state) + } + } + const running = [...turns].find(([, state]) => state === 'running')?.[0] ?? null + working.push( + isStructuredAgentSessionMainAgentWorking(running, [...submissions.values()], fence) + ) + } + }) + const body = hostTestMessage('hi') + await host.send(CALLER, { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: SESSION, + fields: { body } + }) + }, + body + }) + await settled() + const connection = claude.current.connections[0]! + // Claude echoes the written message back, which is what opens its turn. + connection.handlers.onMessage?.({ ...connection.sent.at(-1)!, uuid: 'echo-uuid' }) + await settled() + + expect([...submissions.values()].map((submission) => submission.dispatchState)).toEqual([ + 'accepted' + ]) + expect([...turns.values()]).toEqual(['running']) + expect(working).not.toContain(false) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-conversation-stop.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-conversation-stop.test.ts new file mode 100644 index 00000000000..ab0368a6b92 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-conversation-stop.test.ts @@ -0,0 +1,277 @@ +// A Stop that names no turn stops what the conversation has in flight: it withdraws what is +// queued, and interrupts a handed-over message even before the provider has opened its turn — +// the gap no client can name a turn for. Against the real host, store and journal. + +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import type { AgentJournalSubmission } from '../../../shared/agent-session-journal-types' +import { DISPATCH_REJECTED_CANCELLED } from '../../../shared/structured-agent-session-dispatch-rejection' +import { CancelParams } from '../../../shared/rpc-contract/structured-agent-session-params' +import { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' +import type { StructuredAgentSessionAdapter } from './structured-agent-session-adapter' +import { StructuredAgentSessionHost } from './structured-agent-session-host' +import { + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestAttachParams, + hostTestMessage, + hostTestOperationId, + resetHostTestOperationIds +} from './structured-agent-session-host-test-data' + +const CALLER = { callerKey: 'client-1' } +const ALREADY_FINISHED = 'The provider had already finished this turn.' + +let root: string +let store: AgentSessionRecordStore +let host: StructuredAgentSessionHost +let dispatch: Mock +let cancelTurn: Mock +let awaitStarted: Mock> + +function eventually(assertion: () => void | Promise): Promise { + return vi.waitFor(assertion, { timeout: 10_000 }) +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-conversation-stop-')) + resetHostTestOperationIds() + // Admitted, not accepted: the message is written and its turn has not opened. + dispatch = vi.fn(async () => ({ state: 'admitted' as const })) + cancelTurn = vi.fn(async () => ({ cancelled: true })) + awaitStarted = vi.fn(async () => undefined) + store = await AgentSessionRecordStore.open({ directory: join(root, 'store'), hostId: 'local' }) + host = new StructuredAgentSessionHost({ + store, + adapter: { + acquire: async ({ fence, spawnToken }) => ({ + process: { hostId: 'local', pid: 4242, processStartTimeMs: 1_700_000_000_000, spawnToken }, + acquisitionGeneration: 'generation-1', + link: { + linkId: `link-${fence}`, + handle: { provider: 'codex' as const, threadId: THREAD }, + origin: 'created' as const, + mintedAtFence: fence, + observedAt: NOW + } + }), + dispatch, + awaitStarted, + closeSession: vi.fn(async () => true), + releaseAcquisition: vi.fn(async () => true), + cancelTurn, + answerPrompt: vi.fn(async () => undefined), + setOption: vi.fn(async () => undefined) + }, + journalRoot: root, + claimKeyId: 'key-1', + mintSpawnToken: () => 'spawn-1', + now: () => NOW + }) + expect(await host.attach(CALLER, hostTestAttachParams(null))).toMatchObject({ ok: true }) +}) + +afterEach(async () => { + await host.flushAllStreamedEvents() + await rm(root, { recursive: true, force: true }) +}) + +function send(text: string) { + const body = hostTestMessage(text) + const clientOperationId = hostTestOperationId() + const result = host.send(CALLER, { + envelope: { + sessionId: SESSION, + clientOperationId, + expectedRuntimeFence: 1, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: SESSION, + fields: { body } + }) + }, + body + }) + return { id: clientOperationId, result } +} + +function stop(turnId?: string, clientOperationId = hostTestOperationId()) { + const fields = turnId === undefined ? {} : { turnId } + return host.cancel(CALLER, { + envelope: { + sessionId: SESSION, + clientOperationId, + expectedRuntimeFence: null, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.cancel', + sessionId: SESSION, + fields + }) + }, + ...fields + }) +} + +async function submission(id: string): Promise { + return (await host.journalSnapshot(SESSION)).submissions.find( + (entry) => entry.clientMessageId === id + ) +} + +async function statusRows(): Promise { + return (await host.journalSnapshot(SESSION)).items.flatMap((item) => + item.body.kind === 'status' ? [item.body.text] : [] + ) +} + +describe('a Stop that names no turn', () => { + it('is a valid cancel, and only a plain Stop may omit the turn', () => { + const envelope = { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: 1, + payloadFingerprint: '0'.repeat(64) + } + expect(CancelParams.safeParse({ envelope }).success).toBe(true) + expect( + CancelParams.safeParse({ envelope, prompt: { itemId: 'item-1', expectedRevision: 1 } }) + .success + ).toBe(false) + expect(CancelParams.safeParse({ envelope, scope: 'background-tasks' }).success).toBe(false) + }) + + it('interrupts a handed-over message before its turn opens, as a cancellation', async () => { + const { id, result } = send('hello') + await result + await eventually(async () => expect((await submission(id))?.handedOverAt).toBeDefined()) + expect( + (await host.journalSnapshot(SESSION)).items.some((item) => item.body.kind === 'turn') + ).toBe(false) + + const stopped = await stop() + + expect(stopped).toEqual({ + ok: true, + replayed: false, + fence: 1, + cursor: expect.anything(), + value: { cancelled: true } + }) + expect(cancelTurn).toHaveBeenCalledTimes(1) + expect(cancelTurn.mock.calls[0]![0]).not.toHaveProperty('turnId') + expect(cancelTurn.mock.calls[0]![0]).toMatchObject({ sessionId: SESSION, fence: 1 }) + expect(await statusRows()).toEqual(['Cancellation requested.']) + }) + + it('withdraws what is queued on a ready child and asks the provider for nothing more', async () => { + const started = Promise.withResolvers() + awaitStarted.mockImplementationOnce(() => started.promise) + const { id, result } = send('hello') + await result + await eventually(() => expect(awaitStarted).toHaveBeenCalled()) + + expect(await stop()).toMatchObject({ ok: true, value: { cancelled: true } }) + started.resolve(undefined) + + expect(await submission(id)).toMatchObject({ + dispatchState: 'rejected', + reason: DISPATCH_REJECTED_CANCELLED + }) + expect(cancelTurn).not.toHaveBeenCalled() + await host.flushStreamedEvents(SESSION) + expect(dispatch).not.toHaveBeenCalled() + expect(await statusRows()).toEqual([]) + }) + + it('withdraws a send still on its way in, which the host takes first', async () => { + const { id, result } = send('hello') + const stopped = stop() + + expect(await result).toMatchObject({ ok: true }) + expect(await stopped).toMatchObject({ ok: true, value: { cancelled: true } }) + expect(await submission(id)).toMatchObject({ + dispatchState: 'rejected', + reason: DISPATCH_REJECTED_CANCELLED + }) + await host.flushStreamedEvents(SESSION) + expect(dispatch).not.toHaveBeenCalled() + }) + + it('says the agent did not stop, in its words, when it refused', async () => { + const { id, result } = send('hello') + await result + await eventually(async () => expect((await submission(id))?.handedOverAt).toBeDefined()) + cancelTurn.mockResolvedValueOnce({ + cancelled: false, + refusal: { detail: { text: 'no active turn to interrupt', audience: 'person' } } + }) + + expect(await stop()).toMatchObject({ ok: true, value: { cancelled: false } }) + + expect(cancelTurn).toHaveBeenCalledOnce() + expect(await statusRows()).toEqual(["Codex didn't stop: no active turn to interrupt."]) + }) + + it('says the Stop is unconfirmed, not that nothing ran, when the provider took it', async () => { + const { id, result } = send('hello') + await result + await eventually(async () => expect((await submission(id))?.handedOverAt).toBeDefined()) + cancelTurn.mockResolvedValueOnce({ cancelled: false, unconfirmed: true }) + + expect(await stop()).toMatchObject({ ok: true, value: { cancelled: false } }) + + expect(await statusRows()).toEqual(['Cancellation was not confirmed.']) + }) + + it('says the agent had no turn to stop when it had none', async () => { + const { id, result } = send('hello') + await result + await eventually(async () => expect((await submission(id))?.handedOverAt).toBeDefined()) + cancelTurn.mockResolvedValueOnce({ cancelled: false }) + + expect(await stop()).toMatchObject({ ok: true, value: { cancelled: false } }) + + expect(await statusRows()).toEqual(['Codex had no turn running to stop.']) + }) + + it('stops nothing when it reuses the id of a Stop the host already ran', async () => { + const operationId = hostTestOperationId() + expect(await stop(undefined, operationId)).toMatchObject({ ok: true, replayed: false }) + const { id, result } = send('hello') + await result + await eventually(async () => expect((await submission(id))?.handedOverAt).toBeDefined()) + + // Why the client never reuses a no-turn Stop's id: the same id is the same Stop. + expect(await stop(undefined, operationId)).toMatchObject({ + ok: true, + replayed: true, + value: { cancelled: false } + }) + expect(cancelTurn).not.toHaveBeenCalled() + expect(await stop()).toMatchObject({ ok: true, value: { cancelled: true } }) + expect(cancelTurn).toHaveBeenCalledOnce() + }) + + it('is a quiet no-op with nothing in flight', async () => { + expect(await stop()).toMatchObject({ ok: true, value: { cancelled: false } }) + expect(cancelTurn).not.toHaveBeenCalled() + expect(await statusRows()).toEqual([]) + }) +}) + +describe('a Stop that names its turn, as an older client sends it', () => { + it('reaches the provider with that turn and keeps its not-cancelled note', async () => { + cancelTurn.mockResolvedValueOnce({ cancelled: false }) + + expect(await stop('turn-1')).toMatchObject({ + ok: true, + value: { turnId: 'turn-1', cancelled: false } + }) + expect(cancelTurn).toHaveBeenCalledWith(expect.objectContaining({ turnId: 'turn-1' })) + expect(await statusRows()).toEqual([ALREADY_FINISHED]) + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts index 35782b676c2..1586bd4a1c1 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts @@ -21,6 +21,7 @@ import type { AgentSessionThreadGoalChange, AgentSessionThreadGoalResult } from '../../../shared/agent-session-wire' +import { isStructuredAgentSessionMainAgentWorking } from '../../../shared/structured-agent-session-main-agent-working' import { agentSessionFailureWords, type AgentJournalDispatchRejection @@ -38,6 +39,7 @@ import { openForWrite, openWithAgent, sendPreparation, + structuredAgentSessionFailureWordsContext, structuredAgentSessionSendBlock } from './structured-agent-session-send-preparation' import { @@ -138,7 +140,7 @@ export function cancelStructuredAgentSessionTurn( caller: StructuredAgentSessionCaller, params: { envelope: AgentSessionMutationEnvelope - turnId: string + turnId?: string scope?: 'background-tasks' taskId?: string prompt?: { itemId: string; expectedRevision: number } @@ -176,15 +178,29 @@ export function cancelStructuredAgentSessionTurn( ctx.fence, agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }) ) + const named = params.turnId !== undefined ? { turnId: params.turnId } : {} const child = context.sessions.get(ctx.sessionId)?.child if (child?.phase === 'starting') { // A start that may never land is the one thing here Stop has to end; the chat stays. await context.stopAgent(ctx.sessionId) - return { ok: true, value: { turnId: params.turnId, cancelled: true } } + return { ok: true, value: { ...named, cancelled: true } } } - return child - ? plan.run(ctx) - : { ok: true, value: { turnId: params.turnId, cancelled: withdrawn.length > 0 } } + // A Stop naming no turn ends nothing more unless the session reads working, by the rule + // every session list and the chat's own Stop read it. + const inFlight = + params.turnId !== undefined || + isStructuredAgentSessionMainAgentWorking( + ctx.journal.activeTurnId(), + ctx.journal.submissions(), + ctx.fence + ) + const record = context.deps.store.getRecord(ctx.sessionId) + return child && inFlight + ? plan.run({ + ...ctx, + failureTextContext: structuredAgentSessionFailureWordsContext(record) + }) + : { ok: true, value: { ...named, cancelled: withdrawn.length > 0 } } } }, openForWrite(context, params.envelope) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-main-agent-working-agreement.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-main-agent-working-agreement.test.ts new file mode 100644 index 00000000000..35c02972829 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-main-agent-working-agreement.test.ts @@ -0,0 +1,229 @@ +// The chat's own Stop and every session list read whether the main agent is working through one +// rule, but over two copies of the host's journal: the chat reduces its stream, and a list reads the +// status feed. Both leave the host from one publication edge, so once each has landed they must say +// the same thing. Against the real host, store, journal, stream and status feed. + +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import type { AgentSessionBackgroundTaskState } from '../../../shared/agent-session-background-task-wire' +import type { AgentJournalItemBody } from '../../../shared/agent-session-journal-types' +import type { AgentSessionStatusSummary } from '../../../shared/agent-session-wire' +import { structuredAgentSessionAgentStatus } from '../../../shared/structured-agent-session-agent-status' +import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' +import { isStructuredAgentSessionMainAgentWorking } from '../../../shared/structured-agent-session-main-agent-working' +import { + EMPTY_STRUCTURED_AGENT_SESSION, + reduceStructuredAgentSession, + type StructuredAgentSessionState +} from '../../../shared/structured-agent-session-reducer' +import { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' +import type { StructuredAgentSessionAdapter } from './structured-agent-session-adapter' +import type { StructuredAgentSessionEventSink } from './structured-agent-session-event-sink' +import { StructuredAgentSessionHost } from './structured-agent-session-host' +import { + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestAttachParams, + hostTestMessage, + hostTestOperationId, + resetHostTestOperationIds +} from './structured-agent-session-host-test-data' + +const CALLER = { callerKey: 'client-1' } +const PROVIDER_ROW = { provider: 'codex' as const, threadId: THREAD, turnId: 'turn-1' } + +let root: string +let store: AgentSessionRecordStore +let host: StructuredAgentSessionHost +let dispatch: Mock +let events: StructuredAgentSessionEventSink | undefined +let backgroundTasks: AgentSessionBackgroundTaskState | null +let chat: StructuredAgentSessionState +let listed: AgentSessionStatusSummary | undefined + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-main-agent-working-')) + resetHostTestOperationIds() + events = undefined + backgroundTasks = null + chat = EMPTY_STRUCTURED_AGENT_SESSION + listed = undefined + // Written, and the provider has neither opened a turn for it nor answered it. + dispatch = vi.fn(async () => ({ state: 'admitted' as const })) + store = await AgentSessionRecordStore.open({ directory: join(root, 'store'), hostId: 'local' }) + host = new StructuredAgentSessionHost({ + store, + adapter: { + acquire: async (input) => { + events = input.events + return { + process: { + hostId: 'local', + pid: 4242, + processStartTimeMs: 1_700_000_000_000, + spawnToken: input.spawnToken + }, + acquisitionGeneration: 'generation-1', + link: { + linkId: `link-${input.fence}`, + handle: { provider: 'codex' as const, threadId: THREAD }, + origin: 'created' as const, + mintedAtFence: input.fence, + observedAt: NOW + } + } + }, + dispatch, + awaitStarted: vi.fn(async () => undefined), + closeSession: vi.fn(async () => true), + releaseAcquisition: vi.fn(async () => true), + cancelTurn: vi.fn(async () => ({ cancelled: true })), + answerPrompt: vi.fn(async () => undefined), + setOption: vi.fn(async () => undefined), + backgroundTaskState: () => backgroundTasks + }, + journalRoot: root, + claimKeyId: 'key-1', + mintSpawnToken: () => 'spawn-1', + now: () => NOW + }) + expect(await host.attach(CALLER, hostTestAttachParams(null))).toMatchObject({ ok: true }) + host.subscribe({ + id: 'chat-1', + sessionId: SESSION, + emit: (event) => { + chat = reduceStructuredAgentSession(chat, { type: 'event', event: structuredClone(event) }) + } + }) + host.subscribeStatus({ + id: 'list-1', + emit: (event) => { + if (event.type === 'status' && event.session.sessionId === SESSION) { + listed = structuredClone(event.session) + } else if (event.type === 'snapshot') { + listed = event.sessions.find((session) => session.sessionId === SESSION) ?? listed + } + } + }) +}) + +afterEach(async () => { + await host.flushAllStreamedEvents() + await rm(root, { recursive: true, force: true }) +}) + +async function send(text: string): Promise { + const body = hostTestMessage(text) + const clientOperationId = hostTestOperationId() + expect( + await host.send(CALLER, { + envelope: { + sessionId: SESSION, + clientOperationId, + expectedRuntimeFence: 1, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: SESSION, + fields: { body } + }) + }, + body + }) + ).toMatchObject({ ok: true }) + return clientOperationId +} + +async function provider(ordinal: number, body: AgentJournalItemBody): Promise { + events!.appendItem({ ...PROVIDER_ROW, ordinal }, body) + events!.publish() + await host.flushStreamedEvents(SESSION) +} + +/** What the chat's Stop reads: the transport state's rule over the chat's reduced stream. */ +function chatReadsWorking(): boolean { + return isStructuredAgentSessionMainAgentWorking( + activeStructuredAgentSessionTurnId(chat.items), + chat.submissions, + chat.fence + ) +} + +/** What a session list's row reads for the main agent, and the whole row, from the status feed. */ +function listReads(): { mainAgent: string; row: string } { + const summary = listed + if (!summary?.status) { + return { mainAgent: 'none', row: 'none' } + } + const status = structuredAgentSessionAgentStatus({ ...summary, status: summary.status }) + return { mainAgent: status.mainAgent.state, row: status.state } +} + +describe('the main agent read by the chat and by a session list', () => { + it('agrees while a rate-limited request retries with no turn open', async () => { + const id = await send('hello') + await vi.waitFor(async () => + expect((await host.journalSnapshot(SESSION)).submissions[0]?.handedOverAt).toBeDefined() + ) + // What Claude writes for an HTTP 429 retry: a status row, no echo, no turn. + await provider(1, { kind: 'status', text: 'rate_limit', tone: 'error' }) + await provider(2, { kind: 'status', text: 'rate_limit', tone: 'error' }) + + expect(chat.submissions.map((submission) => submission.clientMessageId)).toEqual([id]) + expect(activeStructuredAgentSessionTurnId(chat.items)).toBeNull() + expect(chatReadsWorking()).toBe(true) + expect(listReads().mainAgent).toBe('working') + }) + + it('agrees once the handed-over message is answered and only a subagent still runs', async () => { + dispatch.mockResolvedValueOnce({ + state: 'accepted', + providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 0 } + }) + await send('fan out') + await vi.waitFor(async () => + expect((await host.journalSnapshot(SESSION)).submissions[0]?.dispatchState).toBe('accepted') + ) + await provider(1, { kind: 'turn', turnId: 'turn-1', state: 'running' }) + expect(chatReadsWorking()).toBe(true) + expect(listReads().mainAgent).toBe('working') + + await provider(1, { kind: 'turn', turnId: 'turn-1', state: 'completed', outcome: 'success' }) + backgroundTasks = { + state: 'monitoring', + tasks: [{ id: 'task-1', kind: 'agent', name: 'deep_review', state: 'working' }] + } + host.publishBackgroundTaskState(SESSION) + await host.flushStreamedEvents(SESSION) + + expect(chat.backgroundTasks?.tasks).toHaveLength(1) + // The row reads Working for the subagent; the main agent, and so Stop, does not. + expect(listReads()).toEqual({ mainAgent: 'done', row: 'working' }) + expect(chatReadsWorking()).toBe(false) + }) + + it('agrees when the child that was handed the message exits', async () => { + await send('hello') + await vi.waitFor(async () => + expect((await host.journalSnapshot(SESSION)).submissions[0]?.handedOverAt).toBeDefined() + ) + expect(chatReadsWorking()).toBe(true) + + await host.handleAdapterEvent({ + type: 'ended', + sessionId: SESSION, + fence: store.getRecord(SESSION)!.lease.runtimeFence, + acquisitionGeneration: 'generation-1', + reason: 'codex app-server crashed', + cause: 'unexpected-exit' + }) + await host.flushStreamedEvents(SESSION) + + expect(chat.fence).toBe(store.getRecord(SESSION)!.lease.runtimeFence) + expect(chatReadsWorking()).toBe(false) + expect(listReads().mainAgent).not.toBe('working') + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-plans.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-plans.ts index fd56944f3bd..2007f9bc174 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-plans.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-plans.ts @@ -98,7 +98,7 @@ export function sendPlan(params: { export function cancelPlan(params: { envelope: AgentSessionMutationEnvelope - turnId: string + turnId?: string scope?: 'background-tasks' taskId?: string prompt?: { itemId: string; expectedRevision: number } @@ -108,7 +108,7 @@ export function cancelPlan(params: { // Stop is a conversation write; a prompt or background-task cancel needs the live child. ...(params.scope || params.prompt ? {} : { conversationWrite: true as const }), fields: { - turnId: params.turnId, + ...(params.turnId !== undefined ? { turnId: params.turnId } : {}), ...(params.scope ? { scope: params.scope } : {}), ...(params.taskId ? { taskId: params.taskId } : {}), ...(params.prompt ? { prompt: params.prompt } : {}) @@ -116,14 +116,17 @@ export function cancelPlan(params: { run: (ctx) => performCancel(ctx, { clientOperationId: params.envelope.clientOperationId, - turnId: params.turnId, + ...(params.turnId !== undefined ? { turnId: params.turnId } : {}), ...(params.scope ? { scope: params.scope } : {}), ...(params.taskId ? { taskId: params.taskId } : {}), ...(params.prompt ? { prompt: params.prompt } : {}) }), // Interrupting twice would kill a turn the client never asked to stop, so a // replay reports the turn as already handled instead. - replay: () => ({ turnId: params.turnId, cancelled: false }) + replay: () => ({ + ...(params.turnId !== undefined ? { turnId: params.turnId } : {}), + cancelled: false + }) } } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-turns.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-turns.ts index 49642b9a897..46c4638dc4e 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-turns.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-turns.ts @@ -27,6 +27,7 @@ import { DISPATCH_DOUBT_PERSISTENCE_FAILED } from '../agent-session-journal/jour import type { AgentSessionJournal } from '../agent-session-journal/journal-store' import { latestJournalDispatchObservation } from '../agent-session-journal/journal-dispatch-observation' import type { + AgentSessionCancelOutcome, AgentSessionDispatchOutcome, StructuredAgentSessionAdapter, StructuredAgentSessionProviderChildPhase @@ -53,6 +54,8 @@ export type AgentSessionTurnContext = { flushStreamedEvents: () => Promise /** What the host holds about the child this dispatch is for, read at the moment it is needed. */ providerChildPhase?: () => StructuredAgentSessionProviderChildPhase | undefined + /** Who a Stop's refusal row names. */ + failureTextContext?: AgentSessionFailureWordsContext now: () => number } @@ -239,7 +242,8 @@ export async function performCancel( ctx: AgentSessionTurnContext, input: { clientOperationId: string - turnId: string + /** Absent: whatever the conversation has in flight; present: only while that turn is current. */ + turnId?: string scope?: 'background-tasks' taskId?: string prompt?: { itemId: string; expectedRevision: number } @@ -252,30 +256,51 @@ export async function performCancel( } } let cancelled = false - let note: AgentJournalStatusItem = { kind: 'status', text: 'Cancellation requested.' } + let note: AgentJournalStatusItem | null = { kind: 'status', text: 'Cancellation requested.' } try { const dispatchStatus = latestJournalDispatchObservation(ctx.journal, ctx.fence) - cancelled = input.scope - ? ( - await ctx.adapter.stopBackgroundTasks?.({ - sessionId: ctx.sessionId, - fence: ctx.fence, - ...(input.taskId ? { taskId: input.taskId } : {}) - }) - )?.cancelled === true - : ( - await ctx.adapter.cancelTurn({ - sessionId: ctx.sessionId, - turnId: input.turnId, - fence: ctx.fence, - // The journal is what the client read to name a turn, so it is what judges the request. - resolveLiveTurnId: () => ctx.journal.activeTurnId(), - ...(dispatchStatus ? { dispatchStatus } : {}), - ...(input.prompt ? { prompt: { itemId: input.prompt.itemId } } : {}) - }) - ).cancelled - if (!cancelled) { + const outcome: AgentSessionCancelOutcome = input.scope + ? { + cancelled: + ( + await ctx.adapter.stopBackgroundTasks?.({ + sessionId: ctx.sessionId, + fence: ctx.fence, + ...(input.taskId ? { taskId: input.taskId } : {}) + }) + )?.cancelled === true + } + : await ctx.adapter.cancelTurn({ + sessionId: ctx.sessionId, + ...(input.turnId !== undefined ? { turnId: input.turnId } : {}), + fence: ctx.fence, + // The journal is what the client read to name a turn, so it is what judges the request. + resolveLiveTurnId: () => ctx.journal.activeTurnId(), + ...(dispatchStatus ? { dispatchStatus } : {}), + ...(input.prompt ? { prompt: { itemId: input.prompt.itemId } } : {}) + }) + cancelled = outcome.cancelled + if (!cancelled && input.turnId !== undefined) { note = { kind: 'status', text: 'The provider had already finished this turn.' } + } else if (!cancelled && input.prompt) { + note = null + } else if (!cancelled && outcome.unconfirmed) { + note = { + kind: 'status', + ...agentSessionFailureWords(agentSessionFailureFact('cancelUnconfirmed'), { + surface: 'row' + }) + } + } else if (!cancelled) { + // Sent only while the chat reads working, so a Stop that ended nothing must say why. + const detail = outcome.refusal?.detail + note = { + kind: 'status', + ...agentSessionFailureWords( + agentSessionFailureFact('stopRefused', detail ? { detail } : {}), + { ...ctx.failureTextContext, surface: 'row' } + ) + } } } catch (error) { if (input.prompt) { @@ -290,10 +315,11 @@ export async function performCancel( if (cancelled && input.prompt) { await ctx.flushStreamedEvents() } - if (input.scope) { - return { ok: true, value: { turnId: input.turnId, cancelled } } + const value = { ...(input.turnId !== undefined ? { turnId: input.turnId } : {}), cancelled } + if (input.scope || note === null) { + return { ok: true, value } } // Keyed by the operation id so a replayed cancel upserts one item, not two. await appendStatus(ctx, input.clientOperationId, note) - return { ok: true, value: { turnId: input.turnId, cancelled } } + return { ok: true, value } } diff --git a/src/main/runtime/rpc/methods/structured-agent-session.test.ts b/src/main/runtime/rpc/methods/structured-agent-session.test.ts index a8378489c02..f1e27aec3de 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' import { AGENT_SESSION_ACCEPTED_SEND_RUNTIME_CAPABILITY, + AGENT_SESSION_CONVERSATION_STOP_RUNTIME_CAPABILITY, AGENT_SESSION_PENDING_SEND_RESULT_RUNTIME_CAPABILITY, RUNTIME_CAPABILITIES, RUNTIME_PROTOCOL_VERSION, @@ -153,6 +154,8 @@ describe('capability gating', () => { expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_PENDING_SEND_RESULT_RUNTIME_CAPABILITY) // A client tells a host that accepts first, and admits a writer-free Stop before a turn, by it. expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_ACCEPTED_SEND_RUNTIME_CAPABILITY) + // And a cancel naming no turn, which a host that only accepts first still refuses as invalid. + expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_CONVERSATION_STOP_RUNTIME_CAPABILITY) expect(RUNTIME_CAPABILITIES).toContain(STRUCTURED_AGENT_SESSION_HOLD_RUNTIME_CAPABILITY) expect(RUNTIME_CAPABILITIES).toContain(STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY) // Separate from the structured capability on purpose: a host can serve the rest of the diff --git a/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts b/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts index fc06a2a782b..c86f7c85242 100644 --- a/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts +++ b/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts @@ -1,5 +1,6 @@ // A Codex send the turn it went into never took: the Stop that interrupts that turn -// withdraws it, and nothing reads as working after. Driven through the shipped host, +// withdraws it, and nothing reads as working after. A Stop sent before Codex opens that +// turn waits for it to open, since Codex refuses an interrupt until then. Driven through the shipped host, // journal and Codex adapter; only the Codex child is fake, keeping Codex 0.157's // turn bookkeeping. @@ -13,6 +14,8 @@ import type { openCodexAppServerConnection } from '../codex/codex-app-server-connection' import { codexTurnLifecycleFake } from '../codex/codex-turn-lifecycle-fake' +import { settledWithin } from '../codex/codex-structured-dispatch-test-support' +import { CODEX_STOP_TURN_OPEN_WAIT_MS } from '../codex/codex-structured-prompt-ownership' import { computeAgentSessionPayloadFingerprint } from '../../shared/agent-session-mutation-envelope' import type { AgentJournalSubmission } from '../../shared/agent-session-journal-types' import { classifyDispatchRejection } from '../../shared/structured-agent-session-dispatch-rejection' @@ -24,6 +27,7 @@ import { hostTestMessage } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' +import { CHILD_EVICTION_TIMEOUT_MS } from '../native-chat/agent-session-wire/structured-agent-session-host-teardown' import { ensureStructuredAgentSessionHost, stopStructuredAgentSessionRuntime @@ -50,6 +54,8 @@ let host: StructuredAgentSessionHost let fence: number let handlers: CodexAppServerConnectionHandlers | undefined let answers: number +let interrupts: number +let childCloses: number let turns: ReturnType let operations = 0 @@ -78,10 +84,10 @@ async function send(text: string): Promise { return sent.value.clientMessageId } -async function stop(turnId: string): Promise { +async function stop(turnId?: string): Promise { const stopped = await host.cancel(CALLER, { - envelope: envelope('agentSession.cancel', { turnId }), - turnId + envelope: envelope('agentSession.cancel', turnId === undefined ? {} : { turnId }), + ...(turnId === undefined ? {} : { turnId }) }) if (!stopped.ok) { throw new Error(JSON.stringify(stopped.refusal)) @@ -111,6 +117,8 @@ function verdictOf(submissions: readonly AgentJournalSubmission[], clientMessage beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-codex-turn-end-')) answers = 0 + interrupts = 0 + childCloses = 0 turns = codexTurnLifecycleFake( THREAD, () => (method, params) => handlers?.onNotification?.(method, params) @@ -135,6 +143,7 @@ beforeEach(async () => { return turns.routes['turn/start']() } if (method === 'turn/interrupt') { + interrupts += 1 return turns.routes['turn/interrupt'](params) } return {} @@ -142,7 +151,10 @@ beforeEach(async () => { notify: () => {}, respond: () => {}, respondWithError: () => {}, - close: async () => true + close: async () => { + childCloses += 1 + return true + } } return connection } @@ -215,3 +227,98 @@ describe('a Codex send its turn ended without taking it', () => { expect(after.owesWork).toBe(false) }) }) + +describe('a Stop sent after Codex answered a cold send, before it opened the turn', () => { + it('waits for the turn to open, then stops it and withdraws the send', async () => { + const sent = await send('look around') + await vi.waitFor(() => expect(answers).toBe(1)) + + const stopping = stop() + // Without the wait, it would reach Codex now, which would refuse it, and be done. + expect(await settledWithin(stopping, 1_000)).toBe('held') + expect(interrupts).toBe(0) + turns.start() + await stopping + + expect(interrupts).toBe(1) + expect(turns.turnId).toBeNull() + await vi.waitFor(async () => + expect(verdictOf((await settled()).submissions, sent)).toBe('withdrawn') + ) + expect((await settled()).owesWork).toBe(false) + }) +}) + +describe('a Stop in that window that the turn never opens for', () => { + async function statusRows(): Promise { + return (await host.journalSnapshot(SESSION)).items.flatMap((item) => + item.body.kind === 'status' ? [item.body.text] : [] + ) + } + + async function waitingStop(): Promise<{ stopping: Promise }> { + await send('look around') + await vi.waitFor(() => expect(answers).toBe(1)) + const stopping = stop() + expect(await settledWithin(stopping, 200)).toBe('held') + return { stopping } + } + + it('says Codex had no turn running when that turn ends first', async () => { + const { stopping } = await waitingStop() + + turns.end('interrupted') + await stopping + + expect(interrupts).toBe(0) + expect(await statusRows()).toContain('Codex had no turn running to stop.') + }) + + it('lets a chat closed behind it close within its bound and one eviction', async () => { + const { stopping } = await waitingStop() + + const closing = host.close(SESSION) + + expect( + await settledWithin(closing, CODEX_STOP_TURN_OPEN_WAIT_MS + CHILD_EVICTION_TIMEOUT_MS) + ).not.toBe('held') + expect(await settledWithin(stopping, 0)).not.toBe('held') + expect(childCloses).toBe(1) + expect(interrupts).toBe(0) + expect(await statusRows()).toContain('Codex had no turn running to stop.') + }) + + it('lets the app quit behind it within the eviction budget, and still close the child', async () => { + await waitingStop() + + expect( + await settledWithin(stopStructuredAgentSessionRuntime(), CHILD_EVICTION_TIMEOUT_MS) + ).not.toBe('held') + expect(childCloses).toBe(1) + }) +}) + +describe('a cold send with no Stop behind it', () => { + /** Well inside one eviction step's budget, and far inside the bound a Stop waits. */ + const PROMPTLY_MS = 1_000 + + async function answeredColdSend(): Promise { + await send('look around') + await vi.waitFor(() => expect(answers).toBe(1)) + expect(turns.turnId).toBe('turn-1') + } + + it('never delays closing the chat', async () => { + await answeredColdSend() + + expect(await settledWithin(host.close(SESSION), PROMPTLY_MS)).not.toBe('held') + expect(childCloses).toBe(1) + }) + + it('never delays quitting the app', async () => { + await answeredColdSend() + + expect(await settledWithin(stopStructuredAgentSessionRuntime(), PROMPTLY_MS)).not.toBe('held') + expect(childCloses).toBe(1) + }) +}) diff --git a/src/renderer/src/components/native-chat/NativeChatComposer.test.tsx b/src/renderer/src/components/native-chat/NativeChatComposer.test.tsx index 8eb4c9b7469..bf0cdd4bc6c 100644 --- a/src/renderer/src/components/native-chat/NativeChatComposer.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatComposer.test.tsx @@ -100,7 +100,7 @@ vi.mock('@/lib/native-chat-telemetry', () => ({ vi.mock('./use-native-chat-draft', () => ({ useNativeChatDraft: (scopeKey: string) => { mocks.draftScopeKeys.push(scopeKey) - return { draft: mocks.draft, setDraft: mocks.setDraft } + return { draft: mocks.draft, setDraft: mocks.setDraft, flushDraftAppends: () => {} } } })) vi.mock('./native-chat-draft-cache', () => ({ diff --git a/src/renderer/src/components/native-chat/NativeChatComposer.tsx b/src/renderer/src/components/native-chat/NativeChatComposer.tsx index 60735d705e2..922ddfd20cd 100644 --- a/src/renderer/src/components/native-chat/NativeChatComposer.tsx +++ b/src/renderer/src/components/native-chat/NativeChatComposer.tsx @@ -74,7 +74,11 @@ const NativeChatComposerPane = forwardRef(null) const [dictationPressed, setDictationPressed] = useState(false) - const imeEnterGesture = useImeEnterGestureOwnership() const { textareaRef } = useNativeChatComposerAppMenuSelection(imeEnterGesture.isComposing) const { cancelPendingSends, trackPendingSend } = useNativeChatSendLifecycle( terminalTabId, @@ -386,6 +389,7 @@ const NativeChatComposerPane = forwardRef(), messages: null as null | unknown[], messageListProps: initialMessageListProps, - composerProps: null as null | { + composerProps: nullable<{ launchSeed?: NativeChatLaunchSeed structuredTransport?: Record isWorking?: boolean - }, + onStop?: () => void + }>(), approvalCardProps: initialApprovalCardProps, questionCardProps: null as NativeChatQuestionCardProps | null, promptItems: [] as AgentJournalRenderItem[], journalItems: new Array(), respond: vi.fn<(...args: never[]) => unknown>(), cancel: vi.fn<(...args: never[]) => unknown>(), + stop: vi.fn<() => unknown>(), handlePasteEvent: vi.fn<(...args: never[]) => unknown>(), pasteFromClipboard: vi.fn<(...args: never[]) => unknown>(), submissions: [] as unknown[], @@ -99,6 +101,8 @@ export function createStructuredSessionMocks() { showBackgroundTasks: false, isWorking: false, turnId: null as string | null, + // Unset: Stop follows the turn, as against an older host. + canStop: nullable(), supportsBackgroundTaskStop: false, supportsBackgroundTaskStopAll: true, backgroundTasks: [] as AgentSessionBackgroundTask[], @@ -178,6 +182,8 @@ export function createStructuredSessionMocks() { supportsStopAll: mocks.supportsBackgroundTaskStopAll }, turnId: mocks.turnId, + canStop: mocks.canStop ?? mocks.turnId !== null, + stop: mocks.stop, threadGoal: mocks.threadGoal, cancel: mocks.cancel, stopBackgroundTask: (taskId?: string) => @@ -288,6 +294,7 @@ export function createStructuredSessionMocks() { mocks.journalItems = [] mocks.respond.mockReset() mocks.cancel.mockReset() + mocks.stop.mockReset() mocks.handlePasteEvent.mockReset() mocks.pasteFromClipboard.mockReset() mocks.submissions = [] @@ -295,6 +302,7 @@ export function createStructuredSessionMocks() { mocks.showBackgroundTasks = false mocks.isWorking = false mocks.turnId = null + mocks.canStop = null mocks.supportsBackgroundTaskStop = false mocks.supportsBackgroundTaskStopAll = true mocks.stopBackgroundTask.mockReset() diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx index 9a40f63530d..9279ca63f20 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.test.tsx @@ -27,6 +27,7 @@ vi.mock('./NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard vi.mock('./NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard()) import { NativeChatStructuredSession } from './NativeChatStructuredSession' +import { structuredAgentSessionPaneKey } from '../../../../shared/structured-agent-session-projection' describe('NativeChatStructuredSession', () => { afterEach(() => { @@ -34,6 +35,22 @@ describe('NativeChatStructuredSession', () => { resetStructuredSessionMocks() }) + it('gives what a Stop withdrew back to the composer this pane shows', () => { + render( + + ) + const paneKey = structuredAgentSessionPaneKey('structured-tab-1', 'session-1') + expect(mocks.composerProps).toMatchObject({ paneKey }) + expect(mocks.controllerProps).toMatchObject({ composerScopeKey: paneKey }) + }) + it('routes the launch draft and app-menu paste to the structured composer', () => { const draft = { tabId: 'structured-draft-tab', @@ -367,6 +384,16 @@ describe('NativeChatStructuredSession', () => { expect(screen.getByRole('list', { name: 'Agents' })).toBeTruthy() }) + it('offers Stop before any turn opens when the controller can stop, and stops through it', () => { + mocks.canStop = true + render(claudeSessionView('structured-tab-pre-turn', 'session-pre-turn')) + + expect(mocks.composerProps?.isWorking).toBe(true) + act(() => mocks.composerProps?.onStop?.()) + expect(mocks.stop).toHaveBeenCalledOnce() + expect(mocks.cancel).not.toHaveBeenCalled() + }) + it('keeps the strip mounted through a running turn, with the turn owning the voice', () => { // The strip stands for work that OUTLIVES a turn, so `show` is true while // `isMonitoring` is false: mounted, but not speaking as the live indicator. diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index a6bb8ad8d28..1f416bcc070 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -43,8 +43,13 @@ export function NativeChatStructuredSession( const { sendThroughRelaunch } = provisionalLaunch // The host's own word on whether the provider child has answered startup yet. const hostExecution = useStructuredAgentSessionHostExecution(props.sessionId, props.target) + const paneKey = useMemo( + () => structuredAgentSessionPaneKey(props.tabId, props.sessionId), + [props.sessionId, props.tabId] + ) const controller = useStructuredAgentSession({ ...props, + composerScopeKey: paneKey, providerStarting: hostExecution.phase === 'starting', transportEnabled: provisionalLaunch.transportEnabled, ...(provisionalLaunch.launch ? { launch: provisionalLaunch.launch } : {}) @@ -62,10 +67,6 @@ export function NativeChatStructuredSession( id: string sequence: number } | null>(null) - const paneKey = useMemo( - () => structuredAgentSessionPaneKey(props.tabId, props.sessionId), - [props.sessionId, props.tabId] - ) const rootRef = useRef(null) const composerRef = useRef(null) const paneCommands = useStructuredNativeChatPaneCommands({ @@ -376,14 +377,8 @@ export function NativeChatStructuredSession( targetPtyId={null} agent={props.agent} canSend={!prompt} - // Stop, not status: only a provider-minted turn can be interrupted, so the button - // must not flip while a dispatch is still unanswered. - isWorking={controller.turnId !== null} - onStop={() => { - if (controller.turnId) { - void controller.cancel(controller.turnId) - } - }} + isWorking={controller.canStop} + onStop={() => void controller.stop()} structuredTransport={structuredTransport} launchSeed={{ ...launchDraftSignal, ownsTabWideLaunchDraft: true }} /> diff --git a/src/renderer/src/components/native-chat/NativeChatView.test.tsx b/src/renderer/src/components/native-chat/NativeChatView.test.tsx index cc25dabc125..e7e09d2070a 100644 --- a/src/renderer/src/components/native-chat/NativeChatView.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatView.test.tsx @@ -35,8 +35,10 @@ function renderResolution( ) } +const notComposing = (): boolean => false + function DraftProbe({ paneKey, sessionId }: { paneKey: string; sessionId: string | null }) { - const { draft, setDraft } = useNativeChatDraft(paneKey) + const { draft, setDraft } = useNativeChatDraft(paneKey, notComposing) return (